summaryrefslogtreecommitdiff
path: root/gui/src/components/modals/UserModal.tsx
blob: 4a7f812ef174749145251a9a7c5dbf7de9df4a51 (plain)
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import "@/styles/Profile.css";
import "@/styles/UserModal.css";
import Modal from "./Modal";
import Avatar from "../Avatar";
import Icon from "@/components/Icon";
import useLocalState from "@/state/state";
import { useLocation } from "wouter";
import toast from "react-hot-toast";
import { generateNprofile } from "@/logic/nostr";
import { useEffect, useState } from "react";
import type { UserType } from "@/types/nostrill";

export default function ({ user }: { user: UserType }) {
  const { setModal, api, lastFact, pubkey, profiles, following, followers } =
    useLocalState((s) => ({
      setModal: s.setModal,
      api: s.api,
      pubkey: s.pubkey,
      profiles: s.profiles,
      following: s.following,
      followers: s.followers,
      lastFact: s.lastFact,
    }));
  const [_, navigate] = useLocation();
  const [isLoading, setLoading] = useState(false);

  function close() {
    setModal(null);
  }

  const itsMe =
    "urbit" in user
      ? user.urbit === api?.airlock.our
      : "nostr" in user
        ? user.nostr === pubkey
        : false;

  const userString = "urbit" in user ? user.urbit : user.nostr;
  const profile = profiles.get(userString);
  const isFollowing = following.has(userString);
  const isFollower = followers.includes(userString);

  // Get follower/following counts from the user's feed if available
  const userFeed = following.get(userString);
  const postCount = userFeed ? Object.keys(userFeed.feed).length : 0;

  // useEffect(() => {
  //   if (!lastFact) return;
  //   if (!("fols" in lastFact)) return;
  //   if (!("new" in lastFact.fols)) return;
  //   if (lastFact.fols.new.user === userString) setLoading(false);
  //   const name = profile?.name || userString;
  //   toast.success(`Followed ${name}`);
  // }, [lastFact]);

  async function copy(e: React.MouseEvent) {
    e.stopPropagation();
    await navigator.clipboard.writeText(userString);
    toast.success("Copied to clipboard");
  }

  async function handleFollow(e: React.MouseEvent) {
    if ("error" in user) return;
    e.stopPropagation();
    if (!api) return;

    setLoading(true);
    try {
      if (isFollowing) {
        const result = await api.unfollow(user);
        console.log(result);
        // if ("ok" in result) {
        //   toast.success(`Unfollowed ${profile?.name || userString}`);
        // } else {
        //   toast.error(result.error);
        // }
      } else {
        const result = await api.follow(user);
        console.log(result);
        // if ("ok" in result) {
        //   toast.success(`Following ${profile?.name || userString}`);
        // } else {
        //   toast.error(result.error);
        // }
      }
    } catch (err) {
      toast.error("Action failed");
    } finally {
      // setLoading(false);
    }
  }

  async function handleAvatarClick(e: React.MouseEvent) {
    e.stopPropagation();
    if ("nostr" in user) {
      const nprof = generateNprofile(userString);
      const href = `https://primal.net/p/${nprof}`;
      window.open(href, "_blank");
    }
  }

  const displayName = profile?.name || ("urbit" in user ? user.urbit : "Anon");
  const truncatedId =
    userString.length > 20
      ? `${userString.slice(0, 10)}...${userString.slice(-8)}`
      : userString;

  // Get banner image from profile.other
  const bannerImage = profile?.other?.banner || profile?.other?.Banner;

  // Filter out banner from other fields since we display it separately
  const otherFields = profile?.other
    ? Object.entries(profile.other).filter(
        ([key]) => key.toLowerCase() !== "banner",
      )
    : [];

  return (
    <Modal close={close}>
      <div className="user-modal">
        {/* Banner Image */}
        {bannerImage && (
          <div className="user-banner">
            <img src={bannerImage} alt="Profile banner" />
          </div>
        )}

        {/* Header with Avatar and Basic Info */}
        <div className="user-modal-header">
          <div
            className="user-modal-avatar-wrapper"
            onClick={handleAvatarClick}
            style={{ cursor: "nostr" in user ? "pointer" : "default" }}
          >
            <Avatar
              user={user}
              userString={userString}
              profile={profile}
              size={80}
              picOnly
            />
          </div>

          <div className="user-modal-info">
            <h2 className="user-modal-name">{displayName}</h2>
            <div className="user-modal-id-row">
              <span className="user-modal-id" title={userString}>
                {"urbit" in user ? user.urbit : truncatedId}
              </span>
              <Icon
                name="copy"
                size={16}
                className="user-modal-copy-icon cp"
                onClick={copy}
                title="Copy to clipboard"
              />
            </div>

            {/* User type badge */}
            <div className="user-modal-badge">
              {"urbit" in user ? (
                <span className="badge badge-urbit">Urbit</span>
              ) : (
                <span className="badge badge-nostr">Nostr</span>
              )}
              {itsMe && <span className="badge badge-me">You</span>}
              {isFollower && !itsMe && (
                <span className="badge badge-follows">Follows you</span>
              )}
            </div>
          </div>
        </div>

        {/* Profile About Section */}
        {profile?.about && (
          <div className="user-modal-about">
            <p>{profile.about}</p>
          </div>
        )}

        {/* Stats */}
        <div className="user-modal-stats">
          {postCount > 0 && (
            <div className="stat">
              <span className="stat-value">{postCount}</span>
              <span className="stat-label">Posts</span>
            </div>
          )}
          {/* Additional stats could go here */}
        </div>

        {/* Custom Fields */}
        {otherFields.length > 0 && (
          <div className="user-modal-custom-fields">
            <h4>Additional Info</h4>
            {otherFields.map(([key, value]) => {
              console.log({ key, value });
              return (
                <div key={key} className="custom-field-item">
                  <span className="field-key">{key}:</span>
                  <ProfValue value={value} />
                </div>
              );
            })}
          </div>
        )}

        {/* Action Buttons */}
        <div className="user-modal-actions">
          {!itsMe && (
            <button
              className={`action-btn ${isFollowing ? "following" : "follow"}`}
              onClick={handleFollow}
              disabled={isLoading}
            >
              <Icon name="pals" size={16} />
              {isLoading ? "..." : isFollowing ? "Following" : "Follow"}
            </button>
          )}
          <>
            <button
              className="action-btn secondary"
              onClick={() => {
                navigate(`/u/${userString}`);
                close();
              }}
            >
              <Icon name="home" size={16} />
              View Feed
            </button>
          </>

          {"nostr" in user ? (
            <button
              className="action-btn secondary"
              onClick={handleAvatarClick}
            >
              <Icon name="nostr" size={16} />
              View on Primal
            </button>
          ) : null}
        </div>
      </div>
    </Modal>
  );
}

// Check if a string is a URL
const isURL = (str: string): boolean => {
  if (!str) return false;
  try {
    new URL(str);
    return true;
  } catch {
    return false;
  }
};

export function ProfValue({ value }: { value: any }) {
  if (typeof value === "string")
    return isURL(value) ? (
      <a
        href={value}
        target="_blank"
        rel="noopener noreferrer"
        className="field-value field-link"
        onClick={(e) => e.stopPropagation()}
      >
        {value}
        <Icon name="nostr" size={12} className="external-link-icon" />
      </a>
    ) : (
      <span className="field-value">{value}</span>
    );
  else if (typeof value === "number")
    return <span className="field-value">{value}</span>;
  else if (typeof value === "object")
    return <span className="field-value">{JSON.stringify(value)}</span>;
  else return <span className="field-value">{JSON.stringify(value)}</span>;
}