soapbox/app/soapbox/features/emoji/search.ts

55 wiersze
1.2 KiB
TypeScript
Czysty Zwykły widok Historia

2022-07-05 02:08:47 +00:00
import { Index } from 'flexsearch';
import data from './data';
2022-07-05 04:03:09 +00:00
import type { Emoji } from './index';
import type { Emoji as EmojiMart, CustomEmoji } from 'emoji-mart';
2022-07-05 02:08:47 +00:00
const index = new Index({
tokenize: 'forward',
optimize: true,
});
for (const [key, emoji] of Object.entries(data.emojis)) {
index.add(key, emoji.name);
}
2022-07-04 23:07:04 +00:00
2022-07-04 20:30:35 +00:00
export interface searchOptions {
maxResults?: number;
}
2022-07-05 04:03:09 +00:00
export const addCustomToPool = (customEmojis: EmojiMart<CustomEmoji>[]) => {
2022-07-05 02:08:47 +00:00
let i = 0;
2022-07-04 20:30:35 +00:00
2022-07-05 02:08:47 +00:00
for (const emoji of customEmojis) {
index.add(i++, emoji.id);
}
2022-07-04 20:30:35 +00:00
};
2022-07-05 04:03:09 +00:00
const search = (str: string, options: searchOptions, custom_emojis: any): Emoji[] => {
2022-07-05 02:08:47 +00:00
return index.search(str, options.maxResults)
.flatMap(id => {
if (Number.isInteger(id)) {
const { shortcode, static_url } = custom_emojis.get(id).toJS();
2022-07-05 03:11:46 +00:00
2022-07-05 02:08:47 +00:00
return {
id: shortcode,
colons: ':' + shortcode + ':',
custom: true,
imageUrl: static_url,
};
}
2022-07-05 03:11:46 +00:00
const { skins } = data.emojis[id];
2022-07-05 02:08:47 +00:00
return {
2022-07-05 03:11:46 +00:00
id: id as string,
colons: ':' + id + ':',
2022-07-05 02:08:47 +00:00
unified: skins[0].unified,
native: skins[0].native,
};
});
2022-07-04 20:30:35 +00:00
};
export default search;