Skip to content

Commit

Permalink
day wise messages added in message list and each quill renderer for e…
Browse files Browse the repository at this point in the history
…ach message
  • Loading branch information
Diivvuu committed Oct 15, 2024
1 parent 68d7eb1 commit d3062a1
Show file tree
Hide file tree
Showing 8 changed files with 217 additions and 4 deletions.
Binary file modified bun.lockb
Binary file not shown.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1",
"convex": "^1.16.0",
"date-fns": "^4.1.0",
"jotai": "^2.10.0",
"lucide-react": "^0.438.0",
"next": "14.2.7",
Expand Down
4 changes: 4 additions & 0 deletions src/app/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -126,3 +126,7 @@
font-weight: 400 !important;
@apply truncate;
}
.messages-scrollbar {
scrollbar-width: thin;
scrollbar-color: #dcdcdc #f8f8f8;
}
15 changes: 11 additions & 4 deletions src/app/workspace/[workspaceId]/channel/[channelId]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,17 @@ import { Loader, TriangleAlert } from "lucide-react";
import { Header } from "./Header";
import { ChatInput } from "./chat-input";
import { useGetMessages } from "@/features/messages/api/use-get-messages";
import { MessageList } from "@/components/message-list";

const ChannelIdPage = () => {
const channelId = useChannelId();

const { results } = useGetMessages({ channelId });
const { results, status, loadMore } = useGetMessages({ channelId });
const { data: channel, isLoading: channelLoading } = useGetChannel({
id: channelId,
});
console.log({ results });
if (channelLoading) {
if (channelLoading || status === "LoadingFirstPage") {
return (
<div className="h-full flex-1 flex items-center justify-center">
<Loader className="animate-spin size-5 text-muted-foreground" />
Expand All @@ -35,8 +36,14 @@ const ChannelIdPage = () => {
return (
<div className="flex flex-col h-full">
<Header title={channel.name} />
<div className="flex-1" />
{JSON.stringify(results)}
<MessageList
channelName={channel.name}
channelCreationTime={channel._creationTime}
data={results}
loadMore={loadMore}
isLoadingMore={status === "LoadingMore"}
canLoadMore={status === "CanLoadMore"}
/>
<ChatInput placeholder={`Message # ${channel.name}`} />
</div>
);
Expand Down
14 changes: 14 additions & 0 deletions src/components/Editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,19 @@ interface EditorProps {
variant?: "create" | "update";
}

const toolbarOptions = [
["bold", "italic", "underline", "strike"], // toggled buttons
["blockquote", "code-block"],
["link", "formula"],

[{ list: "ordered" }, { list: "bullet" }, { list: "check" }],

[{ header: [1, 2, 3, 4, 5, 6, false] }],

[{ color: [] }, { background: [] }], // dropdown with defaults from theme
[{ font: [] }],
];

const Editor = ({
onCancel,
onSubmit,
Expand Down Expand Up @@ -78,6 +91,7 @@ const Editor = ({
placeholder: placeholderRef.current,

modules: {
toolbar: toolbarOptions,
keyboard: {
bindings: {
enter: {
Expand Down
92 changes: 92 additions & 0 deletions src/components/message-list.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { format, isToday, isYesterday } from "date-fns";
import { GetMessageReturnType } from "@/features/messages/api/use-get-messages";
import { Message } from "./message";

interface MessageListProps {
memberName?: string;
memberImage?: string;
channelName?: string;
channelCreationTime?: number;
variant?: "channel" | "thread" | "conversation";
data: GetMessageReturnType | undefined;
loadMore: () => void;
isLoadingMore: boolean;
canLoadMore: boolean;
}

const formatDateLabel = (dateStr: string) => {
console.log(dateStr);

// Replace double hyphens with single hyphen
const correctedDateStr = dateStr.replace(/--/g, "-");
const date = new Date(correctedDateStr);

console.log(date);

if (isToday(date)) return "Today";
if (isYesterday(date)) return "Yesterday";
return format(date, "EEEE, MMMM d");
};

export const MessageList = ({
memberName,
memberImage,
channelName,
channelCreationTime,
data,
variant = "channel",
loadMore,
isLoadingMore,
canLoadMore,
}: MessageListProps) => {
const groupedMessages = data?.reduce(
(groups, message) => {
const date = new Date(message._creationTime);
const dateKey = format(date, "yyyy--MM-dd");
if (!groups[dateKey]) {
groups[dateKey] = [];
}
groups[dateKey].unshift(message);
return groups;
},
{} as Record<string, typeof data>
);
return (
<div className="flex-1 flex flex-col-reverse pb-4 overflow-y-auto messages-scrollbar">
{Object.entries(groupedMessages || {}).map(([dateKey, messages]) => (
<div key={dateKey}>
<div className="text-center my-2 relative">
<hr className="absolute top-1/2 left-0 right-0 border-t border-gray-300" />
<span className="relative inline-block px-4 py-1 rounded-full text-xs broder border-gray-300 shadow-sm">
{formatDateLabel(dateKey)}
</span>
</div>
{messages.map((message, index) => {
return (
<Message
key={message._id}
id={message._id}
memberId={message.memberId}
authorImage={message.user.image}
authorName={message.user.name}
isAuthor={false}
reactions={message.reactions}
body={message.body}
image={message.image}
updatedAt={message.updatedAt}
createdAt={message._creationTime}
isEditing={false}
setEditingId={() => {}}
isCompact={false}
hideThreadButton={false}
threadCount={message.threadCount}
threadImage = {message.threadImage}
threadTimestamp={message.threadTimestamp}
/>
);
})}
</div>
))}
</div>
);
};
53 changes: 53 additions & 0 deletions src/components/message.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { Doc, Id } from "../../convex/_generated/dataModel";
import dynamic from "next/dynamic";

const Renderer = dynamic(() => import("@/components/renderer"), { ssr: false });
interface MessageProps {
id: Id<"messages">;
memberId: Id<"members">;
authorImage?: string;
authorName?: string;
isAuthor?: boolean;
reactions: Array<
Omit<Doc<"reactions">, "memberId"> & {
count: number;
memberIds: Id<"members">[];
}
>;
body: Doc<"messages">["body"];
image: string | null | undefined;
createdAt: Doc<"messages">["_creationTime"];
updatedAt: Doc<"messages">["updatedAt"];
isEditing: boolean;
isCompact?: boolean;
setEditingId: (id: Id<"messages"> | null) => void;
hideThreadButton?: boolean;
threadCount?: number;
threadImage?: string;
threadTimestamp?: number;
}
export const Message = ({
id,
isAuthor,
memberId,
authorImage,
authorName = "Member",
reactions,
body,
image,
createdAt,
updatedAt,
isEditing,
isCompact,
setEditingId,
hideThreadButton,
threadCount,
threadImage,
threadTimestamp,
}: MessageProps) => {
return (
<div className="flex flex-col gap-2 p-1.5 px-5 hover:bg-gray-100">
<Renderer value={body} />
</div>
);
};
42 changes: 42 additions & 0 deletions src/components/renderer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import Quill from "quill";
import { useEffect, useRef, useState } from "react";

interface RendererProps {
value: string;
}

const Renderer = ({ value }: RendererProps) => {
const [isEmpty, setIsEmpty] = useState(false);
const rendererRef = useRef<HTMLDivElement>(null);

useEffect(() => {
if (!rendererRef.current) return;
const container = rendererRef.current;
const quill = new Quill(document.createElement("div"), {
theme: "snow",
});
quill.enable(false);
const contents = JSON.parse(value);
quill.setContents(contents);
const isEmpty =
quill
.getText()
.replace(/,(.|\n)*?>/g, "")
.trim().length === 0;

setIsEmpty(isEmpty);

container.innerHTML = quill.root.innerHTML;

return () => {
if (container) {
container.innerHTML = "";
}
};
}, [value]);

if (isEmpty) return null;
return <div ref={rendererRef} className="ql-editor ql-renderer" />;
};

export default Renderer;

0 comments on commit d3062a1

Please sign in to comment.