Skip to content

Open-source and local-first Slack and Notion alternative that puts you in control of your data

Implement message reactions

Hakan Shehu702f5dce4577
diff --git a/desktop/src/components/messages/message-editor.tsx b/desktop/src/components/messages/message-editor.tsx
index aa27f4a7..c81d6bc7 100644
--- a/desktop/src/components/messages/message-editor.tsx
+++ b/desktop/src/components/messages/message-editor.tsx
@@ -3,7 +3,6 @@ import type { JSONContent } from '@tiptap/core';
import { EditorContent, useEditor } from '@tiptap/react';
import isHotkey from 'is-hotkey';
import { MessageGifPicker } from '@/components/messages/message-gif-picker';
-import { MessageReactionPicker } from '@/components/messages/message-reaction-picker';
import {
DropdownMenu,
DropdownMenuContent,
@@ -143,13 +142,13 @@ export const MessageEditor = (props: MessageEditorProps) => {
/>
</div>
<div className="flex flex-row gap-2">
- <MessageReactionPicker
+ {/* <MessageReactionPicker
size={20}
className="cursor-pointer"
onEmojiSelect={(emoji) => {
console.log(emoji);
}}
- />
+ /> */}
<MessageGifPicker />
<span className="h-5 border-l-2 border-l-gray-300" />
{props.loading ? (
diff --git a/desktop/src/components/messages/message-reaction-picker.tsx b/desktop/src/components/messages/message-reaction-create-popover.tsx
similarity index 58%
rename from desktop/src/components/messages/message-reaction-picker.tsx
rename to desktop/src/components/messages/message-reaction-create-popover.tsx
index 0b32fae1..22250444 100644
--- a/desktop/src/components/messages/message-reaction-picker.tsx
+++ b/desktop/src/components/messages/message-reaction-create-popover.tsx
@@ -1,5 +1,4 @@
import React from 'react';
-
import { Icon } from '@/components/ui/icon';
import {
Popover,
@@ -9,24 +8,26 @@ import {
import { EmojiPicker } from '@/components/emojis/emoji-picker';
interface MessageReactionProps {
- onEmojiSelect: (emoji: string) => void;
- size?: string | number;
- className?: string;
+ onReactionClick: (reaction: string) => void;
}
-export const MessageReactionPicker = ({
- size,
- className,
+export const MessageReactionCreatePopover = ({
+ onReactionClick,
}: MessageReactionProps) => {
const [open, setOpen] = React.useState(false);
return (
- <Popover onOpenChange={setOpen} open={open} modal={true}>
+ <Popover open={open} onOpenChange={setOpen} modal={true}>
<PopoverTrigger asChild>
- <Icon name="emoji-sticker-line" size={size} className={className} />
+ <Icon name="emoji-sticker-line" />
</PopoverTrigger>
<PopoverContent className="w-max p-0" align="end">
- <EmojiPicker onEmojiClick={console.log} />
+ <EmojiPicker
+ onEmojiClick={(emoji) => {
+ onReactionClick(emoji.id);
+ setOpen(false);
+ }}
+ />
</PopoverContent>
</Popover>
);
diff --git a/desktop/src/components/messages/message-reactions.tsx b/desktop/src/components/messages/message-reactions.tsx
index 0aa6f0ae..611a1d66 100644
--- a/desktop/src/components/messages/message-reactions.tsx
+++ b/desktop/src/components/messages/message-reactions.tsx
@@ -1,8 +1,10 @@
import React from 'react';
-import { LocalNode } from '@/types/nodes';
+import { MessageNode } from '@/types/messages';
+import { EmojiElement } from '@/components/emojis/emoji-element';
+import { cn } from '@/lib/utils';
interface MessageReactionsProps {
- message: LocalNode;
+ message: MessageNode;
onReactionClick: (reaction: string) => void;
}
@@ -10,12 +12,30 @@ export const MessageReactions = ({
message,
onReactionClick,
}: MessageReactionsProps) => {
- const [openDialog, setOpenDialog] = React.useState(false);
+ if (message.reactionCounts.length === 0) {
+ return null;
+ }
+
return (
- <React.Fragment>
- <div className="my-1 flex flex-row gap-2">
- <p>Message reactions here.</p>
- </div>
- </React.Fragment>
+ <div className="my-1 flex flex-row gap-2">
+ {message.reactionCounts.map((reaction) => {
+ const hasReacted = message.userReactions.includes(reaction.reaction);
+
+ return (
+ <div
+ key={reaction.reaction}
+ className={cn(
+ 'rouded flex flex-row items-center gap-2 px-1 py-0.5 shadow',
+ 'cursor-pointer text-sm text-muted-foreground hover:text-foreground',
+ hasReacted ? 'bg-blue-100' : 'bg-gray-50',
+ )}
+ onClick={() => onReactionClick(reaction.reaction)}
+ >
+ <EmojiElement id={reaction.reaction} className="h-5 w-5" />
+ <span>{reaction.count}</span>
+ </div>
+ );
+ })}
+ </div>
);
};
diff --git a/desktop/src/components/messages/message.tsx b/desktop/src/components/messages/message.tsx
index 2d4fe2a6..59ecf4c1 100644
--- a/desktop/src/components/messages/message.tsx
+++ b/desktop/src/components/messages/message.tsx
@@ -7,51 +7,63 @@ import {
} from '@/components/ui/tooltip';
import { formatDate, timeAgo } from '@/lib/utils';
import { InView } from 'react-intersection-observer';
-import { MessageReactionPicker } from '@/components/messages/message-reaction-picker';
+import { MessageReactionCreatePopover } from '@/components/messages/message-reaction-create-popover';
import { Icon } from '@/components/ui/icon';
import { MessageDeleteButton } from '@/components/messages/message-delete-button';
import { NodeRenderer } from '@/editor/renderers/node';
import { MessageNode } from '@/types/messages';
+import { MessageReactions } from '@/components/messages/message-reactions';
+import { useReactionCreateMutation } from '@/mutations/use-reaction-create-mutation';
+import { useReactionDeleteMutation } from '@/mutations/use-reaction-delete-mutation';
interface MessageProps {
message: MessageNode;
previousMessage?: MessageNode;
}
-export const Message = ({ message, previousMessage }: MessageProps) => {
- const shouldDisplayUserInfo = () => {
- if (!previousMessage) {
- return true;
- }
+const shouldDisplayUserInfo = (
+ message: MessageNode,
+ previousMessage?: MessageNode,
+) => {
+ if (!previousMessage) {
+ return true;
+ }
- const previousMessageDate = new Date(previousMessage.createdAt);
- const currentMessageDate = new Date(message.createdAt);
+ const previousMessageDate = new Date(previousMessage.createdAt);
+ const currentMessageDate = new Date(message.createdAt);
- if (previousMessageDate.getDate() !== currentMessageDate.getDate()) {
- return true;
- }
+ if (previousMessageDate.getDate() !== currentMessageDate.getDate()) {
+ return true;
+ }
- return !previousMessage || previousMessage.author.id !== message.author.id;
- };
+ return previousMessage.author.id !== message.author.id;
+};
- const canEdit = true;
- const canDelete = true;
- const canReplyInThread = false;
+export const Message = ({ message, previousMessage }: MessageProps) => {
+ const { mutate: createReaction, isPending: isCreatingReaction } =
+ useReactionCreateMutation();
+ const { mutate: deleteReaction, isPending: isDeletingReaction } =
+ useReactionDeleteMutation();
if (!message.content || message.content.length === 0) {
return null;
}
+ const canEdit = true;
+ const canDelete = true;
+ const canReplyInThread = false;
+ const displayUserInfo = shouldDisplayUserInfo(message, previousMessage);
+
return (
<div
id={`message-${message.id}`}
key={`message-${message.id}`}
className={`group flex flex-row px-1 hover:bg-gray-50 ${
- shouldDisplayUserInfo() ? 'mt-2 first:mt-0' : ''
+ displayUserInfo ? 'mt-2 first:mt-0' : ''
}`}
>
<div className="mr-2 w-10 pt-1">
- {shouldDisplayUserInfo() && (
+ {displayUserInfo && (
<Avatar
id={message.author.id}
name={message.author.name}
@@ -61,7 +73,7 @@ export const Message = ({ message, previousMessage }: MessageProps) => {
</div>
<div className="relative w-full">
- {shouldDisplayUserInfo() && (
+ {displayUserInfo && (
<p className="font-medium">
{message.author.name}
<Tooltip>
@@ -87,28 +99,22 @@ export const Message = ({ message, previousMessage }: MessageProps) => {
>
<ul className="invisible absolute -top-2 right-1 z-10 flex flex-row bg-gray-100 text-muted-foreground shadow group-hover:visible">
{canReplyInThread && (
- <li
- className="flex h-8 w-7 cursor-pointer items-center justify-center hover:bg-gray-200"
- onClick={() => {
- // workspace.openPanel(data.id);
- }}
- >
+ <li className="flex h-8 w-7 cursor-pointer items-center justify-center hover:bg-gray-200">
<Icon name="question-answer-line" className="cursor-pointer" />
</li>
)}
<li className="flex h-8 w-7 cursor-pointer items-center justify-center hover:bg-gray-200">
- <MessageReactionPicker
- onEmojiSelect={(emoji) => {
- console.log(emoji);
+ <MessageReactionCreatePopover
+ onReactionClick={(reaction) => {
+ if (isCreatingReaction || isDeletingReaction) {
+ return;
+ }
+
+ createReaction({ nodeId: message.id, reaction });
}}
/>
</li>
- <li
- className="flex h-8 w-7 cursor-pointer items-center justify-center hover:bg-gray-200"
- onClick={() => {
- // onReply?.(data.id, data.createdBy);
- }}
- >
+ <li className="flex h-8 w-7 cursor-pointer items-center justify-center hover:bg-gray-200">
<Icon name="reply-line" className="cursor-pointer" />
</li>
{canDelete && (
@@ -117,22 +123,27 @@ export const Message = ({ message, previousMessage }: MessageProps) => {
</li>
)}
</ul>
- {/*{data.messageReference && <MessageReference />}*/}
<div className="text-foreground">
{message.content.map((node) => (
<NodeRenderer key={node.id} node={node} keyPrefix={node.id} />
))}
</div>
- {/*<MessageReactions*/}
- {/* message={message}*/}
- {/* onReactionClick={handleEmojiSelect}*/}
- {/*/>*/}
- {/*{canReplyInThread && (*/}
- {/* <MessageThread*/}
- {/* message={data}*/}
- {/* onClick={() => workspace.openPanel(data.id)}*/}
- {/* />*/}
- {/*)}*/}
+ {message.reactionCounts.length > 0 && (
+ <MessageReactions
+ message={message}
+ onReactionClick={(reaction) => {
+ if (isCreatingReaction || isDeletingReaction) {
+ return;
+ }
+
+ if (message.userReactions.includes(reaction)) {
+ deleteReaction({ nodeId: message.id, reaction });
+ } else {
+ createReaction({ nodeId: message.id, reaction });
+ }
+ }}
+ />
+ )}
</InView>
</div>
</div>
diff --git a/desktop/src/data/migrations/workspace.ts b/desktop/src/data/migrations/workspace.ts
index f60a02ec..643b0bb8 100644
--- a/desktop/src/data/migrations/workspace.ts
+++ b/desktop/src/data/migrations/workspace.ts
@@ -71,6 +71,31 @@ const createNodeAttributesTable: Migration = {
},
};
+const createNodeReactionsTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('node_reactions')
+ .addColumn('node_id', 'text', (col) =>
+ col.references('nodes.id').onDelete('cascade'),
+ )
+ .addColumn('reactor_id', 'text', (col) =>
+ col.references('nodes.id').onDelete('cascade'),
+ )
+ .addColumn('reaction', 'text', (col) => col.notNull())
+ .addColumn('created_at', 'text', (col) => col.notNull())
+ .addColumn('server_created_at', 'text')
+ .addPrimaryKeyConstraint('node_reactions_pkey', [
+ 'node_id',
+ 'reactor_id',
+ 'reaction',
+ ])
+ .execute();
+ },
+ down: async (db) => {
+ await db.schema.dropTable('node_reactions').execute();
+ },
+};
+
const createMutationsTable: Migration = {
up: async (db) => {
await db.schema
@@ -340,6 +365,63 @@ const createNodeAttributesDeleteTrigger: Migration = {
},
};
+const createNodeReactionsInsertTrigger: Migration = {
+ up: async (db) => {
+ await sql`
+ CREATE TRIGGER after_insert_node_reactions
+ AFTER INSERT ON node_reactions
+ FOR EACH ROW
+ WHEN NEW.server_created_at IS NULL
+ BEGIN
+ INSERT INTO mutations ('action', 'table', 'after', 'created_at')
+ VALUES (
+ 'insert',
+ 'node_reactions',
+ json_object(
+ 'node_id', NEW.'node_id',
+ 'reactor_id', NEW.'reactor_id',
+ 'reaction', NEW.'reaction',
+ 'created_at', NEW.'created_at',
+ 'server_created_at', NEW.'server_created_at'
+ ),
+ datetime('now')
+ );
+ END;
+ `.execute(db);
+ },
+ down: async (db) => {
+ await sql`DROP TRIGGER after_insert_node_reactions`.execute(db);
+ },
+};
+
+const createNodeReactionsDeleteTrigger: Migration = {
+ up: async (db) => {
+ await sql`
+ CREATE TRIGGER after_delete_node_reactions
+ AFTER DELETE ON node_reactions
+ FOR EACH ROW
+ BEGIN
+ INSERT INTO mutations ('action', 'table', 'before', 'created_at')
+ VALUES (
+ 'delete',
+ 'node_reactions',
+ json_object(
+ 'node_id', OLD.'node_id',
+ 'reactor_id', OLD.'reactor_id',
+ 'reaction', OLD.'reaction',
+ 'created_at', OLD.'created_at',
+ 'server_created_at', OLD.'server_created_at'
+ ),
+ datetime('now')
+ );
+ END;
+ `.execute(db);
+ },
+ down: async (db) => {
+ await sql`DROP TRIGGER after_delete_node_reactions`.execute(db);
+ },
+};
+
export const workspaceDatabaseMigrations: Record<string, Migration> = {
'00001_create_nodes_table': createNodesTable,
'00002_create_nodes_parent_id_and_type_index':
@@ -355,4 +437,9 @@ export const workspaceDatabaseMigrations: Record<string, Migration> = {
createNodeAttributesUpdateTrigger,
'00010_create_node_attributes_delete_trigger':
createNodeAttributesDeleteTrigger,
+ '00011_create_node_reactions_table': createNodeReactionsTable,
+ '00012_create_node_reactions_insert_trigger':
+ createNodeReactionsInsertTrigger,
+ '00013_create_node_reactions_delete_trigger':
+ createNodeReactionsDeleteTrigger,
};
diff --git a/desktop/src/data/schemas/workspace.ts b/desktop/src/data/schemas/workspace.ts
index c9f35959..eba3fab5 100644
--- a/desktop/src/data/schemas/workspace.ts
+++ b/desktop/src/data/schemas/workspace.ts
@@ -44,6 +44,18 @@ export type SelectNodeAttribute = Selectable<NodeAttributeTable>;
export type CreateNodeAttribute = Insertable<NodeAttributeTable>;
export type UpdateNodeAttribute = Updateable<NodeAttributeTable>;
+interface NodeReactionTable {
+ node_id: ColumnType<string, string, never>;
+ reactor_id: ColumnType<string, string, never>;
+ reaction: ColumnType<string, string, never>;
+ created_at: ColumnType<string, string, never>;
+ server_created_at: ColumnType<string | null, string | null, string | null>;
+}
+
+export type SelectNodeReaction = Selectable<NodeReactionTable>;
+export type CreateNodeReaction = Insertable<NodeReactionTable>;
+export type UpdateNodeReaction = Updateable<NodeReactionTable>;
+
interface MutationTable {
id: ColumnType<number, never, never>;
table: ColumnType<string, string, never>;
@@ -61,4 +73,5 @@ export interface WorkspaceDatabaseSchema {
nodes: NodeTable;
node_attributes: NodeAttributeTable;
mutations: MutationTable;
+ node_reactions: NodeReactionTable;
}
diff --git a/desktop/src/mutations/use-reaction-create-mutation.tsx b/desktop/src/mutations/use-reaction-create-mutation.tsx
new file mode 100644
index 00000000..a43e47d3
--- /dev/null
+++ b/desktop/src/mutations/use-reaction-create-mutation.tsx
@@ -0,0 +1,28 @@
+import { useWorkspace } from '@/contexts/workspace';
+import { useMutation } from '@tanstack/react-query';
+
+interface ReactionCreateInput {
+ nodeId: string;
+ reaction: string;
+}
+
+export const useReactionCreateMutation = () => {
+ const workspace = useWorkspace();
+
+ return useMutation({
+ mutationFn: async (input: ReactionCreateInput) => {
+ const query = workspace.schema
+ .insertInto('node_reactions')
+ .values({
+ node_id: input.nodeId,
+ reactor_id: workspace.userId,
+ reaction: input.reaction,
+ created_at: new Date().toISOString(),
+ })
+ .onConflict((b) => b.doNothing())
+ .compile();
+
+ await workspace.mutate(query);
+ },
+ });
+};
diff --git a/desktop/src/mutations/use-reaction-delete-mutation.tsx b/desktop/src/mutations/use-reaction-delete-mutation.tsx
new file mode 100644
index 00000000..95e1bef0
--- /dev/null
+++ b/desktop/src/mutations/use-reaction-delete-mutation.tsx
@@ -0,0 +1,24 @@
+import { useWorkspace } from '@/contexts/workspace';
+import { useMutation } from '@tanstack/react-query';
+
+interface ReactionDeleteInput {
+ nodeId: string;
+ reaction: string;
+}
+
+export const useReactionDeleteMutation = () => {
+ const workspace = useWorkspace();
+
+ return useMutation({
+ mutationFn: async (input: ReactionDeleteInput) => {
+ const query = workspace.schema
+ .deleteFrom('node_reactions')
+ .where('node_id', '=', input.nodeId)
+ .where('reactor_id', '=', workspace.userId)
+ .where('reaction', '=', input.reaction)
+ .compile();
+
+ await workspace.mutate(query);
+ },
+ });
+};
diff --git a/desktop/src/queries/use-messages-query.tsx b/desktop/src/queries/use-messages-query.tsx
index f267735e..f1e806a9 100644
--- a/desktop/src/queries/use-messages-query.tsx
+++ b/desktop/src/queries/use-messages-query.tsx
@@ -6,18 +6,23 @@ import {
mapNodeWithAttributes,
} from '@/lib/nodes';
import { compareString } from '@/lib/utils';
-import { MessageNode } from '@/types/messages';
+import { MessageNode, MessageReactionCount } from '@/types/messages';
import { User } from '@/types/users';
import { InfiniteData, useInfiniteQuery } from '@tanstack/react-query';
import { QueryResult, sql } from 'kysely';
const MESSAGES_PER_PAGE = 50;
+type MessageRow = SelectNodeWithAttributes & {
+ reaction_counts: string | null;
+ user_reactions: string | null;
+};
+
export const useMessagesQuery = (conversationId: string) => {
const workspace = useWorkspace();
return useInfiniteQuery<
- QueryResult<SelectNodeWithAttributes>,
+ QueryResult<MessageRow>,
Error,
MessageNode[],
string[],
@@ -42,16 +47,16 @@ export const useMessagesQuery = (conversationId: string) => {
},
queryFn: async ({ queryKey, pageParam }) => {
const offset = pageParam * MESSAGES_PER_PAGE;
- const query = sql<SelectNodeWithAttributes>`
- WITH message_nodes AS (
+ const query = sql<MessageRow>`
+ WITH message_nodes AS (
SELECT *
FROM nodes
WHERE parent_id = ${conversationId} AND type = ${NodeTypes.Message}
ORDER BY id DESC
LIMIT ${sql.lit(MESSAGES_PER_PAGE)}
OFFSET ${sql.lit(offset)}
- ),
- descendant_nodes AS (
+ ),
+ descendant_nodes AS (
SELECT *
FROM nodes
WHERE parent_id IN (SELECT id FROM message_nodes)
@@ -59,45 +64,78 @@ export const useMessagesQuery = (conversationId: string) => {
SELECT child.*
FROM nodes child
INNER JOIN descendant_nodes parent ON child.parent_id = parent.id
- ),
- author_nodes AS (
+ ),
+ author_nodes AS (
SELECT *
FROM nodes
WHERE id IN (SELECT DISTINCT created_by FROM message_nodes)
- ),
- all_nodes AS (
+ ),
+ all_nodes AS (
SELECT * FROM message_nodes
UNION ALL
SELECT * FROM descendant_nodes
UNION ALL
SELECT * FROM author_nodes
- )
- SELECT
+ ),
+ node_attributes_aggregated AS (
+ SELECT
+ na.node_id,
+ json_group_array(
+ json_object(
+ 'node_id', na.'node_id',
+ 'type', na.'type',
+ 'key', na.'key',
+ 'text_value', na.'text_value',
+ 'number_value', na.'number_value',
+ 'foreign_node_id', na.'foreign_node_id',
+ 'created_at', na.'created_at',
+ 'updated_at', na.'updated_at',
+ 'created_by', na.'created_by',
+ 'updated_by', na.'updated_by',
+ 'version_id', na.'version_id',
+ 'server_created_at', na.'server_created_at',
+ 'server_updated_at', na.'server_updated_at',
+ 'server_version_id', na.'server_version_id'
+ )
+ ) AS attributes
+ FROM node_attributes na
+ WHERE na.node_id IN (SELECT id FROM all_nodes)
+ GROUP BY na.node_id
+ ),
+ message_reaction_counts AS (
+ SELECT
+ mrc.node_id,
+ json_group_array(
+ json_object(
+ 'reaction', mrc.'reaction',
+ 'count', mrc.'count'
+ )
+ ) AS reaction_counts
+ FROM (
+ SELECT node_id, reaction, COUNT(*) as count
+ FROM node_reactions
+ WHERE node_id IN (SELECT id FROM message_nodes)
+ GROUP BY node_id, reaction
+ ) mrc
+ GROUP BY mrc.node_id
+ ),
+ user_reactions AS (
+ SELECT
+ ur.node_id,
+ json_group_array(ur.reaction) AS user_reactions
+ FROM node_reactions ur
+ WHERE ur.node_id IN (SELECT id FROM message_nodes) AND ur.reactor_id = ${workspace.userId}
+ GROUP BY ur.node_id
+ )
+ SELECT
n.*,
- CASE
- WHEN COUNT(na.node_id) = 0 THEN json('[]')
- ELSE json_group_array(
- json_object(
- 'node_id', na.'node_id',
- 'type', na.'type',
- 'key', na.'key',
- 'text_value', na.'text_value',
- 'number_value', na.'number_value',
- 'foreign_node_id', na.'foreign_node_id',
- 'created_at', na.'created_at',
- 'updated_at', na.'updated_at',
- 'created_by', na.'created_by',
- 'updated_by', na.'updated_by',
- 'version_id', na.'version_id',
- 'server_created_at', na.'server_created_at',
- 'server_updated_at', na.'server_updated_at',
- 'server_version_id', na.'server_version_id'
- )
- )
- END as attributes
- FROM all_nodes n
- LEFT JOIN node_attributes na ON n.id = na.node_id
- GROUP BY n.id;
+ COALESCE(na.attributes, json('[]')) AS attributes,
+ COALESCE(mrc.reaction_counts, json('[]')) AS reaction_counts,
+ COALESCE(ur.user_reactions, json('[]')) AS user_reactions
+ FROM all_nodes n
+ LEFT JOIN node_attributes_aggregated na ON n.id = na.node_id
+ LEFT JOIN message_reaction_counts mrc ON n.id = mrc.node_id
+ LEFT JOIN user_reactions ur ON n.id = ur.node_id;
`.compile(workspace.schema);
return await workspace.queryAndSubscribe({
@@ -106,9 +144,7 @@ export const useMessagesQuery = (conversationId: string) => {
query,
});
},
- select: (
- data: InfiniteData<QueryResult<SelectNodeWithAttributes>>,
- ): MessageNode[] => {
+ select: (data: InfiniteData<QueryResult<MessageRow>>): MessageNode[] => {
const pages = data?.pages ?? [];
const rows = pages.map((page) => page.rows).flat();
return buildMessages(rows);
@@ -116,45 +152,57 @@ export const useMessagesQuery = (conversationId: string) => {
});
};
-const buildMessages = (rows: SelectNodeWithAttributes[]): MessageNode[] => {
- const nodes = rows.map(mapNodeWithAttributes);
- const messageNodes = nodes.filter((node) => node.type === NodeTypes.Message);
+const buildMessages = (rows: MessageRow[]): MessageNode[] => {
+ const messageRows = rows.filter((row) => row.type === NodeTypes.Message);
+ const authorRows = rows.filter((row) => row.type === NodeTypes.User);
+ const contentNodes = rows
+ .filter(
+ (row) => row.type !== NodeTypes.User && row.type !== NodeTypes.Message,
+ )
+ .map(mapNodeWithAttributes);
- const authorNodes = nodes.filter((node) => node.type === NodeTypes.User);
const messages: MessageNode[] = [];
const authorMap = new Map<string, User>();
-
- for (const author of authorNodes) {
- const name = author.attributes.find(
+ for (const authorRow of authorRows) {
+ const authorNode = mapNodeWithAttributes(authorRow);
+ const name = authorNode.attributes.find(
(attr) => attr.type === AttributeTypes.Name,
)?.textValue;
- const avatar = author.attributes.find(
+ const avatar = authorNode.attributes.find(
(attr) => attr.type === AttributeTypes.Avatar,
)?.textValue;
- authorMap.set(author.id, {
- id: author.id,
+ authorMap.set(authorRow.id, {
+ id: authorRow.id,
name: name ?? 'Unknown User',
avatar,
});
}
- for (const node of messageNodes) {
- const author = authorMap.get(node.createdBy);
- const children = nodes
- .filter((n) => n.parentId === node.id)
- .map((n) => buildNodeWithAttributesAndChildren(n, nodes));
+ for (const messageRow of messageRows) {
+ const messageNode = mapNodeWithAttributes(messageRow);
+ const author = authorMap.get(messageNode.createdBy);
+ const children = contentNodes
+ .filter((n) => n.parentId === messageNode.id)
+ .map((n) => buildNodeWithAttributesAndChildren(n, contentNodes));
+
+ const reactionCounts: MessageReactionCount[] = JSON.parse(
+ messageRow.reaction_counts,
+ );
+ const userReactions: string[] = JSON.parse(messageRow.user_reactions);
const message: MessageNode = {
- id: node.id,
- createdAt: node.createdAt,
+ id: messageNode.id,
+ createdAt: messageNode.createdAt,
author: author ?? {
- id: node.createdBy,
+ id: messageNode.createdBy,
name: 'Unknown User',
avatar: null,
},
content: children,
+ reactionCounts,
+ userReactions,
};
messages.push(message);
diff --git a/desktop/src/types/messages.ts b/desktop/src/types/messages.ts
index 007a3ed4..64993e3d 100644
--- a/desktop/src/types/messages.ts
+++ b/desktop/src/types/messages.ts
@@ -6,4 +6,11 @@ export type MessageNode = {
content: LocalNodeWithAttributesAndChildren[];
createdAt: string;
author: User;
+ reactionCounts: MessageReactionCount[];
+ userReactions: string[];
+};
+
+export type MessageReactionCount = {
+ reaction: string;
+ count: number;
};