Compare commits

..
Author SHA1 Message Date
minaChoi 117de90c3e fix: 아래 창(로그인 등)이 열리고 닫힐 때 버벅여 보이던 것 — 반투명으로 40px만 올라와 뒤 탭 바가 비쳤고 닫힐 땐 툭 사라지며 쓰기 칸 테두리가 번쩍였음, 불투명하게 아래에서 끝까지 올라오고 내려가며 닫히게 2026-10-27 15:08:40 +09:00
minaChoi be60551f49 Merge branch 'fix/composer-login-no-keyboard' — 로그인 전 쓰기 칸은 키보드 없이 로그인 창 2026-10-27 14:55:46 +09:00
minaChoi dcf2fe5a53 fix: 로그인 안 한 채 쓰기 칸을 누르면 로그인 창이 버벅이던 것 — 칸에 포커스가 가며 키보드가 떴다 내려갔음, 로그인 전엔 읽기 전용으로 두고 누르면 로그인 창 2026-10-27 14:55:46 +09:00
minaChoi 132301dc28 Merge branch 'fix/google-button-skeleton' — 로그인 창 구글 버튼 스켈레톤 2026-10-27 14:49:42 +09:00
minaChoi dd133c9d52 fix: 로그인 창 구글 버튼 자리에 스켈레톤 — 빈칸에 버튼이 늦게 툭 튀어나와 버벅이는 것처럼 보이던 것, 다 그려지면 부드럽게 바꿔 보임 2026-10-27 14:49:41 +09:00
minaChoi 5459b97ba0 Merge branch 'fix/foliage-card-slide2' — 단풍 카드 2번째 장 가림, 히어로 아이콘 간격, 로그인 창 첫 열기 버벅임, 토스 글 종류 필터 되돌림 2026-10-27 14:40:33 +09:00
minaChoi 1908433e46 fix: 토스에서 가리던 글 종류(카드뉴스 등) 다시 보이게 — 토스 번들이 업데이트돼 d3d872b 필터를 되돌림 2026-10-27 14:40:33 +09:00
minaChoi 7dcd6c6a4c fix: 로그인 창을 처음 열 때 버벅이던 것 줄임 — 구글 로그인 스크립트는 한가할 때 미리 받고, 구글 버튼과 뒤 화면 멈추기는 창이 다 올라온 뒤에 2026-10-27 14:39:41 +09:00
minaChoi 7d84226105 fix: 히어로 하트·댓글·보내기 간격이 숫자가 붙으면 어긋나던 문제 — 버튼마다 좌우 여백을 같게 2026-10-27 14:39:41 +09:00
minaChoi c45940c358 fix: 피드 단풍 지도 카드 2번째 장(지금 가기 좋은 곳) 왼쪽이 가려지던 문제 — 가운데 맞추려 민 지도가 옆 장을 덮었음, 1번째 장 밖은 자름 2026-10-27 14:29:34 +09:00
minaChoi 09e8b4734a Merge branch 'feat/app-moon-bot' — 앱 히어로·달 포스트 실제 달 모양, 캐릭터 댓글 표시 2026-10-27 14:05:03 +09:00
11 changed files with 168 additions and 98 deletions

No files matched your search

