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

50 lines
1.8 KiB
TypeScript
Raw Normal View History

2025-07-01 21:44:05 +08:00
import {htmlEscape} from '../../utils/html.ts';
import {fomanticQuery} from '../../modules/fomantic/base.ts';
2021-10-17 01:28:04 +08:00
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;
const includeOrgs = searchUserBox.getAttribute('data-include-orgs') === 'true';
fomanticQuery(searchUserBox).search({
2021-10-17 01:28:04 +08:00
minCharacters: 2,
apiSettings: {
url: `${appSubUrl}/user/search_candidates?q={query}&orgs=${includeOrgs}`,
2025-01-22 08:11:51 +01:00
onResponse(response: any) {
const resultItems = [];
2025-12-03 03:13:16 +01:00
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
});
}