aboutsummaryrefslogtreecommitdiffstats
path: root/site/src/components/NewsFeed.tsx
blob: 8e67af38ff1892755d6715038f035a38d65115f4 (plain) (blame)
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
import { useState, useEffect } from "react";
import { getGameTitle, getShortenedGameName } from "../utils.ts";
import { useSearchParams } from "react-router-dom";
import { useTranslation } from "react-i18next";

export interface NewsData {
  date: string;
  identifier: string;
  type: string | null;
  timestamp: number;
  headline: string | null;
  content: string;
  url: string | null;
  images: Array<{
    image: string;
    link: string | null;
  }>;
  en_headline: string | null;
  en_content: string | null;
  is_ai_summary: boolean | null;
  archive_hash: string | null;
}

interface NewsFeedProps {
  newsItems: NewsData[];
}

type Sentinel = { _sentinel: "nothing-new" | "caught-up" };

const VIEWED_KEY = "viewedNewsIds";

const computeNewsId = (news: NewsData): string => {
  const contentHash =
    news.content
      .split("")
      .reduce(
        (hash, char) => (hash << 5) + hash + char.charCodeAt(0),
        5381,
      ) >>> 0;
  const headlineHash =
    (news.headline || "null")
      .split("")
      .reduce(
        (hash, char) => (hash << 5) + hash + char.charCodeAt(0),
        5381,
      ) >>> 0;
  const legacyId = `${news.identifier}-${news.timestamp}-${contentHash.toString(16)}-${headlineHash.toString(16)}`;
  return news.archive_hash || legacyId;
};

