{"size": 1462, "ext": "js", "max_stars_repo_path": "src/tidy.js", "max_stars_repo_name": "holtwick/hostic-dom", "max_stars_repo_stars_event_min_datetime": "2020-09-08T19:10:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-10T08:44:57.000Z", "max_issues_repo_path": "src/tidy.js", "max_issues_repo_name": "holtwick/hostic-dom", "max_issues_repo_issues_event_min_datetime": "2021-01-28T17:11:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-20T11:57:25.000Z", "max_forks_repo_path": "src/tidy.js", "max_forks_repo_name": "holtwick/hostic-dom", "max_forks_repo_forks_event_min_datetime": "2021-07-17T13:02:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-17T13:02:04.000Z"}
{"max_stars_count": 4, "max_issues_count": 3, "max_forks_count": 1, "avg_line_length": 26.1071428571, "max_line_length": 133, "alphanum_fraction": 0.5827633379}
import { VNode } from "./vdom.js"
import { VTextNode } from "./vdom.js"

function level(element) {
  let indent = ""
  while (element.parentNode) {
    indent += "  "
    element = element.parentNode
  }
  return indent.substr(2)
}

export function tidyDOM(document, opt) {
  let selector =
    "meta,link,script,p,h1,h2,h3,h4,h5,h6,blockquote,div,ul,ol,li,article,section,footer,head,body,title,nav,section,article,hr,form"
  document.handle(selector, (e) => {
    // Ignore if inside PRE etc.
    let ee = e
    while (ee) {
      if (["PRE", "CODE", "SCRIPT", "STYLE", "TT"].includes(ee.tagName)) return
      ee = ee.parentNode
    }

    let prev = e.previousSibling
    if (
      !prev ||
      prev.nodeType !== VNode.TEXT_NODE ||
      !prev.nodeValue?.endsWith("\n")
    ) {
      e.parentNode?.insertBefore(new VTextNode("\n"), e)
    }
    e.parentNode?.insertBefore(new VTextNode(level(e)), e)

    let next = e.nextSibling
    if (
      !next ||
      next.nodeType !== VNode.TEXT_NODE ||
      !next.nodeValue?.startsWith("\n")
    ) {
      if (next) {
        e.parentNode?.insertBefore(new VTextNode("\n"), next)
      } else {
        e.parentNode?.appendChild(new VTextNode("\n"))
      }
    }

    if (e.childNodes.length) {
      let first = e.firstChild
      if (first.nodeType === VNode.TEXT_NODE) {
        e.insertBefore(new VTextNode("\n" + level(e) + "  "))
      }
      e.appendChild(new VTextNode("\n" + level(e)))
    }
  })
}
