@@ -79,7 +94,7 @@ function Pic({ name, className }: { name: string; className?: string }) {
const slideBase = 'relative flex h-full w-full shrink-0 flex-col px-5 py-[22px]'
-function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
+function SlideView({ slide, bg, img }: { slide: Slide; bg: SlideBg; img?: CSSProperties }) {
const { open } = useSheet()
if (slide.kind === 'hours') {
const temps = slide.hours.flatMap((h) => (h.temp_c == null ? [] : [h.temp_c]))
@@ -114,7 +129,7 @@ function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
}
if (slide.kind === 'gak')
return (
-
+
오늘의 각 · {slide.rank}위
{slide.line}
@@ -223,7 +238,7 @@ function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
)
return (
-
+
{slide.eyebrow}
@@ -312,7 +327,6 @@ export function PostCardSkel() {
function FullCard({ post }: PostProps) {
const { open } = useSheet()
- const { loggedIn } = useAuth()
const liked = !!post.liked
const likeCount = post.like_count
const queryClient = useQueryClient()
@@ -338,7 +352,6 @@ function FullCard({ post }: PostProps) {
// 화면을 먼저 바꾸고, 실패하면 되돌린다 (서버는 실패도 200 + result.success=false 로 준다)
const setLike = (on: boolean) => {
- if (!loggedIn) return open({ type: 'login' })
if (on === liked || like.isPending || unlike.isPending) return
if (on) setPop((p) => p + 1)
setLikeFailed(0)
@@ -363,7 +376,7 @@ function FullCard({ post }: PostProps) {
if ((e.target as HTMLElement).closest('button')) return
const now = Date.now()
if (now - lastTap.current < 320) {
- if (liked && loggedIn) setPop((p) => p + 1)
+ if (liked) setPop((p) => p + 1)
else setLike(true)
}
lastTap.current = now
@@ -401,7 +414,7 @@ function FullCard({ post }: PostProps) {
>
{post.slides.map((s, i) => (
-
+
))}
@@ -457,3 +470,43 @@ function FullCard({ post }: PostProps) {
)
}
+
+type FrameProps = { title: string; account: string; avatar: string; caption?: ReactNode; more?: ReactNode; shot?: RefObject
; children: ReactNode }
+
+/** 피드 글과 같은 틀(계정 줄·본문·보내기 줄)에 날씨·각 같은 화면 조각을 담는다. 보내기는 shot(공유용 틀)이 있으면 그것을, 없으면 본문을 이미지로 */
+export function PostFrame({ title, account, avatar, caption, more, shot, children }: FrameProps) {
+ const { open } = useSheet()
+ const bodyRef = useRef(null)
+ const share = () => {
+ const el = shot?.current ?? bodyRef.current
+ if (el) open({ type: 'share', share: { title, slides: [el] } })
+ }
+ return (
+
+
+
+
+
+
+
+
+ 날씨각
+ {account}
+
+
+ {children}
+
+
+ {more && {more}}
+
+ {caption && (
+
+ 날씨각
+ {caption}
+
+ )}
+
+ )
+}
diff --git a/frontend/src/b/Sheets.tsx b/frontend/src/b/Sheets.tsx
index b208dec..edf2a15 100644
--- a/frontend/src/b/Sheets.tsx
+++ b/frontend/src/b/Sheets.tsx
@@ -26,7 +26,6 @@ import { cx } from '../lib/utils'
import { useAuth } from './authContext'
import { ago, ARTICLE_CAT, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from './lib'
import { MixSheet } from './myGak'
-import { useMyGak } from './myGakState'
import { ownPage, useRegion } from './regionContext'
import { useSky } from './skyContext'
import { SHARE_SIZES, shareImage, type ShareSize } from './storyImage'
@@ -134,7 +133,7 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
{state.type === 'login' && open(then) : onClose} />}
{state.type === 'me' && }
{state.type === 'region' && }
- {state.type === 'mix' && }
+ {state.type === 'mix' && }
)}
{!state &&
}
@@ -326,8 +325,6 @@ function Radar({ name, factors, size = 250 }: { name: string; factors: Factor[];
function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: string) => void }) {
const { region } = useRegion()
- const { open } = useSheet()
- const { mixable } = useMyGak()
const q = useQuery(getIndexOptions({ path: { index_id: indexId }, query: { region: region.code } }))
const d: ResIndexDetail | undefined = q.data
const g = d?.index
@@ -360,11 +357,6 @@ function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: string)
{g.score}
{!g.active && 지금 시간대엔 해당 없어요. 점수는 오늘 가장 좋은 시간대 기준이에요.
}
- {mixable.has(g.index_id) && (
-
- )}
{now && (
{now.low}~{now.high}점
@@ -624,8 +616,6 @@ const EMOJIS = ['☀️', '🌂', '🍻', '🌇', '😍', '👍']
function CommentRow({ c, postId }: { c: CommentData; postId: number }) {
const { region } = useRegion()
- const { loggedIn } = useAuth()
- const { open } = useSheet()
const queryClient = useQueryClient()
const [liked, setLiked] = useState(c.liked)
const [count, setCount] = useState(c.like_count)
@@ -636,7 +626,6 @@ function CommentRow({ c, postId }: { c: CommentData; postId: number }) {
const [likeFailed, setLikeFailed] = useState(false)
const toggle = () => {
- if (!loggedIn) return open({ type: 'login' })
if (like.isPending || unlike.isPending) return
const next = !liked
setLikeFailed(false)
diff --git a/frontend/src/b/TodayPage.tsx b/frontend/src/b/TodayPage.tsx
index 07b2a0d..16c84be 100644
--- a/frontend/src/b/TodayPage.tsx
+++ b/frontend/src/b/TodayPage.tsx
@@ -1,16 +1,21 @@
-import { Fragment, useEffect, useState, type ReactNode } from 'react'
+import { Fragment, useEffect, useRef, useState, type ReactNode } from 'react'
import { Link } from 'react-router'
import { useQuery } from '@tanstack/react-query'
import { getFeedOptions, getWeatherTodayOptions } from '../api/client/@tanstack/react-query.gen'
-import { RainType, Sky, type BandArticle, type BandEvent, type Hero as HeroData, type ResWeatherToday, type TopIndex, type WeatherSlot } from '../api/client/types.gen'
+import { RainType, Sky, type BandArticle, type BandEvent, type Hero as HeroData, type ResWeatherToday, type TalkData, type TopIndex, type WeatherSlot } from '../api/client/types.gen'
import { cx } from '../lib/utils'
import { cardBg, fall, kindOfHour, kst, type Load, loadOf, MEDALS, type TimeKind, WEEKDAYS } from './lib'
import { MyGakRow } from './myGak'
-import { PostCard, PostCardSkel } from './Post'
+import { fromShare } from './myGakState'
+import { PostCard, PostCardSkel, PostFrame } from './Post'
+import { FeedComposer, TalkCard } from './talk'
+import { useFeedTalks } from './talkState'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
import { useSky } from './skyContext'
-import { Ic, Rail, Sec, Skel, SkelRail, StateBox, Thumb } from './ui'
+import { GakShareCard, HeroShareCard, type HeroShare } from './shareCards'
+import { SendIcon } from './svg'
+import { Ic, Rail, Sec, Skel, StateBox, TAP44, Thumb } from './ui'
import { deg, slotAt } from './weatherText'
type Mode = 'now' | TimeKind
@@ -103,6 +108,9 @@ const CLOUD_N: Record = { clear: 0, partly: 2, cloudy: 3, rain:
function Hero({ hero, today, ranked, feedLoad, todayLoad }: HeroProps) {
const { open } = useSheet()
+ const { region } = useRegion()
+ const tplRef = useRef(null)
+ const share = () => tplRef.current && open({ type: 'share', share: { title: `${region.name} 오늘 날씨`, slides: [tplRef.current] } })
const { preview, setServerKind, setPreview } = useSky()
const mode: Mode = preview ?? 'now'
const clock = useNow()
@@ -138,9 +146,26 @@ function Hero({ hero, today, ranked, feedLoad, todayLoad }: HeroProps) {
const rain = weather === 'rain' || weather === 'sleet'
const snow = weather === 'snow' || weather === 'sleet'
+ const shareData: HeroShare = {
+ kind,
+ sky: weather,
+ date: `${t.mo}월 ${t.d}일 ${WEEKDAYS[t.wd]}요일`,
+ place: region.name,
+ label: `${slotScore != null && mode !== 'now' ? PREVIEW[mode].label : '지금'} 날씨 점수`,
+ score,
+ bubble,
+ summary: top1?.summary,
+ status: status.map((x) => ({ label: x.label, value: x.value, warn: x.tone === 'warn' })),
+ slots: KINDS.map((k) => {
+ const s = slotOf(k === nowKind ? 'now' : k)
+ return { label: k === nowKind ? '지금' : PREVIEW[k].label, icon: k === 'night' && weatherOf(s) === 'clear' ? 'moon' : WEATHER_ICON[weatherOf(s)], temp: s?.temp_c != null ? deg(s.temp_c) : '–', on: k === kind }
+ }),
+ }
+
// 시안 D4-2: 가운데 해(점수)와 하늘 날씨, 결론 두 줄, 상태 한 줄, 아래 하루 흐름 칸(누르면 그 시간대 하늘로)
return (
+
{STARS.map((s, i) => (
@@ -155,9 +180,14 @@ function Hero({ hero, today, ranked, feedLoad, todayLoad }: HeroProps) {
{snow && FLAKES.map((s, i) => )}
)}
-
- {t.mo}월 {t.d}일 {WEEKDAYS[t.wd]}요일
-
+
+
+ {t.mo}월 {t.d}일 {WEEKDAYS[t.wd]}요일
+
+
+
{CLOUDS.slice(0, CLOUD_N[weather]).map((c) => (
@@ -228,27 +258,34 @@ function moonPath(pct: number, r: number, lit: boolean) {
return `M0,${-r} A${r},${r} 0 0 ${lit ? 1 : 0} 0,${r} ${edge}`
}
-function Stories({ items }: { items: TopIndex[] }) {
+function GakCard({ items, place, at }: { items: TopIndex[]; place: string; at: string }) {
const { open } = useSheet()
+ const tplRef = useRef
(null)
+ const top = items.filter((g) => g.active).slice(0, 5)
return (
-
- {items.map((g, i) => (
-
- ))}
-
+ 전체 보기} caption="누르면 계산 근거를 보여 줘요" shot={tplRef}>
+
+
+
+ 오늘의 각 · {place} {at}
+
+
+ {top.map((g, i) => (
+ -
+
+
+ ))}
+
+
+
)
}
@@ -261,27 +298,6 @@ function PostsSkel() {
)
}
-const STORY_SKELS = Array.from({ length: 6 }, (_, i) => i)
-
-/** Stories 와 같은 칸(68px 동그라미 + 이름 + 점수)을 6개 */
-function StoriesSkel() {
- return (
-
- {STORY_SKELS.map((i) => (
-
-
-
-
-
-
-
-
-
- ))}
-
- )
-}
-
function Band({ tone, title, sub, to, children }: { tone: 1 | 2 | 3; title: string; sub: string; to: string; children: ReactNode }) {
return (
@@ -310,25 +326,6 @@ function EventsBand({ events }: { events: BandEvent[] }) {
)
}
-function TopBand({ items, sub }: { items: TopIndex[]; sub: string }) {
- const { open } = useSheet()
- return (
-
-
- {items.slice(0, 5).map((g, i) => (
-
- ))}
-
-
- )
-}
-
function SeasonBand({ news }: { news: BandArticle[] }) {
const { open } = useSheet()
return (
@@ -361,25 +358,28 @@ export function TodayPage() {
const bands = f?.bands
const nowAt = f?.hero?.now_at
const load = loadOf(feed)
+ const [mine, setMine] = useState([])
+ // 사람들이 쓴 글은 운영 포스트 3개마다 하나씩. 방금 올린 내 글은 글쓰기 칸 아래에 따로 있으니 빼고
+ const talks = useFeedTalks().filter((t) => !mine.some((m) => m.talk_id === t.talk_id))
useEffect(() => {
window.scrollTo({ top: 0 })
}, [region.code])
- // 친구가 보낸 섞은 각 링크(/?mix=3,8)로 들어오면 내 동네 기준으로 보여 준다
+ // 친구가 보낸 내 각 링크(/?my=...)로 들어오면 내 동네 기준으로 보여 준다
useEffect(() => {
const url = new URL(window.location.href)
- const ids = url.searchParams.get('mix')?.split(',').map(Number).filter(Number.isInteger)
- if (!ids || ids.length !== 2) return
- url.searchParams.delete('mix')
+ const code = url.searchParams.get('my')
+ if (!code) return
+ url.searchParams.delete('my')
window.history.replaceState(window.history.state, '', url)
- open({ type: 'mix', ids, shared: true })
+ const g = fromShare(code)
+ if (g) open({ type: 'mix', shared: g })
}, [open])
// 디자인대로 3·6·9번째 글 뒤에 띠를 넣고, 글이 모자라면 남은 띠는 맨 뒤에 붙인다
const bandAt: [number, ReactNode][] = [
[3, bands?.events?.length ? : null],
- [6, bands?.top5?.length ? g.active) : bands.top5} sub={sloted ? `${PREVIEW[preview].label} 기준` : nowAt ? `${kst(nowAt).h}시 기준` : '오늘 기준'} /> : null],
[9, bands?.season?.length ? : null],
]
@@ -387,10 +387,19 @@ export function TodayPage() {
// 피드 칸은 전국 공통이라 지역이 바뀌어도 글 번호가 같다. 지역마다 새로 그려 넘긴 슬라이드·펼친 상태가 남지 않게 한다
-
-
- {/* 실패 안내는 여기 한 번만, 각 줄 스켈레톤과 같은 크기로 */}
- {stories.length ? : load === 'loading' ? : feed.refetch()} empty="오늘 계산된 각이 없어요." hold={} className="inset-x-3 top-3 bottom-1" />}
+ setMine((m) => [t, ...m])} />
+ {mine.map((t) => (
+
+ ))}
+
+ {/* 실패 안내는 여기 한 번만, 각 카드 스켈레톤과 같은 크기로 */}
+ {stories.some((g) => g.active) ? (
+
+ ) : load === 'loading' ? (
+
+ ) : (
+ feed.refetch()} empty="오늘 계산된 각이 없어요." hold={} className="inset-x-3 top-3 bottom-1" />
+ )}
{load === 'loading' &&
}
{/* 글이 없거나 못 받아도 스켈레톤 두 장 자리는 그대로 둔다 */}
@@ -400,6 +409,7 @@ export function TodayPage() {
{posts.map((p, i) => (
+ {(i + 1) % 3 === 0 && talks[(i + 1) / 3 - 1] && }
{bandAt.find(([at]) => at === i + 1)?.[1]}
))}
diff --git a/frontend/src/b/lib.ts b/frontend/src/b/lib.ts
index fd57469..a0b5cfe 100644
--- a/frontend/src/b/lib.ts
+++ b/frontend/src/b/lib.ts
@@ -1,6 +1,6 @@
import type { CSSProperties } from 'react'
-const SHARED = new Set(['bear', 'bike', 'bronze', 'camping', 'carwash', 'chimaek', 'cloud', 'coldwind', 'delivery', 'dog', 'garden', 'glasses', 'gold', 'hiking', 'iced_hot', 'jjamppong', 'laundry', 'letter', 'makeup', 'makgeolli', 'maple', 'moon', 'muggy', 'naengmyeon', 'photo', 'picnic', 'rabbit', 'rain', 'running', 'silver', 'snow', 'stars', 'sun_cloud', 'sun', 'sunset', 'taxi', 'umbrella', 'vent', 'walk', 'yajang', 'baseball', 'study', 'netflix', 'chestnut', 'peanut', 'tangerine', 'sweet_potato', 'fallen_leaf', 'kimchi', 'apple', 'mask', 'golf', 'jipkok', 'fishing', 'drive', 'kite', 'waterplay', 'riverwind', 'trot', 'pajeon', 'bingsu', 'blanket', 'indoordry', 'flower', 'bungeoppang', 'singing_rain'])
+const SHARED = new Set(['bear', 'bike', 'bronze', 'camping', 'carwash', 'chimaek', 'cloud', 'coldwind', 'delivery', 'dog', 'garden', 'glasses', 'gold', 'hiking', 'iced_hot', 'jjamppong', 'laundry', 'letter', 'makeup', 'makgeolli', 'maple', 'moon', 'muggy', 'naengmyeon', 'photo', 'picnic', 'rabbit', 'rain', 'running', 'silver', 'snow', 'stars', 'sun_cloud', 'sun', 'sunset', 'taxi', 'umbrella', 'vent', 'walk', 'yajang', 'baseball', 'study', 'netflix', 'chestnut', 'peanut', 'tangerine', 'sweet_potato', 'fallen_leaf', 'kimchi', 'apple', 'mask', 'golf', 'jipkok', 'fishing', 'drive', 'kite', 'waterplay', 'riverwind', 'trot', 'pajeon', 'bingsu', 'blanket', 'indoordry', 'flower', 'bungeoppang', 'singing_rain', 'hangang', 'themepark', 'date', 'frizz', 'boiler', 'sunscreen', 'mosquito', 'tennis', 'hyodo', 'thanks', 'gift', 'party', 'game', 'selfie', 'sentimental'])
const OWN = new Set(['fireworks', 'bulb', 'calendar', 'thermo', 'sheaf', 'popup', 'exhibition', 'concert'])
/** 아이콘 이름 → 파일 경로 (공용 public/icons, B 전용 public/b/icons). 'none'(데이터 없는 칸)은 그림 없음 */
diff --git a/frontend/src/b/myGak.tsx b/frontend/src/b/myGak.tsx
index 7e0c661..6fc07eb 100644
--- a/frontend/src/b/myGak.tsx
+++ b/frontend/src/b/myGak.tsx
@@ -1,134 +1,197 @@
-import { useQuery } from '@tanstack/react-query'
-import { useState } from 'react'
-import { getFeedOptions } from '../api/client/@tanstack/react-query.gen'
-import type { TopIndex } from '../api/client/types.gen'
+import { useState, type ReactNode } from 'react'
+import type { MyGakRule, MyGakScore } from '../api/client/types.gen'
import { cx } from '../lib/utils'
-import { mix, shareUrl, useMyGak } from './myGakState'
+import { gakName, shareUrl, SLOTS, type MyGak, type Slot, useMyGak, useMyGakScores } from './myGakState'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
-import { Ic, Sec } from './ui'
+import { Sec } from './ui'
-function Bar({ g, low }: { g: TopIndex; low: boolean }) {
+const SLOT_WORD = Object.fromEntries(SLOTS) as Record
+
+function Score({ s, big }: { s?: MyGakScore; big?: boolean }) {
+ const v = s?.score
return (
-
- {g.name}
- {g.score}
-
-
-
-
+
+ {v ?? '–'}
+
)
}
-/** 오늘 탭의 내 각 줄: 섞은 각 카드들과 새로 섞기 */
-export function MyGakRow({ stories }: { stories: TopIndex[] }) {
+function Reasons({ s }: { s?: MyGakScore }) {
+ if (!s?.slot) return 예보를 불러오는 중이에요
+ return (
+
+ {SLOT_WORD[s.slot as Slot]}
+ {s.reasons?.join(' · ')}
+
+ )
+}
+
+/** 오늘 탭의 내 각 줄: 내가 정한 조건으로 매긴 오늘 점수 */
+export function MyGakRow() {
const { open } = useSheet()
- const { pairs, remove } = useMyGak()
- const [copied, setCopied] = useState(null)
- const send = (ids: number[], name: string) => {
- const url = shareUrl(ids)
+ const { items, remove } = useMyGak()
+ const scores = useMyGakScores(items.map((g) => g.rule)).data?.scores ?? []
+ const [copied, setCopied] = useState(null)
+ const send = (g: MyGak, i: number) => {
+ const url = shareUrl(g)
if (navigator.share) {
- navigator.share({ title: `${name} · 날씨각`, url }).catch((e: unknown) => {
+ navigator.share({ title: `${g.name} · 날씨각`, url }).catch((e: unknown) => {
if (!(e instanceof DOMException && e.name === 'AbortError')) console.error('[myGak] share', e)
})
return
}
navigator.clipboard.writeText(url).then(
- () => setCopied(ids.join()),
+ () => setCopied(i),
(e: unknown) => console.error('[myGak] copy', e),
)
}
- if (!stories.length) return null
return (
<>
-
+
- {pairs.map((p) => {
- const m = mix(stories, p.ids)
- if (!m) return null
- return (
-
-
-
-
- {m.name}
- {m.score}
-
-
-
-
-
-
-
+ {items.map((g, i) => (
+
+
+ {g.name}
+
- )
- })}
+
+
+
+
+
+
+ ))}
>
)
}
-/** 섞을 각 고르기와 미리보기. ids 가 둘이면(받은 링크) 바로 미리보기 */
-export function MixSheet({ ids: start = [], shared = false, onDone }: { ids?: number[]; shared?: boolean; onDone: () => void }) {
+function Row({ label, on, onToggle, children }: { label: string; on: boolean; onToggle: () => void; children: ReactNode }) {
+ return (
+
+
+ {on ?
{children}
:
상관없음}
+
+ )
+}
+
+function Num({ value, onChange, min, max, label }: { value: number; onChange: (v: number) => void; min: number; max: number; label: string }) {
+ return (
+
{
+ const v = Number(e.target.value)
+ if (e.target.value !== '' && Number.isFinite(v)) onChange(Math.min(max, Math.max(min, v)))
+ }}
+ className="w-[58px] rounded-xl bg-[#f3f6fb] px-2 py-1.5 text-center tabular-nums"
+ />
+ )
+}
+
+function Choice
({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
+ return (
+
+ {options.map(([k, word]) => (
+
+ ))}
+
+ )
+}
+
+type Filled = { [K in keyof T]-?: NonNullable }
+const DEFAULT_RULE: Filled = { temp: [15, 25], rain: 'dry', wind_max: 4, air: 'normal', humidity: [30, 60], slots: ['morning', 'day', 'evening', 'night'] }
+type Cond = 'temp' | 'rain' | 'wind_max' | 'air' | 'humidity'
+
+/** 내 각 만들기(이름과 조건)와 미리보기. shared 면 받은 각을 내 동네 점수로 보여 주고 가져오기만 */
+export function MixSheet({ shared, onDone }: { shared?: MyGak; onDone: () => void }) {
const { region } = useRegion()
- const stories = useQuery(getFeedOptions({ query: { region: region.code } })).data?.stories ?? []
- const { mixable, has, create, pending } = useMyGak()
- const [ids, setIds] = useState(start.slice(0, 2))
- const choices = stories.filter((g) => mixable.has(g.index_id))
- const m = ids.length === 2 ? mix(stories, ids) : null
- const owned = ids.length === 2 && has(ids)
- const toggle = (id: number) => setIds((now) => (now.includes(id) ? now.filter((x) => x !== id) : now.length < 2 ? [...now, id] : [now[0], id]))
+ const { create, pending, failed } = useMyGak()
+ const [name, setName] = useState(shared?.name ?? '')
+ const [vals, setVals] = useState({ ...DEFAULT_RULE, ...(shared?.rule ?? {}) } as typeof DEFAULT_RULE)
+ const [on, setOn] = useState>(
+ shared ? { temp: !!shared.rule.temp, rain: !!shared.rule.rain, wind_max: shared.rule.wind_max != null, air: !!shared.rule.air, humidity: !!shared.rule.humidity } : { temp: true, rain: true, wind_max: false, air: false, humidity: false },
+ )
+ const set = (k: K, v: (typeof vals)[K]) => setVals((x) => ({ ...x, [k]: v }))
+ const toggle = (k: Cond) => setOn((x) => ({ ...x, [k]: !x[k] }))
+ const rule: MyGakRule = { slots: vals.slots, ...(Object.fromEntries((Object.keys(on) as Cond[]).filter((k) => on[k]).map((k) => [k, vals[k]])) as Partial) }
+ const valid = Object.values(on).some(Boolean) && vals.slots.length > 0 && (!on.temp || vals.temp[0] < vals.temp[1]) && (!on.humidity || vals.humidity[0] < vals.humidity[1])
+ const score = useMyGakScores(valid ? [rule] : []).data?.scores?.[0]
+ const title = gakName(name) || '이름 없는 각'
+ const toggleSlot = (s: Slot) => set('slots', vals.slots.includes(s) ? vals.slots.filter((x) => x !== s) : SLOTS.map(([k]) => k).filter((k) => k === s || vals.slots.includes(k)))
return (
- {!shared && (
- <>
-
{ids.length === 2 ? '이 둘을 섞어요' : ids.length ? '하나 더 골라요' : '섞을 각 두 개를 골라요'}
-
함께 할 일끼리 골라요. 점수는 둘 중 낮은 쪽이에요
-
- {choices.map((g) => {
- const on = ids.includes(g.index_id)
- return (
-
- )
- })}
-
- >
+ {shared ? (
+
친구가 보낸 각이에요. {region.name} 기준 점수예요
+ ) : (
+
)}
- {m && (
-
- {shared &&
친구가 보낸 각이에요. {region.name} 기준 점수예요
}
-
-
-
- {m.name}
- {m.score}
-
-
-
-
- {m.a.score === m.b.score ? '두 각 점수가 같아요' : `오늘은 ${m.low.name} 점수를 따라가요`}
-
+
+
+
+ {title}
+
+
+ {valid ?
:
조건과 시간대를 하나 이상 골라요
}
+
+ {failed &&
저장하지 못했어요. 이름에 링크나 긴 숫자가 있으면 빼 주세요
}
)
diff --git a/frontend/src/b/myGakState.ts b/frontend/src/b/myGakState.ts
index 66968d5..82ae29d 100644
--- a/frontend/src/b/myGakState.ts
+++ b/frontend/src/b/myGakState.ts
@@ -2,22 +2,29 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useEffect, useSyncExternalStore } from 'react'
import { SITE_URL } from '../api/setup'
import { addMyGakMutation, deleteMyGakMutation, listMyGakOptions, listMyGakQueryKey } from '../api/client/@tanstack/react-query.gen'
-import type { TopIndex } from '../api/client/types.gen'
+import { scoreMyGak } from '../api/client/sdk.gen'
+import type { MyGakRule, MyGakScore } from '../api/client/types.gen'
import { useAuth } from './authContext'
+import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
-const KEY = 'nalssigak.b.myGak'
+const KEY = 'nalssigak.b.myRule'
-/** 로그인하지 않으면 이 기기에 하나만 */
-export type Pair = { id?: number; ids: [number, number] }
+export type Slot = 'morning' | 'day' | 'evening' | 'night'
+export const SLOTS: [Slot, string][] = [
+ ['morning', '아침'],
+ ['day', '낮'],
+ ['evening', '저녁'],
+ ['night', '밤'],
+]
-const sameIds = (a: number[], b: number[]) => a.length === 2 && b.length === 2 && a[0] === b[0] && a[1] === b[1]
-const sorted = (ids: number[]) => [...ids].sort((x, y) => x - y) as [number, number]
+/** 내 각 하나. 로그인하지 않으면 이 기기에 하나만(id 없음) */
+export type MyGak = { id?: number; name: string; rule: MyGakRule }
-function readLocal(): [number, number] | null {
+function readLocal(): MyGak | null {
try {
const raw = localStorage.getItem(KEY)
- return raw ? sorted(JSON.parse(raw) as number[]) : null
+ return raw ? (JSON.parse(raw) as MyGak) : null
} catch {
// 사파리 프라이빗 모드 등에서는 저장소를 못 쓴다 → 이번 방문엔 없는 것으로
return null
@@ -32,68 +39,94 @@ const subscribe = (cb: () => void) => {
return () => listeners.delete(cb)
}
-function setLocal(ids: [number, number] | null) {
- local = ids
+function setLocal(g: MyGak | null) {
+ local = g
listeners.forEach((cb) => cb())
try {
- if (ids) localStorage.setItem(KEY, JSON.stringify(ids))
+ if (g) localStorage.setItem(KEY, JSON.stringify(g))
else localStorage.removeItem(KEY)
} catch (e) {
console.warn('[myGak] 기기에 저장하지 못함', e)
}
}
-/** 두 각 이름을 이어 붙인 이름: 러닝각 + 치맥각 → 러닝·치맥각 */
-const pairName = (a: TopIndex, b: TopIndex) => `${a.name.replace(/각$/, '')}·${b.name}`
-
-/** 섞은 각 점수: 둘 다 좋아야 좋은 날이라 낮은 쪽 */
-export function mix(stories: TopIndex[], ids: number[]) {
- const a = stories.find((g) => g.index_id === ids[0])
- const b = stories.find((g) => g.index_id === ids[1])
- if (!a || !b) return null
- return { a, b, name: pairName(a, b), score: Math.min(a.score, b.score), low: a.score <= b.score ? a : b }
+/** 이름 끝에 '각'을 붙인다 (서버와 같은 규칙) */
+export const gakName = (name: string) => {
+ const n = name.trim().replace(/\s+/g, ' ')
+ return n && !n.endsWith('각') ? `${n}각` : n
}
-export const shareUrl = (ids: number[]) => `${SITE_URL}/?mix=${ids.join(',')}`
+/** 받은 링크(/?my=...)에 이름과 조건을 그대로 담는다 */
+export function shareUrl(g: MyGak) {
+ const json = JSON.stringify({ n: g.name, r: g.rule })
+ const b64 = btoa(String.fromCharCode(...new TextEncoder().encode(json)))
+ return `${SITE_URL}/?my=${b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')}`
+}
+
+export function fromShare(code: string): MyGak | null {
+ try {
+ const bin = atob(code.replace(/-/g, '+').replace(/_/g, '/'))
+ const v = JSON.parse(new TextDecoder().decode(Uint8Array.from(bin, (c) => c.charCodeAt(0)))) as { n?: unknown; r?: unknown }
+ return typeof v.n === 'string' && v.r && typeof v.r === 'object' ? { name: v.n, rule: v.r as MyGakRule } : null
+ } catch (e) {
+ console.warn('[myGak] 받은 링크를 읽지 못함', e)
+ return null
+ }
+}
+
+/** 조건들의 우리 동네 오늘 점수. 조건이 같으면 캐시를 같이 쓴다 */
+export function useMyGakScores(rules: MyGakRule[]) {
+ const { region } = useRegion()
+ return useQuery({
+ queryKey: ['myGakScore', region.code, rules],
+ enabled: rules.length > 0,
+ staleTime: 5 * 60_000,
+ queryFn: async (): Promise<{ nowSlot?: Slot | null; scores: MyGakScore[] }> => {
+ const { data } = await scoreMyGak({ body: { region_code: region.code, rules } })
+ if (!data.result?.success) throw new Error(data.result?.desc ?? 'score')
+ return { nowSlot: data.now_slot, scores: data.scores ?? [] }
+ },
+ })
+}
export function useMyGak() {
const { loggedIn } = useAuth()
const { open } = useSheet()
const queryClient = useQueryClient()
- const q = useQuery(listMyGakOptions())
+ const q = useQuery({ ...listMyGakOptions(), enabled: loggedIn })
const saved = useSyncExternalStore(subscribe, () => local)
- const add = useMutation({ ...addMyGakMutation(), onSuccess: () => queryClient.invalidateQueries({ queryKey: listMyGakQueryKey() }) })
- const del = useMutation({ ...deleteMyGakMutation(), onSuccess: () => queryClient.invalidateQueries({ queryKey: listMyGakQueryKey() }) })
+ const refresh = () => queryClient.invalidateQueries({ queryKey: listMyGakQueryKey() })
+ const add = useMutation({ ...addMyGakMutation(), onSuccess: refresh })
+ const del = useMutation({ ...deleteMyGakMutation(), onSuccess: refresh })
// 로그인하면 이 기기에 만들어 둔 각을 계정으로 옮긴다
const { mutate } = add
useEffect(() => {
if (!loggedIn || !saved) return
- mutate({ body: { index_ids: saved } }, { onSuccess: () => setLocal(null) })
+ mutate({ body: { name: saved.name, rule: saved.rule } }, { onSuccess: () => setLocal(null) })
}, [loggedIn, saved, mutate])
- const pairs: Pair[] = loggedIn ? (q.data?.items ?? []).map((g) => ({ id: g.my_gak_id, ids: sorted(g.index_ids) })) : saved ? [{ ids: saved }] : []
- const has = (ids: number[]) => pairs.some((p) => sameIds(p.ids, sorted(ids)))
+ const items: MyGak[] = loggedIn ? (q.data?.items ?? []).map((g) => ({ id: g.my_gak_id, name: g.name, rule: g.rule })) : saved ? [saved] : []
/** 로그인 없이 두 번째를 만들려 하면 로그인 창을 띄운다 */
- const create = (ids: number[], onDone?: () => void) => {
- const two = sorted(ids)
+ const create = (g: MyGak, onDone?: () => void) => {
+ const item = { name: gakName(g.name), rule: g.rule }
if (loggedIn) {
- add.mutate({ body: { index_ids: two } }, { onSuccess: onDone })
+ add.mutate({ body: item }, { onSuccess: (res) => res.result?.success && onDone?.() })
return
}
- if (saved && !sameIds(saved, two)) {
+ if (saved) {
open({ type: 'login' })
return
}
- setLocal(two)
+ setLocal(item)
onDone?.()
}
- const remove = (p: Pair) => {
- if (p.id != null) return del.mutate({ path: { my_gak_id: p.id } })
+ const remove = (g: MyGak) => {
+ if (g.id != null) return del.mutate({ path: { my_gak_id: g.id } })
setLocal(null)
}
- return { mixable: new Set(q.data?.mixable ?? []), pairs, has, create, remove, pending: add.isPending }
+ return { items, create, remove, pending: add.isPending, failed: add.data?.result?.success === false }
}
diff --git a/frontend/src/b/shareCards.tsx b/frontend/src/b/shareCards.tsx
new file mode 100644
index 0000000..49bf9ad
--- /dev/null
+++ b/frontend/src/b/shareCards.tsx
@@ -0,0 +1,88 @@
+import type { Ref } from 'react'
+import { createPortal } from 'react-dom'
+import type { TopIndex } from '../api/client/types.gen'
+import { cx } from '../lib/utils'
+import { MEDALS } from './lib'
+import { Ic } from './ui'
+
+/** 공유 이미지 전용 틀. 화면 밖에 그려 두고 보내기 때 이것만 찍는다 (화면의 버튼은 이미지에서 빠지므로 글자만으로 만든다) */
+function Offscreen({ children }: { children: React.ReactNode }) {
+ return createPortal(
+
+ {children}
+
,
+ document.body,
+ )
+}
+
+export type HeroShare = {
+ kind: string
+ sky: string
+ date: string
+ place: string
+ label: string
+ score?: number | null
+ bubble?: string | null
+ summary?: string | null
+ status: { label: string; value: string; warn: boolean }[]
+ slots: { label: string; icon: string; temp: string; on: boolean }[]
+}
+
+export function HeroShareCard({ d, ref }: { d: HeroShare; ref: Ref
}) {
+ return (
+
+
+
+ {d.date} · {d.place}
+
+
+
+ {d.label}
+ {d.score ?? '–'}
+
+
+
{d.bubble}
+ {d.summary &&
{d.summary}
}
+
+ {d.status.map((x) => (
+
+ {x.label} {x.value}
+
+ ))}
+
+
+ {d.slots.map((s) => (
+
+ {s.label}
+
+ {s.temp}
+
+ ))}
+
+
+
+ )
+}
+
+export function GakShareCard({ items, title, ref }: { items: TopIndex[]; title: string; ref: Ref }) {
+ return (
+
+
+
{title}
+
+ {items.map((g, i) => (
+ -
+ {i < 3 ? : {i + 1}}
+
+
+ {g.name}
+ {g.summary && {g.summary}}
+
+ {g.score}
+
+ ))}
+
+
+
+ )
+}
diff --git a/frontend/src/b/sheetContext.ts b/frontend/src/b/sheetContext.ts
index f5e2aa9..954d6e2 100644
--- a/frontend/src/b/sheetContext.ts
+++ b/frontend/src/b/sheetContext.ts
@@ -1,3 +1,4 @@
+import type { MyGak } from './myGakState'
import { createContext, use } from 'react'
export type SharePayload = { title: string; slides: HTMLElement[] }
@@ -12,7 +13,7 @@ export type SheetState =
| { type: 'login'; then?: CommentsState }
| { type: 'me' }
| { type: 'region' }
- | { type: 'mix'; ids?: number[]; shared?: boolean }
+ | { type: 'mix'; shared?: MyGak }
| null
export type SheetApi = { open: (s: Exclude) => void; close: () => void }
diff --git a/frontend/src/b/talk.tsx b/frontend/src/b/talk.tsx
index 1d86dc4..15f51c2 100644
--- a/frontend/src/b/talk.tsx
+++ b/frontend/src/b/talk.tsx
@@ -1,24 +1,26 @@
-import { useInfiniteQuery, useMutation, useQueryClient } from '@tanstack/react-query'
-import { useState, type FormEvent } from 'react'
+import { useMutation, useQueryClient } from '@tanstack/react-query'
+import { useEffect, useRef, useState, type ChangeEvent, type FormEvent } from 'react'
import {
addTalkMutation,
blockTalkAuthorMutation,
deleteTalkMutation,
likeTalkMutation,
- listTalksInfiniteOptions,
reportTalkMutation,
unlikeTalkMutation,
} from '../api/client/@tanstack/react-query.gen'
+import { uploadTalkImage } from '../api/client/sdk.gen'
import { TalkReport, type TalkData } from '../api/client/types.gen'
+import { API_BASE_URL } from '../api/setup'
import { cx } from '../lib/utils'
import { useAuth } from './authContext'
-import { ago, kst, loadOf } from './lib'
+import { ago, kst } from './lib'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
import { HeartIcon } from './svg'
-import { Avatar, Sec, StateBox, TAP44 } from './ui'
+import { Avatar, TAP44 } from './ui'
const BODY_MAX = 100
+const PHOTO_MAX = 10 * 1024 * 1024
// 서버 ErrorType 이름 → 안내
const WRITE_ERRORS: Record = {
@@ -45,7 +47,7 @@ function useRefreshTalks() {
return () => queryClient.invalidateQueries({ queryKey: [{ _id: 'listTalks' }] })
}
-function Composer() {
+function Composer({ onDone }: { onDone?: (t: TalkData) => void }) {
const { region } = useRegion()
const { loggedIn, me } = useAuth()
const { open } = useSheet()
@@ -53,22 +55,62 @@ function Composer() {
const add = useMutation(addTalkMutation())
const [text, setText] = useState('')
const [error, setError] = useState(null)
+ const [photo, setPhoto] = useState<{ file: File; src: string } | null>(null)
+ const [uploading, setUploading] = useState(false)
+ const fileRef = useRef(null)
+ const busy = add.isPending || uploading
+
+ useEffect(() => {
+ if (!photo) return
+ return () => URL.revokeObjectURL(photo.src)
+ }, [photo])
+
+ const pick = (e: ChangeEvent) => {
+ const file = e.target.files?.[0]
+ e.target.value = ''
+ if (!file) return
+ if (file.size > PHOTO_MAX) return setError('사진은 10MB까지 올릴 수 있어요.')
+ setError(null)
+ setPhoto({ file, src: URL.createObjectURL(file) })
+ }
+
+ // 사진이 있으면 먼저 올려 주소를 받고, 그 주소를 글에 붙인다
+ const upload = async (): Promise => {
+ if (!photo) return undefined
+ setUploading(true)
+ try {
+ const { data } = await uploadTalkImage({ body: { file: photo.file } })
+ if (!data.result?.success || !data.image) throw new Error(data.result?.desc ?? 'upload')
+ return data.image
+ } finally {
+ setUploading(false)
+ }
+ }
const submit = (e: FormEvent) => {
e.preventDefault()
if (!loggedIn) return open({ type: 'login' })
const body = text.trim()
- if (!body || add.isPending) return
+ if (!body || busy) return
setError(null)
- add.mutate(
- { body: { region_code: region.code, body } },
- {
- onSuccess: (res) => {
- if (!res.result?.success) return setError(WRITE_ERRORS[res.result?.desc ?? ''] ?? '글을 올리지 못했어요. 다시 해 주세요.')
- setText('')
- refresh()
- },
- onError: () => setError('글을 올리지 못했어요. 다시 해 주세요.'),
+ upload().then(
+ (image) =>
+ add.mutate(
+ { body: { region_code: region.code, body, image } },
+ {
+ onSuccess: (res) => {
+ if (!res.result?.success) return setError(WRITE_ERRORS[res.result?.desc ?? ''] ?? '글을 올리지 못했어요. 다시 해 주세요.')
+ setText('')
+ setPhoto(null)
+ refresh()
+ if (res.talk) onDone?.(res.talk)
+ },
+ onError: () => setError('글을 올리지 못했어요. 다시 해 주세요.'),
+ },
+ ),
+ (e: unknown) => {
+ console.error('[talk] photo upload', e)
+ setError('사진을 올리지 못했어요. 사진 파일인지 확인해 주세요.')
},
)
}
@@ -79,20 +121,32 @@ function Composer() {
value={text}
onChange={(e) => setText(e.target.value)}
onFocus={() => !loggedIn && open({ type: 'login' })}
- readOnly={add.isPending}
+ readOnly={busy}
maxLength={BODY_MAX}
rows={2}
placeholder={`지금 ${region.name.split(' ').at(-1)} 날씨 어때요?`}
aria-label="동네 이야기 쓰기"
className="w-full resize-none rounded-2xl bg-[#f3f6fb] px-3 py-2.5 text-[14.5px]"
/>
+ {photo && (
+
+

+
+
+ )}
+
- {me ? `${me.nickname} · ${region.name.split(' ').at(-1)} · 지금 날씨가 함께 올라가요` : '로그인하면 쓸 수 있어요'}
+
+ {me ? `${me.nickname} · ${region.name.split(' ').at(-1)} · 지금 날씨가 함께 올라가요` : '로그인하면 쓸 수 있어요'}
{text.length}/{BODY_MAX}
-
{error && (
@@ -119,7 +173,6 @@ function TalkRow({ t }: { t: TalkData }) {
const [failed, setFailed] = useState(false)
const toggle = () => {
- if (!loggedIn) return open({ type: 'login' })
if (like.isPending || unlike.isPending) return
const next = !liked
setLiked(next)
@@ -160,6 +213,7 @@ function TalkRow({ t }: { t: TalkData }) {
{[t.region_name, slotWord(t.created_at), t.weather].filter(Boolean).join(' · ')}
{t.body}
+ {t.image &&
}
{ago(t.created_at)} · 좋아요 {count}개 ·{' '}
setMenu(menu === 'closed' ? 'open' : 'closed')} aria-expanded={menu !== 'closed'} className="cursor-pointer font-bold text-(--ink3)">
@@ -206,30 +260,20 @@ function TalkRow({ t }: { t: TalkData }) {
}
/** 이야기 탭: 쓰기 칸과 전국 최신 글 (아래로 더 받기) */
-export function TalkPage() {
- const list = useInfiniteQuery({
- ...listTalksInfiniteOptions(),
- initialPageParam: {},
- getNextPageParam: (last) => last.next_cursor ?? undefined,
- })
- const talks = list.data?.pages.flatMap((p) => p.talks ?? []) ?? []
- const load = loadOf(list)
+/** 피드 위 쓰는 칸. 늘 펼쳐 두고, 방금 올린 글은 바로 아래에 보인다 (피드 사이 글은 새로 받을 때 섞인다) */
+export function FeedComposer({ onPosted }: { onPosted: (t: TalkData) => void }) {
return (
-
-
-
-
- {talks.length ? (
- talks.map((t) => )
- ) : (
- list.refetch()} empty="아직 글이 없어요. 첫 이야기를 남겨 보세요." className="inset-0" />
- )}
- {list.hasNextPage && (
- list.fetchNextPage()} disabled={list.isFetchingNextPage} className="w-full cursor-pointer border-t border-(--line) py-2.5 text-center text-sm font-bold text-(--ink2) disabled:opacity-50">
- {list.isFetchingNextPage ? '불러오는 중…' : '더 보기'}
-
- )}
-
-
+
+
+
+ )
+}
+
+/** 피드에 끼우는 글 한 장 */
+export function TalkCard({ t }: { t: TalkData }) {
+ return (
+
+
+
)
}
diff --git a/frontend/src/b/talkState.ts b/frontend/src/b/talkState.ts
new file mode 100644
index 0000000..82fd87c
--- /dev/null
+++ b/frontend/src/b/talkState.ts
@@ -0,0 +1,12 @@
+import { useInfiniteQuery } from '@tanstack/react-query'
+import { listTalksInfiniteOptions } from '../api/client/@tanstack/react-query.gen'
+
+/** 사람들이 쓴 글. 오늘 피드에 운영 포스트 사이사이 섞는다 */
+export function useFeedTalks() {
+ const list = useInfiniteQuery({
+ ...listTalksInfiniteOptions(),
+ initialPageParam: {},
+ getNextPageParam: (last) => last.next_cursor ?? undefined,
+ })
+ return list.data?.pages.flatMap((p) => p.talks ?? []) ?? []
+}