Files

61 lines
2.1 KiB
TypeScript
Raw Permalink Normal View History

import {emojiKeys, emojiHTML, emojiString} from './emoji.ts';
2025-07-01 21:44:05 +08:00
import {html, htmlRaw} from '../utils/html.ts';
2026-03-07 21:37:37 +01:00
import {fetchMentions} from '../utils/match.ts';
2026-02-02 01:00:34 +08:00
import type {TributeCollection} from 'tributejs';
2026-03-07 21:37:37 +01:00
import type {Mention} from '../types.ts';
2020-05-21 04:00:43 +02:00
2025-01-22 08:11:51 +01:00
export async function attachTribute(element: HTMLElement) {
2026-03-29 12:24:30 +02:00
const {default: Tribute} = await import('tributejs');
2026-03-07 21:37:37 +01:00
const mentionsUrl = element.closest('[data-mentions-url]')?.getAttribute('data-mentions-url');
2025-01-22 08:11:51 +01:00
2026-02-02 01:00:34 +08:00
const emojiCollection: TributeCollection<string> = { // emojis
trigger: ':',
requireLeadingSpace: true,
values: (query: string, cb: (matches: Array<string>) => void) => {
const matches = [];
for (const name of emojiKeys) {
if (name.includes(query)) {
matches.push(name);
if (matches.length > 5) break;
}
2026-02-02 01:00:34 +08:00
}
cb(matches);
},
lookup: (item) => item,
selectTemplate: (item) => {
if (item === undefined) return '';
return emojiString(item.original) ?? '';
},
menuItemTemplate: (item) => {
return html`<div class="tribute-item">${htmlRaw(emojiHTML(item.original))}<span>${item.original}</span></div>`;
},
};
2026-03-07 21:37:37 +01:00
const mentionCollection: TributeCollection<Mention> = {
values: async (_query: string, cb: (matches: Mention[]) => void) => { // eslint-disable-line @typescript-eslint/no-misused-promises
cb(mentionsUrl ? await fetchMentions(mentionsUrl) : []);
},
2026-02-02 01:00:34 +08:00
requireLeadingSpace: true,
menuItemTemplate: (item) => {
const fullNameHtml = item.original.fullname && item.original.fullname !== '' ? html`<span class="fullname">${item.original.fullname}</span>` : '';
return html`
<div class="tribute-item">
<img alt src="${item.original.avatar}" width="21" height="21"/>
<span class="name">${item.original.name}</span>
${htmlRaw(fullNameHtml)}
</div>
`;
2025-01-22 08:11:51 +01:00
},
2026-02-02 01:00:34 +08:00
};
2026-02-02 01:00:34 +08:00
const tribute = new Tribute({
2026-02-10 06:09:56 +01:00
collection: [
emojiCollection as TributeCollection<any>,
mentionCollection as TributeCollection<any>,
],
2026-02-02 01:00:34 +08:00
noMatchTemplate: () => '',
});
tribute.attach(element);
2020-05-21 04:00:43 +02:00
return tribute;
}