File size: 9,444 Bytes
9d4a3b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
"use client";

import { useEffect, useState } from "react";
import { Image as ImageIcon, MessageCircle, Newspaper, Send, ThumbsUp, Video } from "lucide-react";
import { Avatar } from "./Avatar";
import { currentUser, posts as seedPosts } from "@/lib/demo-data";
import { useCurrentUser } from "@/lib/client-session";

type FeedPost = typeof seedPosts[number];

export function FeedComposer({ onPost }: { onPost: (content: string, id: string) => void }) {
  const sessionUser = useCurrentUser();
  const [open, setOpen] = useState(false);
  const [content, setContent] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");

  async function submit() {
    const value = content.trim();
    if (!value || submitting) return;
    setSubmitting(true);
    setError("");

    try {
      const response = await fetch("/api/posts", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ content: value }) });
      const result = await response.json().catch(() => ({})) as { post?: { id?: string }, error?: string };
      if (!response.ok || !result.post?.id) throw new Error(result.error ?? "Unable to publish this post.");
      onPost(value, result.post.id);
      setContent("");
      setOpen(false);
    } catch (caught) {
      setError(caught instanceof Error ? caught.message : "Unable to publish this post.");
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <section className="surface composer">
      <div className="composer-row">
        <Avatar name={sessionUser.name} src={sessionUser.avatarUrl ?? undefined} />
        <button className="composer-trigger" onClick={() => setOpen(true)}>Start a post</button>
      </div>
      {open && (
        <div className="composer-editor">
          <textarea autoFocus value={content} onChange={(event) => setContent(event.target.value)} placeholder="Share an idea with your professional community" />
          {error && <div className="form-error" role="alert">{error}</div>}
          <div><button className="button button-quiet" disabled={submitting} onClick={() => setOpen(false)}>Cancel</button><button className="button button-primary" disabled={submitting} onClick={submit}>{submitting ? "Posting…" : "Post"}</button></div>
        </div>
      )}
      <div className="composer-actions">
        <button><Video size={20} /> Video</button>
        <button><ImageIcon size={20} /> Photo</button>
        <button><Newspaper size={20} /> Write article</button>
      </div>
    </section>
  );
}

