SupportForm.state.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import type { ExtendedSupportCategories } from './Support.constants'
  2. import { neverGuard } from '@/lib/helpers'
  3. export type SupportFormState =
  4. | {
  5. type: 'initializing'
  6. }
  7. | {
  8. type: 'editing'
  9. }
  10. | {
  11. type: 'submitting'
  12. }
  13. | {
  14. type: 'success'
  15. sentProjectRef: string | undefined
  16. sentOrgSlug: string | undefined
  17. sentCategory: ExtendedSupportCategories
  18. }
  19. | {
  20. type: 'error'
  21. message: string
  22. }
  23. export type SupportFormActions =
  24. | { type: 'INITIALIZE'; debugSource?: string }
  25. | { type: 'SUBMIT'; debugSource?: string }
  26. | {
  27. type: 'SUCCESS'
  28. sentProjectRef: string | undefined
  29. sentOrgSlug: string | undefined
  30. sentCategory: ExtendedSupportCategories
  31. debugSource?: string
  32. }
  33. | { type: 'ERROR'; message: string; debugSource?: string }
  34. | { type: 'RETURN_TO_EDITING'; debugSource?: string }
  35. export function createInitialSupportFormState(): SupportFormState {
  36. return {
  37. type: 'initializing',
  38. }
  39. }
  40. export function supportFormReducer(
  41. state: SupportFormState,
  42. action: SupportFormActions
  43. ): SupportFormState {
  44. switch (state.type) {
  45. case 'initializing':
  46. if (action.type === 'INITIALIZE') {
  47. return { type: 'editing' }
  48. }
  49. console.warn(
  50. `[SupportForm > supportFormReducer] ${action.type} action not allowed in 'initializing' state`
  51. )
  52. return state
  53. case 'editing':
  54. if (action.type === 'SUBMIT') {
  55. return { type: 'submitting' }
  56. }
  57. console.warn(
  58. `[SupportForm > supportFromReducer] ${action.type} action not allowed in 'filling_out' state`
  59. )
  60. return state
  61. case 'submitting':
  62. if (action.type === 'SUCCESS') {
  63. return {
  64. type: 'success',
  65. sentProjectRef: action.sentProjectRef,
  66. sentOrgSlug: action.sentOrgSlug,
  67. sentCategory: action.sentCategory,
  68. }
  69. }
  70. if (action.type === 'ERROR') {
  71. return {
  72. type: 'error',
  73. message: action.message,
  74. }
  75. }
  76. console.warn(
  77. `[SupportForm > supportFormReducer] ${action.type} action not allowed in 'submitting' state`
  78. )
  79. return state
  80. case 'success':
  81. console.warn(`[SupportForm > supportFormReducer] ${action.type} allowed in 'success' state`)
  82. return state
  83. case 'error':
  84. if (action.type === 'RETURN_TO_EDITING') {
  85. return { type: 'editing' }
  86. }
  87. console.warn(`[SupportForm > supportFormReducer] ${action.type} allowed in 'success' state`)
  88. return state
  89. default:
  90. return neverGuard(state)
  91. }
  92. }