File size: 6,030 Bytes
062a991
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
"use client";

import { useState } from "react";
import { MoreHorizontal, Search, Send } from "lucide-react";
import { Avatar } from "./Avatar";
import { people } from "@/lib/demo-data";

type Message = { mine: boolean; body: string; time: string };
type MessageFilter = "focused" | "unread" | "jobs" | "connections" | "inmail" | "starred";

const messageFilters: Array<{ value: MessageFilter; label: string }> = [
  { value: "focused", label: "Focused" },
  { value: "unread", label: "Unread" },
  { value: "jobs", label: "Jobs" },
  { value: "connections", label: "Connections" },
  { value: "inmail", label: "InMail" },
  { value: "starred", label: "Starred" },
];

const mayaThread: Message[] = [
  { mine: false, body: "Hey Maya, your post about design reviews landed with our team.", time: "9:42 AM" },
  { mine: true, body: "I’m glad it was useful. We changed the format after a lot of trial and error.", time: "9:48 AM" },
  { mine: false, body: "Would you be open to sharing how you structure the pre-read?", time: "9:50 AM" },
];

const initialMessagesByPerson = people.reduce<Record<string, Message[]>>((acc, person, index) => {
  acc[person.id] = index === 0
    ? mayaThread
    : [{ mine: false, body: "Thanks for connecting. Looking forward to staying in touch.", time: "Mon" }];
  return acc;
}, {});

export function MessagingView() {
  const [messagesByPerson, setMessagesByPerson] = useState(initialMessagesByPerson);
  const [draft, setDraft] = useState("");
  const [active, setActive] = useState(people[0]);
  const [searchQuery, setSearchQuery] = useState("");
  const [sending, setSending] = useState(false);
  const [error, setError] = useState("");
  const [activeFilter, setActiveFilter] = useState<MessageFilter>("focused");
  const activeMessages = messagesByPerson[active.id] ?? [];
  const filteredConversations = people.filter((person, index) => {
    const latestMessage = messagesByPerson[person.id]?.at(-1)?.body ?? "";
    const matchesSearch = `${person.name} ${person.headline} ${latestMessage}`.toLowerCase().includes(searchQuery.trim().toLowerCase());
    const matchesFilter = activeFilter === "focused" || activeFilter === "connections"
      || (activeFilter === "unread" && index === 1)
      || (activeFilter === "starred" && index === 0);
    return matchesSearch && matchesFilter;
  });

  async function send() {
    const body = draft.trim();
    if (!body || sending) return;
    setSending(true);
    setError("");
    try {
      const response = await fetch("/api/messages", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ recipientId: active.id, body }) });
      const result = await response.json().catch(() => ({})) as { message?: { id?: string }, error?: string };
      if (!response.ok || !result.message?.id) throw new Error(result.error ?? "Unable to send this message.");
      setMessagesByPerson((items) => ({
        ...items,
        [active.id]: [...(items[active.id] ?? []), { mine: true, body, time: "Now" }],
      }));
      setDraft("");
    } catch (caught) {
      setError(caught instanceof Error ? caught.message : "Unable to send this message.");
    } finally {
      setSending(false);
    }
  }

  return (
    <section className="surface messages-shell">
      <aside className="conversation-list">
        <header><h1>Messaging</h1><button className="icon-button"><MoreHorizontal size={20} /></button></header>
        <label><Search size={17} /><input value={searchQuery} onChange={(event) => setSearchQuery(event.target.value)} placeholder="Search messages" /></label>
        <div className="message-filters" role="tablist" aria-label="Message filters">
          {messageFilters.map((filter) => <button className={activeFilter === filter.value ? "active" : ""} aria-selected={activeFilter === filter.value} key={filter.value} onClick={() => setActiveFilter(filter.value)} role="tab" type="button">{filter.label}</button>)}
        </div>
        {filteredConversations.length ? filteredConversations.map((person) => {
          const preview = messagesByPerson[person.id]?.at(-1)?.body ?? "No messages yet.";
          const time = messagesByPerson[person.id]?.at(-1)?.time ?? "";
          return (
          <button className={`conversation-row ${active.id === person.id ? "active" : ""}`} onClick={() => setActive(person)} key={person.id}>
            <Avatar name={person.name} src={person.avatar} />
            <span><b>{person.name}</b><small>{preview}</small></span><time>{time}</time>
          </button>
          );
        }) : <div className="empty-state"><Search size={30} /><h3>No conversations found</h3><p>Try a name, role, or recent message.</p></div>}
      </aside>
      <div className="conversation-panel">
        <header><div><b>{active.name}</b><span>{active.headline}</span></div><button className="icon-button"><MoreHorizontal size={20} /></button></header>
        <div className="message-history">
          <div className="conversation-intro"><Avatar name={active.name} src={active.avatar} size="lg" /><h2>{active.name}</h2><p>{active.headline}</p></div>
          {activeMessages.map((message, index) => (
            <div className={`message-bubble ${message.mine ? "mine" : ""}`} key={`${message.body}-${index}`}>
              {!message.mine && <Avatar name={active.name} src={active.avatar} size="sm" />}
              <div><p>{message.body}</p><time>{message.time}</time></div>
            </div>
          ))}
        </div>
        {error && <div className="form-error" role="alert">{error}</div>}
        <div className="message-composer"><textarea value={draft} onChange={(event) => setDraft(event.target.value)} onKeyDown={(event) => { if (event.key === "Enter" && !event.shiftKey) { event.preventDefault(); void send(); } }} placeholder="Write a message…" /><button className="button button-primary" disabled={sending} onClick={() => { void send(); }}><Send size={17} /> {sending ? "Sending…" : "Send"}</button></div>
      </div>
    </section>
  );
}