Skip to content

Commit

Permalink
refactor matrix event renderer hook
Browse files Browse the repository at this point in the history
  • Loading branch information
ajbura committed Mar 21, 2024
1 parent 84f2b2c commit fd638f9
Show file tree
Hide file tree
Showing 3 changed files with 443 additions and 468 deletions.
58 changes: 8 additions & 50 deletions src/app/hooks/useMatrixEventRenderer.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,8 @@
import { ReactNode } from 'react';
import { MessageEvent, StateEvent } from '../../types/matrix/room';

export type EventRenderer<T extends unknown[]> = (...args: T) => ReactNode;

export type EventRendererOpts<T extends unknown[]> = {
renderRoomMessage?: EventRenderer<T>;
renderRoomEncrypted?: EventRenderer<T>;
renderSticker?: EventRenderer<T>;
renderRoomMember?: EventRenderer<T>;
renderRoomName?: EventRenderer<T>;
renderRoomTopic?: EventRenderer<T>;
renderRoomAvatar?: EventRenderer<T>;
renderStateEvent?: EventRenderer<T>;
renderEvent?: EventRenderer<T>;
};
export type EventRendererOpts<T extends unknown[]> = Record<string, EventRenderer<T>>;

export type RenderMatrixEvent<T extends unknown[]> = (
eventType: string,
Expand All @@ -22,45 +11,14 @@ export type RenderMatrixEvent<T extends unknown[]> = (
) => ReactNode;

export const useMatrixEventRenderer =
<T extends unknown[]>({
renderRoomMessage,
renderRoomEncrypted,
renderSticker,
renderRoomMember,
renderRoomName,
renderRoomTopic,
renderRoomAvatar,
renderStateEvent,
renderEvent,
}: EventRendererOpts<T>): RenderMatrixEvent<T> =>
<T extends unknown[]>(
typeToRenderer: EventRendererOpts<T>,
renderStateEvent?: EventRenderer<T>,
renderEvent?: EventRenderer<T>
): RenderMatrixEvent<T> =>
(eventType, isStateEvent, ...args) => {
if (eventType === MessageEvent.RoomMessage && renderRoomMessage) {
return renderRoomMessage(...args);
}

if (eventType === MessageEvent.RoomMessageEncrypted && renderRoomEncrypted) {
return renderRoomEncrypted(...args);
}

if (eventType === MessageEvent.Sticker && renderSticker) {
return renderSticker(...args);
}

if (eventType === StateEvent.RoomMember && renderRoomMember) {
return renderRoomMember(...args);
}

if (eventType === StateEvent.RoomName && renderRoomName) {
return renderRoomName(...args);
}

if (eventType === StateEvent.RoomTopic && renderRoomTopic) {
return renderRoomTopic(...args);
}

if (eventType === StateEvent.RoomAvatar && renderRoomAvatar) {
return renderRoomAvatar(...args);
}
const renderer = typeToRenderer[eventType];
if (typeToRenderer[eventType]) return renderer(...args);

if (isStateEvent && renderStateEvent) {
return renderStateEvent(...args);
Expand Down
Loading

0 comments on commit fd638f9

Please sign in to comment.