+2 -13
View File
@@ -1,10 +1,10 @@
from typing import Optional from typing import Optional
from fastapi import APIRouter, Depends, Path, Query, Request from fastapi import APIRouter, Depends, Path, Query
from common.auth import optional_user from common.auth import optional_user
from common.database.model.models import User from common.database.model.models import User
from common.enums import ErrorType, PostType from common.enums import ErrorType
from common.liker import Liker, liker from common.liker import Liker, liker
from common.models.errors import error_info from common.models.errors import error_info
from router.v1.feed.protocol import Res_Feed, Res_Post from router.v1.feed.protocol import Res_Feed, Res_Post
@@ -13,26 +13,15 @@ from services.reaction_service import ReactionService
router = APIRouter(prefix="/v1/feed", tags=["feed"]) router = APIRouter(prefix="/v1/feed", tags=["feed"])
# 토스에 올라간 10/13 번들은 UV 까지만 알아서, 그 뒤에 생긴 글 종류(카드뉴스 등)가 오면 흰 화면이 된다
TOSS_KNOWN_MAX = PostType.UV.value
def _from_toss(request: Request) -> bool:
ref = request.headers.get("origin") or request.headers.get("referer") or ""
return "AppsInToss" in request.headers.get("user-agent", "") or ".tossmini.com" in ref
@router.get("", response_model=Res_Feed, response_model_exclude_none=True, summary="메인 피드: 하늘 영역, 오늘의 각, 오늘 포스트 전부, 띠") @router.get("", response_model=Res_Feed, response_model_exclude_none=True, summary="메인 피드: 하늘 영역, 오늘의 각, 오늘 포스트 전부, 띠")
async def get_feed( async def get_feed(
request: Request,
region: str = Query(..., description="구 행정코드"), user: Optional[User] = Depends(optional_user), who: Liker = Depends(liker), region: str = Query(..., description="구 행정코드"), user: Optional[User] = Depends(optional_user), who: Liker = Depends(liker),
service: FeedService = Depends(), reactions: ReactionService = Depends(), service: FeedService = Depends(), reactions: ReactionService = Depends(),
) -> Res_Feed: ) -> Res_Feed:
err, feed = await service.feed(region) err, feed = await service.feed(region)
if err is not ErrorType.SUCCESS: if err is not ErrorType.SUCCESS:
return Res_Feed(result=error_info(err)) return Res_Feed(result=error_info(err))
if _from_toss(request):
feed = feed.model_copy(update={"posts": [p for p in feed.posts if p.post_type.value <= TOSS_KNOWN_MAX]})
pinned = [x for x in (feed.hero_post, feed.gak_post, feed.foliage_post, feed.events_post, feed.season_post) if x is not None] pinned = [x for x in (feed.hero_post, feed.gak_post, feed.foliage_post, feed.events_post, feed.season_post) if x is not None]
ids = [p.post_id for p in feed.posts] + [x.post_id for x in pinned] ids = [p.post_id for p in feed.posts] + [x.post_id for x in pinned]
counts = await reactions.counts(ids) counts = await reactions.counts(ids)
-18
View File
@@ -1,18 +0,0 @@
from starlette.requests import Request
from common.enums import PostType
from router.v1.feed.feed import TOSS_KNOWN_MAX, _from_toss
def _req(headers: dict) -> Request:
return Request({"type": "http", "headers": [(k.lower().encode(), v.encode()) for k, v in headers.items()]})
def test_from_toss_by_referer_or_user_agent():
assert _from_toss(_req({"referer": "https://nalssigak.apps.tossmini.com/"}))
assert _from_toss(_req({"user-agent": "Mozilla/5.0 ... AppsInToss TossApp/5.282.1"}))
assert not _from_toss(_req({"referer": "https://weather.o2o.kr/", "user-agent": "Mozilla/5.0 Safari"}))
def test_card_is_hidden_from_old_toss_bundle():
assert PostType.CARD.value > TOSS_KNOWN_MAX >= PostType.UV.value
+12 -2
View File
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react' import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
import { NavLink, Outlet, useLocation, useNavigationType } from 'react-router' import { NavLink, Outlet, useLocation, useNavigationType } from 'react-router'
import { useIsFetching, useQuery } from '@tanstack/react-query' import { useIsFetching, useQuery, useQueryClient } from '@tanstack/react-query'
import { getSeasonWeekOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen' import { authConfigOptions, getSeasonWeekOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { IS_TOSS } from '../lib/platform' import { IS_TOSS } from '../lib/platform'
import { cx } from '../lib/utils' import { cx } from '../lib/utils'
import { kindOfHour, kst, seasonOf, type TimeKind } from '@nalssigak/shared/lib' import { kindOfHour, kst, seasonOf, type TimeKind } from '@nalssigak/shared/lib'
@@ -9,6 +9,7 @@ import './b.css'
import { AuthProvider } from './auth' import { AuthProvider } from './auth'
import { RegionProvider } from './region' import { RegionProvider } from './region'
import { useAuth } from './authContext' import { useAuth } from './authContext'
import { preloadGoogle } from './googleScript'
import { useRegion } from './regionContext' import { useRegion } from './regionContext'
import { useSheet } from './sheetContext' import { useSheet } from './sheetContext'
import { SheetProvider } from './Sheets' import { SheetProvider } from './Sheets'
@@ -47,7 +48,16 @@ function TopBar() {
const { region, locateStatus } = useRegion() const { region, locateStatus } = useRegion()
const { open } = useSheet() const { open } = useSheet()
const { me, mePending } = useAuth() const { me, mePending } = useAuth()
const queryClient = useQueryClient()
const tab = TABS.find((t) => t.to !== '/' && pathname.startsWith(t.to)) const tab = TABS.find((t) => t.to !== '/' && pathname.startsWith(t.to))
const loggedOut = !IS_TOSS && !mePending && !me
// 로그인 창을 처음 열 때 버벅이지 않게 구글 로그인 준비물을 미리 받아 둔다
useEffect(() => {
if (!loggedOut) return
void queryClient.prefetchQuery({ ...authConfigOptions(), staleTime: Infinity })
return preloadGoogle()
}, [loggedOut, queryClient])
return ( return (
<header className="sticky top-0 z-20 flex h-[calc(54px+env(safe-area-inset-top,0px))] items-center justify-between gap-2 px-4 pt-[env(safe-area-inset-top,0px)]"> <header className="sticky top-0 z-20 flex h-[calc(54px+env(safe-area-inset-top,0px))] items-center justify-between gap-2 px-4 pt-[env(safe-area-inset-top,0px)]">
+42 -21
View File
@@ -34,7 +34,7 @@ import { ago, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf,
import { GoogleButton } from './googleLogin' import { GoogleButton } from './googleLogin'
import { useInstall, useInstallable } from './install' import { useInstall, useInstallable } from './install'
import { InstallSheet } from './installBanner' import { InstallSheet } from './installBanner'
import { ARTICLE_CAT } from './lib' import { ARTICLE_CAT, SHEET_CLOSE_MS, SHEET_OPEN_MS } from './lib'
import { MixSheet } from './myGak' import { MixSheet } from './myGak'
import { ownPage, useRegion } from './regionContext' import { ownPage, useRegion } from './regionContext'
import { WeatherWhySheet } from './weatherWhy' import { WeatherWhySheet } from './weatherWhy'
@@ -95,11 +95,25 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
const [gakTitle, setGakTitle] = useState('') const [gakTitle, setGakTitle] = useState('')
const [articleTitle, setArticleTitle] = useState('') const [articleTitle, setArticleTitle] = useState('')
// 닫히는 동안에도 내려가는 창에 내용이 남아 있게, 마지막으로 연 창을 들고 있는다
const [shown, setShown] = useState<SheetState>(state)
if (state && state !== shown) setShown(state)
const closing = !state && shown != null
useEffect(() => { useEffect(() => {
const el = ref.current const el = ref.current
if (!el) return if (!el) return
if (state && !el.open) el.showModal() if (state) {
if (!state && el.open) el.close() if (!el.open) el.showModal()
return
}
if (!el.open) return
// 내려가는 애니메이션이 끝난 뒤에 실제로 닫는다
const t = setTimeout(() => {
el.close()
setShown(null)
}, SHEET_CLOSE_MS)
return () => clearTimeout(t)
}, [state]) }, [state])
// 창이 열려 있는 동안 뒤 페이지는 스크롤되지 않게 잠근다 // 창이 열려 있는 동안 뒤 페이지는 스크롤되지 않게 잠근다
@@ -109,15 +123,17 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
const root = document.documentElement const root = document.documentElement
const before = root.style.overflow const before = root.style.overflow
root.style.overflow = 'hidden' root.style.overflow = 'hidden'
root.classList.add('b-sheet-open') // 뒤 화면 움직임 멈추기는 페이지 전체 스타일을 다시 계산하게 해서, 창이 다 올라온 뒤에 한다
const pause = setTimeout(() => root.classList.add('b-sheet-open'), SHEET_OPEN_MS)
return () => { return () => {
clearTimeout(pause)
root.style.overflow = before root.style.overflow = before
root.classList.remove('b-sheet-open') root.classList.remove('b-sheet-open')
} }
}, [isOpen]) }, [isOpen])
const then = state?.type === 'login' ? state.then : undefined const then = shown?.type === 'login' ? shown.then : undefined
const title = !state ? '' : state.type === 'gak' ? gakTitle : state.type === 'article' ? articleTitle || TITLES.article : state.type === 'mix' ? (state.shared ? '받은 각' : '내 각 만들기') : TITLES[state.type] const title = !shown ? '' : shown.type === 'gak' ? gakTitle : shown.type === 'article' ? articleTitle || TITLES.article : shown.type === 'mix' ? (shown.shared ? '받은 각' : '내 각 만들기') : TITLES[shown.type]
return ( return (
<dialog <dialog
@@ -125,12 +141,17 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
aria-label={title} aria-label={title}
data-t={kind} data-t={kind}
onClose={onClose} onClose={onClose}
// ESC 도 바로 닫지 않고 내려가며 닫히게
onCancel={(e) => {
e.preventDefault()
onClose()
}}
onClick={(e) => { onClick={(e) => {
if (e.target === e.currentTarget) onClose() if (e.target === e.currentTarget) onClose()
}} }}
className="b-sheet-dialog b-app fixed inset-x-0 top-auto bottom-0 m-0 mx-auto max-h-[86dvh] w-full max-w-[440px] overflow-visible bg-transparent p-0 text-(--ink)" className={cx('b-sheet-dialog b-app fixed inset-x-0 top-auto bottom-0 m-0 mx-auto max-h-[86dvh] w-full max-w-[440px] overflow-visible bg-transparent p-0 text-(--ink)', closing && 'b-sheet-closing')}
> >
{state && ( {shown && (
<div className="b-sheet flex max-h-[86dvh] flex-col rounded-t-[22px] bg-white pb-[env(safe-area-inset-bottom,0px)]"> <div className="b-sheet flex max-h-[86dvh] flex-col rounded-t-[22px] bg-white pb-[env(safe-area-inset-bottom,0px)]">
<div className="relative border-b border-(--line) px-4 pt-2 pb-2.5 text-center"> <div className="relative border-b border-(--line) px-4 pt-2 pb-2.5 text-center">
<div className="mx-auto mb-2.5 h-1 w-10 rounded-full bg-(--line)" aria-hidden="true" /> <div className="mx-auto mb-2.5 h-1 w-10 rounded-full bg-(--line)" aria-hidden="true" />
@@ -139,21 +160,21 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
× ×
</button> </button>
</div> </div>
{state.type === 'gak' && <GakSheet indexId={state.indexId} onTitle={setGakTitle} />} {shown.type === 'gak' && <GakSheet indexId={shown.indexId} onTitle={setGakTitle} />}
{state.type === 'article' && <ArticleSheet articleId={state.articleId} onTitle={setArticleTitle} />} {shown.type === 'article' && <ArticleSheet articleId={shown.articleId} onTitle={setArticleTitle} />}
{state.type === 'seasonWeek' && <SeasonWeekSheet />} {shown.type === 'seasonWeek' && <SeasonWeekSheet />}
{state.type === 'share' && <ShareSheet share={state.share} />} {shown.type === 'share' && <ShareSheet share={shown.share} />}
{state.type === 'comments' && <CommentsSheet postId={state.postId} draft={state.draft} />} {shown.type === 'comments' && <CommentsSheet postId={shown.postId} draft={shown.draft} />}
{state.type === 'login' && <LoginSheet onDone={onClose} onLoggedIn={then ? () => open(then) : onClose} />} {shown.type === 'login' && <LoginSheet onDone={onClose} onLoggedIn={then ? () => open(then) : onClose} />}
{state.type === 'me' && <MeSheet onDone={onClose} />} {shown.type === 'me' && <MeSheet onDone={onClose} />}
{state.type === 'region' && <RegionSheet onDone={onClose} />} {shown.type === 'region' && <RegionSheet onDone={onClose} />}
{state.type === 'mix' && <MixSheet shared={state.shared} onDone={onClose} />} {shown.type === 'mix' && <MixSheet shared={shown.shared} onDone={onClose} />}
{state.type === 'install' && <InstallSheet />} {shown.type === 'install' && <InstallSheet />}
{state.type === 'weatherWhy' && <WeatherWhySheet d={state.why} />} {shown.type === 'weatherWhy' && <WeatherWhySheet d={shown.why} />}
{state.type === 'talk' && <TalkSheet talk={state.talk} />} {shown.type === 'talk' && <TalkSheet talk={shown.talk} />}
</div> </div>
)} )}
{!state && <RegionLinks />} {!shown && <RegionLinks />}
</dialog> </dialog>
) )
} }
+2 -1
View File
@@ -160,7 +160,8 @@ const WEATHER_ICON: Record<Weather, string> = {
} }
// 구름 수: 구름 많음 둘, 흐림·비·눈 셋 // 구름 수: 구름 많음 둘, 흐림·비·눈 셋
// 히어로 오른쪽 위 좋아요·댓글·보내기: 셋 다 같은 32px 칸에 아이콘 가운데, 수는 아이콘 옆 // 히어로 오른쪽 위 좋아요·댓글·보내기: 셋 다 같은 32px 칸에 아이콘 가운데, 수는 아이콘 옆
const HERO_ACT = 'relative flex h-8 min-w-8 cursor-pointer items-center justify-center gap-1 text-[13px] font-extrabold' // 아이콘마다 좌우 여백을 같게: 숫자가 붙어도 아이콘 사이 간격이 그대로
const HERO_ACT = 'relative flex h-8 cursor-pointer items-center justify-center gap-1 px-[5px] text-[13px] leading-none font-extrabold tabular-nums'
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' },
{ cls: 'top-[96px] left-[63%] h-9 w-[96px]', d: '.25s', f: '6.4s' }, { cls: 'top-[96px] left-[63%] h-9 w-[96px]', d: '.25s', f: '6.4s' },
+31 -5
View File
@@ -120,13 +120,37 @@
} }
} }
/* 아래 창은 불투명한 채로 화면 아래에서 끝까지 올라오고, 닫힐 땐 다시 내려간다 (반투명으로 올라오면 뒤 탭 바가 비쳐 깜빡여 보였다) */
.b-sheet { .b-sheet {
animation: b-up 0.26s cubic-bezier(0.2, 0.9, 0.3, 1); animation: b-up 0.28s cubic-bezier(0.2, 0.9, 0.3, 1);
}
.b-sheet-dialog[open]::backdrop {
animation: b-fade-in 0.2s ease-out;
}
.b-sheet-closing .b-sheet {
animation: b-down 0.2s ease-in forwards;
}
.b-sheet-closing::backdrop {
animation: b-fade-out 0.2s ease-in forwards;
} }
@keyframes b-up { @keyframes b-up {
from { from {
transform: translateY(40px); transform: translateY(100%);
opacity: 0.4; }
}
@keyframes b-down {
to {
transform: translateY(100%);
}
}
@keyframes b-fade-in {
from {
opacity: 0;
}
}
@keyframes b-fade-out {
to {
opacity: 0;
} }
} }
@@ -150,11 +174,13 @@
.b-fall, .b-fall,
.b-heart-pop, .b-heart-pop,
.b-like-bit, .b-like-bit,
.b-sheet { .b-sheet,
.b-sheet-dialog[open]::backdrop {
animation: none !important; animation: none !important;
} }
.b-heart-pop, .b-heart-pop,
.b-like-bit { .b-like-bit,
.b-sheet-closing .b-sheet {
opacity: 0; opacity: 0;
} }
} }
+2 -1
View File
@@ -66,7 +66,8 @@ export function FoliageCard({ post }: { post?: PostReaction | null }) {
</span> </span>
<div ref={sliderRef} className="overflow-hidden" role="region" aria-label="슬라이드 2장, 옆으로 넘겨 보세요"> <div ref={sliderRef} className="overflow-hidden" role="region" aria-label="슬라이드 2장, 옆으로 넘겨 보세요">
<div className="flex"> <div className="flex">
<div className="min-w-0 shrink-0 grow-0 basis-full"> {/* 밀어 낸 지도가 옆 장(가기 좋은 곳)을 덮지 않게 이 장 밖은 자른다 */}
<div className="min-w-0 shrink-0 grow-0 basis-full overflow-hidden">
{/* 지도 그림은 땅이 왼쪽에 치우쳐 있어 오른쪽(빈 바다)으로 밀어 가운데에 맞춘다 */} {/* 지도 그림은 땅이 왼쪽에 치우쳐 있어 오른쪽(빈 바다)으로 밀어 가운데에 맞춘다 */}
<div ref={mapRef} onClick={tapMap} className="b-keep-bg relative mx-auto aspect-square w-full translate-x-[7%] bg-[#fff6ea]"> <div ref={mapRef} onClick={tapMap} className="b-keep-bg relative mx-auto aspect-square w-full translate-x-[7%] bg-[#fff6ea]">
<img src={MAP_SRC} alt="" className={MAP_IMG} /> <img src={MAP_SRC} alt="" className={MAP_IMG} />
+20 -34
View File
@@ -2,43 +2,20 @@ import { useMutation, useQuery } from '@tanstack/react-query'
import { useEffect, useRef, useState } from 'react' import { useEffect, useRef, useState } from 'react'
import { authConfigOptions, googleLoginMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen' import { authConfigOptions, googleLoginMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import type { ResAuth } from '@nalssigak/shared/api/client/types.gen' import type { ResAuth } from '@nalssigak/shared/api/client/types.gen'
import { cx } from '../lib/utils'
type GoogleId = { import { loadGoogle } from './googleScript'
initialize: (o: { client_id: string; callback: (r: { credential?: string }) => void; ux_mode?: 'popup' }) => void import { SHEET_OPEN_MS } from './lib'
renderButton: (el: HTMLElement, o: Record<string, string | number>) => void import { Skel } from './ui'
}
declare global {
interface Window {
google?: { accounts: { id: GoogleId } }
}
}
const SCRIPT = 'https://accounts.google.com/gsi/client'
let loading: Promise<GoogleId> | null = null
/** 구글 로그인 스크립트는 로그인 창을 처음 열 때 한 번만 받는다 */
function loadGoogle(): Promise<GoogleId> {
if (window.google?.accounts.id) return Promise.resolve(window.google.accounts.id)
loading ??= new Promise((resolve, reject) => {
const s = document.createElement('script')
s.src = SCRIPT
s.async = true
s.onload = () => (window.google?.accounts.id ? resolve(window.google.accounts.id) : reject(new Error('gsi missing')))
s.onerror = () => {
loading = null
reject(new Error('gsi load failed'))
}
document.head.appendChild(s)
})
return loading
}
/** 구글로 계속하기 버튼. 서버에 클라이언트 ID가 없으면 아무것도 그리지 않는다 */ /** 구글로 계속하기 버튼. 서버에 클라이언트 ID가 없으면 아무것도 그리지 않는다 */
export function GoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) => void; onFail: () => void }) { export function GoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) => void; onFail: () => void }) {
const clientId = useQuery({ ...authConfigOptions(), staleTime: Infinity }).data?.google_client_id const config = useQuery({ ...authConfigOptions(), staleTime: Infinity })
const clientId = config.data?.google_client_id
const login = useMutation(googleLoginMutation()) const login = useMutation(googleLoginMutation())
const box = useRef<HTMLDivElement>(null) const box = useRef<HTMLDivElement>(null)
const [broken, setBroken] = useState(false) const [broken, setBroken] = useState(false)
// 구글 버튼(iframe)이 다 그려지기 전엔 같은 크기의 스켈레톤을 보여 준다. 빈칸에 버튼이 툭 튀어나오면 버벅이는 것처럼 보여서
const [ready, setReady] = useState(false)
const { mutate } = login const { mutate } = login
// 로그인 창이 다시 그려질 때마다 버튼을 새로 만들지 않게 콜백은 ref 로 들고 있는다 // 로그인 창이 다시 그려질 때마다 버튼을 새로 만들지 않게 콜백은 ref 로 들고 있는다
const cb = useRef({ onResult, onFail }) const cb = useRef({ onResult, onFail })
@@ -49,8 +26,10 @@ export function GoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) =>
useEffect(() => { useEffect(() => {
if (!clientId || !box.current) return if (!clientId || !box.current) return
let alive = true let alive = true
loadGoogle().then( // 버튼(iframe)을 만드는 일이 무거워, 로그인 창이 다 올라온 뒤에 만든다. 자리는 min-h 로 잡아 둬서 밀리지 않는다
(g) => { const wait = new Promise((r) => setTimeout(r, SHEET_OPEN_MS))
Promise.all([loadGoogle(), wait]).then(
([g]) => {
if (!alive || !box.current) return if (!alive || !box.current) return
g.initialize({ g.initialize({
client_id: clientId, client_id: clientId,
@@ -61,6 +40,9 @@ export function GoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) =>
}, },
}) })
g.renderButton(box.current, { theme: 'outline', size: 'large', shape: 'pill', text: 'continue_with', locale: 'ko', width: box.current.offsetWidth }) g.renderButton(box.current, { theme: 'outline', size: 'large', shape: 'pill', text: 'continue_with', locale: 'ko', width: box.current.offsetWidth })
const frame = box.current.querySelector('iframe')
if (frame) frame.addEventListener('load', () => alive && setReady(true), { once: true })
else setReady(true)
}, },
(e: unknown) => { (e: unknown) => {
console.error('[google] script', e) console.error('[google] script', e)
@@ -72,10 +54,14 @@ export function GoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) =>
} }
}, [clientId, mutate]) }, [clientId, mutate])
if (config.isPending) return <Skel shape className="mx-auto h-[44px] w-full max-w-[400px] rounded-full" />
if (!clientId) return null if (!clientId) return null
return ( return (
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<div ref={box} className="flex min-h-[44px] justify-center" aria-busy={login.isPending} /> <div className="relative">
{!ready && !broken && <Skel shape className="absolute inset-x-0 top-0 mx-auto h-[44px] w-full max-w-[400px] rounded-full" />}
<div ref={box} className={cx('flex min-h-[44px] justify-center transition-opacity duration-200', ready ? 'opacity-100' : 'opacity-0')} aria-busy={login.isPending || !ready} />
</div>
{broken && <p className="m-0 text-center text-[13px] font-bold text-(--ink3)">구글 로그인을 불러오지 못했어요. 잠시 뒤에 다시 해 주세요.</p>} {broken && <p className="m-0 text-center text-[13px] font-bold text-(--ink3)">구글 로그인을 불러오지 못했어요. 잠시 뒤에 다시 해 주세요.</p>}
</div> </div>
) )
+40
View File
@@ -0,0 +1,40 @@
export type GoogleId = {
initialize: (o: { client_id: string; callback: (r: { credential?: string }) => void; ux_mode?: 'popup' }) => void
renderButton: (el: HTMLElement, o: Record<string, string | number>) => void
}
declare global {
interface Window {
google?: { accounts: { id: GoogleId } }
}
}
const SCRIPT = 'https://accounts.google.com/gsi/client'
let loading: Promise<GoogleId> | null = null
/** 구글 로그인 스크립트는 한 번만 받는다. 실패하면 다음에 다시 받는다 */
export function loadGoogle(): Promise<GoogleId> {
if (window.google?.accounts.id) return Promise.resolve(window.google.accounts.id)
loading ??= new Promise((resolve, reject) => {
const s = document.createElement('script')
s.src = SCRIPT
s.async = true
s.onload = () => (window.google?.accounts.id ? resolve(window.google.accounts.id) : reject(new Error('gsi missing')))
s.onerror = () => {
loading = null
reject(new Error('gsi load failed'))
}
document.head.appendChild(s)
})
return loading
}
/** 로그인 안 한 사람은 화면이 한가할 때 스크립트를 미리 받아 둔다. 로그인 창이 올라오는 도중에 스크립트를 실행하느라 화면이 멈추지 않게. 돌려준 함수로 취소 */
export function preloadGoogle(): () => void {
const run = () => void loadGoogle().catch((e: unknown) => console.error('[google] preload', e))
if ('requestIdleCallback' in window) {
const id = requestIdleCallback(run, { timeout: 4000 })
return () => cancelIdleCallback(id)
}
const id = setTimeout(run, 2500)
return () => clearTimeout(id)
}
+5
View File
@@ -14,3 +14,8 @@ export function iconSrc(name: string) {
export const fall = (d: string, f = '4.8s') => ({ '--d': d, '--f': f }) as CSSProperties export const fall = (d: string, f = '4.8s') => ({ '--d': d, '--f': f }) as CSSProperties
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)'] } 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)'] }
/** 아래 창이 다 올라오는 시간(.b-sheet 0.26s). 무거운 일은 이 뒤로 미뤄 올라오는 동안 버벅이지 않게 */
export const SHEET_OPEN_MS = 280
/** 아래 창이 내려가며 닫히는 시간(.b-sheet-closing 0.2s). 이 뒤에 실제로 닫는다 */
export const SHEET_CLOSE_MS = 200
+12 -3
View File
@@ -130,13 +130,19 @@ function Composer({ onDone }: { onDone?: (t: TalkData) => void }) {
id={COMPOSE_ID} id={COMPOSE_ID}
value={text} value={text}
onChange={(e) => setText(e.target.value)} onChange={(e) => setText(e.target.value)}
onFocus={(e) => { // 로그인 전엔 읽기 전용이라 눌러도 키보드가 안 올라온다 (키보드가 떴다 내려가며 로그인 창이 버벅이던 것). 누르거나 Enter 면 로그인 창
onClick={(e) => {
if (loggedIn) return if (loggedIn) return
// 로그인 창(<dialog>)은 닫힐 때 포커스를 이 칸으로 돌려놓아 다시 열리므로, 열기 전에 포커스를 뺀다 // 창이 닫힐 때 포커스가 이 칸으로 돌아와 테두리가 번쩍이지 않게
e.currentTarget.blur() e.currentTarget.blur()
open({ type: 'login' }) open({ type: 'login' })
}} }}
readOnly={busy} onKeyDown={(e) => {
if (loggedIn || (e.key !== 'Enter' && e.key !== ' ')) return
e.preventDefault()
open({ type: 'login' })
}}
readOnly={busy || !loggedIn}
maxLength={BODY_MAX} maxLength={BODY_MAX}
rows={2} rows={2}
placeholder={`지금 ${region.name.split(' ').at(-1)} 날씨 어때요?`} placeholder={`지금 ${region.name.split(' ').at(-1)} 날씨 어때요?`}
@@ -360,7 +366,10 @@ export function TalkGroup({ title, topic, talks }: { title: string; topic?: numb
export function FirstTalkCard() { export function FirstTalkCard() {
const { region } = useRegion() const { region } = useRegion()
const place = region.name.split(' ').at(-1) const place = region.name.split(' ').at(-1)
const { loggedIn } = useAuth()
const { open } = useSheet()
const go = () => { const go = () => {
if (!loggedIn) return open({ type: 'login' })
const el = document.getElementById(COMPOSE_ID) const el = document.getElementById(COMPOSE_ID)
el?.scrollIntoView({ behavior: 'smooth', block: 'center' }) el?.scrollIntoView({ behavior: 'smooth', block: 'center' })
el?.focus({ preventScroll: true }) el?.focus({ preventScroll: true })