index.mjs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. /*
  2. * md ast - pluggable markdown parser
  3. */
  4. const syntax = {
  5. img:{
  6. paired: true,
  7. recursive: false,
  8. startRegexp: /!(\S*)\[(.*)\]\(/,
  9. endRegexp: /\)/,
  10. content: {
  11. start: {
  12. point: 'end',
  13. offset: 0
  14. },
  15. end: {
  16. point: 'start',
  17. offset: 0
  18. }
  19. },
  20. begin: 0,
  21. forward: {
  22. point: 'end', //start, startEnd, end, endEnd
  23. offset: 1
  24. },
  25. title: {
  26. index: 2,
  27. recursive: false,
  28. },
  29. onbuild(md, mdTags, buildAST){ //this = {tag: }
  30. }
  31. },
  32. a:{
  33. paired: true,
  34. recursive: false,
  35. startRegexp: /\[(.*)\]\(/,
  36. endRegexp: /\)/,
  37. content: {
  38. start: {
  39. point: 'end',
  40. offset: 0
  41. },
  42. end: {
  43. point: 'start',
  44. offset: 0
  45. }
  46. },
  47. begin: 0,
  48. forward: {
  49. point: 'end', //start, startEnd, end, endEnd
  50. offset: 1
  51. },
  52. title: {
  53. //index: 1,
  54. recursive: true,
  55. },
  56. onbuild(md, mdTags, buildAST){ //this = {tag: }
  57. }
  58. },
  59. strike: {
  60. paired: true,
  61. recursive: true,
  62. startRegexp: /\~\~\S.*/,
  63. endRegexp: /\~\~\W/,
  64. content: {
  65. start: {
  66. point: 'start',
  67. offset: 2
  68. },
  69. end: {
  70. point: 'start',
  71. offset: 0
  72. }
  73. },
  74. begin: 0,
  75. forward: {
  76. point: 'endEnd', //start, startEnd, end, endEnd
  77. offset: -1
  78. }
  79. },
  80. bold1: {
  81. paired: true,
  82. recursive: true,
  83. startRegexp: /\*\*\S.*/,
  84. endRegexp: /\*\*\W/,
  85. content: {
  86. start: {
  87. point: 'start',
  88. offset: 2
  89. },
  90. end: {
  91. point: 'start',
  92. offset: 0
  93. }
  94. },
  95. begin: 0,
  96. forward: {
  97. point: 'endEnd', //start, startEnd, end, endEnd
  98. offset: -1
  99. }
  100. },
  101. bold2: {
  102. paired: true,
  103. recursive: true,
  104. startRegexp: /\s__\S.*/,
  105. endRegexp: /__\W/,
  106. content: {
  107. start: {
  108. point: 'start',
  109. offset: 3
  110. },
  111. end: {
  112. point: 'start',
  113. offset: 0
  114. }
  115. },
  116. begin: 1,
  117. forward: {
  118. point: 'endEnd', //start, startEnd, end, endEnd
  119. offset: -1
  120. }
  121. },
  122. italic1: {
  123. paired: true,
  124. recursive: true,
  125. startRegexp: /\*\S.*/,
  126. endRegexp: /\S\*[^*]/,
  127. content: {
  128. start: {
  129. point: 'start',
  130. offset: 1
  131. },
  132. end: {
  133. point: 'start',
  134. offset: 1
  135. }
  136. },
  137. begin: 0,
  138. forward: {
  139. point: 'endEnd', //start, startEnd, end, endEnd
  140. offset: -1
  141. }
  142. },
  143. italic2: {
  144. paired: true,
  145. recursive: true,
  146. startRegexp: /\s_\S.*/,
  147. endRegexp: /\S_\W/,
  148. content: {
  149. start: {
  150. point: 'start',
  151. offset: 2
  152. },
  153. end: {
  154. point: 'start',
  155. offset: 1
  156. }
  157. },
  158. begin: 1,
  159. forward: {
  160. point: 'endEnd', //start, startEnd, end, endEnd
  161. offset: -1
  162. }
  163. },
  164. root: {
  165. paired: true,
  166. recursive: true,
  167. startRegexp: /^/,
  168. endRegexp: /$/,
  169. content: {
  170. start: {
  171. point: 'start',
  172. offset: 1
  173. },
  174. end: {
  175. point: 'end',
  176. offset: 0
  177. }
  178. },
  179. begin: 0,
  180. forward: {
  181. point: 'endEnd', //start, startEnd, end, endEnd
  182. offset: -1
  183. }
  184. },
  185. heading6: {
  186. paired: true,
  187. recursive: true,
  188. startRegexp: /\n######[ \t]*([^\[]*)(\[#(\S*)[ \t]*(.*)\])?\n/,
  189. endRegexp: /\n#\s/,
  190. content: {
  191. start: {
  192. point: 'end',
  193. offset: -1
  194. },
  195. end: {
  196. point: 'start',
  197. offset: 0
  198. }
  199. },
  200. begin: 0,
  201. forward: {
  202. point: 'end', //start, startEnd, end, endEnd
  203. offset: 0
  204. },
  205. title: {
  206. //index: 1,
  207. recursive: true,
  208. },
  209. onbuild(md, mdTags, buildAST){ //this = {tag: }
  210. }
  211. },
  212. heading5: {
  213. paired: true,
  214. recursive: true,
  215. startRegexp: /\n#####[ \t]*([^\[]*)(\[#(\S*)[ \t]*(.*)\])?\n/,
  216. endRegexp: /\n#{1,5}\s/,
  217. content: {
  218. start: {
  219. point: 'end',
  220. offset: -1
  221. },
  222. end: {
  223. point: 'start',
  224. offset: 0
  225. }
  226. },
  227. begin: 0,
  228. forward: {
  229. point: 'end', //start, startEnd, end, endEnd
  230. offset: 0
  231. },
  232. title: {
  233. //index: 1,
  234. recursive: true,
  235. },
  236. onbuild(md, mdTags, buildAST){ //this = {tag: }
  237. }
  238. },
  239. heading4: {
  240. paired: true,
  241. recursive: true,
  242. startRegexp: /\n####[ \t]*([^\[]*)(\[#(\S*)[ \t]*(.*)\])?\n/,
  243. endRegexp: /\n#{1,4}\s/,
  244. content: {
  245. start: {
  246. point: 'end',
  247. offset: -1
  248. },
  249. end: {
  250. point: 'start',
  251. offset: 0
  252. }
  253. },
  254. begin: 0,
  255. forward: {
  256. point: 'end', //start, startEnd, end, endEnd
  257. offset: 0
  258. },
  259. title: {
  260. //index: 1,
  261. recursive: true,
  262. },
  263. onbuild(md, mdTags, buildAST){ //this = {tag: }
  264. }
  265. },
  266. heading3: {
  267. paired: true,
  268. recursive: true,
  269. startRegexp: /\n###[ \t]*([^\[]*)(\[#(\S*)[ \t]*(.*)\])?\n/,
  270. endRegexp: /\n#{1,3}\s/,
  271. content: {
  272. start: {
  273. point: 'end',
  274. offset: -1
  275. },
  276. end: {
  277. point: 'start',
  278. offset: 0
  279. }
  280. },
  281. begin: 0,
  282. forward: {
  283. point: 'end', //start, startEnd, end, endEnd
  284. offset: 0
  285. },
  286. title: {
  287. //index: 1,
  288. recursive: true,
  289. },
  290. onbuild(md, mdTags, buildAST){ //this = {tag: }
  291. }
  292. },
  293. heading2: {
  294. paired: true,
  295. recursive: true,
  296. startRegexp: /\n##[ \t]*([^\[]*)(\[#(\S*)[ \t]*(.*)\])?\n/,
  297. endRegexp: /\n#{1,2}\s/,
  298. content: {
  299. start: {
  300. point: 'end',
  301. offset: -1
  302. },
  303. end: {
  304. point: 'start',
  305. offset: 0
  306. }
  307. },
  308. begin: 0,
  309. forward: {
  310. point: 'end', //start, startEnd, end, endEnd
  311. offset: 0
  312. },
  313. title: {
  314. //index: 1,
  315. recursive: true,
  316. },
  317. onbuild(md, mdTags, buildAST){ //this = {tag: }
  318. }
  319. },
  320. heading1: {
  321. paired: true,
  322. recursive: true,
  323. startRegexp: /\n#[ \t]*([^\[]*)(\[#(\S*)[ \t]*(.*)\])?\n/,
  324. endRegexp: /\n#\s/,
  325. content: {
  326. start: {
  327. point: 'end',
  328. offset: -1
  329. },
  330. end: {
  331. point: 'start',
  332. offset: 0
  333. }
  334. },
  335. begin: -1,
  336. forward: {
  337. point: 'end', //start, startEnd, end, endEnd
  338. offset: 0
  339. },
  340. title: {
  341. //index: 1,
  342. recursive: true,
  343. },
  344. onbuild(md, mdTags, buildAST){ //this = {tag: }
  345. }
  346. },
  347. code: {
  348. paired: true,
  349. recursive: false,
  350. startRegexp: /`/,
  351. endRegexp: /`/,
  352. content: {
  353. start: {
  354. point: 'start',
  355. offset: 1
  356. },
  357. end: {
  358. point: 'start',
  359. offset: 0
  360. }
  361. },
  362. begin: 0,
  363. forward: {
  364. point: 'end', //start, startEnd, end, endEnd
  365. offset: 1
  366. }
  367. },
  368. codeMultiLine: {
  369. paired: true,
  370. recursive: false,
  371. startRegexp: /\n```\s*\n/,
  372. endRegexp: /\n```\s*\n/,
  373. content:{
  374. start:{
  375. point: 'end',
  376. offset: 0
  377. },
  378. end:{
  379. point: 'start',
  380. offset: 0
  381. }
  382. },
  383. begin: 1,
  384. forward: {
  385. point: 'endEnd',
  386. offset: 0
  387. },
  388. },
  389. codeLanguage: {
  390. paired: true,
  391. recursive: false,
  392. startRegexp: /\n```(\w+)\s*\n/,
  393. endRegexp: /\n```\s*\n/,
  394. title: {
  395. recursive: false
  396. },
  397. content:{
  398. start:{
  399. point: 'end',
  400. offset: 0
  401. },
  402. end:{
  403. point: 'start',
  404. offset: 0
  405. }
  406. },
  407. begin: 1,
  408. forward: {
  409. point: 'endEnd',
  410. offset: 0
  411. },
  412. },
  413. unOrderedList: {
  414. indent: true,
  415. childName: 'unOrderedListItem',
  416. //paired: true,
  417. recursive: true,
  418. regexp: /-\s*\S/,
  419. content:{
  420. start:{
  421. point: 'end',
  422. offset: -1
  423. },
  424. end:{
  425. point: 'start',
  426. offset: 0
  427. }
  428. },
  429. begin: 1,
  430. forward: {
  431. point: 'end',
  432. offset: 0
  433. }
  434. },
  435. orderedList: {
  436. indent: true,
  437. childName: 'orderedListItem',
  438. //paired: true,
  439. recursive: true,
  440. regexp: /\d+\.\s*\S/,
  441. content:{
  442. start:{
  443. point: 'end',
  444. offset: -1
  445. },
  446. end:{
  447. point: 'start',
  448. offset: 0
  449. }
  450. },
  451. begin: 1,
  452. forward: {
  453. point: 'end',
  454. offset: 0
  455. }
  456. },
  457. p:{
  458. paired: true,
  459. recursive: true,
  460. startRegexp: /\n\s*\S/,
  461. endRegexp: /\n/,
  462. content: {
  463. start: {
  464. point: 'start',
  465. offset: 1
  466. },
  467. end: {
  468. point: 'start',
  469. offset: 0
  470. }
  471. },
  472. begin: 1,
  473. forward: {
  474. point: 'end', //start, startEnd, end, endEnd
  475. offset: 0
  476. },
  477. },
  478. }
  479. const indentRegexp = (regexp,count) => new RegExp(`\\n([ \\t]${count === undefined ? '*' : `{${count}}` })` + regexp.toString().slice(1,-1))
  480. const indentEndRegexp = (count) => new RegExp(`\\n([ \\t]${count === undefined ? '*' : `{0,${count}}` })\\S`)
  481. function findNearest(md, mdTags, offset=0){
  482. let nearest, nearestMatch = {index: Infinity};
  483. for (let [mdTag, {paired,
  484. startRegexp,
  485. regexp, indent}] of Object.entries(mdTags)) {
  486. if (mdTag === 'root') continue;
  487. regexp = startRegexp || regexp
  488. regexp = indent ? indentRegexp(regexp) : regexp
  489. let match = md.offsetMatch(offset, regexp)
  490. if (match && match.index < nearestMatch.index){
  491. nearestMatch = match
  492. nearest = mdTag
  493. }
  494. }
  495. return [nearest, nearestMatch]
  496. }
  497. //node:
  498. //{
  499. // tag: 'keyFromSyntax',
  500. // children: [String, Node]
  501. // parent: node
  502. //}
  503. //
  504. String.prototype.offsetMatch = function(offset, ...params){
  505. return this.slice(offset).match(...params)
  506. }
  507. Array.prototype.last = function(amount=-1){
  508. return this[this.length +amount]
  509. }
  510. String.prototype.cutIndent = function(indent){
  511. let lines = this.split('\n').map(line => line.slice(0, indent).match(/^\s*$/) ? line.slice(indent) : line)
  512. return lines.join('\n')
  513. }
  514. function buildAST(md, mdTags=syntax, offset=0, tree={tag: 'root'}, stack=[]){
  515. let currentNode = stack.last() || tree
  516. if (currentNode.tag === 'root') md = '\n' + md + '\n'
  517. currentNode.children = currentNode.children || []
  518. const { children } = currentNode
  519. let {indent, childName, title, recursive, regexp, endRegexp, content: {end: {offset: offsetEnd, point} }, forward } = mdTags[currentNode.tag]
  520. if (indent){
  521. if (currentNode.parent.tag !== currentNode.tag){ //li
  522. let { parent: {children: siblings} } = currentNode
  523. if (siblings.length > 1 && siblings.last(-2).tag === currentNode.tag){
  524. siblings.pop()
  525. currentNode = siblings.last()
  526. }
  527. const { children } = currentNode
  528. const indentLength = currentNode.startMatch[1].length
  529. console.log(indentLength)
  530. currentNode.indentLength = indentLength
  531. endRegexp = indentEndRegexp(indentLength)
  532. let endMatch = md.offsetMatch(offset, endRegexp) || {index: md.length +1, 0: 'zzz'}
  533. let listMD = md.slice(offset, endMatch.index + offset).cutIndent(currentNode.startMatch[0].length -2)
  534. const newNode = {tag: childName, startOffset: offset, parent: currentNode, startMatch: currentNode.startMatch}
  535. children.push(newNode)
  536. newNode.children = buildAST(listMD, mdTags).children
  537. newNode.children.forEach(item => ((typeof item === 'object') && (item.parent = currentNode)))
  538. offset = newNode.endOffset = currentNode.endOffset = endMatch.index + offset
  539. }
  540. }
  541. if (title){
  542. const {index=1, recursive} = title
  543. const {[index]: titleContent } = currentNode.startMatch
  544. if (titleContent && recursive){
  545. currentNode.title = buildAST(titleContent, mdTags).children
  546. currentNode.title.forEach(item => ((typeof item === 'object') && (item.parent = currentNode)))
  547. }
  548. else {
  549. currentNode.title = [titleContent]
  550. }
  551. }
  552. while(offset < md.length){
  553. const [nearest, nearestMatch] = findNearest(md, mdTags, offset)
  554. let endMatch = md.offsetMatch(offset, endRegexp)
  555. if (!recursive || endMatch) { //if we (should) find closing tag
  556. if (!recursive || !nearest || endMatch.index <= nearestMatch.index ){ //if closing tag closer than new nested tag
  557. endMatch = endMatch || {index: md.length - offset, 0: "zzz"}
  558. currentNode.endContent = offset + endMatch.index + offsetEnd + (point === 'end' ? endMatch[0].length : 0)
  559. offset !== currentNode.endContent && children.push(md.slice(offset, currentNode.endContent))
  560. offset += endMatch.index + forward.offset + (forward.point === 'endEnd' ? endMatch[0].length : 0)
  561. currentNode.endOffset = offset
  562. currentNode.endMatch = endMatch
  563. return currentNode
  564. }
  565. }
  566. if (nearest){ //new nested tag
  567. const {begin,content: {start}} = mdTags[nearest]
  568. if (nearestMatch.index){ //if just text before nested tag
  569. nearestMatch.index + begin > 0 && children.push(md.slice(offset, offset + nearestMatch.index + begin))
  570. offset += nearestMatch.index
  571. }
  572. else { //if new tag right under cursor (offset)
  573. let newNode = {tag: nearest, startOffset: offset, parent: currentNode, startMatch: nearestMatch}
  574. children.push(newNode)
  575. newNode = buildAST(md, mdTags, offset + start.offset + (start.point === 'end' ? nearestMatch[0].length : 0), tree, [...stack, newNode])
  576. offset = newNode.endOffset
  577. }
  578. }
  579. else { //no nearest - rest of line to children as text
  580. children.push(md.slice(offset))
  581. offset = md.length
  582. }
  583. }
  584. return currentNode
  585. }
  586. const Heading = ({react:React, children, title, node: {tag, startMatch}}) => {
  587. const level = +tag.slice(-1)
  588. const _ = React.createElement.bind(React)
  589. const [m, m1,m2, id, rest] = startMatch
  590. if (isNaN(level)) throw new SyntaxError('wrong heading name')
  591. return _(React.Fragment, null,
  592. _(`h${level}`, id && {id}, ...title),
  593. _(`div`, null, ...children)
  594. )
  595. }
  596. const A = ({react:React, children, title}) =>{
  597. const _ = React.createElement.bind(React)
  598. return _("a", {children: title, href: children})
  599. }
  600. const Img = ({react:React, children, title, node}) =>{
  601. const _ = React.createElement.bind(React)
  602. return _("img", {alt: title, src: children, className: node.startMatch[1] || undefined})
  603. }
  604. export const defaultMapMDToComponents = {
  605. heading1: Heading,
  606. heading2: Heading,
  607. heading3: Heading,
  608. heading4: Heading,
  609. heading5: Heading,
  610. heading6: Heading,
  611. strike: "strike",
  612. bold1: "strong",
  613. bold2: "strong",
  614. p: "p",
  615. a: A,
  616. img: Img,
  617. italic1: "i",
  618. italic2: "i",
  619. unOrderedList: 'ul',
  620. orderedList: 'ol',
  621. unOrderedListItem: 'li',
  622. orderedListItem: 'li',
  623. code: 'code',
  624. codeMultiLine: 'pre',
  625. codeLanguage: 'pre',
  626. root: ""
  627. }
  628. function toReact(ast, React, mapMDToComponents=defaultMapMDToComponents){
  629. mapMDToComponents = {...defaultMapMDToComponents, ...mapMDToComponents}
  630. const gC = (tag, c) => (c = mapMDToComponents[tag]) ? c : (c === "" ? React.Fragment : "span")
  631. const RenderComponent = gC(ast.tag)
  632. const _ = React.createElement.bind(React)
  633. const childToReact = child => typeof child === 'string' ? child :
  634. toReact(child, React, mapMDToComponents)
  635. const props = {key: Math.random(),
  636. children: ast.children.map(childToReact)}
  637. if (typeof RenderComponent !== 'string' && RenderComponent !== React.Fragment)
  638. Object.assign(props,{node: ast,
  639. title: ast.title && ast.title.map(childToReact),
  640. react: React})
  641. return _(RenderComponent, props)
  642. }
  643. export {buildAST, toReact}