69 lines
3.4 KiB
TypeScript
69 lines
3.4 KiB
TypeScript
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<HTMLDivElement>(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 <Skel shape className="mx-auto h-[44px] w-full max-w-[400px] rounded-full" />
|
|
if (!clientId) return null
|
|
return (
|
|
<div className="flex flex-col gap-2">
|
|
<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>}
|
|
</div>
|
|
)
|
|
}
|