import React , { FunctionComponent , useEffect , useMemo } from "react" ; import { graphql } from "react-relay" ; import { SetViewMutation } from "coral-auth/mutations" ; import { View } from "coral-auth/mutations/SetViewMutation" ; import { useLocal , useMutation , withFragmentContainer , } from "coral-framework/lib/relay" ; import { AccountCompletionContainer_auth } from "coral-auth/__generated__/AccountCompletionContainer_auth.graphql" ; import { AccountCompletionContainer_viewer } from "coral-auth/__generated__/AccountCompletionContainer_viewer.graphql" ; import { AccountCompletionContainerLocal } from "coral-auth/__generated__/AccountCompletionContainerLocal.graphql" ; import CompleteAccountMutation from "./CompleteAccountMutation" ; interface Props { auth : AccountCompletionContainer_auth ; viewer : AccountCompletionContainer_viewer | null ; } const AccountCompletionContainer = ( { viewer , auth , children , } ) => { const completeAccount = useMutation ( CompleteAccountMutation ) ; const setView = useMutation ( SetViewMutation ) ; const [ { view : currentView , accessToken , duplicateEmail } ] = useLocal < AccountCompletionContainerLocal > ( graphql `
    fragment AccountCompletionContainerLocal on Local {
      accessToken
      view
      duplicateEmail
    }
  ` ) ; const localProfileEnabled = auth . integrations . local . enabled && auth . integrations . local . targetFilter . stream ; const hasUsername = ! ! viewer ?. username ; const hasEmail = ! ! viewer ?. email ; const hasLocalProfile = ! ! viewer ?. profiles . some ( ( p ) => p . __typename === "LocalProfile" ) ; const view = useMemo ( ( ) => { if ( ! viewer || ! accessToken ) { return currentView as View ; } if ( ! hasEmail ) { if ( ( duplicateEmail || viewer . duplicateEmail ) && currentView !== "ADD_EMAIL_ADDRESS" ) { return "LINK_ACCOUNT" ; } return "ADD_EMAIL_ADDRESS" ; } if ( ! hasUsername ) { return "CREATE_USERNAME" ; } if ( localProfileEnabled && ! hasLocalProfile ) { return "CREATE_PASSWORD" ; } void completeAccount ( { accessToken } ) ; return false ; } , [ accessToken , completeAccount , currentView , duplicateEmail , hasEmail , hasLocalProfile , hasUsername , localProfileEnabled , viewer , ] ) ; useEffect ( ( ) => { if ( ! view || currentView === view ) { return ; } setView ( { view } ) ; } , [ currentView , setView , view ] ) ; if ( ! view || view !== currentView ) { return null ; } return < > { children } < />; } ; const enhanced = withFragmentContainer < Props > ( { auth : graphql `
    fragment AccountCompletionContainer_auth on Auth {
      integrations {
        local {
          enabled
          targetFilter {
            stream
          }
        }
      }
    }
  ` , viewer : graphql `
    fragment AccountCompletionContainer_viewer on User {
      username
      email
      duplicateEmail
      profiles {
        __typename
      }
    }
  ` , } ) ( AccountCompletionContainer ) ; export default enhanced ;