Skip to content
Merged
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
5 changes: 5 additions & 0 deletions .changeset/bright-peaches-change.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@clerk/elements": patch
---

Refactor form hooks and utils into separate files
1 change: 1 addition & 0 deletions packages/elements/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ module.exports = {
globals: {
PACKAGE_NAME: '@clerk/elements',
PACKAGE_VERSION: '0.0.0-test',
__DEV__: false,
},
displayName: name.replace('@clerk', ''),
injectGlobals: true,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { renderHook } from '@testing-library/react';

import * as internalFormHooks from '~/internals/machines/form/form.context';

import { useFieldFeedback } from '../use-field-feedback';

type Props = Parameters<typeof useFieldFeedback>[0];

describe('useFieldFeedback', () => {
it('should correctly output feedback', () => {
const initialProps = { name: 'foo' };
const returnValue = { codes: 'bar', message: 'baz', type: 'error' };

jest.spyOn(internalFormHooks, 'useFormSelector').mockReturnValue(returnValue);

const { result } = renderHook((props: Props) => useFieldFeedback(props), { initialProps });

expect(result.current).toEqual({ feedback: returnValue });
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { fireEvent, render, renderHook } from '@testing-library/react';
import { createActor, createMachine } from 'xstate';

import { ClerkElementsError } from '~/internals/errors';

import { useForm } from '../use-form';
import * as errorHooks from '../use-global-errors';

describe('useForm', () => {
const machine = createMachine({
on: {
RESET: '.idle',
},
initial: 'idle',
states: {
idle: {
on: {
SUBMIT: 'success',
},
},
success: {},
},
});

const actor = createActor(machine).start();

beforeEach(() => {
actor.send({ type: 'RESET' });
});

it('should correctly output props (no errors)', () => {
jest.spyOn(errorHooks, 'useGlobalErrors').mockReturnValue({ errors: [] });

const { result } = renderHook(() => useForm({ flowActor: actor }));

expect(result.current).toEqual({
props: {
onSubmit: expect.any(Function),
},
});
});

it('should correctly output props (has errors)', () => {
jest.spyOn(errorHooks, 'useGlobalErrors').mockReturnValue({
errors: [new ClerkElementsError('email-link-verification-failed', 'Email verification failed')],
});

const { result } = renderHook(() => useForm({ flowActor: actor }));

expect(result.current).toEqual({
props: {
'data-global-error': true,
onSubmit: expect.any(Function),
},
});
});

it('should create an onSubmit handler', () => {
jest.spyOn(errorHooks, 'useGlobalErrors').mockReturnValue({ errors: [] });

const { result } = renderHook(() => useForm({ flowActor: actor }));
const { getByTestId } = render(
<form
data-testid='form'
onSubmit={result.current.props.onSubmit}
/>,
);

fireEvent.submit(getByTestId('form'));

expect(actor.getSnapshot().value).toEqual('success');
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { renderHook } from '@testing-library/react';

import { ClerkElementsError } from '~/internals/errors';
import * as internalFormHooks from '~/internals/machines/form/form.context';

import { useGlobalErrors } from '../use-global-errors';

describe('useGlobalErrors', () => {
it('should correctly output errors (no errors)', () => {
const returnValue: ClerkElementsError[] = [];

jest.spyOn(internalFormHooks, 'useFormSelector').mockReturnValue([]);

const { result } = renderHook(() => useGlobalErrors());

expect(result.current).toEqual({ errors: returnValue });
});

it('should correctly output errors (has errors)', () => {
const returnValue = [new ClerkElementsError('email-link-verification-failed', 'Email verification failed')];

jest.spyOn(internalFormHooks, 'useFormSelector').mockReturnValue(returnValue);

const { result } = renderHook(() => useGlobalErrors());

expect(result.current).toEqual({ errors: returnValue });
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { renderHook } from '@testing-library/react';

import { usePrevious } from '../use-previous';

describe('usePrevious', () => {
it('should retain the previous value', () => {
const { result, rerender } = renderHook((props: string) => usePrevious(props), { initialProps: 'foo' });
expect(result.current).toBeUndefined();

rerender('bar');
expect(result.current).toBe('foo');

rerender('baz');
expect(result.current).toBe('bar');
});
});
9 changes: 9 additions & 0 deletions packages/elements/src/react/common/form/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export { useField } from './use-field';
export { useFieldContext, FieldContext } from './use-field-context';
export { useFieldFeedback } from './use-field-feedback';
export { useFieldState } from './use-field-state';
export { useForm } from './use-form';
export { useGlobalErrors } from './use-global-errors';
export { useInput } from './use-input';
export { usePrevious } from './use-previous';
export { useValidityStateContext, ValidityStateContext } from './use-validity-state-context';
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import * as React from 'react';

import type { FieldDetails } from '~/internals/machines/form';

export const FieldContext = React.createContext<Pick<FieldDetails, 'name'> | null>(null);
export const useFieldContext = () => React.useContext(FieldContext);
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { type FieldDetails, fieldFeedbackSelector, useFormSelector } from '~/internals/machines/form';

export function useFieldFeedback({ name }: Partial<Pick<FieldDetails, 'name'>>) {
const feedback = useFormSelector(fieldFeedbackSelector(name));

return {
feedback,
};
}
43 changes: 43 additions & 0 deletions packages/elements/src/react/common/form/hooks/use-field-state.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { type FieldDetails, fieldHasValueSelector, useFormSelector } from '~/internals/machines/form';

import { FIELD_STATES, type FieldStates } from '../types';
import { useFieldFeedback } from './use-field-feedback';

/**
* Given a field name, determine the current state of the field
*/
export function useFieldState({ name }: Partial<Pick<FieldDetails, 'name'>>) {
const { feedback } = useFieldFeedback({ name });
const hasValue = useFormSelector(fieldHasValueSelector(name));

/**
* If hasValue is false, the state should be idle
* The rest depends on the feedback type
*/
let state: FieldStates = FIELD_STATES.idle;

if (!hasValue) {
state = FIELD_STATES.idle;
}

switch (feedback?.type) {
case 'error':
state = FIELD_STATES.error;
break;
case 'warning':
state = FIELD_STATES.warning;
break;
case 'info':
state = FIELD_STATES.info;
break;
case 'success':
state = FIELD_STATES.success;
break;
default:
break;
}

return {
state,
};
}
19 changes: 19 additions & 0 deletions packages/elements/src/react/common/form/hooks/use-field.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { type FieldDetails, fieldHasValueSelector, useFormSelector } from '~/internals/machines/form';

import { useFieldFeedback } from './use-field-feedback';

export function useField({ name }: Partial<Pick<FieldDetails, 'name'>>) {
const hasValue = useFormSelector(fieldHasValueSelector(name));
const { feedback } = useFieldFeedback({ name });

const shouldBeHidden = false; // TODO: Implement clerk-js utils
const hasError = feedback ? feedback.type === 'error' : false;

return {
hasValue,
props: {
'data-hidden': shouldBeHidden ? true : undefined,
serverInvalid: hasError,
},
};
}
30 changes: 30 additions & 0 deletions packages/elements/src/react/common/form/hooks/use-form.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { useCallback } from 'react';
import type { BaseActorRef } from 'xstate';

import { useGlobalErrors } from './use-global-errors';

/**
* Provides the form submission handler along with the form's validity via a data attribute
*/
export function useForm({ flowActor }: { flowActor?: BaseActorRef<{ type: 'SUBMIT' }> }) {
const { errors } = useGlobalErrors();

// Register the onSubmit handler for form submission
// TODO: merge user-provided submit handler
const onSubmit = useCallback(
(event: React.FormEvent<Element>) => {
event.preventDefault();
if (flowActor) {
flowActor.send({ type: 'SUBMIT' });
}
},
[flowActor],
);

return {
props: {
...(errors.length > 0 ? { 'data-global-error': true } : {}),
onSubmit,
},
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { globalErrorsSelector, useFormSelector } from '~/internals/machines/form';

export function useGlobalErrors() {
const errors = useFormSelector(globalErrorsSelector);

return {
errors,
};
}
Loading