generated from taylorbryant/gatsby-starter-tailwind
-
-
Notifications
You must be signed in to change notification settings - Fork 113
/
cragSummary.tsx
660 lines (596 loc) · 20.7 KB
/
cragSummary.tsx
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
import React, { useState, useEffect } from 'react'
import { useRouter } from 'next/router'
import dynamic from 'next/dynamic'
import { useForm, FormProvider } from 'react-hook-form'
import { useSession } from 'next-auth/react'
import * as Portal from '@radix-ui/react-portal'
import { MapPinIcon } from '@heroicons/react/24/outline'
import { toast } from 'react-toastify'
import { Summary } from '@/app/(default)/components/ui/Summary'
import { AreaUpdatableFieldsType, AreaType, ClimbDisciplineRecord, ClimbDiscipline, ChangesetType, AuthorMetadata, OrganizationType } from '../../js/types'
import { IndividualClimbChangeInput, UpdateOneAreaInputType } from '../../js/graphql/gql/contribs'
import { getMapHref, sortByLeftRightIndex, removeTypenameFromDisciplines } from '../../js/utils'
import { AREA_NAME_FORM_VALIDATION_RULES, AREA_LATLNG_FORM_VALIDATION_RULES, AREA_DESCRIPTION_FORM_VALIDATION_RULES } from '../edit/EditAreaForm'
import { AreaDesignationRadioGroupProps, areaDesignationToDb, areaDesignationToForm } from '../edit/form/AreaDesignationRadioGroup'
import { ClimbListPreview, findDeletedCandidates } from './ClimbListPreview'
import useUpdateClimbsCmd from '../../js/hooks/useUpdateClimbsCmd'
import useUpdateAreasCmd from '../../js/hooks/useUpdateAreasCmd'
import { DeleteAreaTrigger } from '../edit/Triggers'
import { AreaCRUD } from '../edit/AreaCRUD'
import { StickyHeader, Skeleton as HeaderSkeleton } from './StickyHeader'
import { InplaceTextInput, InplaceEditor } from '../editor'
import EditModeToggle from '../editor/EditModeToggle'
import { FormSaveActionProps } from '../../components/editor/FormSaveAction'
import { ArticleLastUpdate } from '../edit/ArticleLastUpdate'
import Grade, { GradeHelper } from '../../js/grades/Grade'
import { BulkEditorTooltip, BulkEditorTipSheet } from './BulkEditorTooltip'
import { PageBanner as LCOBanner } from '../lco/PageBanner'
import { DialogContent, DialogTrigger, MobileDialog } from '../ui/MobileDialog'
import RecentChangeHistory from '../edit/RecentChangeHistory'
import { isEmpty } from 'underscore'
export type AreaSummaryType = Pick<AreaType, 'uuid' | 'areaName' | 'climbs' | 'children' | 'totalClimbs'> & { metadata: Pick<AreaType['metadata'], 'leaf' | 'isBoulder' | 'isDestination'> }
export interface EditableClimbType {
id: string
climbId: string
name: string
gradeStr?: string
leftRightIndex: number
errors?: Record<'gradeStr' | 'disciplines', string | undefined>
isNew?: boolean
disciplines: Partial<ClimbDisciplineRecord>
}
type AreaTypeFormProp = 'crag' | 'area' | 'boulder'
export type SummaryHTMLFormProps = Required<
Pick<AreaUpdatableFieldsType, 'areaName' | 'description'>
> & {
uuid: string
latlng: string
areaType: AreaTypeFormProp
climbList: EditableClimbType[]
}
/**
* Responsive summary of major attributes for a crag / boulder.
*
* **Note:** There's no need to wrap backend API calls in a try/catch block
* because react-hook-form `handleSubmit()` handles it for us and sends exeptions
* to `onError()` callback.
*/
interface CragSummaryProps {
area: AreaType
history: ChangesetType[]
}
export default function CragSummary ({ area, history }: CragSummaryProps): JSX.Element {
const {
uuid,
areaName: initTitle,
content: { description: initDescription },
metadata: areaMeta,
climbs,
ancestors,
organizations,
pathTokens,
children: childAreas,
gradeContext,
authorMetadata
} = area
const { lat: initLat, lng: initLng } = areaMeta
const router = useRouter()
const session = useSession()
/**
* Hold the ref to the area add & delete components.
* We use Portal to avoid nesting the add/delete form inside the Edit form which causes
* unwanted submit.
*/
const [deletePlaceholderRef, setDeletePlaceholderRef] =
useState<HTMLElement | null>()
const [addAreaPlaceholderRef, setAddAreaPlaceholderRef] =
useState<HTMLElement | null>()
/**
* Change this value will trigger a form control reset to Lexical-backed components.
* We use Lexical to build inplace editing components and I don't know of a good way
* to imperatively reset/clear Lexical content without resorting to complicated ref
* forwarding.
* As a workaround (maybe this is how you're supposed to do it) there's a custom
* Lexical plugin that reacts to resetSignal change in useEffect() and resets Lexical
* content.
*/
const [resetSignal, setResetSignal] = useState(0)
const [editMode, setEditMode] = useState(false)
/**
* False during SSR or Next build.
*/
const [clientSide, setClientSide] = useState(false)
/**
* A working copy of child areas that can be updated client side.
* Initially set to the childAreas prop coming from Next build, the cache
* may be updated by the users in the AreaCRUD component.
*/
const [childAreasCache, setChildAreasCache] = useState(sortByLeftRightIndex(childAreas))
useEffect(() => {
setChildAreasCache(sortByLeftRightIndex(childAreas))
}, [childAreas])
/**
* Hold the form base states aka default values. Since we use Next SSG,
* this component props become stale the moment a user submits a change.
* Every time a user submits the form, this cache needs to be updated.
*/
const [cache, setCache] = useState<SummaryHTMLFormProps>({
uuid,
areaName: initTitle,
description: initDescription,
latlng: `${initLat.toString()},${initLng.toString()}`,
areaType: areaDesignationToForm(areaMeta),
climbList: sortByLeftRightIndex(climbs).map(
({
id,
name,
grades,
type: disciplines,
metadata: { leftRightIndex }
}) => {
const sanitizedDisciplines = removeTypenameFromDisciplines(disciplines)
return {
id, // to be used as react key
climbId: id,
name,
gradeStr: new Grade(
gradeContext,
grades,
sanitizedDisciplines,
areaMeta.isBoulder
).toString(),
leftRightIndex,
disciplines: sanitizedDisciplines
}
}
)
})
const { updateClimbCmd, deleteClimbsCmd } = useUpdateClimbsCmd({
parentId: uuid,
accessToken: session?.data?.accessToken as string
})
const { updateOneAreaCmd: updateAreaCmd, getAreaByIdCmd } = useUpdateAreasCmd(
{
areaId: uuid,
accessToken: session?.data?.accessToken as string
}
)
const { data, refetch } = getAreaByIdCmd({ skip: !clientSide || !editMode })
const onAreaCRUDChangeHandler = (): void => {
if (editMode) {
void refetch()
}
void router.replace(router.asPath)
}
// React-hook-form declaration
const form = useForm<SummaryHTMLFormProps>({
mode: 'onBlur',
defaultValues: { ...cache }
})
const {
handleSubmit,
formState: { dirtyFields },
reset,
watch
} = form
const currentLatLngStr = watch('latlng')
const currentClimbList = watch('climbList')
const currentareaType = watch('areaType')
/**
* Form submit handler
*/
const submitHandler = async (
formData: SummaryHTMLFormProps
): Promise<void> => {
const { uuid, areaName, description, latlng, areaType, climbList } =
formData
const [lat, lng] = latlng.split(',')
const updatedClimbs = extractDirtyClimbs(
dirtyFields?.climbList,
climbList,
currentareaType === 'boulder'
)
const deleteCandidiates = findDeletedCandidates(cache.climbList, climbList)
// Extract only dirty fields to send to the Update Area API
const onlyDirtyFields: UpdateOneAreaInputType = {
...(dirtyFields?.areaName === true && { areaName }),
...(dirtyFields?.areaType === true &&
canChangeAreaType &&
areaDesignationToDb(areaType)),
...(dirtyFields?.latlng === true && {
lat: parseFloat(lat),
lng: parseFloat(lng)
}),
...(dirtyFields?.description === true && { description })
}
/**
* Submit button should be disabled (this submitHandler() can't be triggered) when the
* form's global dirty flag is false.
* We still double-check here just in case things fall through the cracks.
*/
const isCragSummaryDirty = Object.keys(onlyDirtyFields).length > 0
const isClimbListDirty = updatedClimbs.length > 0
const hasSomethingToDelete = deleteCandidiates.length > 0
if (!isCragSummaryDirty && !isClimbListDirty && !hasSomethingToDelete) {
toast.warn('Nothing to save. Please make at least 1 edit.')
return
}
if (hasSomethingToDelete) {
const idList = deleteCandidiates.map((entry) => entry.climbId)
await deleteClimbsCmd(idList)
}
// Send climb updates to backend
if (isClimbListDirty) {
await updateClimbCmd({
parentId: uuid,
changes: updatedClimbs
})
}
// Send crag updates to backend
if (isCragSummaryDirty) {
await updateAreaCmd({
...onlyDirtyFields
})
}
setCache({ ...formData })
reset(formData, { keepValues: true })
}
const FormAction = (
<ClientSideFormSaveAction
cache={cache}
editMode={editMode}
onReset={() => setResetSignal(Date.now())}
/>
)
const { areaName, description } = cache
const parentAreaId = ancestors[ancestors.length - 2]
const latlngPair = parseLatLng(currentLatLngStr)
// we're allowed to change area designation when the area has neither climbs nor areas.
const canChangeAreaType =
currentClimbList.length === 0 &&
cache.climbList.length === 0 &&
childAreasCache.length === 0
const canAddAreas =
(currentareaType === 'area' || cache.areaType === 'area') &&
cache.climbList.length === 0
const canAddClimbs = !canAddAreas
/**
* Update refs to divs inside the main form
*/
useEffect(() => {
const deleteAreaDiv = document.getElementById('deleteButtonPlaceholder')
if (deleteAreaDiv != null) {
setDeletePlaceholderRef(deleteAreaDiv)
}
const addAreaDiv = document.getElementById('addAreaPlaceholder')
if (addAreaDiv != null) {
setAddAreaPlaceholderRef(addAreaDiv)
}
}, [editMode, canAddAreas])
/**
* We're in edit mode so let's update local cache with new data from the DB
*/
useEffect(() => {
if (data?.area != null) {
setChildAreasCache(sortByLeftRightIndex(data.area.children))
const { uuid, areaName, metadata, content, climbs } = data.area as AreaType
const { lat, lng } = metadata
setCache((current) => ({
...current,
uuid,
areaName,
description: content.description,
areaType: areaDesignationToForm(metadata),
latlng: `${lat.toString()},${lng.toString()}`,
climbList: sortByLeftRightIndex(climbs).map(
({
id,
name,
grades,
type: disciplines,
metadata: { leftRightIndex }
}) => {
const sanitizedDisciplines =
removeTypenameFromDisciplines(disciplines)
return {
id, // to be used as react key
climbId: id,
name,
gradeStr: new Grade(
gradeContext,
grades,
sanitizedDisciplines,
areaMeta.isBoulder
).toString(),
leftRightIndex,
disciplines: sanitizedDisciplines
}
}
)
}))
}
}, [data?.area])
/**
* Enable clientSide flag so that we can re-fetch child areas from the DB
*/
useEffect(() => {
setClientSide(true)
}, [])
return (
<>
{deletePlaceholderRef != null && (
<Portal.Root container={deletePlaceholderRef}>
{editMode && (
<DeleteAreaTrigger
areaName={areaName}
areaUuid={uuid}
parentUuid={parentAreaId}
disabled={!canChangeAreaType}
/>
)}
</Portal.Root>
)}
{addAreaPlaceholderRef != null && (
<Portal.Root container={addAreaPlaceholderRef}>
{canAddAreas && (
<AreaCRUD
uuid={uuid}
areaName={areaName}
childAreas={childAreasCache}
onChange={onAreaCRUDChangeHandler}
editMode={editMode}
/>
)}
</Portal.Root>
)}
<FormProvider {...form}>
{/* eslint-disable-next-line */}
<form onSubmit={handleSubmit(submitHandler)}>
<StickyHeader
ancestors={ancestors}
pathTokens={pathTokens}
formAction={FormAction}
/>
<div className='mt-4 justify-end items-center flex flex-row' id='editTogglePlaceholder'>
<div className='mr-2' id='editTogglePlaceholder'>
<EditModeToggle onChange={setEditMode} />
</div>
{!isEmpty(history) && (
<MobileDialog>
<DialogTrigger className='btn btn-secondary btn-sm'>
Show Change History
</DialogTrigger>
<DialogContent title='Change history'>
<RecentChangeHistory history={history} />
</DialogContent>
</MobileDialog>
)}
</div>
<Summary
columns={{
left: (
<AreaSection
areaName={areaName}
resetSignal={resetSignal}
editMode={editMode}
currentLatLngStr={currentLatLngStr}
latlngPair={latlngPair}
authorMetadata={authorMetadata}
canChangeAreaType={canChangeAreaType}
/>
),
right: (
<DescriptionSection
description={description}
resetSignal={resetSignal}
editMode={editMode}
organizations={organizations}
/>
)
}}
/>
<div className='mt-4 block lg:hidden'>
{/* Mobile-only */}
{FormAction}
</div>
{canAddAreas && (
<div className='block mt-16 min-h-[8rem]' id='addAreaPlaceholder' />
)}
{canAddClimbs && <ClimbListPreview editable={editMode} />}
{editMode && canAddClimbs && (
<div className='mt-12 fadeinEffect flex flex-col gap-4'>
<div className='flex items-center gap-4'>
<h3>Power Editor</h3>
<BulkEditorTooltip />
</div>
<BulkEditorTipSheet />
<ClimbBulkEditor
name='climbList'
initialClimbs={cache.climbList}
resetSignal={resetSignal}
editable
gradeHelper={new GradeHelper(gradeContext, areaMeta.isBoulder)}
/>
</div>
)}
</form>
</FormProvider>
</>
)
}
/**
* Split lat,lng string into lat and lng tuple. Return null if string is invalid.
*/
export const parseLatLng = (s: string): [number, number] | null => {
const [latStr, lngStr] = s.split(',')
const lat = parseFloat(latStr)
const lng = parseFloat(lngStr)
if (Number.isNaN(lat) || Number.isNaN(lng)) {
return null
}
return [lat, lng]
}
type ClimbDirtyFieldsType = Omit<
Partial<Record<keyof EditableClimbType, boolean>>,
'disciplines' | 'errors'
> & {
disciplines?: Partial<Record<ClimbDiscipline, boolean>>
}
/**
* Use react-hook-form's dirty field flags to return only updated fields
* @param dirtyFields See react-hook-form
* @param climbList Active list extracted from form
*/
const extractDirtyClimbs = (
dirtyFields: ClimbDirtyFieldsType[] = [],
climbList: EditableClimbType[],
isBoulder: boolean
): IndividualClimbChangeInput[] => {
// Reduce climb list in html form to list of objects compatible with `updateClimbs` API
const updateList = climbList.reduce<IndividualClimbChangeInput[]>(
(acc, curr, index) => {
const dirtyObj = dirtyFields?.[index] ?? {}
if (Object.keys(dirtyObj).length === 0) {
// Climb object unchanged, skip
return acc
}
// There's a change
const { climbId, name, leftRightIndex, gradeStr, disciplines } = curr
const isDirtyDisciplines =
Object.values(dirtyObj?.disciplines ?? {}).filter((v) => v).length > 0
acc.push({
id: climbId, // A new random ID will cause an 'upsert', adding it as a new climb
...(dirtyObj?.name === true && { name }), // Include name if changed
...(dirtyObj?.id === true && { leftRightIndex }), // Include ordering index if array index has changed
...(isBoulder && { disciplines: { bouldering: true } }),
...(dirtyObj?.gradeStr === true && { grade: gradeStr, disciplines }),
...(isDirtyDisciplines && { disciplines })
})
return acc
},
[]
)
return updateList
}
/**
* Area/climb main skeleton
*/
export const Skeleton: React.FC = () => (
<div>
<HeaderSkeleton />
<div className='mt-4 text-right'>
<EditModeToggle onChange={() => {}} showSkeleton />
</div>
<div className='area-climb-page-summary'>
<div className='area-climb-page-summary-left'>
<h1 className='text-4xl md:text-5xl rounded-box bg-base-200/10 w-72'>
</h1>
</div>
<div className='area-climb-page-summary-right'>
<h3 className='rounded-box bg-base-200/10 w-48'> </h3>
<div className='mt-4 rounded-box bg-base-200/10 w-full h-80' />
</div>
</div>
</div>
)
export const ClientSideFormSaveAction = dynamic<FormSaveActionProps>(
async () =>
await import('../../components/editor/FormSaveAction').then(
(module) => module.FormSaveAction
),
{
ssr: false
}
)
const ClimbBulkEditor = dynamic(async () => await import('../editor/CsvEditor'))
const AreaDesignationRadioGroup = dynamic<AreaDesignationRadioGroupProps>(
async () =>
await import('../edit/form/AreaDesignationRadioGroup').then(
(module) => module.AreaDesignationRadioGroup
)
)
const AreaSection: React.FC<{ areaName: string, resetSignal: number, editMode: boolean, currentLatLngStr: string, latlngPair: [number, number] | null, authorMetadata: AuthorMetadata, canChangeAreaType: boolean }> = ({
areaName, resetSignal, editMode, currentLatLngStr, latlngPair, authorMetadata, canChangeAreaType
}) => {
return (
<>
<h1 className='text-4xl md:text-5xl'>
<InplaceTextInput
initialValue={areaName}
name='areaName'
reset={resetSignal}
editable={editMode}
placeholder='Area name'
rules={AREA_NAME_FORM_VALIDATION_RULES}
/>
</h1>
{editMode
? (
<InplaceTextInput
initialValue={currentLatLngStr}
name='latlng'
reset={resetSignal}
editable={editMode}
placeholder='Enter a latitude,longitude. Ex: 46.433333,11.85'
rules={AREA_LATLNG_FORM_VALIDATION_RULES}
/>
)
: (
latlngPair != null && (
<div className='flex flex-col text-xs text-base-300 border-t border-b divide-y'>
<a
href={getMapHref({
lat: latlngPair[0],
lng: latlngPair[1]
})}
target='blank'
className='flex items-center gap-2 py-3'
>
<MapPinIcon className='w-5 h-5' />
<span className='mt-0.5'>
<b>LAT,LNG</b>
<span className='link-dotted'>
{latlngPair[0].toFixed(5)}, {latlngPair[1].toFixed(5)}
</span>
</span>
</a>
<ArticleLastUpdate {...authorMetadata} />
</div>
)
)}
{editMode && (
<div className='fadeinEffect'>
<div className='mt-8'>
<h3>Housekeeping</h3>
<AreaDesignationRadioGroup disabled={!canChangeAreaType} />
</div>
<div className='mt-6 form-control'>
<label className='label'>
<span className='label-text font-semibold'>Permanently delete this area</span>
</label>
<div className='ml-2' id='deleteButtonPlaceholder' />
</div>
</div>
)}
</>
)
}
const DescriptionSection: React.FC<{ description: string, resetSignal: number, editMode: boolean, organizations: OrganizationType[] }> = ({
description, resetSignal, editMode, organizations
}) => {
return (
<>
<h3>Description</h3>
<InplaceEditor
initialValue={description}
name='description'
reset={resetSignal}
editable={editMode}
placeholder='Area description'
rules={AREA_DESCRIPTION_FORM_VALIDATION_RULES}
/>
{!editMode && <LCOBanner orgs={organizations} />}
</>
)
}