Module: Asciidoctor::Html::Search

Included in:
Book
Defined in:
lib/asciidoctor/html/search.rb

Overview

Mixed in to Book class to provide full text search

Constant Summary collapse

SEARCH_RESULT_OVERFLOW =

characters

10

Instance Method Summary collapse

Instance Method Details

#build_index(key, html) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/asciidoctor/html/search.rb', line 43

def build_index(key, html)
  filename = "#{key}.html"
  doctree = Nokogiri::HTML5.parse html, max_errors: 10
  puts("! #{filename}") unless doctree.errors.empty?
  doctree.errors.each do |err|
    puts err
  end
  ref = @refs[key]
  page_text = []
  index = [{
    id: filename,
    title: ref["chapref"]
  }]
  doctree.css(".title-prefix").each { |el| el.content += ": " }
  doctree.css(".title-suffix").each { |el| el.content = " (#{el.content})" }
  doctree.at_css("#content-container").elements.each do |el|
    if el.name == "section" && (sectid = el.attribute "id")
      index << {
        id: "#{filename}##{sectid}",
        title: "#{ref["chapref"]} › #{ref[sectid.to_s]}",
        text: el.text
      }
    else
      page_text << el.text
    end
  end
  index.first[:text] = page_text.join(" ")
  @search_index[key] = index
end

#lunr_scriptObject



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/asciidoctor/html/search.rb', line 81

def lunr_script
  "    (function() {\n      const normalisePossessive = function (builder) {\n        // Define a pipeline function that removes apostrophe\n        const pipelineFunction = function (token) {\n          if(token.toString().endsWith('\u2019s')) {\n            return token.update(() => token.toString().slice(0,-2));\n          } else {\n            return token;\n          }\n        }\n        // Register the pipeline function so the index can be serialised\n        lunr.Pipeline.registerFunction(pipelineFunction, 'normalisePossessive');\n        // Add the pipeline function to both the indexing pipeline and the\n        // searching pipeline\n        builder.pipeline.before(lunr.stemmer, pipelineFunction);\n        builder.searchPipeline.before(lunr.stemmer, pipelineFunction);\n      }\n      const resultsContainer = document.getElementById('search-results-container');\n      const nmatches = document.getElementById('search-nmatches');\n      const searchResults = document.getElementById('search-results');\n      const searchForm = document.getElementById('search-form');\n      const searchBox = document.getElementById('search-text');\n      const positionOverflow = 20;\n      const documents = \#{search_json};\n      const idx = lunr(function() {\n        this.use(normalisePossessive);\n        this.ref('id');\n        this.field('text');\n        this.metadataWhitelist = ['position'];\n\n        documents.forEach(doc => {\n          this.add(doc);\n        });\n      });\n      function processSearchText(searchText) {\n        const results = idx.search(searchText).map(match => {\n          const doc = documents.find(d => d.id == match.ref);\n          const result = document.createElement('li');\n          result.classList.add('list-group-item');\n          const link = document.createElement('a');\n          const br = document.createElement('br');\n          link.setAttribute('href', match.ref);\n          link.innerHTML = doc.title;\n          result.append(link, br);\n          const metadata = match.matchData.metadata;\n          for(const term in metadata) {\n            const datum = metadata[term];\n            for(const type in datum) {\n              datum[type].position.forEach(pos => {\n                const start = pos[0];\n                const end = pos[0] + pos[1];\n                const text = doc[type];\n                const textMatch = text.substring(start, end);\n                const matchingText = document.createElement('mark');\n                const overflowLeft = document.createElement('span');\n                overflowLeft.classList.add('overflow-text-left');\n                const overflowRight = document.createElement('span');\n                overflowRight.classList.add('overflow-text-right');\n                let left = start - \#{SEARCH_RESULT_OVERFLOW};\n                while(text[left] && text[left].trim() == text[left]) {\n                  left--;\n                }\n                let right = end + \#{SEARCH_RESULT_OVERFLOW};\n                while(text[right] && text[right].trim() == text[right]) {\n                  right++;\n                }\n                let overflowRightText = text.substring(end, right);\n                if(overflowRightText.length > 0 && text[right - 1] != '.') {\n                  overflowRightText += '\u2026 ';\n                } else {\n                  overflowRightText += ' ';\n                }\n                overflowLeft.textContent = text.substring(left + 1, start);\n                matchingText.textContent = textMatch;\n                overflowRight.textContent = overflowRightText;\n                result.append(overflowLeft, matchingText, overflowRight);\n              });\n            }\n          }\n          return result;\n        });\n        searchResults.replaceChildren(...results);\n        const n = results.length;\n        nmatches.textContent = n == 1 ? (n + ' match') : (n + ' matches');\n        resultsContainer.classList.remove('hidden');\n      }\n      document.getElementById('search-form-spinner').classList.add('hidden');\n      searchForm.classList.remove('hidden');\n      searchForm.addEventListener('submit', e => {\n        e.preventDefault();\n        const searchText = searchBox.value;\n        processSearchText(searchText);\n      });\n      searchBox.focus();\n    })();\n  JS\nend\n"

#search_jsonObject



73
74
75
76
77
78
79
# File 'lib/asciidoctor/html/search.rb', line 73

def search_json
  index_arr = []
  @search_index.each_value do |search_data|
    index_arr.concat search_data
  end
  index_arr.to_json
end

#search_pageObject



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
# File 'lib/asciidoctor/html/search.rb', line 11

def search_page
  content = "    <div class=\"search-form-container\">\n      <div id=\"search-form-spinner\" class=\"d-flex justify-content-center\">\n        <div class=\"spinner-border\" role=\"status\">\n          <span class=\"visually-hidden\">Loading...</span>\n        </div>\n      </div>\n      <form id=\"search-form\" class=\"search-form hidden\">\n        <input type=\"text\" id=\"search-text\" name=\"search-text\" class=\"form-control search-box\" placeholder=\"Search\">\n        <button type=\"submit\" class=\"btn btn-primary search-btn\">Go</button>\n      </form>\n    </div>\n    <div id=\"search-results-container\" class=\"hidden\">\n    <h5 class=\"search-matches-title\">Found <span id=\"search-nmatches\">0 matches</span></h5>\n    <ul id=\"search-results\" class=\"search-results list-group list-group-flush\"></ul>\n    </div>\n  HTML\n  Template.html(\n    content,\n    nav_items,\n    title: @title,\n    short_title: @short_title,\n    authors: display_authors,\n    date: @date,\n    chapsubheading: \"Search\",\n    langs: [],\n    at_head_end: %(<script defer src=\"https://cdn.jsdelivr.net/npm/[email protected]/lunr.min.js\"></script>),\n    at_body_end: %(<script type=\"module\">\#{lunr_script}</script>)\n  )\nend\n"