Skip to content

Replace custom multi-view component with an implementation using react-router #232

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
"react": "^16.9.24",
"react-dom": "^16.9.24",
"react-phone-number-input": "^3.4.3",
"react-router-dom": "^6.28.0",
"react-transition-group": "4.4.2",
"remarkable": "2.0.1",
"validator": "^13.11.0"
Expand Down
6 changes: 3 additions & 3 deletions src/components/miscComponent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React, { AnchorHTMLAttributes, ComponentType, HTMLAttributes, MouseEvent

import { Remarkable } from 'remarkable';
import styled from 'styled-components';
import { useRouting } from '../contexts/routing'
import { useNavigate } from 'react-router-dom';

export const Heading = styled.div`
margin-bottom: ${props => props.theme.spacing * 1.5}px;
Expand Down Expand Up @@ -74,12 +74,12 @@ export const Alternative = styled.div`
`;

export const Link = styled(({ target, href = '#', children, className, controller }: {controller?: AbortController} & AnchorHTMLAttributes<HTMLAnchorElement>) => {
const { goTo } = useRouting()
const navigate = useNavigate()

const onClick = target ? ((e: MouseEvent<HTMLAnchorElement>) => {
controller?.abort(`Going to ${target}`)
e.preventDefault();
goTo(target);
navigate(target);
}) : (() => { });

return (
Expand Down
34 changes: 34 additions & 0 deletions src/components/widget/widget.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React, { ComponentType } from 'react';
import { ThemeProvider } from 'styled-components'
import type { SessionInfo, Client as CoreClient } from '@reachfive/identity-core'
import { createMemoryRouter, Navigate, RouterProvider } from 'react-router-dom';

import type { Config, Prettify } from '../../types'
import type { I18nMessages } from '../../core/i18n';
Expand Down Expand Up @@ -113,3 +114,36 @@ function multiViewWidget<P, U>({ initialView, views, initialState = {} as MultiW
}
}
}

export interface RouterWidgetProps<P, U> {
fallbackElement?: React.ReactNode
initialView: ((props: Omit<U, 'theme'>) => string) | string
prepare?: PrepareFn<P, U>
routes: Record<string, React.ComponentType<Omit<U, 'theme'>>>
}

export function createRouterWidget<P, U = P>({ fallbackElement, initialView, prepare, routes }: RouterWidgetProps<P, U>) {
console.log(window.location)
return createWidget<P, U>({
component: (props: Omit<U, 'theme'>) => {
const initialRoute = typeof initialView === 'function' ? initialView(props) : initialView
const router = createMemoryRouter([
...Object.entries(routes).map(([path, RouteComponent]) => ({
path,
element: <RouteComponent {...props} />,
index: true,
})),
{ path: '*', element: <Navigate to={initialRoute} replace /> }
])
console.log(router)
return (
<RouterProvider
router={router}
fallbackElement={fallbackElement}
/>
)
},
prepare: prepare,
noIntro: true
});
}
24 changes: 12 additions & 12 deletions src/widgets/accountRecovery/accountRecoveryWidget.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import React from 'react';
import styled from 'styled-components'
import { useNavigate } from 'react-router-dom';

import { parseQueryString } from '../../helpers/queryString'

import { Alternative, Heading, Info, Link, Intro, Separator } from '../../components/miscComponent';
import { createMultiViewWidget } from '../../components/widget/widget';
import { createRouterWidget } from '../../components/widget/widget';
import { useReachfive } from '../../contexts/reachfive';
import { useRouting } from '../../contexts/routing';
import { useI18n } from '../../contexts/i18n';
import { createForm } from '../../components/form/formComponent'
import { PasswordEditorForm, PasswordEditorFormData } from '../passwordEditor/passwordEditorWidget.tsx'
import { ReactComponent as Passkeys } from '../../icons/passkeys.svg'
import styled from 'styled-components'


interface MainViewProps {
Expand Down Expand Up @@ -79,7 +79,7 @@ const NewPasskey = ({
}: PropsWithAuthentication<MainViewProps>) => {
const coreClient = useReachfive()
const i18n = useI18n()
const {goTo} = useRouting()
const navigate = useNavigate()

const handleSubmit = () => {
return coreClient.resetPasskeys({
Expand All @@ -91,7 +91,7 @@ const NewPasskey = ({

const handleSuccess = () => {
onSuccess();
goTo('passkey-success');
navigate('/passkey-success');
};

return (
Expand All @@ -108,7 +108,7 @@ const NewPasskey = ({
{allowCreatePassword &&
<Alternative>
<Separator text={i18n('or')} />
<Intro><Link target="new-password">Create a new password</Link></Intro>
<Intro><Link target="/new-password">Create a new password</Link></Intro>
</Alternative>
}
</div>
Expand Down Expand Up @@ -157,7 +157,7 @@ export const NewPasswordView = ({
}: PropsWithAuthentication<MainViewProps>) => {
const coreClient = useReachfive()
const i18n = useI18n()
const { goTo } = useRouting()
const navigate = useNavigate()

const handleSubmit = ({ password }: PasswordEditorFormData) => {
return coreClient.updatePassword({
Expand All @@ -168,7 +168,7 @@ export const NewPasswordView = ({

const handleSuccess = () => {
onSuccess();
goTo('password-success');
navigate('/password-success');
};

return (
Expand All @@ -181,15 +181,15 @@ export const NewPasswordView = ({
onSuccess={handleSuccess}
onError={onError} />
<Alternative>
<Link target="new-passkey">Back</Link>
<Link target="/new-passkey">Back</Link>
</Alternative>
</div>
)
}

const resolveCode = () => {
const qs = (window.location.search && window.location.search.length)
? window.location.search.substr(1)
? window.location.search.substring(1)
: '';
const {verificationCode, email, clientId} = parseQueryString(qs)
return {authentication: { verificationCode, email, clientId } as Authentication};
Expand All @@ -201,9 +201,9 @@ type PropsWithAuthentication<P> = P & { authentication: Authentication }
export interface AccountRecoveryWidgetProps extends MainViewProps, SuccessViewProps {
}

export default createMultiViewWidget<AccountRecoveryWidgetProps, PropsWithAuthentication<AccountRecoveryWidgetProps>>({
export default createRouterWidget<AccountRecoveryWidgetProps, PropsWithAuthentication<AccountRecoveryWidgetProps>>({
initialView: 'new-passkey',
views: {
routes: {
'new-passkey': NewPasskey,
'new-password': NewPasswordView,
'passkey-success': PasskeySuccessView,
Expand Down
6 changes: 3 additions & 3 deletions src/widgets/auth/authWidget.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { type SessionInfo } from '@reachfive/identity-core'

import { UserError } from '../../helpers/errors';
import { createMultiViewWidget } from '../../components/widget/widget';
import { createRouterWidget } from '../../components/widget/widget';

import LoginView, { type LoginViewProps } from './views/loginViewComponent'
import LoginWithWebAuthnView, { type LoginWithWebAuthnViewProps } from './views/loginWithWebAuthnViewComponent'
Expand Down Expand Up @@ -56,7 +56,7 @@ export function selectLogin(initialScreen?: InitialScreen, allowWebAuthnLogin?:
return !allowWebAuthnLogin ? 'login' : 'login-with-web-authn'
}

export default createMultiViewWidget<AuthWidgetProps, PropsWithSession<AuthWidgetProps>>({
export default createRouterWidget<AuthWidgetProps, PropsWithSession<AuthWidgetProps>>({
initialView({
initialScreen,
allowLogin = true,
Expand All @@ -79,7 +79,7 @@ export default createMultiViewWidget<AuthWidgetProps, PropsWithSession<AuthWidge
|| (allowSignup && 'signup')
|| 'forgot-password';
},
views: {
routes: {
'login': LoginView,
'login-with-web-authn': LoginWithWebAuthnView,
'login-with-password': LoginWithPasswordView,
Expand Down
6 changes: 3 additions & 3 deletions src/widgets/auth/views/accountRecoveryViewComponent.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React, { useCallback, useLayoutEffect } from 'react';
import { RequestAccountRecoveryParams } from '@reachfive/identity-core/es/main/profileClient';
import { useNavigate } from 'react-router-dom';

import { AppError } from '../../../helpers/errors'

Expand All @@ -11,7 +12,6 @@ import { simpleField } from '../../../components/form/fields/simpleField';
import ReCaptcha, {importGoogleRecaptchaScript} from '../../../components/reCaptcha';

import { useI18n } from '../../../contexts/i18n'
import { useRouting } from '../../../contexts/routing';
import { useReachfive } from '../../../contexts/reachfive';

const AccountRecoveryForm = createForm<RequestAccountRecoveryParams>({
Expand Down Expand Up @@ -80,7 +80,7 @@ export const AccountRecoveryView = ({
returnToAfterAccountRecovery,
}: AccountRecoveryViewProps) => {
const coreClient = useReachfive()
const { goTo } = useRouting()
const navigate = useNavigate()
const i18n = useI18n()

const callback = useCallback((data: RequestAccountRecoveryParams) =>
Expand All @@ -104,7 +104,7 @@ export const AccountRecoveryView = ({
<AccountRecoveryForm
showLabels={showLabels}
handler={callback}
onSuccess={() => goTo('account-recovery-success')}
onSuccess={() => navigate('/account-recovery-success')}
skipError={displaySafeErrorMessage && skipError} />
{allowLogin && <Alternative>
<Link target={'login'}>{i18n('accountRecovery.backToLoginLink')}</Link>
Expand Down
34 changes: 17 additions & 17 deletions src/widgets/auth/views/forgotPasswordViewComponent.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React, { useCallback, useLayoutEffect, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';

import { AppError } from '../../../helpers/errors'

Expand All @@ -11,7 +12,6 @@ import { simpleField } from '../../../components/form/fields/simpleField';
import ReCaptcha, {importGoogleRecaptchaScript} from '../../../components/reCaptcha';

import { useI18n } from '../../../contexts/i18n'
import { useRouting } from '../../../contexts/routing';
import { useReachfive } from '../../../contexts/reachfive';
import { selectLogin } from '../authWidget.tsx';
import { InitialScreen } from '../../../../constants.ts';
Expand Down Expand Up @@ -170,7 +170,7 @@ export const ForgotPasswordView = ({
}: ForgotPasswordViewProps) => {
const coreClient = useReachfive()
const config = useConfig()
const { goTo } = useRouting()
const navigate = useNavigate()
const i18n = useI18n()

const callback = useCallback(
Expand All @@ -185,7 +185,7 @@ export const ForgotPasswordView = ({
[coreClient, recaptcha_enabled, recaptcha_site_key, redirectUrl, returnToAfterPasswordReset]
)

const onSuccess = () => goTo('forgot-password-success')
const onSuccess = () => navigate('/forgot-password-success')

useLayoutEffect(() => {
importGoogleRecaptchaScript(recaptcha_site_key)
Expand All @@ -203,7 +203,7 @@ export const ForgotPasswordView = ({
/>
{allowPhoneNumberResetPassword && config.sms && (
<Alternative>
<DefaultButton onClick={() => goTo('forgot-password-phone-number')}>{i18n('forgotPassword.usePhoneNumberButton')}</DefaultButton>
<DefaultButton onClick={() => navigate('/forgot-password-phone-number')}>{i18n('forgotPassword.usePhoneNumberButton')}</DefaultButton>
</Alternative>
)}
{allowLogin && (
Expand All @@ -227,7 +227,7 @@ export const ForgotPasswordPhoneNumberView = ({
returnToAfterPasswordReset,
}: ForgotPasswordViewProps) => {
const coreClient = useReachfive()
const { goTo } = useRouting()
const navigate = useNavigate()
const i18n = useI18n()

const [phoneNumber, setPhoneNumber] = useState<string>('')
Expand All @@ -245,7 +245,7 @@ export const ForgotPasswordPhoneNumberView = ({
[coreClient, recaptcha_enabled, recaptcha_site_key, redirectUrl, returnToAfterPasswordReset]
)

const onSuccess = () => goTo<PhoneNumberIdentifier>('forgot-password-code', { phoneNumber })
const onSuccess = () => navigate('/forgot-password-code', { state: { phoneNumber } satisfies PhoneNumberIdentifier})

useLayoutEffect(() => {
importGoogleRecaptchaScript(recaptcha_site_key)
Expand All @@ -262,13 +262,11 @@ export const ForgotPasswordPhoneNumberView = ({
skipError={displaySafeErrorMessage && skipError}
/>
<Alternative>
<DefaultButton onClick={() => goTo('forgot-password')}>{i18n('forgotPassword.useEmailButton')}</DefaultButton>
<DefaultButton onClick={() => navigate('/forgot-password')}>{i18n('forgotPassword.useEmailButton')}</DefaultButton>
</Alternative>
{allowLogin && (
<Alternative>
<Link target={selectLogin(initialScreen, allowWebAuthnLogin)}>{i18n('forgotPassword.backToLoginLink')}</Link>
</Alternative>
)}
{allowLogin && <Alternative>
<Link target={selectLogin(initialScreen, allowWebAuthnLogin)}>{i18n('forgotPassword.backToLoginLink')}</Link>
</Alternative>}
</div>
)
}
Expand All @@ -283,14 +281,16 @@ export const ForgotPasswordCodeView = ({
showLabels = false
}: ForgotPasswordViewProps) => {
const coreClient = useReachfive()
const { goTo, params } = useRouting()
const navigate = useNavigate()
const location = useLocation()
const params = location.state as PhoneNumberIdentifier
const i18n = useI18n()

console.log(params)
const callback = useCallback(
({ passwordConfirmation: _, ...data }: VerificationCodeFormData) => {
return coreClient.updatePassword({ ...(params as PhoneNumberIdentifier), ...data })
return coreClient.updatePassword({ ...params, ...data })
},
[coreClient, redirectUrl, returnToAfterPasswordReset]
[coreClient, params, redirectUrl, returnToAfterPasswordReset]
)

return (
Expand All @@ -300,7 +300,7 @@ export const ForgotPasswordCodeView = ({
<VerificationCodeForm
showLabels={showLabels}
handler={callback}
onSuccess={() => goTo('login')}
onSuccess={() => navigate('/login')}
skipError={displaySafeErrorMessage && skipError}
/>
{allowLogin && (
Expand Down
Loading