-
Notifications
You must be signed in to change notification settings - Fork 99
Expand file tree
/
Copy pathvocab-search.js
More file actions
413 lines (396 loc) · 16 KB
/
vocab-search.js
File metadata and controls
413 lines (396 loc) · 16 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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
/* global Vue, $t, onTranslationReady */
function startVocabSearchApp () {
const vocabSearch = Vue.createApp({
data () {
return {
selectedLanguage: null,
searchTerm: null,
searchCounter: null,
renderedResultsList: [],
languageStrings: null,
uriPrefixes: {},
showDropdown: false,
showNotation: null
}
},
computed: {
searchPlaceholder () {
return $t('Search in this vocabulary')
},
anyLanguages () {
return $t('Any language')
},
noResults () {
return $t('No results')
},
selectSearchLanguageAriaMessage () {
return $t('Select search language')
},
searchFieldAriaMessage () {
return $t('Search in this vocabulary')
},
searchButtonAriaMessage () {
return $t('Search')
},
clearSearchAriaMessage () {
return $t('Clear search field')
}
},
mounted () {
this.selectedLanguage = this.parseSearchLang()
this.searchCounter = 0 // used for matching the query and the response in case there are many responses
this.languageStrings = this.formatLanguages()
this.renderedResultsList = []
this.uriPrefixes = {}
this.showNotation = window.SKOSMOS.showNotation
},
methods: {
autoComplete () {
const delayMs = 300
// when new autocomplete is fired, empty the previous result
this.renderedResultsList = []
// cancel the timer for upcoming API call
clearTimeout(this._timerId)
this.hideAutoComplete()
// delay call, but don't execute if the search term is not at least two characters
if (this.searchTerm.length > 1) {
this._timerId = setTimeout(() => { this.search() }, delayMs)
}
},
search () {
const mySearchCounter = this.searchCounter + 1 // make sure we can identify this search later in case of several ongoing searches
this.searchCounter = mySearchCounter
let skosmosSearchUrl = 'rest/v1/' + window.SKOSMOS.vocab + '/search?'
const skosmosSearchUrlParams = new URLSearchParams({ query: this.formatSearchTerm(), unique: true })
if (this.selectedLanguage !== 'all') skosmosSearchUrlParams.set('lang', this.selectedLanguage)
skosmosSearchUrl += skosmosSearchUrlParams.toString()
fetch(skosmosSearchUrl)
.then(data => data.json())
.then(data => {
if (mySearchCounter === this.searchCounter) {
this.renderedResultsList = data.results // update results (update cache if it is implemented)
this.uriPrefixes = data['@context']
this.renderResults() // render after the fetch has finished
}
})
},
formatLanguages () {
const languages = window.SKOSMOS.contentLanguages
const anyLanguagesEntry = { all: this.anyLanguages }
return { ...languages, ...anyLanguagesEntry }
},
formatSearchTerm () {
if (this.searchTerm.includes('*')) { return this.searchTerm }
return this.searchTerm + '*'
},
notationMatches (searchTerm, notation) {
if (notation && notation.toLowerCase().includes(searchTerm.toLowerCase())) {
return true
}
return false
},
parseSearchLang () {
// if content language can be found from uri params, use that and update it to SKOSMOS object and to search lang cookie
const urlParams = new URLSearchParams(window.location.search)
const paramLang = urlParams.get('clang')
const anyLang = urlParams.get('anylang')
if (anyLang) {
this.changeLang('all')
return 'all'
}
if (paramLang) {
this.changeLang(paramLang)
return paramLang
}
// otherwise pick content lang from SKOSMOS object (it should always exist)
if (window.SKOSMOS.content_lang) {
return window.SKOSMOS.content_lang
}
return null
},
renderMatchingPart (searchTerm, label, lang = null) {
if (label) {
let langSpec = ''
if (lang && this.selectedLanguage === 'all') {
langSpec = ' (' + lang + ')'
}
const searchTermLowerCase = searchTerm.toLowerCase()
const labelLowerCase = label.toLowerCase()
if (labelLowerCase.includes(searchTermLowerCase)) {
const startIndex = labelLowerCase.indexOf(searchTermLowerCase)
const endIndex = startIndex + searchTermLowerCase.length
return {
before: label.substring(0, startIndex),
match: label.substring(startIndex, endIndex),
after: label.substring(endIndex) + langSpec
}
}
return label + langSpec
}
return null
},
renderType (typeUri) {
const label = window.SKOSMOS.types[typeUri]
if (label) return label
const [prefix, local] = typeUri.split(':')
const iriBase = this.uriPrefixes[prefix]
if (iriBase) {
const iri = iriBase + local
return window.SKOSMOS.types[iri] || typeUri
}
return typeUri
},
/*
* renderResults is used when the search string has been indexed in the cache
* it also shows the autocomplete results list
*/
renderResults () {
const renderedSearchTerm = this.searchTerm // save the search term in case it changes while rendering
this.renderedResultsList.forEach(result => {
if ('hiddenLabel' in result) {
result.hitType = 'hidden'
result.hit = this.renderMatchingPart(renderedSearchTerm, result.prefLabel, result.lang)
} else if ('altLabel' in result) {
result.hitType = 'alt'
result.hit = this.renderMatchingPart(renderedSearchTerm, result.altLabel, result.lang)
result.hitPref = this.renderMatchingPart(renderedSearchTerm, result.prefLabel)
} else {
if (this.notationMatches(renderedSearchTerm, result.notation)) {
result.hitType = 'notation'
result.hit = this.renderMatchingPart(renderedSearchTerm, result.notation, result.lang)
} else if ('matchedPrefLabel' in result) {
result.hitType = 'pref'
result.hit = this.renderMatchingPart(renderedSearchTerm, result.matchedPrefLabel, result.lang)
} else if ('prefLabel' in result) {
result.hitType = 'pref'
result.hit = this.renderMatchingPart(renderedSearchTerm, result.prefLabel, result.lang)
}
}
if ('uri' in result) { // create relative Skosmos page URL from the search result URI
result.pageUrl = window.SKOSMOS.vocab + '/' + window.SKOSMOS.lang + '/page?'
const urlParams = new URLSearchParams({ uri: result.uri })
if (this.selectedLanguage !== window.SKOSMOS.lang) { // add content language parameter
urlParams.append('clang', this.selectedLanguage)
}
result.pageUrl += urlParams.toString()
}
// render search result renderedTypes
if (result.type.length > 1) { // remove the type for SKOS concepts if the result has more than one type
result.type.splice(result.type.indexOf('skos:Concept'), 1)
}
// use the renderType function to map translations for the type IRIs
result.renderedType = result.type.map(uri => this.renderType(uri)).join(', ')
result.showNotation = this.showNotation
})
if (this.renderedResultsList.length === 0) { // show no results message
this.renderedResultsList.push({
prefLabel: this.noResults,
lang: window.SKOSMOS.lang
})
}
this.showAutoComplete()
},
hideAutoComplete () {
this.showDropdown = false
this.$forceUpdate()
},
gotoSearchPage () {
if (!this.searchTerm) return
const searchUrlParams = new URLSearchParams({ clang: window.SKOSMOS.content_lang, q: this.searchTerm })
if (this.selectedLanguage === 'all') searchUrlParams.set('anylang', 'true')
const searchUrl = window.SKOSMOS.vocab + '/' + window.SKOSMOS.lang + '/search?' + searchUrlParams.toString()
window.location.href = searchUrl
},
changeLang (clang) {
this.selectedLanguage = clang
if (clang !== 'all') {
window.SKOSMOS.content_lang = clang
}
this.resetSearchTermAndHideDropdown()
},
changeContentLangAndReload (clang) {
this.changeLang(clang)
const params = new URLSearchParams(window.location.search)
if (clang === 'all') {
params.set('anylang', 'true')
} else {
params.delete('anylang')
params.set('clang', clang)
}
this.$forceUpdate()
window.location.search = params.toString()
},
resetSearchTermAndHideDropdown () {
this.searchTerm = ''
this.renderedResultsList = []
this.hideAutoComplete()
this.$nextTick(() => {
this.$refs.searchInputField.focus()
})
},
/*
* Show the existing autocomplete list if it was hidden by onClickOutside()
*/
showAutoComplete () {
this.showDropdown = true
this.$forceUpdate()
}
},
template: `
<div class="input-group ps-xl-2 flex-nowrap" id="search-wrapper">
<div class="dropdown" id="language-selector">
<button class="btn btn-outline-secondary dropdown-toggle"
role="button"
data-bs-toggle="dropdown"
aria-expanded="false"
:aria-label="selectSearchLanguageAriaMessage"
v-if="languageStrings">
{{ languageStrings[selectedLanguage] }}
<i class="fa-solid fa-chevron-down"></i>
</button>
<ul class="dropdown-menu" id="language-list" role="menu">
<li v-for="(value, key) in languageStrings" :key="key" role="none">
<a
class="dropdown-item"
:value="key"
@click="changeContentLangAndReload(key)"
@keydown.enter="changeContentLangAndReload(key)"
role="menuitem"
tabindex=0 >
{{ value }}
</a>
</li>
</ul>
</div>
<span id="headerbar-search" class="dropdown">
<input type="search"
ref="searchInputField"
class="form-control"
id="search-field"
autocomplete="off"
data-bs-toggle=""
:aria-label="searchFieldAriaMessage"
:placeholder="searchPlaceholder"
v-click-outside="hideAutoComplete"
v-model="searchTerm"
@input="autoComplete()"
@keyup.enter="gotoSearchPage()"
@click="showAutoComplete()">
<ul id="search-autocomplete-results"
class="dropdown-menu w-100"
:class="{ 'show': showDropdown }"
aria-labelledby="search-field">
<li class="autocomplete-result container" v-for="result in renderedResultsList"
:key="result.prefLabel" >
<template v-if="result.pageUrl">
<a :href=result.pageUrl>
<div class="row pb-1">
<div class="col" v-if="result.hitType == 'hidden'">
<span class="result">
<template v-if="result.showNotation && result.notation">
{{ result.notation }}
</template>
<template v-if="result.hit.hasOwnProperty('match')">
{{ result.hit.before }}<b>{{ result.hit.match }}</b>{{ result.hit.after }}
</template>
<template v-else>
{{ result.hit }}
</template>
</span>
</div>
<div class="col" v-else-if="result.hitType == 'alt'">
<span>
<i>
<template v-if="result.showNotation && result.notation">
{{ result.notation }}
</template>
<template v-if="result.hit.hasOwnProperty('match')">
{{ result.hit.before }}<b>{{ result.hit.match }}</b>{{ result.hit.after }}
</template>
<template v-else>
{{ result.hit }}
</template>
</i>
</span>
<span> → <span class="result">
<template v-if="result.showNotation && result.notation">
{{ result.notation }}
</template>
<template v-if="result.hitPref.hasOwnProperty('match')">
{{ result.hitPref.before }}<b>{{ result.hitPref.match }}</b>{{ result.hitPref.after }}
</template>
<template v-else>
{{ result.hitPref }}
</template>
</span>
</span>
</div>
<div class="col" v-else-if="result.hitType == 'notation'">
<span class="result">
<template v-if="result.hit.hasOwnProperty('match')">
{{ result.hit.before }}<b>{{ result.hit.match }}</b>{{ result.hit.after }}
</template>
<template v-else>
{{ result.hit }}
</template>
</span>
<span>
{{ result.prefLabel }}
</span>
</div>
<div class="col" v-else-if="result.hitType == 'pref'">
<span class="result">
<template v-if="result.showNotation && result.notation">
{{ result.notation }}
</template>
<template v-if="result.hit.hasOwnProperty('match')">
{{ result.hit.before }}<b>{{ result.hit.match }}</b>{{ result.hit.after }}
</template>
<template v-else>
{{ result.hit }}
</template>
</span>
</div>
<div class="col-auto align-self-end pr-1" v-html="result.renderedType"></div>
</div>
</a>
</template>
<template v-else>
{{ result.prefLabel }}
</template>
</li>
</ul>
</span>
<button id="clear-button"
class="btn btn-danger"
type="clear"
:aria-label="clearSearchAriaMessage"
v-if="searchTerm"
@click="resetSearchTermAndHideDropdown()">
<i class="fa-solid fa-xmark"></i>
</button>
<button id="search-button" class="btn btn-outline-secondary" :aria-label="searchButtonAriaMessage" @click="gotoSearchPage()">
<i class="fa-solid fa-magnifying-glass"></i>
</button>
</div>
`
})
vocabSearch.directive('click-outside', {
beforeMount: (el, binding) => {
el.clickOutsideEvent = event => {
// Ensure the click was outside the element
if (!(el === event.target || el.contains(event.target))) {
binding.value(event) // Call the method provided in the directive's value
}
}
document.addEventListener('click', el.clickOutsideEvent)
},
unmounted: el => {
document.removeEventListener('click', el.clickOutsideEvent)
}
})
if (document.getElementById('search-vocab')) {
vocabSearch.mount('#search-vocab')
}
}
onTranslationReady(startVocabSearchApp)