JSFiddle - React, Tailwind, and code Playground
Babel + JSX
const
createUOL = ({type = 'ul', lis = []} = {}) => ({type, lis}),
createLI = ({name = '', uol} = {}) => ({name, uol}),
L = l => { //l = line
const
type = l[0] === '-' ? 'ul' : 'ol',
level = l.split(' ')[0].length - (type === 'ul' ? 0 : 1),
name = l.substring(level + 1).trim()
return {type, level, name}
},
getUOL = (lines) => createUOL({type: lines[0].type, lis: getLIs(lines)}),
getLIs = (lines) => {
let lis = [], li, i = 0, l1 = lines[0], next
while (i < lines.length) {
next = lines[i+1]
const li = createLI({name: lines[i].name})
if (next && next.level > l1.level) {
li.uol = getUOL(lines.slice(i+1))
i += li.uol.lis.length + 1
lis.push(li)
} else if ((next && next.level === l1.level) || !next) {
i ++
lis.push(li)
} else {
lis.push(li)
break
}
}
return lis
}
let lines = [
'1- 1',
'-- 1.1',
'--- 1.1.1',
'- 2'
].map(l => L(l))
const res = getUOL(lines) //Objet qui contient le résultat, non formaté en HTML
// Le code suivant convertit l'objet "res" en HTML (ce code fonctionne bien)
const
getHTML = uol => {
const uol1 = document.createElement(uol.type)
for (let li of uol.lis) {
const
li1 = document.createElement('li'),
name = document.createTextNode(li.name)
li1.appendChild(name)
if (li.uol) li1.appendChild(getHTML(li.uol))
uol1.appendChild(li1)
}
return uol1
},
html = getHTML(res).outerHTML
document.body.innerHTML = html