function PostCard({ post, following, onFollowingChange }: { post: FeedPost; following: boolean; onFollowingChange: (targetUserId: string, following: boolean) => void }) {
  const sessionUser = useCurrentUser();
  const [liked, setLiked] = useState(post.liked);
  const [commenting, setCommenting] = useState(false);
  const [comments, setComments] = useState<string[]>([]);
  const [draft, setDraft] = useState("");
  const [likePending, setLikePending] = useState(false);
  const [commentSubmitting, setCommentSubmitting] = useState(false);
  const [actionError, setActionError] = useState("");
  const [followPending, setFollowPending] = useState(false);

  async function toggleFollow() {
    if (followPending || post.author.id === sessionUser.id) return;
    setFollowPending(true);
    setActionError("");
    try {
      const response = await fetch("/api/follows", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ targetUserId: post.author.id }) });
      const result = await response.json().catch(() => ({})) as { following?: boolean, error?: string };
      if (!response.ok || typeof result.following !== "boolean") throw new Error(result.error ?? "Unable to update this follow.");
      onFollowingChange(post.author.id, result.following);
    } catch (caught) {
      setActionError(caught instanceof Error ? caught.message : "Unable to update this follow.");
    } finally {
      setFollowPending(false);
    }
  }

  async function toggleLike() {
    if (likePending) return;
    setLikePending(true);
    setActionError("");

    try {
      const response = await fetch("/api/likes", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ postId: post.id }) });
      const result = await response.json().catch(() => ({})) as { liked?: boolean, error?: string };
      if (!response.ok || typeof result.liked !== "boolean") throw new Error(result.error ?? "Unable to update this reaction.");
      setLiked(result.liked);
    } catch (caught) {
      setActionError(caught instanceof Error ? caught.message : "Unable to update this reaction.");
    } finally {
      setLikePending(false);
    }
  }

  async function addComment() {
    const value = draft.trim();
    if (!value || commentSubmitting) return;
    setCommentSubmitting(true);
    setActionError("");

    try {
      const response = await fetch("/api/comments", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ postId: post.id, content: value }) });
      const result = await response.json().catch(() => ({})) as { comment?: { id?: string }, error?: string };
      if (!response.ok || !result.comment?.id) throw new Error(result.error ?? "Unable to post this comment.");
      setComments((items) => [...items, value]);
      setDraft("");
    } catch (caught) {
      setActionError(caught instanceof Error ? caught.message : "Unable to post this comment.");
    } finally {
      setCommentSubmitting(false);
    }
  }

  const likeDelta = liked === post.liked ? 0 : liked ? 1 : -1;
  const likeCount = Math.max(0, post.likes + likeDelta);

  return (
    <article className="surface post-card">
      <header className="post-header">
        <Avatar name={post.author.name} src={post.author.avatar} />
        <div><b>{post.author.name}</b><span>{post.author.headline}</span><span>{post.age} · Network</span></div>
        <div className="post-header-actions">
          {post.author.id !== sessionUser.id && <button className={`follow-button ${following ? "following" : ""}`} disabled={followPending} onClick={toggleFollow}>{followPending ? "Saving…" : following ? "Following" : "+ Follow"}</button>}
          <button className="icon-button" aria-label="Post menu">•••</button>
        </div>
      </header>
      <p className="post-copy">{post.content}</p>
      {"image" in post && post.image && <img className="post-image" src={post.image} alt="Colleagues collaborating in a workshop" />}
      <div className="post-social-counts">
        <span><i>✓</i> {likeCount}</span>
        <button onClick={() => setCommenting(true)}>{post.comments + comments.length} comments</button>
      </div>
      <div className="post-actions">
        <button className={liked ? "liked" : ""} disabled={likePending} onClick={toggleLike}><ThumbsUp size={19} /> {likePending ? "Saving…" : "Like"}</button>
        <button onClick={() => setCommenting(true)}><MessageCircle size={19} /> Comment</button>
        <button><Send size={19} /> Send</button>
      </div>
      {actionError && <div className="form-error" role="alert">{actionError}</div>}
      {commenting && (
        <div className="comment-area">
          {comments.map((comment, index) => (
            <div className="comment" key={`${comment}-${index}`}><Avatar name={sessionUser.name} src={sessionUser.avatarUrl ?? undefined} size="sm" /><p><b>{sessionUser.name}</b>{comment}</p></div>
          ))}
          <div className="comment-input"><Avatar name={sessionUser.name} src={sessionUser.avatarUrl ?? undefined} size="sm" /><input value={draft} onChange={(event) => setDraft(event.target.value)} onKeyDown={(event) => { if (event.key === "Enter") { event.preventDefault(); void addComment(); } }} placeholder="Add a comment…" /><button disabled={commentSubmitting} onClick={addComment}>{commentSubmitting ? "Posting…" : "Post"}</button></div>
        </div>
      )}
    </article>
  );
}

export function FeedStream() {
  const sessionUser = useCurrentUser();
  const [items, setItems] = useState(seedPosts);
  const [followingIds, setFollowingIds] = useState<string[]>([]);

  useEffect(() => {
    void fetch("/api/follows", { cache: "no-store" })
      .then(async (response) => {
        const result = await response.json() as { targetUserIds?: string[] };
        if (response.ok && Array.isArray(result.targetUserIds)) setFollowingIds(result.targetUserIds);
      })
      .catch(() => undefined);
  }, []);

  function addPost(content: string, id: string) {
    setItems((existing) => [{
      id,
      author: { ...currentUser, id: sessionUser.id, name: sessionUser.name, username: sessionUser.username, headline: sessionUser.headline, avatar: sessionUser.avatarUrl ?? currentUser.avatar, mutual: 0 },
      age: "Now",
      content,
      likes: 0,
      comments: 0,
      liked: false,
    }, ...existing]);
  }

  function updateFollowing(targetUserId: string, following: boolean) {
    setFollowingIds((ids) => following
      ? ids.includes(targetUserId) ? ids : [...ids, targetUserId]
      : ids.filter((id) => id !== targetUserId));
  }

  return <div className="feed-stream"><FeedComposer onPost={addPost} />{items.map((post) => <PostCard following={followingIds.includes(post.author.id)} onFollowingChange={updateFollowing} post={post} key={post.id} />)}</div>;
}