Skip to content

Commit

Permalink
Make a few helper functions and values public. (#6)
Browse files Browse the repository at this point in the history
* Make a few helper functions and values public.

* More escaping helpers.
  • Loading branch information
mbrandonw authored Oct 3, 2018
1 parent d205ab0 commit 2580768
Showing 1 changed file with 19 additions and 7 deletions.
26 changes: 19 additions & 7 deletions Sources/Html/Render.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,17 @@ public func render(_ nodes: [Node]) -> String {
public func render(_ node: Node) -> String {
switch node {
case let .comment(string):
return "<!-- \(string.replacingOccurrences(of: "-->", with: "--&gt;")) -->"
return "<!-- \(escapeHtmlComment(string)) -->"
case let .doctype(string):
return "<!DOCTYPE \(string.replacingOccurrences(of: ">", with: "&gt;"))>"
return "<!DOCTYPE \(escapeDoctype(string))>"
case let .element(tag, attribs, children):
let renderedAttribs = render(attribs)
guard !children.isEmpty else {
return "<" + tag + renderedAttribs + (voidElements.contains(tag) ? ">" : "/>")
}
return "<" + tag + renderedAttribs + ">" + render(children) + "</" + tag + ">"
case let .text(string):
return escape(html: string)
return escapeTextNode(text: string)
case let .raw(string):
return string
}
Expand All @@ -39,20 +39,32 @@ private func render(_ attribs: [(String, String?)]) -> String {
return attribs
.compactMap { key, value in
value.map {
" " + key + ($0.isEmpty ? "" : "=\"\($0.replacingOccurrences(of: "\"", with: "&quot;"))\"")
" " + key + ($0.isEmpty ? "" : "=\"\(escapeAttributeValue($0))\"")
}
}
.joined()
}

private func escape(html: String) -> String {
return html
public func escapeAttributeValue(_ value: String) -> String {
return value.replacingOccurrences(of: "\"", with: "&quot;")
}

public func escapeTextNode(text: String) -> String {
return text
.replacingOccurrences(of: "&", with: "&amp;")
.replacingOccurrences(of: "<", with: "&lt;")
}

public func escapeDoctype(_ doctype: String) -> String {
return doctype.replacingOccurrences(of: ">", with: "&gt;")
}

public func escapeHtmlComment(_ comment: String) -> String {
return comment.replacingOccurrences(of: "-->", with: "--&gt;")
}

/// A set of self-closing "void" elements that should not contain child nodes.
private let voidElements: Set<String> = [
public let voidElements: Set<String> = [
"area",
"base",
"br",
Expand Down

0 comments on commit 2580768

Please sign in to comment.