support \n in md()

Massimo Melina committed May 13, 2022 at 00:28 UTC f3336a87b038635986da5e1d6b3669ad3bfdadcc
1 file changed +15 -10
admin/src/md.ts
+15 -10
@@ -4,20 +4,25 @@ import { createElement as h, Fragment } from 'react'
4
5 // markdown inspired syntax to transform text into react elements: * for bold, / for italic, _ for underline, ` for code
6 export default function md(text: string) {
7 - const re = /([`*/_])(.+)\1/g
7 + const re = /([`*/_])(.+)\1|(\n)/g
8 const res = []
9 let last = 0
10 let match
11 while (match = re.exec(text)) { //eslint-disable-line no-cond-assign
12 - const tag = ({
13 - '`': 'code',
14 - '*': 'b',
15 - '/': 'i',
16 - '_': 'u',
17 - })[ match[1] ]
18 - if (!tag)
19 - throw Error("should never happen")
20 - res.push( text.slice(last, match.index), h(tag,{}, match[2]) )
12 + res.push( text.slice(last, match.index) )
13 + if (match[3])
14 + res.push(h('br'))
15 + else {
16 + const tag = ({
17 + '`': 'code',
18 + '*': 'b',
19 + '/': 'i',
20 + '_': 'u',
21 + })[ match[1] ]
22 + if (!tag)
23 + throw Error("should never happen")
24 + res.push( h(tag,{}, match[2]) )
25 + }
26 last = match.index + match[0].length
27 }
28 return h(Fragment, {}, ...res, text.slice(last, Infinity))