refactor: 웹·앱 공통 코드를 shared 패키지로 분리 (npm workspaces)

- API 클라이언트·토큰 갱신·순수 함수를 shared/ (@nalssigak/shared) 로 옮김
- 토큰 저장소·API 주소는 configureApi 로 플랫폼에서 넣는다 (웹 localStorage)
- 루트 package.json 에 frontend·mobile·shared workspaces, lock 파일 하나로
- 웹 Docker 빌드 대상을 저장소 루트로 (compose context ., 루트 .dockerignore)
This commit is contained in:
minaChoi committed 2026-10-14 14:27:47 +09:00
1 parent 0d6ab29552
commit 2ab2271d61
51 files changed
+15139 -2994

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
# 저장소 루트를 빌드 대상으로 쓰는 건 frontend 이미지뿐이라 frontend·shared·루트 package 파일만 넘긴다
*
!package.json
!package-lock.json
!frontend
!shared
!mobile/package.json
**/node_modules
**/dist
**/*.log
**/.DS_Store
+3
View File
@@ -4,6 +4,9 @@
.env.* .env.*
!.env.example !.env.example
# npm workspaces 의존성 (frontend·mobile·shared 가 루트 하나를 같이 쓴다)
node_modules/
# Python 바이트코드/캐시 # Python 바이트코드/캐시
__pycache__/ __pycache__/
*.py[cod] *.py[cod]
+7 -3
View File
@@ -4,7 +4,8 @@ services:
# 운영형: docker compose up --build → http://localhost:8080 # 운영형: docker compose up --build → http://localhost:8080
frontend: frontend:
build: build:
context: ./frontend context: .
dockerfile: frontend/Dockerfile
target: prod target: prod
args: args:
# 비우면 같은 주소의 /v1 로 부르고 nginx 가 backend 로 넘긴다 # 비우면 같은 주소의 /v1 로 부르고 nginx 가 backend 로 넘긴다
@@ -19,13 +20,16 @@ services:
frontend-dev: frontend-dev:
profiles: ["dev"] profiles: ["dev"]
build: build:
context: ./frontend context: .
dockerfile: frontend/Dockerfile
target: dev target: dev
ports: ports:
- "5173:5173" - "5173:5173"
volumes: volumes:
- ./frontend:/app - ./frontend:/app/frontend
- ./shared:/app/shared
- /app/node_modules - /app/node_modules
- /app/frontend/node_modules
environment: environment:
- CHOKIDAR_USEPOLLING=true - CHOKIDAR_USEPOLLING=true
- VITE_SITE_URL=${VITE_SITE_URL:-https://weather.o2o.kr} - VITE_SITE_URL=${VITE_SITE_URL:-https://weather.o2o.kr}
-7
View File
@@ -1,7 +0,0 @@
node_modules
dist
.git
*.log
.DS_Store
Dockerfile
.dockerignore
+13 -5
View File
@@ -2,13 +2,19 @@
# ---- deps: package.json이 바뀔 때만 다시 설치 ---- # ---- deps: package.json이 바뀔 때만 다시 설치 ----
FROM node:24-alpine AS deps FROM node:24-alpine AS deps
# 빌드 대상은 저장소 루트(npm workspaces). 웹에 필요한 frontend·shared 만 설치한다
WORKDIR /app WORKDIR /app
COPY package.json package-lock.json ./ COPY package.json package-lock.json ./
RUN npm ci COPY frontend/package.json frontend/
COPY shared/package.json shared/
COPY mobile/package.json mobile/
RUN npm ci -w frontend -w shared
# ---- dev: 코드 수정이 바로 반영되는 개발 서버 ---- # ---- dev: 코드 수정이 바로 반영되는 개발 서버 ----
FROM deps AS dev FROM deps AS dev
COPY . . COPY shared shared
COPY frontend frontend
WORKDIR /app/frontend
EXPOSE 5173 EXPOSE 5173
CMD ["npm", "run", "dev", "--", "--host", "0.0.0.0", "--port", "5173"] CMD ["npm", "run", "dev", "--", "--host", "0.0.0.0", "--port", "5173"]
@@ -18,12 +24,14 @@ ARG VITE_API_BASE_URL=""
ENV VITE_API_BASE_URL=$VITE_API_BASE_URL ENV VITE_API_BASE_URL=$VITE_API_BASE_URL
ARG VITE_SITE_URL="" ARG VITE_SITE_URL=""
ENV VITE_SITE_URL=$VITE_SITE_URL ENV VITE_SITE_URL=$VITE_SITE_URL
COPY . . COPY shared shared
COPY frontend frontend
WORKDIR /app/frontend
RUN npm run build RUN npm run build
# ---- prod: nginx로 정적 파일 제공 ---- # ---- prod: nginx로 정적 파일 제공 ----
FROM nginx:1.29-alpine AS prod FROM nginx:1.29-alpine AS prod
COPY nginx.conf /etc/nginx/conf.d/default.conf COPY frontend/nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/dist /usr/share/nginx/html COPY --from=build /app/frontend/dist /usr/share/nginx/html
EXPOSE 80 EXPOSE 80
HEALTHCHECK --interval=30s --timeout=3s CMD wget -q -O /dev/null http://127.0.0.1/ || exit 1 HEALTHCHECK --interval=30s --timeout=3s CMD wget -q -O /dev/null http://127.0.0.1/ || exit 1
+1 -1
View File
@@ -2,7 +2,7 @@ import { defineConfig } from '@hey-api/openapi-ts'
export default defineConfig({ export default defineConfig({
input: process.env.OPENAPI_INPUT ?? 'http://localhost:9810/openapi.json', input: process.env.OPENAPI_INPUT ?? 'http://localhost:9810/openapi.json',
output: 'src/api/client', output: '../shared/api/client',
parser: { parser: {
patch: { patch: {
// FastAPI operationId("get_feed_v1_feed_get")에서 "_v1_" 앞만 camelCase로 → getFeed / getFeedOptions / addCommentMutation // FastAPI operationId("get_feed_v1_feed_get")에서 "_v1_" 앞만 camelCase로 → getFeed / getFeedOptions / addCommentMutation
-2691
View File
File diff suppressed because it is too large. Load diff
+1
View File
@@ -11,6 +11,7 @@
"api": "openapi-ts" "api": "openapi-ts"
}, },
"dependencies": { "dependencies": {
"@nalssigak/shared": "*",
"@tailwindcss/vite": "^4.3.3", "@tailwindcss/vite": "^4.3.3",
"@tanstack/react-query": "^5.104.0", "@tanstack/react-query": "^5.104.0",
"embla-carousel-react": "^8.6.0", "embla-carousel-react": "^8.6.0",
+9 -67
View File
@@ -1,72 +1,14 @@
import { client } from './client/client.gen' import { configureApi } from '@nalssigak/shared/api/setup'
import { clearTokens, emitAuthRequired, getAccessToken, getRefreshToken, setTokens } from './auth'
export const API_BASE_URL: string = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:9810' export const API_BASE_URL: string = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:9810'
export const SITE_URL: string = (import.meta.env.VITE_SITE_URL || window.location.origin).replace(/\/+$/, '') export const SITE_URL: string = (import.meta.env.VITE_SITE_URL || window.location.origin).replace(/\/+$/, '')
type Refresh = 'ok' | 'rejected' | 'unreachable' // 사파리 프라이빗 모드 등에서는 localStorage 를 읽는 것만으로 에러가 나서 쓸 때마다 꺼낸다
configureApi({
// 401이 한꺼번에 와도 갱신은 한 번만 baseUrl: API_BASE_URL,
let refreshing: Promise<Refresh> | null = null storage: {
getItem: (key) => localStorage.getItem(key),
/** 서버가 거절하면 'rejected', 네트워크 오류·5xx 면 'unreachable' (이때는 토큰을 지우지 않는다) */ setItem: (key, value) => localStorage.setItem(key, value),
function refreshTokens(): Promise<Refresh> { removeItem: (key) => localStorage.removeItem(key),
refreshing ??= (async (): Promise<Refresh> => { },
const token = getRefreshToken()
if (!token) return 'rejected'
const res = await fetch(`${API_BASE_URL}/v1/auth/refresh`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ refresh_token: token }) })
if (res.status >= 500) return 'unreachable'
const body = res.ok ? await res.json() : null
if (!body?.result?.success || !body.access_token) return 'rejected'
setTokens(body.access_token, body.refresh_token ?? token)
return 'ok'
})()
.catch((): Refresh => 'unreachable')
.finally(() => {
refreshing = null
})
return refreshing
}
const NO_REFRESH = ['/v1/auth/login', '/v1/auth/signup', '/v1/auth/refresh']
/** 같은 요청을 토큰만 바꿔(null 이면 빼고) 다시 보낼 수 있게 복사한다 */
function withToken(request: Request, token: string | null) {
const copy = request.clone()
if (token) copy.headers.set('Authorization', `Bearer ${token}`)
else copy.headers.delete('Authorization')
return copy
}
/**
* 401이면 토큰을 한 번 갱신해 같은 요청을 다시 보낸다.
* 갱신이 거절되면 토큰을 지우고, 로그인 없이 되는 요청은 그냥 다시 보내고, 로그인이 꼭 필요한 요청만 로그인 창을 띄운다.
*/
async function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
const request = input instanceof Request && !init ? input : new Request(input, init)
const retry = request.clone()
const response = await fetch(request)
if (response.status !== 401 || NO_REFRESH.includes(new URL(request.url).pathname)) return response
if (request.headers.has('Authorization')) {
const result = await refreshTokens()
if (result === 'unreachable') return response
if (result === 'ok') {
const again = await fetch(withToken(retry, getAccessToken()))
if (again.status !== 401) return again
}
if (getAccessToken()) clearTokens()
const anonymous = await fetch(withToken(retry, null))
if (anonymous.status !== 401) return anonymous
}
// 로그아웃하다 만료된 거면 로그인 창을 띄우지 않는다
if (new URL(request.url).pathname !== '/v1/auth/logout') emitAuthRequired()
return response
}
client.setConfig({ baseUrl: API_BASE_URL, throwOnError: true, fetch: authFetch })
client.interceptors.request.use((request) => {
const token = getAccessToken()
if (token) request.headers.set('Authorization', `Bearer ${token}`)
return request
}) })
+2 -2
View File
@@ -1,9 +1,9 @@
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react' import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
import { NavLink, Outlet, useLocation } from 'react-router' import { NavLink, Outlet, useLocation } from 'react-router'
import { useIsFetching, useQuery } from '@tanstack/react-query' import { useIsFetching, useQuery } from '@tanstack/react-query'
import { getSeasonWeekOptions } from '../api/client/@tanstack/react-query.gen' import { getSeasonWeekOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { cx } from '../lib/utils' import { cx } from '../lib/utils'
import { kindOfHour, kst, seasonOf, type TimeKind } from './lib' import { kindOfHour, kst, seasonOf, type TimeKind } from '@nalssigak/shared/lib'
import './b.css' import './b.css'
import { AuthProvider } from './auth' import { AuthProvider } from './auth'
import { RegionProvider } from './region' import { RegionProvider } from './region'
+3 -3
View File
@@ -1,9 +1,9 @@
import { useState } from 'react' import { useState } from 'react'
import { useQuery } from '@tanstack/react-query' import { useQuery } from '@tanstack/react-query'
import { listArticlesOptions, listIndicesOptions } from '../api/client/@tanstack/react-query.gen' import { listArticlesOptions, listIndicesOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { ArticleCategory, IndexCategory } from '../api/client/types.gen' import { ArticleCategory, IndexCategory } from '@nalssigak/shared/api/client/types.gen'
import { cx } from '../lib/utils' import { cx } from '../lib/utils'
import { kst, loadOf, MEDALS, seasonOf } from './lib' import { kst, loadOf, MEDALS, seasonOf } from '@nalssigak/shared/lib'
import { useRegion } from './regionContext' import { useRegion } from './regionContext'
import { useSheet } from './sheetContext' import { useSheet } from './sheetContext'
import { Chips, Ic, Sec, Skel, StateBox } from './ui' import { Chips, Ic, Sec, Skel, StateBox } from './ui'
+6 -5
View File
@@ -1,12 +1,13 @@
import { useEffect, useRef, useState, type CSSProperties, type MouseEvent, type ReactNode } from 'react' import { useEffect, useRef, useState, type CSSProperties, type MouseEvent, type ReactNode } from 'react'
import { createPortal } from 'react-dom' import { createPortal } from 'react-dom'
import { PostType, SlotTone, type GakSlide, type HoursSlide, type PlanSlide, type PostData, type ResFeed, type RowsSlide, type SunsetSlide, type WeekSlide } from '../api/client/types.gen' import { PostType, SlotTone, type GakSlide, type HoursSlide, type PlanSlide, type PostData, type ResFeed, type RowsSlide, type SunsetSlide, type WeekSlide } from '@nalssigak/shared/api/client/types.gen'
import { cx } from '../lib/utils' import { cx } from '../lib/utils'
import { cardBg, clockShort, fall } from './lib' import { cardBg, clockShort } from '@nalssigak/shared/lib'
import type { SlideBg } from './types' import { fall } from './lib'
import { deg } from './weatherText' import type { SlideBg } from '@nalssigak/shared/lib/types'
import { deg } from '@nalssigak/shared/lib/weatherText'
import { useMutation, useQueryClient, type QueryClient } from '@tanstack/react-query' import { useMutation, useQueryClient, type QueryClient } from '@tanstack/react-query'
import { likePostMutation, unlikePostMutation } from '../api/client/@tanstack/react-query.gen' import { likePostMutation, unlikePostMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { useAuth } from './authContext' import { useAuth } from './authContext'
import { useSheet } from './sheetContext' import { useSheet } from './sheetContext'
import { CommentIcon, HeartIcon, SendIcon } from './svg' import { CommentIcon, HeartIcon, SendIcon } from './svg'
+4 -3
View File
@@ -1,9 +1,10 @@
import { useState } from 'react' import { useState } from 'react'
import { useQuery } from '@tanstack/react-query' import { useQuery } from '@tanstack/react-query'
import { getSeasonWeekOptions, listArticlesOptions } from '../api/client/@tanstack/react-query.gen' import { getSeasonWeekOptions, listArticlesOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { ArticleCategory } from '../api/client/types.gen' import { ArticleCategory } from '@nalssigak/shared/api/client/types.gen'
import { cx } from '../lib/utils' import { cx } from '../lib/utils'
import { ARTICLE_CAT, cardBg, dateRange, fall, loadOf, shortDay } from './lib' import { cardBg, dateRange, loadOf, shortDay } from '@nalssigak/shared/lib'
import { ARTICLE_CAT, fall } from './lib'
import { useSheet } from './sheetContext' import { useSheet } from './sheetContext'
import { Chips, Ic, Skel, StateBox, Thumb } from './ui' import { Chips, Ic, Skel, StateBox, Thumb } from './ui'
+5 -4
View File
@@ -1,6 +1,6 @@
import { useInfiniteQuery, useMutation, useQuery, useQueryClient, type InfiniteData } from '@tanstack/react-query' import { useInfiniteQuery, useMutation, useQuery, useQueryClient, type InfiniteData } from '@tanstack/react-query'
import { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState, type FormEvent, type ReactNode } from 'react' import { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState, type FormEvent, type ReactNode } from 'react'
import { setTokens, subscribeAuth } from '../api/auth' import { setTokens, subscribeAuth } from '@nalssigak/shared/api/auth'
import { SITE_URL } from '../api/setup' import { SITE_URL } from '../api/setup'
import { import {
addCommentMutation, addCommentMutation,
@@ -18,12 +18,13 @@ import {
signupMutation, signupMutation,
unlikeCommentMutation, unlikeCommentMutation,
updateMeMutation, updateMeMutation,
} from '../api/client/@tanstack/react-query.gen' } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import type { CommentData, Factor, ResAuth, ResCommentList, ResIndexDetail } from '../api/client/types.gen' import type { CommentData, Factor, ResAuth, ResCommentList, ResIndexDetail } from '@nalssigak/shared/api/client/types.gen'
import { track } from '../lib/analytics' import { track } from '../lib/analytics'
import { cx } from '../lib/utils' import { cx } from '../lib/utils'
import { useAuth } from './authContext' import { useAuth } from './authContext'
import { ago, ARTICLE_CAT, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from './lib' import { ago, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from '@nalssigak/shared/lib'
import { ARTICLE_CAT } from './lib'
import { useRegion } from './regionContext' import { useRegion } from './regionContext'
import { useSky } from './skyContext' import { useSky } from './skyContext'
import { SHARE_SIZES, shareImage, type ShareSize } from './storyImage' import { SHARE_SIZES, shareImage, type ShareSize } from './storyImage'
+3 -3
View File
@@ -1,9 +1,9 @@
import { useQuery } from '@tanstack/react-query' import { useQuery } from '@tanstack/react-query'
import { useState, type ReactNode } from 'react' import { useState, type ReactNode } from 'react'
import { getSkyOptions, getSkyRankingOptions } from '../api/client/@tanstack/react-query.gen' import { getSkyOptions, getSkyRankingOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import type { BestTime, SkyPlanData } from '../api/client/types.gen' import type { BestTime, SkyPlanData } from '@nalssigak/shared/api/client/types.gen'
import { cx } from '../lib/utils' import { cx } from '../lib/utils'
import { clockShort, loadOf } from './lib' import { clockShort, loadOf } from '@nalssigak/shared/lib'
import { useRegion } from './regionContext' import { useRegion } from './regionContext'
import { MapLink, Sec, Skel, StateBox } from './ui' import { MapLink, Sec, Skel, StateBox } from './ui'
+6 -51
View File
@@ -1,28 +1,21 @@
import { Fragment, useEffect, useState, type ReactNode } from 'react' import { Fragment, useEffect, useState, type ReactNode } from 'react'
import { Link } from 'react-router' import { Link } from 'react-router'
import { useQuery } from '@tanstack/react-query' import { useQuery } from '@tanstack/react-query'
import { getFeedOptions, getWeatherTodayOptions } from '../api/client/@tanstack/react-query.gen' import { getFeedOptions, getWeatherTodayOptions } from '@nalssigak/shared/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 type { BandArticle, BandEvent, Hero as HeroData, ResWeatherToday, TopIndex } from '@nalssigak/shared/api/client/types.gen'
import { cx } from '../lib/utils' import { cx } from '../lib/utils'
import { cardBg, fall, kindOfHour, kst, type Load, loadOf, MEDALS, type TimeKind, WEEKDAYS } from './lib' import { cardBg, kindOfHour, kst, type Load, loadOf, MEDALS, type TimeKind, WEEKDAYS } from '@nalssigak/shared/lib'
import { fall } from './lib'
import { PostCard, PostCardSkel } from './Post' import { PostCard, PostCardSkel } from './Post'
import { useRegion } from './regionContext' import { useRegion } from './regionContext'
import { useSheet } from './sheetContext' import { useSheet } from './sheetContext'
import { useSky } from './skyContext' import { useSky } from './skyContext'
import { Ic, Rail, Sec, Skel, SkelRail, StateBox, Thumb } from './ui' import { Ic, Rail, Sec, Skel, SkelRail, StateBox, Thumb } from './ui'
import { deg, slotAt } from './weatherText' import { deg, slotAt } from '@nalssigak/shared/lib/weatherText'
import { atSlot, KINDS, moonPath, PREVIEW, SLOT_KEY, WANING, type Weather, WEATHER_ICON, weatherOf } from '@nalssigak/shared/lib/today'
type Mode = 'now' | TimeKind type Mode = 'now' | TimeKind
// 하루 흐름 칸 순서와 칸마다 볼 예보 시각
const KINDS: TimeKind[] = ['morning', 'day', 'sunset', 'night']
const PREVIEW: Record<TimeKind, { label: string; hour: number }> = {
morning: { label: '아침', hour: 7 },
day: { label: '낮', hour: 13 },
sunset: { label: '저녁', hour: 18 },
night: { label: '밤', hour: 22 },
}
// 비·눈 줄기: 위치·주기를 엇갈려 고르게 // 비·눈 줄기: 위치·주기를 엇갈려 고르게
const DROPS = Array.from({ length: 22 }, (_, i) => ({ left: `${(i * 41) % 100}%`, '--top': `${(i * 29) % 90}%`, '--dl': `${((i * 37) % 100) / 100}s`, '--dur': `${0.55 + ((i * 13) % 5) / 10}s` })) const DROPS = Array.from({ length: 22 }, (_, i) => ({ left: `${(i * 41) % 100}%`, '--top': `${(i * 29) % 90}%`, '--dl': `${((i * 37) % 100) / 100}s`, '--dur': `${0.55 + ((i * 13) % 5) / 10}s` }))
const FLAKES = Array.from({ length: 16 }, (_, i) => ({ left: `${(i * 47) % 100}%`, '--top': `${(i * 31) % 90}%`, '--dl': `${((i * 53) % 100) / 25}s`, '--dur': `${3.2 + ((i * 7) % 5) / 2}s` })) const FLAKES = Array.from({ length: 16 }, (_, i) => ({ left: `${(i * 47) % 100}%`, '--top': `${(i * 31) % 90}%`, '--dl': `${((i * 53) % 100) / 25}s`, '--dur': `${3.2 + ((i * 7) % 5) / 2}s` }))
@@ -64,34 +57,8 @@ function heroVal(load: Load, v: ReactNode, skel: string) {
const failed = (load: Load) => load === 'error' || load === 'retrying' const failed = (load: Load) => load === 'error' || load === 'retrying'
// 미리보기 탭과 서버 구간 이름. 저녁 탭(노을 하늘)은 서버의 evening 구간
const SLOT_KEY: Record<TimeKind, string> = { morning: 'morning', day: 'day', sunset: 'evening', night: 'night' }
/** 미리보기 시간대면 이미 받은 구간 점수·순위로 다시 줄 세운다. 그 구간과 안 겹치는 각은 흐리게 끝으로. 구간 값이 없으면(예전 캐시) 그대로 */
function atSlot(items: TopIndex[], kind: TimeKind | null): TopIndex[] {
const k = kind && SLOT_KEY[kind]
if (!k || !items.some((g) => Object.keys(g.slot_ranks ?? {}).length)) return items
const on = items.filter((g) => g.slot_ranks?.[k] != null && g.slots?.[k] != null)
return [
...on.map((g) => ({ ...g, score: g.slots![k], rank: g.slot_ranks![k], active: true })).sort((a, b) => a.rank - b.rank),
...items.filter((g) => !on.includes(g)).map((g) => ({ ...g, active: false })),
]
}
type HeroProps = { hero?: HeroData | null; today?: ResWeatherToday; ranked: TopIndex[]; feedLoad: Load; todayLoad: Load } type HeroProps = { hero?: HeroData | null; today?: ResWeatherToday; ranked: TopIndex[]; feedLoad: Load; todayLoad: Load }
type Weather = 'clear' | 'partly' | 'cloudy' | 'rain' | 'snow' | 'sleet'
/** 예보 칸 하나의 하늘: 비·눈이 오면 그걸, 아니면 구름 양 */
function weatherOf(slot?: WeatherSlot): Weather {
const r = slot?.rain_type
if (r === RainType.RAIN || r === RainType.SHOWER) return 'rain'
if (r === RainType.SNOW) return 'snow'
if (r === RainType.SLEET) return 'sleet'
return slot?.sky === Sky.CLOUDY ? 'cloudy' : slot?.sky === Sky.PARTLY ? 'partly' : 'clear'
}
const WEATHER_ICON: Record<Weather, string> = { clear: 'sun', partly: 'sun_cloud', cloudy: 'cloud', rain: 'rain', snow: 'snow', sleet: 'snow' }
// 구름 수: 구름 많음 둘, 흐림·비·눈 셋 // 구름 수: 구름 많음 둘, 흐림·비·눈 셋
const CLOUDS = [ const CLOUDS = [
{ cls: 'top-9 left-[5%] h-8 w-[84px]', d: '.1s', f: '6s' }, { cls: 'top-9 left-[5%] h-8 w-[84px]', d: '.1s', f: '6s' },
@@ -215,18 +182,6 @@ function Hero({ hero, today, ranked, feedLoad, todayLoad }: HeroProps) {
) )
} }
const WANING = ['기우는 달', '하현달', '그믐달']
/**
* 반지름 r 인 달에서 밝은 쪽(lit) 또는 어두운 쪽 경로. 차오르는 달 기준(오른쪽이 밝음), 기우는 달은 좌우를 뒤집어 쓴다.
* 바깥 반원과 명암 경계(가로 반지름 r·|1-2k| 인 타원 호)로 이루어진다.
*/
function moonPath(pct: number, r: number, lit: boolean) {
const k = pct / 100
const edge = `A${r * Math.abs(1 - 2 * k)},${r} 0 0 ${k < 0.5 ? 0 : 1} 0,${-r}`
return `M0,${-r} A${r},${r} 0 0 ${lit ? 1 : 0} 0,${r} ${edge}`
}
function Stories({ items }: { items: TopIndex[] }) { function Stories({ items }: { items: TopIndex[] }) {
const { open } = useSheet() const { open } = useSheet()
return ( return (
+2 -2
View File
@@ -1,8 +1,8 @@
import { useRef, useState, type ReactNode } from 'react' import { useRef, useState, type ReactNode } from 'react'
import { useQuery } from '@tanstack/react-query' import { useQuery } from '@tanstack/react-query'
import { getWeekOptions, getWeekRankingOptions, listEventsOptions, listPlacesOptions } from '../api/client/@tanstack/react-query.gen' import { getWeekOptions, getWeekRankingOptions, listEventsOptions, listPlacesOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { cx } from '../lib/utils' import { cx } from '../lib/utils'
import { cardBg, dateRange, loadOf, shortDay } from './lib' import { cardBg, dateRange, loadOf, shortDay } from '@nalssigak/shared/lib'
import { useRegion } from './regionContext' import { useRegion } from './regionContext'
import { useSheet } from './sheetContext' import { useSheet } from './sheetContext'
import { Arrows, Chips, Ic, MapLink, Rail, Sec, Skel, SkelRail, StateBox, Thumb } from './ui' import { Arrows, Chips, Ic, MapLink, Rail, Sec, Skel, SkelRail, StateBox, Thumb } from './ui'
+3 -3
View File
@@ -1,8 +1,8 @@
import { useQuery, useQueryClient } from '@tanstack/react-query' import { useQuery, useQueryClient } from '@tanstack/react-query'
import { useEffect, useMemo, useSyncExternalStore, type ReactNode } from 'react' import { useEffect, useMemo, useSyncExternalStore, type ReactNode } from 'react'
import { clearTokens, getAccessToken, subscribeAuth } from '../api/auth' import { clearTokens, getAccessToken, subscribeAuth } from '@nalssigak/shared/api/auth'
import { meOptions } from '../api/client/@tanstack/react-query.gen' import { meOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { logout as logoutOnServer } from '../api/client/sdk.gen' import { logout as logoutOnServer } from '@nalssigak/shared/api/client/sdk.gen'
import { AuthContext } from './authContext' import { AuthContext } from './authContext'
const subscribe = (cb: () => void) => subscribeAuth((reason) => reason === 'change' && cb()) const subscribe = (cb: () => void) => subscribeAuth((reason) => reason === 'change' && cb())
+1 -1
View File
@@ -1,5 +1,5 @@
import { createContext, use } from 'react' import { createContext, use } from 'react'
import type { Me } from '../api/client/types.gen' import type { Me } from '@nalssigak/shared/api/client/types.gen'
/** mePending: 토큰은 있고 내 정보를 받는 중 (아바타 자리를 비워 두지 않으려고) */ /** mePending: 토큰은 있고 내 정보를 받는 중 (아바타 자리를 비워 두지 않으려고) */
export type AuthApi = { loggedIn: boolean; me: Me | null; mePending: boolean; logout: () => void } export type AuthApi = { loggedIn: boolean; me: Me | null; mePending: boolean; logout: () => void }
+2 -131
View File
@@ -1,4 +1,5 @@
import type { CSSProperties } from 'react' import type { CSSProperties } from 'react'
import { ARTICLE_LABEL } from '@nalssigak/shared/lib'
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'])
const OWN = new Set(['fireworks', 'bulb', 'calendar', 'thermo', 'sheaf', 'popup', 'exhibition', 'concert']) const OWN = new Set(['fireworks', 'bulb', 'calendar', 'thermo', 'sheaf', 'popup', 'exhibition', 'concert'])
@@ -10,136 +11,6 @@ export function iconSrc(name: string) {
return `/icons/${SHARED.has(name) ? name : 'sun_cloud'}.png` return `/icons/${SHARED.has(name) ? name : 'sun_cloud'}.png`
} }
export const MEDALS = ['gold', 'silver', 'bronze'] as const
/** 고를 수 있는 프로필 캐릭터 (백엔드 CHARACTERS 와 같아야 한다) */
export const CHARACTERS = [
['rabbit', '토끼'],
['bear', '곰'],
['dog', '강아지'],
['sun', '해님'],
['moon', '달님'],
['cloud', '구름'],
] as const
/** 프로필 배경색 (백엔드 COLORS 와 같아야 한다) */
export const AVATAR_COLORS: Record<string, string> = { orange: '#ff8e4e', blue: '#4f97e3', green: '#1f9d62', purple: '#7a5cd6', pink: '#d6457a', brown: '#a8643a' }
/** 오늘 기분 (백엔드 MOODS 와 같아야 한다) */
export const MOODS = [
['clear', '☀️', '맑음'],
['partly', '⛅', '구름 조금'],
['cloudy', '☁️', '흐림'],
['rain', '🌧️', '비'],
['thunder', '⚡', '번개'],
['snow', '❄️', '눈'],
['fog', '🌫️', '안개'],
['rainbow', '🌈', '무지개'],
] as const
export const moodEmoji = (mood?: string | null) => MOODS.find(([k]) => k === mood)?.[1]
export const fall = (d: string, f = '4.8s', amp?: string) => ({ '--d': d, '--f': f, ...(amp ? { '--amp': amp } : {}) }) as CSSProperties export const fall = (d: string, f = '4.8s', amp?: string) => ({ '--d': d, '--f': f, ...(amp ? { '--amp': amp } : {}) }) as CSSProperties
export const WEEKDAYS = ['일', '월', '화', '수', '목', '금', '토'] as const export const ARTICLE_CAT: Record<number, [string, string]> = { 1: [ARTICLE_LABEL[1], 'text-[#1f9d62]'], 2: [ARTICLE_LABEL[2], 'text-[#7a5cd6]'], 3: [ARTICLE_LABEL[3], 'text-(--orange)'] }
// 달(1~12) → 계절 이름과 아이콘. 봄 3–5 · 여름 6–8 · 가을 9–11 · 겨울 12–2 (서버 각 제철 기준과 같다)
const SEASONS: [string, string][] = [['겨울', 'snow'], ['봄', 'garden'], ['여름', 'sun'], ['가을', 'maple']]
export const seasonOf = (month: number) => SEASONS[Math.floor((month % 12) / 3)]
const KST = new Intl.DateTimeFormat('en-US', { timeZone: 'Asia/Seoul', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', hourCycle: 'h23', weekday: 'short' })
const WD_EN = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
/** 한국 시각으로 쪼개기 (브라우저 시간대와 상관없이) */
export function kst(input: string | Date) {
const parts = Object.fromEntries(KST.formatToParts(typeof input === 'string' ? new Date(input) : input).map((p) => [p.type, p.value]))
return { y: +parts.year, mo: +parts.month, d: +parts.day, h: +parts.hour, mi: +parts.minute, wd: WD_EN.indexOf(parts.weekday) }
}
const h12 = (h: number) => h % 12 || 12
/** 18:25 → "18:25" (포스트·플랜과 같은 24시간제) */
export function clockShort(iso: string) {
const t = kst(iso)
return `${t.h}:${String(t.mi).padStart(2, '0')}`
}
const COMPASS = ['북', '북북동', '북동', '동북동', '동', '동남동', '남동', '남남동', '남', '남남서', '남서', '서남서', '서', '서북서', '북서', '북북서']
/** 방위각 → 16방위 이름. 263 → "서" */
/** 네이버 지도에서 장소 이름(또는 주소)으로 찾기 */
export const naverMap = (query: string) => `https://map.naver.com/p/search/${encodeURIComponent(query)}`
export const compass = (deg: number) => COMPASS[Math.round(deg / 22.5) % 16]
/** 18:30 → "6시 반", 18:25 → "6시 25분" */
export function timeWords(iso: string) {
const t = kst(iso)
return `${h12(t.h)}시${t.mi === 0 ? '' : t.mi === 30 ? ' 반' : ` ${t.mi}분`}`
}
/** 발표 시각 → "방금" · "12분 전" · "3시간 전" */
export function ago(iso: string | null | undefined, now = Date.now()) {
if (!iso) return '오늘'
const min = Math.max(0, Math.round((now - new Date(iso).getTime()) / 60000))
if (min < 5) return '방금'
if (min < 60) return `${min}분 전`
return `${Math.floor(min / 60)}시간 전`
}
/** 날짜 칸 이름: 오늘 · 내일 · "토 10.4" */
export function dayLabel(date: string, index: number) {
if (index === 0) return '오늘'
if (index === 1) return '내일'
const [, m, d] = date.split('-').map(Number)
const wd = new Date(`${date}T12:00:00+09:00`).getUTCDay()
return `${WEEKDAYS[wd]} ${m}.${d}`
}
export type TimeKind = 'morning' | 'day' | 'sunset' | 'night'
// 서울 월별 대략 일몰 시각(시). 서버 값(/v1/feed hero.sky_mode)이 없을 때만 쓴다
const SUNSET_HOUR = [17.7, 18.2, 18.6, 19.1, 19.5, 19.9, 19.9, 19.5, 18.9, 18.2, 17.6, 17.3]
/** 피드와 같은 시간대: 아침 05–11 · 낮 11–일몰 2시간 전 · 저녁(sunset) 일몰 2시간 전–일몰 1시간 뒤 · 밤 일몰 1시간 뒤–05 */
export function kindOfHour(h: number, month = new Date().getMonth() + 1, minute = 0): TimeKind {
const at = h + minute / 60
const sunset = SUNSET_HOUR[month - 1]
if (at >= 5 && at < 11) return 'morning'
if (at >= 11 && at < sunset + 1) return at < sunset - 2 ? 'day' : 'sunset'
return 'night'
}
/** "서울 마포구" → "서울" */
export const sidoOf = (regionName: string) => regionName.split(' ')[0]
/** 2026-10-02 ~ 2026-10-11 → "10.2 ~ 10.11", 하루짜리는 "10.3" */
export function dateRange(start: string, end: string) {
return start === end ? shortDay(start) : `${shortDay(start)} ~ ${shortDay(end)}`
}
const CARD_BG = ['night', 'butter', 'lilac', 'mint', 'peach', 'sky'] as const
const ICON_BG: Record<string, (typeof CARD_BG)[number] | 'dusk'> = { picnic: 'mint', walk: 'mint', sunset: 'dusk', chimaek: 'peach', photo: 'butter', fireworks: 'night', popup: 'peach', exhibition: 'lilac', concert: 'night', sheaf: 'butter', rain: 'sky', calendar: 'sky', bulb: 'lilac', maple: 'peach', snow: 'sky', thermo: 'sky', umbrella: 'lilac' }
/** API에 배경색이 없어 아이콘·순서로 카드 배경을 고른다 */
export function cardBg(icon: string, index: number) {
return ICON_BG[icon] && icon !== 'calendar' ? ICON_BG[icon] : CARD_BG[index % CARD_BG.length]
}
/** "2026-09-23" → "9.23" */
export const shortDay = (day: string) => day.split('-').slice(1).map(Number).join('.')
export const ARTICLE_CAT: Record<number, [string, string]> = { 1: ['계절 소식', 'text-[#1f9d62]'], 2: ['날씨 상식', 'text-[#7a5cd6]'], 3: ['각 원리', 'text-(--orange)'] }
/** 읽을거리 한 줄 정보: "계절 소식 · 3분" */
export const articleMeta = (a: { category: number; read_minutes: number }) => `${ARTICLE_CAT[a.category]?.[0] ?? '읽을거리'} · ${a.read_minutes}분`
export type Load = 'loading' | 'error' | 'retrying' | 'ready'
type QueryLike = { data?: unknown; isPending: boolean; isError: boolean; isFetching: boolean; errorUpdateCount: number }
/** 데이터가 있으면 ready. 실패 뒤 다시 받는 중(retrying)은 처음 불러오기(loading)와 구분한다 */
export function loadOf(q: QueryLike): Load {
if (q.data !== undefined) return 'ready'
if (q.isError) return q.isFetching ? 'retrying' : 'error'
return q.isFetching && q.errorUpdateCount > 0 ? 'retrying' : 'loading'
}
+2 -2
View File
@@ -1,8 +1,8 @@
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react' import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import { matchPath, useLocation, useNavigate } from 'react-router' import { matchPath, useLocation, useNavigate } from 'react-router'
import regionPages from '../../seo/region.json' import regionPages from '../../seo/region.json'
import { nearestRegion } from '../api/client/sdk.gen' import { nearestRegion } from '@nalssigak/shared/api/client/sdk.gen'
import type { RegionData } from '../api/client/types.gen' import type { RegionData } from '@nalssigak/shared/api/client/types.gen'
import { track } from '../lib/analytics' import { track } from '../lib/analytics'
import { DEFAULT_REGION, RegionContext, type LocateStatus } from './regionContext' import { DEFAULT_REGION, RegionContext, type LocateStatus } from './regionContext'
+2 -2
View File
@@ -1,11 +1,11 @@
import { createContext, use } from 'react' import { createContext, use } from 'react'
import type { RegionData } from '../api/client/types.gen' import type { RegionData } from '@nalssigak/shared/api/client/types.gen'
export type LocateStatus = 'idle' | 'locating' | 'denied' | 'error' export type LocateStatus = 'idle' | 'locating' | 'denied' | 'error'
export type RegionApi = { region: RegionData; setRegion: (r: RegionData) => void; locate: (onFound?: () => void) => void; locateStatus: LocateStatus } export type RegionApi = { region: RegionData; setRegion: (r: RegionData) => void; locate: (onFound?: () => void) => void; locateStatus: LocateStatus }
export const DEFAULT_REGION: RegionData = { code: '1144000000', name: '서울 마포구', short_name: '마포구', lat: 37.56071, lon: 126.91053 } export { DEFAULT_REGION } from '@nalssigak/shared/lib'
export const RegionContext = createContext<RegionApi | null>(null) export const RegionContext = createContext<RegionApi | null>(null)
+1 -1
View File
@@ -1,5 +1,5 @@
import { createContext, use } from 'react' import { createContext, use } from 'react'
import type { TimeKind } from './lib' import type { TimeKind } from '@nalssigak/shared/lib'
/** 화면 전체 하늘 배경의 시간대. 히어로의 미리보기 버튼으로 고른 값은 탭을 옮겨도 유지된다 */ /** 화면 전체 하늘 배경의 시간대. 히어로의 미리보기 버튼으로 고른 값은 탭을 옮겨도 유지된다 */
export type SkyApi = { kind: TimeKind; preview: TimeKind | null; setServerKind: (k: TimeKind | null) => void; setPreview: (k: TimeKind | null) => void } export type SkyApi = { kind: TimeKind; preview: TimeKind | null; setServerKind: (k: TimeKind | null) => void; setPreview: (k: TimeKind | null) => void }
+2 -1
View File
@@ -2,7 +2,8 @@ import { useState, type CSSProperties, type ReactNode } from 'react'
import { Link } from 'react-router' import { Link } from 'react-router'
import { cx } from '../lib/utils' import { cx } from '../lib/utils'
import { useCarousel, type Carousel } from './carousel' import { useCarousel, type Carousel } from './carousel'
import { AVATAR_COLORS, iconSrc, moodEmoji, naverMap, type Load } from './lib' import { AVATAR_COLORS, moodEmoji, naverMap, type Load } from '@nalssigak/shared/lib'
import { iconSrc } from './lib'
type IcProps = { name: string; className?: string; alt?: string; style?: CSSProperties } type IcProps = { name: string; className?: string; alt?: string; style?: CSSProperties }
+14735
View File
File diff suppressed because it is too large. Load diff
+5
View File
@@ -0,0 +1,5 @@
{
"name": "o2o-weather",
"private": true,
"workspaces": ["frontend", "mobile", "shared"]
}
@@ -1,10 +1,18 @@
// 로그인 토큰 저장소: localStorage + 메모리, 바뀌면 구독자에게 알린다 // 로그인 토큰 저장소: 플랫폼 저장소(웹 localStorage, 앱 SecureStore) + 메모리, 바뀌면 구독자에게 알린다
const ACCESS_KEY = 'nalssigak.accessToken' const ACCESS_KEY = 'nalssigak.accessToken'
const REFRESH_KEY = 'nalssigak.refreshToken' const REFRESH_KEY = 'nalssigak.refreshToken'
export type TokenStorage = {
getItem(key: string): string | null
setItem(key: string, value: string): void
removeItem(key: string): void
}
let storage: TokenStorage | null = null
function readStored(key: string): string | null { function readStored(key: string): string | null {
try { try {
return localStorage.getItem(key) return storage?.getItem(key) ?? null
} catch { } catch {
// 사파리 프라이빗 모드 등에서 저장소 접근이 막히면 로그인 안 한 상태로 시작한다 // 사파리 프라이빗 모드 등에서 저장소 접근이 막히면 로그인 안 한 상태로 시작한다
return null return null
@@ -13,15 +21,21 @@ function readStored(key: string): string | null {
function writeStored(key: string, value: string | null) { function writeStored(key: string, value: string | null) {
try { try {
if (value) localStorage.setItem(key, value) if (value) storage?.setItem(key, value)
else localStorage.removeItem(key) else storage?.removeItem(key)
} catch { } catch {
// 저장이 막혀도 이번 방문 동안은 메모리 토큰으로 계속 쓴다 // 저장이 막혀도 이번 방문 동안은 메모리 토큰으로 계속 쓴다
return return
} }
} }
let accessToken = readStored(ACCESS_KEY) let accessToken: string | null = null
/** 앱이 뜰 때 한 번: 저장된 토큰을 읽어 로그인 상태로 시작한다 */
export function setTokenStorage(next: TokenStorage) {
storage = next
accessToken = readStored(ACCESS_KEY)
}
const listeners = new Set<(reason: 'change' | 'required') => void>() const listeners = new Set<(reason: 'change' | 'required') => void>()
/** 토큰이 바뀌거나(로그인·로그아웃) 로그인이 필요할 때 알림을 받는다 */ /** 토큰이 바뀌거나(로그인·로그아웃) 로그인이 필요할 때 알림을 받는다 */
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+75
View File
@@ -0,0 +1,75 @@
import { client } from './client/client.gen'
import { clearTokens, emitAuthRequired, getAccessToken, getRefreshToken, setTokenStorage, setTokens, type TokenStorage } from './auth'
let baseUrl = ''
type Refresh = 'ok' | 'rejected' | 'unreachable'
// 401이 한꺼번에 와도 갱신은 한 번만
let refreshing: Promise<Refresh> | null = null
/** 서버가 거절하면 'rejected', 네트워크 오류·5xx 면 'unreachable' (이때는 토큰을 지우지 않는다) */
function refreshTokens(): Promise<Refresh> {
refreshing ??= (async (): Promise<Refresh> => {
const token = getRefreshToken()
if (!token) return 'rejected'
const res = await fetch(`${baseUrl}/v1/auth/refresh`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ refresh_token: token }) })
if (res.status >= 500) return 'unreachable'
const body = res.ok ? await res.json() : null
if (!body?.result?.success || !body.access_token) return 'rejected'
setTokens(body.access_token, body.refresh_token ?? token)
return 'ok'
})()
.catch((): Refresh => 'unreachable')
.finally(() => {
refreshing = null
})
return refreshing
}
const NO_REFRESH = ['/v1/auth/login', '/v1/auth/signup', '/v1/auth/refresh']
/** 같은 요청을 토큰만 바꿔(null 이면 빼고) 다시 보낼 수 있게 복사한다 */
function withToken(request: Request, token: string | null) {
const copy = request.clone()
if (token) copy.headers.set('Authorization', `Bearer ${token}`)
else copy.headers.delete('Authorization')
return copy
}
/**
* 401이면 토큰을 한 번 갱신해 같은 요청을 다시 보낸다.
* 갱신이 거절되면 토큰을 지우고, 로그인 없이 되는 요청은 그냥 다시 보내고, 로그인이 꼭 필요한 요청만 로그인 창을 띄운다.
*/
async function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
const request = input instanceof Request && !init ? input : new Request(input, init)
const retry = request.clone()
const response = await fetch(request)
if (response.status !== 401 || NO_REFRESH.includes(new URL(request.url).pathname)) return response
if (request.headers.has('Authorization')) {
const result = await refreshTokens()
if (result === 'unreachable') return response
if (result === 'ok') {
const again = await fetch(withToken(retry, getAccessToken()))
if (again.status !== 401) return again
}
if (getAccessToken()) clearTokens()
const anonymous = await fetch(withToken(retry, null))
if (anonymous.status !== 401) return anonymous
}
// 로그아웃하다 만료된 거면 로그인 창을 띄우지 않는다
if (new URL(request.url).pathname !== '/v1/auth/logout') emitAuthRequired()
return response
}
/** 앱이 뜰 때 한 번: API 주소와 토큰 저장소를 정하고 401 갱신·토큰 헤더를 건다 */
export function configureApi(options: { baseUrl: string; storage: TokenStorage }) {
baseUrl = options.baseUrl
setTokenStorage(options.storage)
client.setConfig({ baseUrl, throwOnError: true, fetch: authFetch })
client.interceptors.request.use((request) => {
const token = getAccessToken()
if (token) request.headers.set('Authorization', `Bearer ${token}`)
return request
})
}
+136
View File
@@ -0,0 +1,136 @@
import type { RegionData } from '../api/client/types.gen'
/** 위치를 모를 때 시작 지역 */
export const DEFAULT_REGION: RegionData = { code: '1144000000', name: '서울 마포구', short_name: '마포구', lat: 37.56071, lon: 126.91053 }
export const MEDALS = ['gold', 'silver', 'bronze'] as const
/** 고를 수 있는 프로필 캐릭터 (백엔드 CHARACTERS 와 같아야 한다) */
export const CHARACTERS = [
['rabbit', '토끼'],
['bear', '곰'],
['dog', '강아지'],
['sun', '해님'],
['moon', '달님'],
['cloud', '구름'],
] as const
/** 프로필 배경색 (백엔드 COLORS 와 같아야 한다) */
export const AVATAR_COLORS: Record<string, string> = { orange: '#ff8e4e', blue: '#4f97e3', green: '#1f9d62', purple: '#7a5cd6', pink: '#d6457a', brown: '#a8643a' }
/** 오늘 기분 (백엔드 MOODS 와 같아야 한다) */
export const MOODS = [
['clear', '☀️', '맑음'],
['partly', '⛅', '구름 조금'],
['cloudy', '☁️', '흐림'],
['rain', '🌧️', '비'],
['thunder', '⚡', '번개'],
['snow', '❄️', '눈'],
['fog', '🌫️', '안개'],
['rainbow', '🌈', '무지개'],
] as const
export const moodEmoji = (mood?: string | null) => MOODS.find(([k]) => k === mood)?.[1]
export const WEEKDAYS = ['일', '월', '화', '수', '목', '금', '토'] as const
// 달(1~12) → 계절 이름과 아이콘. 봄 3–5 · 여름 6–8 · 가을 9–11 · 겨울 12–2 (서버 각 제철 기준과 같다)
const SEASONS: [string, string][] = [['겨울', 'snow'], ['봄', 'garden'], ['여름', 'sun'], ['가을', 'maple']]
export const seasonOf = (month: number) => SEASONS[Math.floor((month % 12) / 3)]
const KST = new Intl.DateTimeFormat('en-US', { timeZone: 'Asia/Seoul', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', hourCycle: 'h23', weekday: 'short' })
const WD_EN = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
/** 한국 시각으로 쪼개기 (브라우저 시간대와 상관없이) */
export function kst(input: string | Date) {
const parts = Object.fromEntries(KST.formatToParts(typeof input === 'string' ? new Date(input) : input).map((p) => [p.type, p.value]))
return { y: +parts.year, mo: +parts.month, d: +parts.day, h: +parts.hour, mi: +parts.minute, wd: WD_EN.indexOf(parts.weekday) }
}
const h12 = (h: number) => h % 12 || 12
/** 18:25 → "18:25" (포스트·플랜과 같은 24시간제) */
export function clockShort(iso: string) {
const t = kst(iso)
return `${t.h}:${String(t.mi).padStart(2, '0')}`
}
const COMPASS = ['북', '북북동', '북동', '동북동', '동', '동남동', '남동', '남남동', '남', '남남서', '남서', '서남서', '서', '서북서', '북서', '북북서']
/** 방위각 → 16방위 이름. 263 → "서" */
/** 네이버 지도에서 장소 이름(또는 주소)으로 찾기 */
export const naverMap = (query: string) => `https://map.naver.com/p/search/${encodeURIComponent(query)}`
export const compass = (deg: number) => COMPASS[Math.round(deg / 22.5) % 16]
/** 18:30 → "6시 반", 18:25 → "6시 25분" */
export function timeWords(iso: string) {
const t = kst(iso)
return `${h12(t.h)}시${t.mi === 0 ? '' : t.mi === 30 ? ' 반' : ` ${t.mi}분`}`
}
/** 발표 시각 → "방금" · "12분 전" · "3시간 전" */
export function ago(iso: string | null | undefined, now = Date.now()) {
if (!iso) return '오늘'
const min = Math.max(0, Math.round((now - new Date(iso).getTime()) / 60000))
if (min < 5) return '방금'
if (min < 60) return `${min}분 전`
return `${Math.floor(min / 60)}시간 전`
}
/** 날짜 칸 이름: 오늘 · 내일 · "토 10.4" */
export function dayLabel(date: string, index: number) {
if (index === 0) return '오늘'
if (index === 1) return '내일'
const [, m, d] = date.split('-').map(Number)
const wd = new Date(`${date}T12:00:00+09:00`).getUTCDay()
return `${WEEKDAYS[wd]} ${m}.${d}`
}
export type TimeKind = 'morning' | 'day' | 'sunset' | 'night'
// 서울 월별 대략 일몰 시각(시). 서버 값(/v1/feed hero.sky_mode)이 없을 때만 쓴다
const SUNSET_HOUR = [17.7, 18.2, 18.6, 19.1, 19.5, 19.9, 19.9, 19.5, 18.9, 18.2, 17.6, 17.3]
/** 피드와 같은 시간대: 아침 05–11 · 낮 11–일몰 2시간 전 · 저녁(sunset) 일몰 2시간 전–일몰 1시간 뒤 · 밤 일몰 1시간 뒤–05 */
export function kindOfHour(h: number, month = new Date().getMonth() + 1, minute = 0): TimeKind {
const at = h + minute / 60
const sunset = SUNSET_HOUR[month - 1]
if (at >= 5 && at < 11) return 'morning'
if (at >= 11 && at < sunset + 1) return at < sunset - 2 ? 'day' : 'sunset'
return 'night'
}
/** "서울 마포구" → "서울" */
export const sidoOf = (regionName: string) => regionName.split(' ')[0]
/** 2026-10-02 ~ 2026-10-11 → "10.2 ~ 10.11", 하루짜리는 "10.3" */
export function dateRange(start: string, end: string) {
return start === end ? shortDay(start) : `${shortDay(start)} ~ ${shortDay(end)}`
}
const CARD_BG = ['night', 'butter', 'lilac', 'mint', 'peach', 'sky'] as const
const ICON_BG: Record<string, (typeof CARD_BG)[number] | 'dusk'> = { picnic: 'mint', walk: 'mint', sunset: 'dusk', chimaek: 'peach', photo: 'butter', fireworks: 'night', popup: 'peach', exhibition: 'lilac', concert: 'night', sheaf: 'butter', rain: 'sky', calendar: 'sky', bulb: 'lilac', maple: 'peach', snow: 'sky', thermo: 'sky', umbrella: 'lilac' }
/** API에 배경색이 없어 아이콘·순서로 카드 배경을 고른다 */
export function cardBg(icon: string, index: number) {
return ICON_BG[icon] && icon !== 'calendar' ? ICON_BG[icon] : CARD_BG[index % CARD_BG.length]
}
/** "2026-09-23" → "9.23" */
export const shortDay = (day: string) => day.split('-').slice(1).map(Number).join('.')
export const ARTICLE_LABEL: Record<number, string> = { 1: '계절 소식', 2: '날씨 상식', 3: '각 원리' }
/** 읽을거리 한 줄 정보: "계절 소식 · 3분" */
export const articleMeta = (a: { category: number; read_minutes: number }) => `${ARTICLE_LABEL[a.category] ?? '읽을거리'} · ${a.read_minutes}분`
export type Load = 'loading' | 'error' | 'retrying' | 'ready'
type QueryLike = { data?: unknown; isPending: boolean; isError: boolean; isFetching: boolean; errorUpdateCount: number }
/** 데이터가 있으면 ready. 실패 뒤 다시 받는 중(retrying)은 처음 불러오기(loading)와 구분한다 */
export function loadOf(q: QueryLike): Load {
if (q.data !== undefined) return 'ready'
if (q.isError) return q.isFetching ? 'retrying' : 'error'
return q.isFetching && q.errorUpdateCount > 0 ? 'retrying' : 'loading'
}
+50
View File
@@ -0,0 +1,50 @@
import { RainType, Sky, type TopIndex, type WeatherSlot } from '../api/client/types.gen'
import type { TimeKind } from '.'
// 하루 흐름 칸 순서와 칸마다 볼 예보 시각
export const KINDS: TimeKind[] = ['morning', 'day', 'sunset', 'night']
export const PREVIEW: Record<TimeKind, { label: string; hour: number }> = {
morning: { label: '아침', hour: 7 },
day: { label: '낮', hour: 13 },
sunset: { label: '저녁', hour: 18 },
night: { label: '밤', hour: 22 },
}
// 미리보기 탭과 서버 구간 이름. 저녁 탭(노을 하늘)은 서버의 evening 구간
export const SLOT_KEY: Record<TimeKind, string> = { morning: 'morning', day: 'day', sunset: 'evening', night: 'night' }
/** 미리보기 시간대면 이미 받은 구간 점수·순위로 다시 줄 세운다. 그 구간과 안 겹치는 각은 흐리게 끝으로. 구간 값이 없으면(예전 캐시) 그대로 */
export function atSlot(items: TopIndex[], kind: TimeKind | null): TopIndex[] {
const k = kind && SLOT_KEY[kind]
if (!k || !items.some((g) => Object.keys(g.slot_ranks ?? {}).length)) return items
const on = items.filter((g) => g.slot_ranks?.[k] != null && g.slots?.[k] != null)
return [
...on.map((g) => ({ ...g, score: g.slots![k], rank: g.slot_ranks![k], active: true })).sort((a, b) => a.rank - b.rank),
...items.filter((g) => !on.includes(g)).map((g) => ({ ...g, active: false })),
]
}
export type Weather = 'clear' | 'partly' | 'cloudy' | 'rain' | 'snow' | 'sleet'
/** 예보 칸 하나의 하늘: 비·눈이 오면 그걸, 아니면 구름 양 */
export function weatherOf(slot?: WeatherSlot): Weather {
const r = slot?.rain_type
if (r === RainType.RAIN || r === RainType.SHOWER) return 'rain'
if (r === RainType.SNOW) return 'snow'
if (r === RainType.SLEET) return 'sleet'
return slot?.sky === Sky.CLOUDY ? 'cloudy' : slot?.sky === Sky.PARTLY ? 'partly' : 'clear'
}
export const WEATHER_ICON: Record<Weather, string> = { clear: 'sun', partly: 'sun_cloud', cloudy: 'cloud', rain: 'rain', snow: 'snow', sleet: 'snow' }
export const WANING = ['기우는 달', '하현달', '그믐달']
/**
* 반지름 r 인 달에서 밝은 쪽(lit) 또는 어두운 쪽 경로. 차오르는 달 기준(오른쪽이 밝음), 기우는 달은 좌우를 뒤집어 쓴다.
* 바깥 반원과 명암 경계(가로 반지름 r·|1-2k| 인 타원 호)로 이루어진다.
*/
export function moonPath(pct: number, r: number, lit: boolean) {
const k = pct / 100
const edge = `A${r * Math.abs(1 - 2 * k)},${r} 0 0 ${k < 0.5 ? 0 : 1} 0,${-r}`
return `M0,${-r} A${r},${r} 0 0 ${lit ? 1 : 0} 0,${r} ${edge}`
}
File renamed without changes.
@@ -1,5 +1,5 @@
import { RainType, Sky, type WeatherSlot } from '../api/client/types.gen' import { RainType, Sky, type WeatherSlot } from '../api/client/types.gen'
import { kst } from './lib' import { kst } from '.'
const RAIN_TEXT: Partial<Record<RainType, string>> = { [RainType.RAIN]: '비', [RainType.SLEET]: '진눈깨비', [RainType.SNOW]: '눈', [RainType.SHOWER]: '소나기' } const RAIN_TEXT: Partial<Record<RainType, string>> = { [RainType.RAIN]: '비', [RainType.SLEET]: '진눈깨비', [RainType.SNOW]: '눈', [RainType.SHOWER]: '소나기' }
const SKY_TEXT: Record<Sky, string> = { [Sky.CLEAR]: '맑음', [Sky.PARTLY]: '구름 많음', [Sky.CLOUDY]: '흐림' } const SKY_TEXT: Record<Sky, string> = { [Sky.CLEAR]: '맑음', [Sky.PARTLY]: '구름 많음', [Sky.CLOUDY]: '흐림' }
+12
View File
@@ -0,0 +1,12 @@
{
"name": "@nalssigak/shared",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"typecheck": "tsc -p ."
},
"peerDependencies": {
"@tanstack/react-query": "^5.104.0"
}
}
+17
View File
@@ -0,0 +1,17 @@
{
"compilerOptions": {
"target": "es2023",
"lib": ["ES2023", "DOM"],
"module": "esnext",
"moduleResolution": "bundler",
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"skipLibCheck": true,
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true
},
"include": ["api", "lib"]
}