65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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
|
# File 'lib/asciidoctor/html/search.rb', line 65
def lunr_script
<<~JS
(function() {
const resultsContainer = document.getElementById('search-results-container');
const nmatches = document.getElementById('search-nmatches');
const searchResults = document.getElementById('search-results');
const searchForm = document.getElementById('search-form');
const searchBox = document.getElementById('search-text');
const positionOverflow = 20;
const documents = #{search_json};
const idx = lunr(function() {
this.ref('id');
this.field('title');
this.field('text');
this.metadataWhitelist = ['position'];
documents.forEach(doc => {
this.add(doc)
});
});
function processSearchText(searchText) {
const results = idx.search(searchText).map(match => {
const doc = documents.find(d => d.id == match.ref);
const result = document.createElement('li');
result.classList.add('list-group-item');
const link = document.createElement('a');
const br = document.createElement('br');
link.setAttribute('href', match.ref);
link.innerHTML = doc.title;
result.append(link, br);
const metadata = match.matchData.metadata;
for(const term in metadata) {
const datum = metadata[term];
for(const type in datum) {
datum[type].position.forEach(pos => {
const start = pos[0];
const end = pos[0] + pos[1];
const text = doc[type];
const textMatch = text.substring(start, end)
const matchingText = document.createElement('mark');
const overflowLeft = document.createElement('span');
overflowLeft.classList.add('overflow-text-left');
const overflowRight = document.createElement('span');
overflowRight.classList.add('overflow-text-right');
const reLeft = /.{#{SEARCH_RESULT_OVERFLOW}}$/s;
let left = text.substring(0, start - 1).search(reLeft) + 1;
while(text[left] && text[left].trim() == text[left]) {
left--;
}
const reRight = /^.{#{SEARCH_RESULT_OVERFLOW}}/s;
let right = text.length;
if(rightMatch = text.substring(end + 1).match(reRight)) {
right = rightMatch[0].length + end;
while(text[right] && text[right].trim() == text[right]) {
right++;
}
}
overflowLeft.textContent = text.substring(left, start - 1);
matchingText.textContent = textMatch;
overflowRight.textContent = text.substring(end + 1, right);
result.append(overflowLeft, matchingText, overflowRight);
});
}
}
return result;
});
searchResults.replaceChildren(...results);
const n = results.length;
nmatches.textContent = n == 1 ? (n + ' match') : (n + ' matches');
resultsContainer.classList.remove('hidden');
}
searchForm.addEventListener('submit', e => {
e.preventDefault();
const searchText = searchBox.value;
processSearchText(searchText);
});
})();
JS
end
|