Highlight

v0.0.10

v0.0.10StableHeadlessStatelessAccessibleApache-2.0
Installation mix mishka.ui.gen.headless highlight
Source View Source

Overview of the Phoenix and LiveView Headless Highlight Component

The Mishka Chelekom Headless Highlight marks the parts of a text that match a query, for Phoenix and LiveView. It splits text on the server at every case-insensitive match of highlight and wraps each match in a <mark>. There is no JavaScript, and the rest of the text is escaped as usual.

highlight takes one string or a list of strings. The wrapper is a <span>, so the component fits inside a paragraph, a link or a heading. The wrapper takes class and each match takes mark_class.

Base UI Highlight example - one query term (Phoenix headless)

Both phoenix and Phoenix match, and each match keeps the capitalization it has in text.

Base UI Highlight example - one query term (Phoenix headless)

Search results for phoenix: the Phoenix framework is fast.
heex
<p class="max-w-sm text-sm text-neutral-700 dark:text-neutral-300">
  <.highlight
    text="Search results for phoenix: the Phoenix framework is fast."
    highlight="phoenix"
    mark_class="rounded bg-lime-200 px-0.5 text-neutral-900"
  />
</p>

Several terms and search results

Give highlight a list to mark more than one term. Terms are matched as literal text, so characters such as . or ( need no escaping. nil and empty strings in the list are ignored. When several terms can match at the same place, the one listed first wins, so list a longer term before a shorter one that it starts with.

heex
<.highlight
  text="Phoenix LiveView keeps the page in sync with the server."
  highlight={["phoenix", "liveview"]}
  mark_class="rounded bg-yellow-200 px-0.5 text-neutral-900"
/>

A common use is a list of search results, where @query is the text the visitor typed.

heex
<ul>
  <li :for={post <- @posts}>
    <.highlight text={post.title} highlight={@query} mark_class="rounded bg-yellow-200 px-0.5" />
  </li>
</ul>

Parts & data attributes

The wrapper carries the structural class chelekom-highlight, and each match carries chelekom-highlight__mark. Only the match has a data-part.

Partdata-partState / ARIAPurpose
Root--The span around the whole text. Takes class and an optional id.
Markmark-A mark element around each match, with the text as it was written in text.

Accessibility

There is no formal WAI-ARIA APG pattern for highlighted text. Each match is a native <mark> element, so it keeps its meaning without CSS. Do not rely on the highlight color alone for information that the text does not already carry.