Files
Atay-Makhzan/web_src/js/features/comp/SearchUserBox.ts
T

49 lines
1.6 KiB
TypeScript
Raw Normal View History

import $ from 'jquery';
2021-10-17 01:28:04 +08:00
import {htmlEscape} from 'escape-goat';
const {appSubUrl} = window.config;
2022-10-19 14:40:28 +02:00
const looksLikeEmailAddressCheck = /^\S+@\S+$/;
export function initCompSearchUserBox() {
const searchUserBox = document.querySelector('#search-user-box');
if (!searchUserBox) return;
const allowEmailInput = searchUserBox.getAttribute('data-allow-email') === 'true';
const allowEmailDescription = searchUserBox.getAttribute('data-allow-email-description') ?? undefined;
$(searchUserBox).search({
2021-10-17 01:28:04 +08:00
minCharacters: 2,
apiSettings: {
url: `${appSubUrl}/user/search_candidates?q={query}`,
2021-10-17 01:28:04 +08:00
onResponse(response) {
const resultItems = [];
const searchQuery = searchUserBox.querySelector('input').value;
2022-10-19 14:40:28 +02:00
const searchQueryUppercase = searchQuery.toUpperCase();
for (const item of response.data) {
2021-10-17 01:28:04 +08:00
const resultItem = {
2024-02-01 18:10:16 +01:00
title: item.login,
image: item.avatar_url,
description: htmlEscape(item.full_name),
2021-10-17 01:28:04 +08:00
};
if (searchQueryUppercase === item.login.toUpperCase()) {
resultItems.unshift(resultItem); // add the exact match to the top
2021-10-17 01:28:04 +08:00
} else {
resultItems.push(resultItem);
2021-10-17 01:28:04 +08:00
}
}
2021-10-17 01:28:04 +08:00
if (allowEmailInput && !resultItems.length && looksLikeEmailAddressCheck.test(searchQuery)) {
2022-10-19 14:40:28 +02:00
const resultItem = {
title: searchQuery,
description: allowEmailDescription,
2022-10-19 14:40:28 +02:00
};
resultItems.push(resultItem);
2022-10-19 14:40:28 +02:00
}
return {results: resultItems};
},
2021-10-17 01:28:04 +08:00
},
searchFields: ['login', 'full_name'],
showNoResults: false,
2021-10-17 01:28:04 +08:00
});
}