# `ElementorexCms.HTML.Sanitizer`
[🔗](https://github.com/rocket4ce/elementorex_cms/blob/v0.1.0/lib/elementorex_cms/html/sanitizer.ex#L1)

Allow-list HTML sanitizer for the rich text and the HTML of documents.

The input is tokenized and rebuilt from scratch: only allowed tags are written
back, each with its allowed attributes, every attribute value is validated
(URLs, CSS, ids, classes...) and escaped again, and text is escaped. Nothing of
the input is copied verbatim, so malformed markup cannot smuggle anything
through.

## Policies

  * `:inline` - formatting inside a line (`<strong>`, `<em>`, `<a>`, `<br>`...),
    for headings and buttons
  * `:rich` - `:inline` plus paragraphs, lists, quotes, `<h2>`-`<h6>`, `<hr>`
    and `<pre>`, for text blocks (the default)
  * `:html` - `:rich` plus layout tags, images, tables, `<details>` and
    `<video>`, for the *HTML* block

Under every policy `<script>`, `<style>`, `<iframe>`, `<object>`, `<svg>`,
`<math>`, forms and their contents are removed, as are comments, event
handlers (`on*`), `phx-*` bindings and URLs with schemes other than http(s),
`mailto` and `tel`. Disallowed tags are removed but their text is kept.

    iex> ElementorexCms.HTML.Sanitizer.sanitize(~s|<p onclick="x()">Hola <b>mundo</b><script>alert(1)</script></p>|)
    "<p>Hola <b>mundo</b></p>"
    iex> ElementorexCms.HTML.Sanitizer.sanitize(~s|<a href="javascript:alert(1)">x</a>|)
    "<a>x</a>"

# `policy`

```elixir
@type policy() :: :inline | :rich | :html
```

# `sanitize`

```elixir
@spec sanitize(String.t() | nil, policy()) :: String.t()
```

Sanitizes `html` with the given policy (`:rich` by default).

# `text`

```elixir
@spec text(String.t() | nil) :: String.t()
```

Plain text of an HTML fragment: tags removed, entities of the basic set
decoded and whitespace collapsed. For excerpts, search and `alt` texts.

    iex> ElementorexCms.HTML.Sanitizer.text("<p>Hola&nbsp;<b>mundo</b></p><p>!</p>")
    "Hola mundo !"

# `text_to_html`

```elixir
@spec text_to_html(String.t() | nil) :: String.t()
```

Escapes plain text as HTML, turning line breaks into `<br>`.

    iex> ElementorexCms.HTML.Sanitizer.text_to_html("a < b\nc")
    "a &lt; b<br>c"

---

*Consult [api-reference.md](api-reference.md) for complete listing*
