import { useMutation, useQuery } from '@tanstack/react-query' import { useEffect, useRef, useState } from 'react' import { authConfigOptions, googleLoginMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen' import type { ResAuth } from '@nalssigak/shared/api/client/types.gen' import { cx } from '../lib/utils' import { loadGoogle } from './googleScript' import { SHEET_OPEN_MS } from './lib' import { Skel } from './ui' /** 구글로 계속하기 버튼. 서버에 클라이언트 ID가 없으면 아무것도 그리지 않는다 */ export function GoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) => void; onFail: () => void }) { const config = useQuery({ ...authConfigOptions(), staleTime: Infinity }) const clientId = config.data?.google_client_id const login = useMutation(googleLoginMutation()) const box = useRef(null) const [broken, setBroken] = useState(false) // 구글 버튼(iframe)이 다 그려지기 전엔 같은 크기의 스켈레톤을 보여 준다. 빈칸에 버튼이 툭 튀어나오면 버벅이는 것처럼 보여서 const [ready, setReady] = useState(false) const { mutate } = login // 로그인 창이 다시 그려질 때마다 버튼을 새로 만들지 않게 콜백은 ref 로 들고 있는다 const cb = useRef({ onResult, onFail }) useEffect(() => { cb.current = { onResult, onFail } }, [onResult, onFail]) useEffect(() => { if (!clientId || !box.current) return let alive = true // 버튼(iframe)을 만드는 일이 무거워, 로그인 창이 다 올라온 뒤에 만든다. 자리는 min-h 로 잡아 둬서 밀리지 않는다 const wait = new Promise((r) => setTimeout(r, SHEET_OPEN_MS)) Promise.all([loadGoogle(), wait]).then( ([g]) => { if (!alive || !box.current) return g.initialize({ client_id: clientId, ux_mode: 'popup', callback: (r) => { if (!r.credential) return cb.current.onFail() mutate({ body: { credential: r.credential } }, { onSuccess: (res) => cb.current.onResult(res), onError: () => cb.current.onFail() }) }, }) 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) => { console.error('[google] script', e) if (alive) setBroken(true) }, ) return () => { alive = false } }, [clientId, mutate]) if (config.isPending) return if (!clientId) return null return (
{!ready && !broken && }
{broken &&

구글 로그인을 불러오지 못했어요. 잠시 뒤에 다시 해 주세요.

}
) }