module

Hwaro::Utils::HtmlMinifier

Constants

BLOCK_TAGS = Set {"address", "article", "aside", "base", "blockquote", "body", "caption", "col", "colgroup", "dd", "details", "dialog", "div", "dl", "dt", "fieldset", "figcaption", "figure", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "iframe", "li", "link", "main", "menu", "meta", "nav", "noscript", "ol", "p", "picture", "pre", "script", "section", "source", "style", "summary", "table", "tbody", "td", "tfoot", "th", "thead", "title", "tr", "track", "ul", "video", "audio", "canvas"}

HTML block-level elements. Whitespace adjacent to a block-level neighbour has no visual effect:

  • between two block siblings the user agent renders them on separate lines anyway,
  • leading whitespace inside a block parent is collapsed by the browser before the first inline child,
  • trailing whitespace before a block close is collapsed after the last inline child. Anything not listed here is treated as inline, where whitespace between siblings collapses to a single rendered space and must therefore be kept as one literal space.
PROTECTED_INLINE = Set {"code", "svg", "math", "textarea"}

Classification of protected tags by default HTML display so the inter-token whitespace pass can treat sealed blocks as if they were their original tag.

PROTECTED_TAGS = ["pre", "textarea", "style", "script", "code", "svg", "math", "noscript"] of ::String

Tags whose content must be preserved verbatim. Extracted into placeholders before any whitespace pass and restored afterward. code is included because inline-code snippets often carry whitespace that authors expect to ship unchanged.

Order matters: a <style> body may legitimately contain the literal string <script> (e.g. content: "<script>"), so style is extracted first to remove that text from view before the script pass runs.

Instance methods

minify(html : String) : String

Minify the given HTML.

Example: minify("

\n

Hello

\n
")

=> "

Hello

"

minify("x\ny")

=> "x y"

Source