File size: 1,693 Bytes
09e4e72
cb8dc08
 
 
 
09e4e72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59fddbd
09e4e72
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
defmodule MedicalTranscriptionWeb.Components.KeywordHighlighter do
  @moduledoc """
  Highlights keywords in transcription text by creating <span> tags for each.
  """

  use MedicalTranscriptionWeb, :html
  # alias Phoenix.HTML.Tag

  def highlight(assigns) do
    # TODO: Eliminate the need to use `raw` here.
    ~H"""
    <%= raw(format_text(@text, @keywords)) %>
    """
  end

  # To highlight the keywords within the transcription, we find the start and end index of each keyword within `text`,
  # split the text at those points, and then join it back together, wrapping the keyword portion in a span with the
  # `text-brand` class.
  defp format_text(text, [first | rest]) do
    if String.contains?(first.label, "and") do
      format_text(text, rest)
    else
      # [one | two] = String.split(text, first.label)
      #
      # keyword =
      #   Tag.content_tag(:span, first.label,
      #     class: "text-brand",
      #     title: "Score: #{Float.round(first.score, 2)}"
      #   )
      #
      # with_replaced_keyword =
      #   Tag.content_tag :div do
      #     "#{one}#{keyword}#{two}"
      #   end

      # with_replaced_keyword = ~E"""
      # #{one}
      # <span class="text-brand" title="Score: #{Float.round(first.score, 2)}">#{first.label}</span>
      # #{two}
      # """

      # with_replaced_keyword = "#{one}#{keyword}#{two}"

      with_replaced_keyword =
        text
        |> String.split(first.label)
        |> Enum.join(
          ~s(<span class="text-brand" title="Score: #{Float.round(first.score, 2)}">#{first.label}</span>)
        )

      format_text(with_replaced_keyword, rest)
    end
  end

  defp format_text(text, []), do: text
end