mirror of
https://github.com/headporter81/ss-front-react.git
synced 2026-12-06 07:41:11 +09:00
feat : 메인 "새 글" 창을 IT 헤드라인(GeekNews)·날씨(Open-Meteo) 창으로 교체
SpecialSource Frontend (React) CD / deploy (push) Successful in 14s
SpecialSource Frontend (React) CD / deploy (push) Successful in 14s
- IT 헤드라인: 백엔드 /api/headlines (로그인 불필요), 줄 클릭 시 새 탭으로 열기 - 날씨: 접속자 위치(거부·무응답 시 서울) 기준 지금/오늘/내일, 좌표는 약 1km 단위로만 전송 - 페이지를 연 동안 한 번만 불러옴 - study-notes 9번 추가 (백엔드 메모리 캐시) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
73ad4705bc
commit
4bbf5c1ba4
7 files changed
+160
-29
No files matched your search
+32
-1
@@ -1,4 +1,4 @@
|
||||
import type { Board, Feed, ListKind } from "./types";
|
||||
import type { Board, Feed, Headline, ListKind, Weather } from "./types";
|
||||
|
||||
// 개발은 로컬 백엔드 직접 호출, 운영(nginx)은 같은 도메인의 /api 프록시. NEXT_PUBLIC_API_URL로 덮어쓰기 가능
|
||||
export const API_URL =
|
||||
@@ -36,5 +36,36 @@ export async function fetchFeed(token: string, kind: ListKind, board: string | n
|
||||
export const fetchBoards = async (token: string): Promise<Board[]> =>
|
||||
(await call("/api/scraped-posts/boards", token)).json();
|
||||
|
||||
/** IT 헤드라인 (GeekNews). 백엔드가 30분마다 피드를 읽어 둠. 로그인 없이 볼 수 있음 */
|
||||
export async function fetchHeadlines(): Promise<Headline[]> {
|
||||
const res = await fetch(`${API_URL}/api/headlines`);
|
||||
if (!res.ok) throw new Error(`※ 서버 오류 (${res.status})`);
|
||||
return res.json();
|
||||
}
|
||||
|
||||
const SEOUL = { lat: 37.57, lon: 126.98, place: "서울" };
|
||||
|
||||
/** 접속자 위치(거부하거나 8초 안에 답이 없으면 서울)의 날씨. Open-Meteo: 무료·API 키 없음·브라우저에서 직접 호출 가능 */
|
||||
export async function fetchWeather(): Promise<Weather> {
|
||||
const at = await new Promise<typeof SEOUL>((resolve) => {
|
||||
setTimeout(() => resolve(SEOUL), 8000); // 위치 권한 팝업을 그냥 두면 응답이 영영 안 옴
|
||||
navigator.geolocation?.getCurrentPosition(
|
||||
// 소수 둘째 자리(약 1km)까지만 보냄: 날씨에는 충분하고 정확한 위치는 밖으로 안 나감
|
||||
(p) => resolve({ lat: +p.coords.latitude.toFixed(2), lon: +p.coords.longitude.toFixed(2), place: "현재 위치" }),
|
||||
() => resolve(SEOUL),
|
||||
{ maximumAge: 30 * 60 * 1000 },
|
||||
);
|
||||
});
|
||||
const q = `latitude=${at.lat}&longitude=${at.lon}¤t=temperature_2m,weather_code&daily=weather_code,temperature_2m_max,temperature_2m_min&timezone=auto&forecast_days=2`;
|
||||
const res = await fetch(`https://api.open-meteo.com/v1/forecast?${q}`);
|
||||
if (!res.ok) throw new Error(`날씨 서버 오류 (${res.status})`);
|
||||
const d = await res.json();
|
||||
return {
|
||||
place: at.place,
|
||||
now: { temp: d.current.temperature_2m, code: d.current.weather_code },
|
||||
days: [0, 1].map((i) => ({ max: d.daily.temperature_2m_max[i], min: d.daily.temperature_2m_min[i], code: d.daily.weather_code[i] })),
|
||||
};
|
||||
}
|
||||
|
||||
export const markViewed = (token: string, id: number) =>
|
||||
call(`/api/scraped-posts/${id}/view`, token, { method: "POST" });
|
||||
@@ -225,16 +225,7 @@ export default function BbsTerminal() {
|
||||
{pulling && <div className={styles.pull}>↓ 놓으면 새로고침</div>}
|
||||
<div className={styles.grid}>
|
||||
{state.screen === "main" && (
|
||||
<MainMenu
|
||||
feed={state.feed}
|
||||
loggedIn={!!state.user}
|
||||
onSelect={submitFromClick}
|
||||
onOpenPost={(num) => {
|
||||
// 메인에서 숫자는 메뉴 번호라서, 게시판으로 옮긴 뒤 글 번호를 실행
|
||||
dispatch({ screen: "list", list: "board", board: null });
|
||||
dispatch(String(num));
|
||||
}}
|
||||
/>
|
||||
<MainMenu feed={state.feed} loggedIn={!!state.user} onSelect={submitFromClick} />
|
||||
)}
|
||||
{state.screen === "login" && (
|
||||
<LoginForm onSuccess={(user, token) => dispatch({ screen: "main", user, token })} />
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { fetchHeadlines, fetchWeather } from "../api";
|
||||
import type { Headline, Weather } from "../types";
|
||||
import styles from "./bbs.module.css";
|
||||
|
||||
// 페이지를 연 동안 한 번만 불러옴 (메인으로 돌아올 때마다 위치를 묻거나 다시 요청하지 않게)
|
||||
let headlinesOnce: Promise<Headline[]> | null = null;
|
||||
let weatherOnce: Promise<Weather> | null = null;
|
||||
|
||||
/** WMO 날씨 코드 → 한글 (https://open-meteo.com/en/docs 의 WMO Weather interpretation codes) */
|
||||
const sky = (c: number) =>
|
||||
c === 0 ? "맑음" : c <= 2 ? "구름조금" : c === 3 ? "흐림" : c <= 48 ? "안개" : c <= 57 ? "이슬비"
|
||||
: c <= 67 ? "비" : c <= 77 ? "눈" : c <= 82 ? "소나기" : c <= 86 ? "눈" : "뇌우";
|
||||
const deg = (t: number) => `${Math.round(t)}℃`;
|
||||
|
||||
/** 메인 화면 오른쪽: IT 헤드라인 + 날씨 */
|
||||
export default function MainInfo() {
|
||||
const [news, setNews] = useState<Headline[] | null>(null);
|
||||
const [weather, setWeather] = useState<Weather | null>(null);
|
||||
const [error, setError] = useState({ news: false, weather: false });
|
||||
|
||||
useEffect(() => {
|
||||
(headlinesOnce ??= fetchHeadlines()).then(setNews).catch(() => {
|
||||
headlinesOnce = null; // 실패하면 다음에 메인으로 올 때 다시 시도
|
||||
setError((e) => ({ ...e, news: true }));
|
||||
});
|
||||
(weatherOnce ??= fetchWeather()).then(setWeather).catch(() => {
|
||||
weatherOnce = null;
|
||||
setError((e) => ({ ...e, weather: true }));
|
||||
});
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className={styles.stack}>
|
||||
<section className={styles.win}>
|
||||
<span className={styles.cap}>═ IT 헤드라인 ═</span>
|
||||
{news ? (
|
||||
<ul className={`${styles.menu} ${styles.news}`}>
|
||||
{news.map((h) => (
|
||||
<li key={h.link}>
|
||||
<a href={h.link} target="_blank" rel="noreferrer">
|
||||
· {h.title}
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<div className={styles.dim}>{error.news ? "헤드라인을 불러오지 못했습니다." : "불러오는 중..."}</div>
|
||||
)}
|
||||
<div className={styles.footer}>출처: GeekNews · 줄을 누르면 새 탭으로 열림</div>
|
||||
</section>
|
||||
|
||||
<section className={styles.win}>
|
||||
<span className={styles.cap}>═ 날씨{weather && ` · ${weather.place}`} ═</span>
|
||||
{weather ? (
|
||||
<table className={styles.tbl}>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td className={styles.accent}>지금</td>
|
||||
<td>{sky(weather.now.code)}</td>
|
||||
<td className={styles.title}>{deg(weather.now.temp)}</td>
|
||||
</tr>
|
||||
{weather.days.map((d, i) => (
|
||||
<tr key={i}>
|
||||
<td className={styles.accent}>{i === 0 ? "오늘" : "내일"}</td>
|
||||
<td>{sky(d.code)}</td>
|
||||
<td className={styles.title}>
|
||||
{deg(d.min)} / {deg(d.max)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
) : (
|
||||
<div className={styles.dim}>{error.weather ? "날씨를 불러오지 못했습니다." : "위치 확인 중..."}</div>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,13 +1,12 @@
|
||||
import { MENU } from "../constants";
|
||||
import type { Feed } from "../types";
|
||||
import { PostTable } from "./PostList";
|
||||
import MainInfo from "./MainInfo";
|
||||
import styles from "./bbs.module.css";
|
||||
|
||||
interface Props {
|
||||
feed: Feed | null;
|
||||
loggedIn: boolean;
|
||||
onSelect: (cmd: string) => void;
|
||||
onOpenPost: (id: number) => void;
|
||||
}
|
||||
|
||||
// 영문 ASCII만 사용: ╔═╗ 같은 박스 문자는 한글 글꼴에서 폭이 달라져 줄이 어긋남
|
||||
@@ -23,7 +22,7 @@ const LOGO = '';
|
||||
// \__ \| (_) || |_| || /| (__ | _|
|
||||
// |___/ \___/ \___/ |_|_\ \___||___|`;
|
||||
|
||||
export default function MainMenu({ feed, loggedIn, onSelect, onOpenPost }: Props) {
|
||||
export default function MainMenu({ feed, loggedIn, onSelect }: Props) {
|
||||
const board = feed?.kind === "board" && !feed.board ? feed : null; // 메인에서는 스크랩 게시판 전체(안 읽은 글)를 불러옴
|
||||
|
||||
return (
|
||||
@@ -51,21 +50,7 @@ export default function MainMenu({ feed, loggedIn, onSelect, onOpenPost }: Props
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section className={styles.win}>
|
||||
<span className={styles.cap}>═ 새 글 ═</span>
|
||||
{!loggedIn ? (
|
||||
<div className={styles.dim}>로그인하면 스크랩된 새 글이 보입니다.</div>
|
||||
) : !board ? (
|
||||
<div className={styles.dim}>불러오는 중...</div>
|
||||
) : board.posts.length === 0 ? (
|
||||
<div className={styles.dim}>새 글을 모두 읽었습니다.</div>
|
||||
) : (
|
||||
<PostTable posts={board.posts.slice(0, 5)} onSelect={onOpenPost} />
|
||||
)}
|
||||
<div className={styles.footer}>
|
||||
줄을 누르면 바로 읽기 · <b>2</b>=게시판 전체
|
||||
</div>
|
||||
</section>
|
||||
<MainInfo />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -66,6 +66,10 @@
|
||||
.menu li .en { margin-left: auto; }
|
||||
.menu li:hover, .menu li:hover * { background: var(--bbs-sel); color: var(--bbs-bar-fg); }
|
||||
|
||||
/* 메인 오른쪽: 헤드라인·날씨 창을 세로로 쌓기 */
|
||||
.stack { display: flex; flex-direction: column; gap: 1.6em; min-width: 0; }
|
||||
.news a { flex: 1; min-width: 0; color: inherit; text-decoration: none; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
|
||||
/* 게시판 표 */
|
||||
.tbl { width: 100%; border-collapse: collapse; font-variant-numeric: tabular-nums; }
|
||||
.tbl th {
|
||||
|
||||
@@ -30,6 +30,19 @@ export type Palette = "blue" | "green" | "amber";
|
||||
export type Screen = "main" | "list" | "post" | "login";
|
||||
export type ListKind = "board" | "viewed";
|
||||
|
||||
/** 메인 화면 IT 헤드라인 (백엔드 /api/headlines) */
|
||||
export interface Headline {
|
||||
title: string;
|
||||
link: string;
|
||||
}
|
||||
|
||||
/** 메인 화면 날씨 (code = WMO 날씨 코드) */
|
||||
export interface Weather {
|
||||
place: string;
|
||||
now: { temp: number; code: number };
|
||||
days: { max: number; min: number; code: number }[]; // [오늘, 내일]
|
||||
}
|
||||
|
||||
/** 백엔드 BoardSummaryResponse와 같은 모양 (스크랩 대상 게시판 하나) */
|
||||
export interface Board {
|
||||
boardKey: string;
|
||||
|
||||
Reference in new issue
Block a user