xinny/src/app/plugins/custom-emoji.ts
Ajay Bura 0b06bed1db
Refactor state & Custom editor (#1190)
* Fix eslint

* Enable ts strict mode

* install folds, jotai & immer

* Enable immer map/set

* change cross-signing alert anim to 30 iteration

* Add function to access matrix client

* Add new types

* Add disposable util

* Add room utils

* Add mDirect list atom

* Add invite list atom

* add room list atom

* add utils for jotai atoms

* Add room id to parents atom

* Add mute list atom

* Add room to unread atom

* Use hook to bind atoms with sdk

* Add settings atom

* Add settings hook

* Extract set settings hook

* Add Sidebar components

* WIP

* Add bind atoms hook

* Fix init muted room list atom

* add navigation atoms

* Add custom editor

* Fix hotkeys

* Update folds

* Add editor output function

* Add matrix client context

* Add tooltip to editor toolbar items

* WIP - Add editor to room input

* Refocus editor on toolbar item click

* Add Mentions - WIP

* update folds

* update mention focus outline

* rename emoji element type

* Add auto complete menu

* add autocomplete query functions

* add index file for editor

* fix bug in getPrevWord function

* Show room mention autocomplete

* Add async search function

* add use async search hook

* use async search in room mention autocomplete

* remove folds prefer font for now

* allow number array in async search

* reset search with empty query

* Autocomplete unknown room mention

* Autocomplete first room mention on tab

* fix roomAliasFromQueryText

* change mention color to primary

* add isAlive hook

* add getMxIdLocalPart to mx utils

* fix getRoomAvatarUrl size

* fix types

* add room members hook

* fix bug in room mention

* add user mention autocomplete

* Fix async search giving prev result after no match

* update folds

* add twemoji font

* add use state provider hook

* add prevent scroll with arrow key util

* add ts to custom-emoji and emoji files

* add types

* add hook for emoji group labels

* add hook for emoji group icons

* add emoji board with basic emoji

* add emojiboard in room input

* select multiple emoji with shift press

* display custom emoji in emojiboard

* Add emoji preview

* focus element on hover

* update folds

* position emojiboard properly

* convert recent-emoji.js to ts

* add use recent emoji hook

* add io.element.recent_emoji to account data evt

* Render recent emoji in emoji board

* show custom emoji from parent spaces

* show room emoji

* improve emoji sidebar

* update folds

* fix pack avatar and name fallback in emoji board

* add stickers to emoji board

* fix bug in emoji preview

* Add sticker icon in room input

* add debounce hook

* add search in emoji board

* Optimize emoji board

* fix emoji board sidebar divider

* sync emojiboard sidebar with scroll & update ui

* Add use throttle hook

* support custom emoji in editor

* remove duplicate emoji selection function

* fix emoji and mention spacing

* add emoticon autocomplete in editor

* fix string

* makes emoji size relative to font size in editor

* add option to render link element

* add spoiler in editor

* fix sticker in emoji board search using wrong type

* render custom placeholder

* update hotkey for block quote and block code

* add terminate search function in async search

* add getImageInfo to matrix utils

* send stickers

* add resize observer hook

* move emoji board component hooks in hooks dir

* prevent editor expand hides room timeline

* send typing notifications

* improve emoji style and performance

* fix imports

* add on paste param to editor

* add selectFile utils

* add file picker hook

* add file paste handler hook

* add file drop handler

* update folds

* Add file upload card

* add bytes to size util

* add blurHash util

* add await to js lib

* add browser-encrypt-attachment types

* add list atom

* convert mimetype file to ts

* add matrix types

* add matrix file util

* add file related dom utils

* add common utils

* add upload atom

* add room input draft atom

* add upload card renderer component

* add upload board component

* add support for file upload in editor

* send files with message / enter

* fix circular deps

* store editor toolbar state in local store

* move msg content util to separate file

* store msg draft on room switch

* fix following member not updating on msg sent

* add theme for folds component

* fix system default theme

* Add reply support in editor

* prevent initMatrix to init multiple time

* add state event hooks

* add async callback hook

* Show tombstone info for tombstone room

* fix room tombstone component border

* add power level hook

* Add room input placeholder component

* Show input placeholder for muted member
2023-06-12 16:45:23 +05:30

294 lines
7.6 KiB
TypeScript

import { IImageInfo, MatrixClient, Room } from 'matrix-js-sdk';
import { AccountDataEvent } from '../../types/matrix/accountData';
import { getAccountData, getStateEvents } from '../utils/room';
import { StateEvent } from '../../types/matrix/room';
// https://github.com/Sorunome/matrix-doc/blob/soru/emotes/proposals/2545-emotes.md
export type PackEventIdToUnknown = Record<string, unknown>;
export type EmoteRoomIdToPackEvents = Record<string, PackEventIdToUnknown>;
export type EmoteRoomsContent = {
rooms?: EmoteRoomIdToPackEvents;
};
export enum PackUsage {
Emoticon = 'emoticon',
Sticker = 'sticker',
}
export type PackImage = {
url: string;
body?: string;
usage?: PackUsage[];
info?: IImageInfo;
};
export type PackImages = Record<string, PackImage>;
export type PackMeta = {
display_name?: string;
avatar_url?: string;
attribution?: string;
usage?: PackUsage[];
};
export type ExtendedPackImage = PackImage & {
shortcode: string;
};
export type PackContent = {
pack?: PackMeta;
images?: PackImages;
};
export class ImagePack {
public id: string;
public content: PackContent;
public displayName?: string;
public avatarUrl?: string;
public usage?: PackUsage[];
public attribution?: string;
public images: Map<string, ExtendedPackImage>;
public emoticons: ExtendedPackImage[];
public stickers: ExtendedPackImage[];
static parsePack(eventId: string, packContent: PackContent) {
if (!eventId || typeof packContent?.images !== 'object') {
return undefined;
}
return new ImagePack(eventId, packContent);
}
constructor(eventId: string, content: PackContent) {
this.id = eventId;
this.content = JSON.parse(JSON.stringify(content));
this.images = new Map();
this.emoticons = [];
this.stickers = [];
this.applyPackMeta(content);
this.applyImages(content);
}
applyPackMeta(content: PackContent) {
const pack = content.pack ?? {};
this.displayName = pack.display_name;
this.avatarUrl = pack.avatar_url;
this.usage = pack.usage ?? [PackUsage.Emoticon, PackUsage.Sticker];
this.attribution = pack.attribution;
}
applyImages(content: PackContent) {
this.images = new Map();
this.emoticons = [];
this.stickers = [];
if (!content.images) return;
Object.entries(content.images).forEach(([shortcode, data]) => {
const { url } = data;
const body = data.body ?? shortcode;
const usage = data.usage ?? this.usage;
const { info } = data;
if (!url) return;
const image: ExtendedPackImage = {
shortcode,
url,
body,
usage,
info,
};
this.images.set(shortcode, image);
if (usage && usage.includes(PackUsage.Emoticon)) {
this.emoticons.push(image);
}
if (usage && usage.includes(PackUsage.Sticker)) {
this.stickers.push(image);
}
});
}
getImages() {
return this.images;
}
getEmojis() {
return this.emoticons;
}
getStickers() {
return this.stickers;
}
getImagesFor(usage: PackUsage) {
if (usage === PackUsage.Emoticon) return this.getEmojis();
if (usage === PackUsage.Sticker) return this.getStickers();
return this.getEmojis();
}
getContent() {
return this.content;
}
getPackAvatarUrl(usage: PackUsage): string | undefined {
return this.avatarUrl || this.getImagesFor(usage)[0].url;
}
private updatePackProperty<K extends keyof PackMeta>(property: K, value: PackMeta[K]) {
if (this.content.pack === undefined) {
this.content.pack = {};
}
this.content.pack[property] = value;
this.applyPackMeta(this.content);
}
setAvatarUrl(avatarUrl?: string) {
this.updatePackProperty('avatar_url', avatarUrl);
}
setDisplayName(displayName?: string) {
this.updatePackProperty('display_name', displayName);
}
setAttribution(attribution?: string) {
this.updatePackProperty('attribution', attribution);
}
setUsage(usage?: PackUsage[]) {
this.updatePackProperty('usage', usage);
}
addImage(key: string, imgContent: PackImage) {
this.content.images = {
[key]: imgContent,
...this.content.images,
};
this.applyImages(this.content);
}
removeImage(key: string) {
if (!this.content.images) return;
if (this.content.images[key] === undefined) return;
delete this.content.images[key];
this.applyImages(this.content);
}
updateImageKey(key: string, newKey: string) {
const { images } = this.content;
if (!images) return;
if (images[key] === undefined) return;
const copyImages: PackImages = {};
Object.keys(images).forEach((imgKey) => {
copyImages[imgKey === key ? newKey : imgKey] = images[imgKey];
});
this.content.images = copyImages;
this.applyImages(this.content);
}
private updateImageProperty<K extends keyof PackImage>(
key: string,
property: K,
value: PackImage[K]
) {
if (!this.content.images) return;
if (this.content.images[key] === undefined) return;
this.content.images[key][property] = value;
this.applyImages(this.content);
}
setImageUrl(key: string, url: string) {
this.updateImageProperty(key, 'url', url);
}
setImageBody(key: string, body?: string) {
this.updateImageProperty(key, 'body', body);
}
setImageInfo(key: string, info?: IImageInfo) {
this.updateImageProperty(key, 'info', info);
}
setImageUsage(key: string, usage?: PackUsage[]) {
this.updateImageProperty(key, 'usage', usage);
}
}
export function getRoomImagePacks(room: Room): ImagePack[] {
const dataEvents = getStateEvents(room, StateEvent.PoniesRoomEmotes);
return dataEvents.reduce<ImagePack[]>((roomPacks, packEvent) => {
const packId = packEvent?.getId();
const content = packEvent?.getContent() as PackContent | undefined;
if (!packId || !content) return roomPacks;
const pack = ImagePack.parsePack(packId, content);
if (pack) {
roomPacks.push(pack);
}
return roomPacks;
}, []);
}
export function getGlobalImagePacks(mx: MatrixClient): ImagePack[] {
const emoteRoomsContent = getAccountData(mx, AccountDataEvent.PoniesEmoteRooms)?.getContent() as
| EmoteRoomsContent
| undefined;
if (typeof emoteRoomsContent !== 'object') return [];
const { rooms } = emoteRoomsContent;
if (typeof rooms !== 'object') return [];
const roomIds = Object.keys(rooms);
const packs = roomIds.flatMap((roomId) => {
if (typeof rooms[roomId] !== 'object') return [];
const room = mx.getRoom(roomId);
if (!room) return [];
return getRoomImagePacks(room);
});
return packs;
}
export function getUserImagePack(mx: MatrixClient): ImagePack | undefined {
const userPackContent = getAccountData(mx, AccountDataEvent.PoniesUserEmotes)?.getContent() as
| PackContent
| undefined;
const userId = mx.getUserId();
if (!userPackContent || !userId) {
return undefined;
}
const userImagePack = ImagePack.parsePack(userId, userPackContent);
return userImagePack;
}
/**
* @param {MatrixClient} mx Provide if you want to include user personal/global pack
* @param {Room[]} rooms Provide rooms if you want to include rooms pack
* @returns {ImagePack[]} packs
*/
export function getRelevantPacks(mx?: MatrixClient, rooms?: Room[]): ImagePack[] {
const userPack = mx && getUserImagePack(mx);
const userPacks = userPack ? [userPack] : [];
const globalPacks = mx ? getGlobalImagePacks(mx) : [];
const globalPackIds = new Set(globalPacks.map((pack) => pack.id));
const roomsPack = rooms?.flatMap(getRoomImagePacks) ?? [];
return userPacks.concat(
globalPacks,
roomsPack.filter((pack) => !globalPackIds.has(pack.id))
);
}