merge <main> and <body>

master
magical 2021-11-16 06:23:37 +00:00
parent 4b4b875f34
commit 6e5ef58613
2 changed files with 37 additions and 2 deletions

View File

@ -121,7 +121,25 @@ func merge(base, doc *html.Node) (out *html.Node) {
n.Parent.RemoveChild(n)
}
_ = main // TODO
// if neither has main, just merge the bodies
// if doc has main but base doesn't, just merge the bodies
// if base has main but doc doesn't, merge doc body into base main
// if both have main, merge doc main(s) into base main and then merge the bodies
if main == nil {
reparentBefore(body, newBody, footer)
} else if findRec(newBody, atom.Main) == nil {
reparentBefore(main, newBody, footer)
} else {
for {
n := findRec(newBody, atom.Main)
if n == nil {
break
}
reparentChildren(main, n)
n.Parent.RemoveChild(n)
}
reparentBefore(body, newBody, footer)
}
return out
}
@ -145,6 +163,21 @@ func reparentChildren(dst, src *html.Node) {
}
}
// reparentBefore reparents all of src's child nodes to dst, inserting them before the given element.
func reparentBefore(dst, src, locus *html.Node) {
if src == nil {
return
}
for {
child := src.FirstChild
if child == nil {
break
}
src.RemoveChild(child)
dst.InsertBefore(child, locus)
}
}
func find(elem *html.Node, tagName atom.Atom) *html.Node {
if elem != nil {
for n := elem.FirstChild; n != nil; n = n.NextSibling {

View File

@ -17,13 +17,15 @@ const pageText = `
<title>This is a title</title>
<style>p { color: red; }</style>
<header><h1>Title</h1></header>
<p>Body text
<p>Body text</p>
`
const mergeText = `<!DOCTYPE html><html><head><style>body { background: #ccc; color: black; }</style>
<title>This is a title</title>
<style>p { color: red; }</style>
</head><body><header><h1>Title</h1></header>
<p>Body text</p>
<footer></footer>
</body></html>`