export const NewsFeed: React.FC<NewsFeedProps> = ({ newsItems }) => {
  const { t } = useTranslation();
  const [showEnglish, setShowEnglish] = useState<Record<string, boolean>>({});
  const [expanded, setExpanded] = useState<Record<string, boolean>>({});
  const [currentImageIndex, setCurrentImageIndex] = useState<
    Record<string, number>
  >({});
  const [loadingImages, setLoadingImages] = useState<Record<string, boolean>>(
    {},
  );
  const [searchParams] = useSearchParams();
  const isMoe = searchParams.has("moe");
  const pfpBaseUrl = import.meta.env.VITE_PFP_BASE_URL;
  const middlewareBase = import.meta.env.VITE_MIDDLEWARE_BASE_URL;

  const [initialViewedIds] = useState<Set<string>>(() => {
    try {
      const raw = localStorage.getItem(VIEWED_KEY);
      if (!raw) return new Set();
      const parsed = JSON.parse(raw) as Array<{ id: string } | string>;
      return new Set(parsed.map((e) => (typeof e === "string" ? e : e.id)));
    } catch {
      return new Set();
    }
  });

  useEffect(() => {
    try {
      const raw = localStorage.getItem(VIEWED_KEY);
      const prev: { id: string; timestamp: number }[] = raw
        ? (JSON.parse(raw) as Array<{ id: string; timestamp?: number } | string>).map(
            (e) => (typeof e === "string" ? { id: e, timestamp: 0 } : { id: e.id, timestamp: e.timestamp ?? 0 }),
          )
        : [];
      const map = new Map(prev.map((e) => [e.id, e.timestamp]));
      for (const news of newsItems) {
        const id = computeNewsId(news);
        if (!map.has(id)) map.set(id, news.timestamp);
      }
      const next = [...map.entries()]
        .map(([id, timestamp]) => ({ id, timestamp }))
        .sort((a, b) => b.timestamp - a.timestamp)
        .slice(0, 100);
      localStorage.setItem(VIEWED_KEY, JSON.stringify(next));
    } catch {
      console.error("Failed to update viewed news items");
    }
  }, [newsItems]);

  const toggleLanguage = (id: string) =>
    setShowEnglish((prev) => ({ ...prev, [id]: !prev[id] }));
  const toggleExpand = (id: string) =>
    setExpanded((prev) => ({ ...prev, [id]: !prev[id] }));
  const changeImage = (id: string, i: number) => {
    if (currentImageIndex[id] == i) return;
    setCurrentImageIndex((p) => ({ ...p, [id]: i }));
    setLoadingImages((p) => ({ ...p, [id]: true }));
  };
  const handleImageLoad = (id: string) =>
    setLoadingImages((p) => ({ ...p, [id]: false }));
  const PREVIEW_CHAR_LIMIT = 600;

  useEffect(() => {
    const initialImageIndex: Record<string, number> = {};
    newsItems.forEach((news) => {
      initialImageIndex[computeNewsId(news)] = 0;
    });
    setCurrentImageIndex(initialImageIndex);
  }, [newsItems]);

  useEffect(() => {
    const fragment = window.location.hash.slice(1);
    if (fragment) {
      const el = document.getElementById(fragment);
      if (el) {
        el.scrollIntoView({ behavior: "smooth", block: "start" });
      } else {
        alert("News Post doesn't or no longer exists...");
      }
    }
  }, [newsItems]);

  const unviewed = newsItems
    .filter((n) => !initialViewedIds.has(computeNewsId(n)))
    .sort((a, b) => b.timestamp - a.timestamp);
  const viewed = newsItems.filter((n) => initialViewedIds.has(computeNewsId(n)));
  const nothingNew = unviewed.length === 0 && newsItems.length > 0;

  const feed: (NewsData | Sentinel)[] = [];
  if (nothingNew) feed.push({ _sentinel: "nothing-new" });
  feed.push(...unviewed);
  if (unviewed.length > 0 && viewed.length > 0) feed.push({ _sentinel: "caught-up" });
  feed.push(...(nothingNew ? newsItems : viewed));

  return (
    <div className="max-w-[600px] w-full mx-auto py-8 space-y-4 font-[Zen_Maru_Gothic]">
      {feed.map((item, idx) => {
        if ("_sentinel" in item) {
          const isFirstSentinel = idx === 0;
          return (
            <div
              key={item._sentinel}
              className={`flex font-bold items-center gap-3 ${isFirstSentinel ? "py-2" : "py-24"} ${isMoe ? "text-pink-400" : "text-gray-100"}`}
            >
              <div className={`flex-1 h-px ${isMoe ? "bg-pink-300" : "bg-gray-700"}`} />
              <span className="text-sm">
                {item._sentinel === t("nothing_new") ? t("nothing_new") : t("caught_up")}
              </span>
              <div className={`flex-1 h-px ${isMoe ? "bg-pink-300" : "bg-gray-700"}`} />
            </div>
          );
        }

        const news = item;
        const date = new Date(news.timestamp * 1000).toLocaleDateString(
          "ja-JP",
          { year: "numeric", month: "2-digit", day: "2-digit" },
        );
        const newsId = computeNewsId(news);
        const isEnglish = showEnglish[newsId];
        const hasTranslation = news.en_headline || news.en_content;
        const displayHeadline =
          isEnglish && news.en_headline ? news.en_headline : news.headline;
        const displayContent =
          isEnglish && news.en_content ? news.en_content : news.content;
        const isLong = displayContent.length > PREVIEW_CHAR_LIMIT;
        const isExpanded = !!expanded[newsId];
        const contentToShow =
          isLong && !isExpanded
            ? displayContent.slice(0, PREVIEW_CHAR_LIMIT) + "…"
            : displayContent;

        return (
          <div
            id={newsId}
            key={newsId}
            className={`${isMoe ? "bg-pink-100 border-pink-300 text-pink-900 font-[Zen_Maru_Gothic]" : "bg-gray-900 border-gray-800 text-white font-sans"} border rounded-lg shadow-lg overflow-hidden`}
          >
            <div className="flex items-center p-3 justify-between">
              <div className="flex items-center space-x-3">
                <a href={`/game/${getShortenedGameName(news.identifier)}`}>
                  <img
                    src={
                      pfpBaseUrl +
                      `/` +
                      getShortenedGameName(news.identifier) +
                      `.webp`
                    }
                    alt={getGameTitle(news.identifier) || ""}
                    className="hover:animate-pulse rounded-full h-8 w-8 object-cover"
                    onError={(e) => {
                      const target = e.target as HTMLImageElement;
                      target.style.display = "none";
                      const placeholder = document.createElement("div");
                      placeholder.className =
                        "hover:animate-pulse rounded-full h-8 w-8 flex items-center justify-center bg-gray-500 text-white font-bold text-sm";
                      placeholder.textContent = (getGameTitle(
                        news.identifier,
                      ) || "G")[0].toUpperCase();
                      target.parentNode?.replaceChild(placeholder, target);
                    }}
                  />
                </a>
                <div className="flex flex-col leading-tight">
                  <span className="text-sm font-semibold hover:underline">
                    <a href={`/game/${getShortenedGameName(news.identifier)}`}>
                      {getGameTitle(news.identifier)}
                    </a>
                  </span>
                  <span className="text-xs opacity-80">{date}</span>
                  {news.type && (
                    <span className="text-xs italic">{news.type}</span>
                  )}
                </div>
              </div>
              {hasTranslation && (
                <button
                  onClick={() => toggleLanguage(newsId)}
                  className={`${isMoe ? "bg-pink-200 hover:bg-pink-300" : "bg-gray-800 hover:bg-gray-700"} text-xs py-1 px-2 rounded`}
                >
                  {isEnglish ? t("view_in_original_text") : t("view_in_english_text")}
                </button>
              )}
            </div>

            <div className="px-3 pt-1 pb-3">
              {displayHeadline && (
                <p className="font-semibold text-sm mb-2">{displayHeadline}</p>
              )}
              <p className="text-sm whitespace-pre-line mb-2">
                {contentToShow
                  .split(/(\[.*?\]\(.*?\)|https?:\/\/[^\s]+)/g)
                  .map((part, idx) => {
                    const m = part.match(/\[(.*?)\]\((.*?)\)/);
                    const u = part.match(/https?:\/\/[^\s]+/);
                    if (m)
                      return (
                        <a
                          key={idx}
                          href={m[2]}
                          className="text-blue-500 underline"
                          target="_blank"
                        >
                          {m[1]}
                        </a>
                      );
                    if (u)
                      return (
                        <a
                          key={idx}
                          href={u[0]}
                          className="text-blue-500 underline"
                          target="_blank"
                        >
                          {u[0]}
                        </a>
                      );
                    return part;
                  })}
              </p>
              {isLong && (
                <button
                  onClick={() => toggleExpand(newsId)}
                  className="text-sm text-blue-500 hover:underline"
                >
                  {isExpanded ? "Show less" : "Show more"}
                </button>
              )}
            </div>

            {/* Copy Link to Post */}
            <div className="px-3 pb-2 text-right">
              <a
                href={`#${newsId}`}
                onClick={(e) => {
                  e.preventDefault();
                  const pathname =
                    window.location.pathname === "/"
                      ? "/news"
                      : window.location.pathname.replace(/^\/game/, "");
                  const url = middlewareBase
                    ? `${middlewareBase}${pathname}?post=${newsId}${isEnglish ? '&lang=en' : ''}`
                    : `${window.location.origin}${pathname === "/news" ? "" : pathname}#${newsId}`;
                  navigator.clipboard.writeText(url);
                  alert(
                    `${t('copy_link_notif')}`
                  );
                }}
                title="Copy permalink"
                className="text-xs text-blue-400 hover:underline cursor-pointer"
              >
                🔗 {`${t('copy_link_to_post')}`}
              </a>
            </div>

            {/* AI Disclaimer */}
            {news.is_ai_summary && (
              <div
                className={`${isMoe ? "bg-pink-200 text-pink-800" : "bg-gray-800 text-white"} px-3 py-2 text-xs text-center`}
              >
                {`${t('ai_summary_note')}`}
              </div>
            )}

            {/* Machine TL Disclaimer */}
            {hasTranslation && isEnglish && (
              <div
                className={`${isMoe ? "bg-pink-200 text-pink-800" : "bg-gray-800 text-white"} px-3 py-2 text-xs text-center`}
              >
              {`${t('machine_tl_note')}`}
              </div>
            )}

            {/* Images */}
            {news.images.length > 0 && (
              <div className="w-full">
                {(() => {
                  const idx = currentImageIndex[newsId] || 0;
                  const img = news.images[idx];
                  return (
                    <div className="relative">
                      {loadingImages[newsId] && (
                        <div className="absolute inset-0 flex items-center justify-center bg-black bg-opacity-50">
                          <div className="loader border-t-2 border-b-2 border-white w-6 h-6 rounded-full animate-spin" />
                        </div>
                      )}
                      <img
                        src={img.image}
                        alt="news visual"
                        className={`w-full object-cover py-2 ${loadingImages[newsId] ? "opacity-0" : "opacity-100"}`}
                        onLoad={() => handleImageLoad(newsId)}
                      />
                    </div>
                  );
                })()}

                {news.images.length > 1 && (
                  <div className="pb-3 overflow-x-auto px-3">
                    <div className="flex space-x-2 w-max mx-auto">
                      {news.images.map((_, idx) => (
                        <button
                          key={idx}
                          onClick={() => changeImage(newsId, idx)}
                          className={`w-9 h-9 shrink-0 rounded-sm flex items-center justify-center ${
                            currentImageIndex[newsId] === idx
                              ? isMoe
                                ? "bg-pink-500 text-white"
                                : "bg-blue-600 text-white"
                              : isMoe
                                ? "bg-pink-200 text-pink-800 hover:bg-pink-300"
                                : "bg-gray-700 text-gray-300 hover:bg-gray-600"
                          }`}
                        >
                          {idx + 1}
                        </button>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            )}

            {news.url && (
              <div
                className={`${isMoe ? "bg-pink-200" : "bg-gray-800"} px-3 py-2 text-center`}
              >
                <a
                  href={news.url}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-sm underline font-bold"
                >
                  READ MORE
                </a>
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
};
send patches to the email below
yukais@pinapelz.com
include the subject [PATCH repo_name]
pinapelz.com
homepage