-
-
Notifications
You must be signed in to change notification settings - Fork 188
Expand file tree
/
Copy pathTickForm.tsx
More file actions
289 lines (273 loc) · 11.9 KB
/
Copy pathTickForm.tsx
File metadata and controls
289 lines (273 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
import { Fragment, useState } from 'react'
import { Dialog, Transition } from '@headlessui/react'
import { useMutation } from '@apollo/client'
import { useSession } from 'next-auth/react'
import { TickType } from '@/js/types'
import Tooltip from '../ui/Tooltip'
import { graphqlClient } from '@/js/graphql/Client'
import { MUTATION_ADD_TICK } from '@/js/graphql/gql/fragments'
import ComboBox from '../ui/ComboBox'
import * as Yup from 'yup'
import { Info } from '@phosphor-icons/react/dist/ssr'
const climbingGlossaryLink = 'https://en.wikipedia.org/wiki/Glossary_of_climbing_terms#'
const CustomTooltip: React.FC<any> = () => {
return (<p>A Glossary of Climbing Terms<br />can be found <a href={climbingGlossaryLink} target='_blank' rel='noreferrer' className='ml-2 mt-1 text-blue-500 underline'>Here</a></p>)
}
// validation schema for ticks
const TickSchema = Yup.object().shape({
name: Yup.string()
.min(2, 'Minimum 2 characters')
.required('Something went wrong, please try again'),
notes: Yup.string()
.max(400, 'Notes can be a maximum of 400 characters'),
climbId: Yup.string()
.required('Something went wrong fetching the climb Id, please try again'),
userId: Yup.string()
.required('Something went wrong fetching your user Id, please try again'),
style: Yup.string(),
attemptType: Yup.string(),
dateClimbed: Yup.date()
.required('Please include a date')
.max(new Date(), 'Please include a date in the past'),
grade: Yup.string()
})
/**
* Options for the dropdown comboboxes
* Tick validation logic is complicated. see [tick_logic.md](https://github.com/OpenBeta/openbeta-graphql/blob/develop/documentation/tick_logic.md).
**/
const allStyles = [
{ id: 1, name: 'Lead' },
{ id: 2, name: 'Follow' },
{ id: 3, name: 'TR' },
{ id: 4, name: 'Solo' },
{ id: 5, name: 'Boulder' },
{ id: 6, name: 'Aid' }
]
const allAttemptTypes = [
{ id: 1, name: 'Onsight' },
{ id: 2, name: 'Flash' },
{ id: 3, name: 'Redpoint' },
{ id: 4, name: 'Pinkpoint' },
{ id: 5, name: 'Send' },
{ id: 6, name: 'Attempt' },
{ id: 7, name: 'Frenchfree' },
{ id: 8, name: 'Repeat' }
]
function hasKey (climbType: object, myList: string[]): boolean { return Object.keys(climbType).some(key => myList.includes(key)) }
function stylesForClimbType (climbType: object): Array<{ id: number, name: string }> {
const leadable = hasKey(climbType, ['trad', 'sport', 'snow', 'ice', 'mixed', 'alpine'])
const topropeable = hasKey(climbType, ['tr']) || (leadable)
const aidable = hasKey(climbType, ['aid'])
const boulderable = hasKey(climbType, ['bouldering'])
const soloable = hasKey(climbType, ['deepwatersolo']) || leadable || aidable || (topropeable && !boulderable)
let styles: Array<{ id: number, name: string }> = []
if (leadable) { styles.push(...allStyles.filter(style => ['Lead', 'Follow'].includes(style.name))) }
if (boulderable) { styles.push(...allStyles.filter(style => ['Boulder'].includes(style.name))) }
if (topropeable) { styles.push(...allStyles.filter(style => ['TR'].includes(style.name))) }
if (aidable) { styles.push(...allStyles.filter(style => ['Aid'].includes(style.name))) }
if (soloable) { styles.push(...allStyles.filter(style => ['Solo'].includes(style.name))) }
if (styles.length === 0) { styles = [...allStyles] } // If a climb doesn't have a type, anything goes
styles.push({ id: 10, name: '\u00A0' })
return styles
}
function attemptTypesForStyle (styleName: string): Array<{ id: number, name: string }> {
const emptyOption = { id: 10, name: '\u00A0' }
switch (styleName) {
case 'Lead':
return [...allAttemptTypes.filter(type => ['Onsight', 'Flash', 'Redpoint', 'Pinkpoint', 'Attempt', 'Frenchfree', 'Repeat'].includes(type.name)), emptyOption]
case 'Solo':
return [...allAttemptTypes.filter(type => ['Onsight', 'Flash', 'Redpoint', 'Attempt', 'Repeat'].includes(type.name)), emptyOption]
case 'Boulder':
return [...allAttemptTypes.filter(type => ['Flash', 'Send', 'Attempt', 'Repeat'].includes(type.name)), emptyOption]
case 'TR':
case 'Follow':
case 'Aid':
return [...allAttemptTypes.filter(type => ['Send', 'Attempt'].includes(type.name)), emptyOption]
default:
return [emptyOption]
}
}
interface Props {
open: boolean
setOpen: Function
setTicks: Function
ticks: TickType[]
isTicked: Function
climbId: string
name?: string
grade?: string
climbType: object
}
export default function TickForm ({ open, setOpen, setTicks, ticks, isTicked, climbId, name, grade, climbType }: Props): JSX.Element {
const styles = stylesForClimbType(climbType)
const [style, setStyle] = useState(styles[0])
const [attemptTypes, setAttemptTypes] = useState(attemptTypesForStyle(style.name))
const defaultAttemptType =
style.name === 'Boulder' ? attemptTypes.find(t => t.name === 'Send') ?? attemptTypes[0] : attemptTypes[0]
const [attemptType, setAttemptType] = useState(defaultAttemptType)
const [dateClimbed, setDateClimbed] = useState<string>(new Date().toLocaleDateString('fr-CA')) // Default is today, use fr-CA to get YYYY-MM-DD format.
const [notes, setNotes] = useState<string>('')
const [errors, setErrors] = useState<string[]>()
const session = useSession()
const [addTick] = useMutation(
MUTATION_ADD_TICK, {
client: graphqlClient,
errorPolicy: 'none'
})
/**
* reset our inputs whenever a form is successfully submitted
*
*/
function resetInputs (): void {
setDateClimbed(new Date().toLocaleDateString('fr-CA'))
const newAttemptTypes = attemptTypesForStyle(styles[0].name)
setAttemptTypes(newAttemptTypes)
setAttemptType(newAttemptTypes[0])
setNotes('')
setStyle(styles[0])
}
function handleStyleChange (newStyle: { id: number, name: string }): void {
setStyle(newStyle)
const newAttemptTypes = attemptTypesForStyle(newStyle.name)
setAttemptTypes(newAttemptTypes)
const defaultAttemptType = newStyle.name === 'Boulder' ? newAttemptTypes.find(t => t.name === 'Send') ?? newAttemptTypes[0] : newAttemptTypes[0]
setAttemptType(defaultAttemptType)
}
async function submitTick (): Promise<void> {
// build a tick object to send to the GraphQL backend
const tick = {
name,
notes,
climbId,
userId: session.data?.user.metadata.uuid,
style: style.name === '\u00A0' ? undefined : style.name,
attemptType: attemptType.name === '\u00A0' ? undefined : attemptType.name,
dateClimbed: new Date(Date.parse(`${dateClimbed}T00:00:00`)), // Date.parse without timezone converts dateClimbed into local timezone.
grade,
source: 'OB' // source manually set as Open Beta
}
// validate the tick object using the YUP schema declared above
// if it doesn't validate or there is some sort of error, render the errors in the form
TickSchema.validate(tick)
.then(async (validTick) => {
const newTick = await addTick({
variables: {
input: validTick
}
})
if (newTick.data !== null) {
const { data } = newTick
// if the tick is persisted in the database
// change the ticks button to the isticked button
isTicked(true)
// todo: add new tick to store whenever that is setup???
setOpen(false)
resetInputs()
// add tick to the previous state
const newTicks = [...ticks, data.addTick]
setTicks(newTicks)
}
})
.catch((error) => {
const gqlErrs = error.graphQLErrors ?? []
if (gqlErrs.length > 0) {
const code = gqlErrs[0].extensions.exception?.code
switch (code) {
case 11000:
case 11001:
setErrors(['Error, duplicate tick found'])
break
default:
setErrors([error.message])
}
} else {
setErrors([error.message])
}
})
}
return (
<Transition.Root show={open} as={Fragment}>
<Dialog as='div' className='relative z-50' onClose={() => setOpen(false)}>
<Transition.Child
as={Fragment}
enter='ease-out duration-300'
enterFrom='opacity-0'
enterTo='opacity-100'
leave='ease-in duration-200'
leaveFrom='opacity-100'
leaveTo='opacity-0'
>
<div className='fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity' />
</Transition.Child>
<div className='fixed z-50 inset-0 overflow-y-auto'>
<div className='flex items-end sm:items-center justify-center min-h-full p-4 text-center sm:p-0'>
<Transition.Child
as={Fragment}
enter='ease-out duration-300'
enterFrom='opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95'
enterTo='opacity-100 translate-y-0 sm:scale-100'
leave='ease-in duration-200'
leaveFrom='opacity-100 translate-y-0 sm:scale-100'
leaveTo='opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95'
>
<Dialog.Panel className='relative bg-white rounded-lg px-4 pt-5 pb-4 text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:max-w-sm sm:w-full sm:p-6'>
<div>
{(errors != null) && errors.length > 0 && errors.map((err, i) => <p className='mt-2 text-ob-primary' key={i}>{err}</p>)}
<label htmlFor='date' className='block text-sm font-medium text-gray-700'>
Date Climbed
</label>
<div className='mt-1'>
<input
type='date'
name='date'
value={dateClimbed}
onChange={(e) => setDateClimbed(e.target.value)}
id='date'
className='py-2 px-3 border border-gray-300 shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md'
/>
</div>
<ComboBox options={styles} value={style} onChange={handleStyleChange} label='Style' />
<div className='flex items-center'>
<label htmlFor='attemptType' className='block text-sm font-medium text-gray-700'>
Attempt Type
</label>
<Tooltip content={<CustomTooltip />}>
<Info className='h-5 w-5' />
</Tooltip>
</div>
<ComboBox options={attemptTypesForStyle(style.name)} value={attemptType} onChange={setAttemptType} label='' />
<div>
<label htmlFor='comment' className='block text-sm font-medium text-gray-700 mt-2'>
Notes
</label>
<div className='mt-1'>
<textarea
rows={6}
name='comment'
value={notes}
onChange={(e) => setNotes(e.target.value)}
id='comment'
className='py-2 px-3 border border-gray-300 shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md'
/>
</div>
</div>
</div>
<div className='mt-5 sm:mt-6'>
<button
type='button'
className='text-center p-2 border-2 rounded-xl border-ob-primary transition
text-ob-primary hover:bg-ob-primary hover:ring hover:ring-ob-primary ring-offset-2
hover:text-white w-full font-bold'
onClick={() => { void submitTick() }}
>
Submit Tick
</button>
</div>
</Dialog.Panel>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition.Root>
)
}