-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkwic.js
More file actions
179 lines (146 loc) · 5.58 KB
/
kwic.js
File metadata and controls
179 lines (146 loc) · 5.58 KB
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
58
59
60
61
62
63
64
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
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
let allHits = [];
let totalHits = 0;
let currentPage = 0;
const pageSize = kwic_config.pageSize;
const ctx_width = kwic_config.ctx_width;
const ddc_cgi_url = kwic_config.ddc_cgi_url;
function getQueryParam(name) {
const urlParams = new URLSearchParams(window.location.search);
return urlParams.get(name);
}
function renderPage() {
const table = document.createElement('table');
table.className = 'kwicTable';
const start = currentPage * pageSize;
const pageHits = allHits.slice(start, start + pageSize);
pageHits.forEach((hit, index) => {
const row = document.createElement('tr');
row.className = (start + index) % 2 === 0 ? 'hit0' : 'hit1';
const docId = hit.meta_?.title || '';
const ctxHit = hit.ctx_?.[1] || []; // actual tokens
// to apply ctx width around flag === 1 tokens
const matchIndexes = ctxHit
.map(([flag, word], i) => flag === 1 ? i : -1)
.filter(i => i !== -1);
let ctxLeft = [];
let ctxMatch = [];
let ctxRight = [];
if (matchIndexes.length === 0) {
ctxHit = ctxHit;
}
else {
const matchIndex = matchIndexes[0]; // first match index
// Calculate slice window boundaries safely
const start = Math.max(0, matchIndex - ctx_width);
const end = Math.min(ctxHit.length, matchIndex + ctx_width + 1);
// Slice window tokens
const windowTokens = ctxHit.slice(start, end);
// Relative position of match in window
const relativeMatchIndex = matchIndex - start;
// Split into left, match, right tokens
ctxLeft = windowTokens.slice(0, relativeMatchIndex);
ctxMatch = windowTokens.slice(relativeMatchIndex, relativeMatchIndex + 1);
ctxRight = windowTokens.slice(relativeMatchIndex + 1);
if (start > 0) {
ctxLeft = [['', '…'], ...ctxLeft];
}
if (end < ctxHit.length) {
ctxRight = [...ctxRight, ['', '…']];
}
}
function renderContext(tokens) {
return tokens.map(([flag, word]) => {
if (flag === 1) {
return `<span class="matchedToken1">${word}<sub>[1]</sub></span>`;
} else if (flag === 2) {
return `<span class="matchedToken2">${word}<sub>[2]</sub></span>`;
} else {
return word;
}
}).join(' ');
}
const contextHtml = `
<span class="kwicLHS">${renderContext(ctxLeft)}</span>
<span class="kwicKW">${renderContext(ctxMatch)}</span>
<span class="kwicRHS">${renderContext(ctxRight)}</span>
`;
const docLink = `${docId}`;
row.innerHTML = `
<td class="dtaHitNumber">${start + index + 1}:</td>
<td class="kwicFile dtaHitFile">[${docLink}]</td>
<td>${contextHtml}</td>
`;
table.appendChild(row);
});
const container = document.getElementById('results');
container.innerHTML = '';
container.appendChild(table);
const startHit = currentPage * pageSize + 1;
const endHit = Math.min((currentPage + 1) * pageSize, totalHits);
document.getElementById('total-hits').textContent =`Hits ${startHit} - ${endHit} of ${totalHits}`;
// Disable/Enable buttons
const prevBtn = document.querySelector('.button-prev');
const nextBtn = document.querySelector('.button-next');
const maxPage = Math.floor((allHits.length - 1) / pageSize);
if (prevBtn) prevBtn.disabled = currentPage === 0;
if (nextBtn) nextBtn.disabled = currentPage >= maxPage;
}
async function loadResults(query = null) {
const q = query || getQueryParam('q');
if (!q) {
document.getElementById('results').innerHTML = '<p>No query provided.</p>';
return;
}
document.getElementById('query-text').value = decodeURIComponent(q);
const apiUrl = `${ddc_cgi_url}?q=${encodeURIComponent(q)}`;
try {
const res = await fetch(apiUrl);
if (!res.ok) throw new Error(`HTTP error ${res.status}`);
const data = await res.json();
allHits = data.hits_ || [];
totalHits = data.nhits_ || allHits.length; // total hits count
if (allHits.length === 0) {
document.getElementById('results').innerHTML = '<p>No results found.</p>';
return;
}
currentPage = 0;
renderPage();
} catch (e) {
document.getElementById('results').innerHTML = `<p>Error loading results: ${e.message}</p>`;
}
}
// Add listeners after DOM is ready
window.onload = function () {
loadResults();
document.getElementById('page-title').textContent = `DDC/${kwic_config.corpusName} Search`;
const prevBtn = document.querySelector('.button-prev');
const nextBtn = document.querySelector('.button-next');
if (prevBtn) {
prevBtn.addEventListener('click', () => {
if (currentPage > 0) {
currentPage--;
renderPage();
}
});
}
if (nextBtn) {
nextBtn.addEventListener('click', () => {
const maxPage = Math.floor((allHits.length - 1) / pageSize);
if (currentPage < maxPage) {
currentPage++;
renderPage();
}
});
}
};
document.querySelector('.button-submit').addEventListener('click', () => {
const newQuery = document.getElementById('query-text').value.trim();
if (newQuery) {
// Update URL parameter without reloading the page
const newUrl = new URL(window.location.href);
newUrl.searchParams.set('q', newQuery);
window.history.replaceState({}, '', newUrl);
// Call loadResults with new query
loadResults(newQuery);
}
});