import { useMutation, useQuery } from '@tanstack/react-query' import { useEffect, useRef, useState } from 'react' import { authConfigOptions, googleLoginMutation } from '../api/client/@tanstack/react-query.gen' import type { ResAuth } from '../api/client/types.gen' type GoogleId = { initialize: (o: { client_id: string; callback: (r: { credential?: string }) => void; ux_mode?: 'popup' }) => void renderButton: (el: HTMLElement, o: Record) => void } declare global { interface Window { google?: { accounts: { id: GoogleId } } } } const SCRIPT = 'https://accounts.google.com/gsi/client' let loading: Promise | null = null /** 구글 로그인 스크립트는 로그인 창을 처음 열 때 한 번만 받는다 */ function loadGoogle(): Promise { 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가 없으면 아무것도 그리지 않는다 */ export function GoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) => void; onFail: () => void }) { const clientId = useQuery({ ...authConfigOptions(), staleTime: Infinity }).data?.google_client_id const login = useMutation(googleLoginMutation()) const box = useRef(null) const [broken, setBroken] = 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 loadGoogle().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 }) }, (e: unknown) => { console.error('[google] script', e) if (alive) setBroken(true) }, ) return () => { alive = false } }, [clientId, mutate]) if (!clientId) return null return (
{broken &&

구글 로그인을 불러오지 못했어요. 아이디로 로그인해 주세요.

}

또는 아이디로

) }