generated from taylorbryant/gatsby-starter-tailwind
-
-
Notifications
You must be signed in to change notification settings - Fork 114
/
AreaCRUD.tsx
253 lines (229 loc) · 8.64 KB
/
AreaCRUD.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
'use client'
import dynamic from 'next/dynamic'
import type { MouseEvent } from 'react'
import clx from 'classnames'
import {
DndContext,
closestCenter,
KeyboardSensor,
useSensor,
useSensors,
DragOverlay,
DragStartEvent,
DragEndEvent,
MouseSensor as LibMouseSensor
} from '@dnd-kit/core'
import {
arrayMove,
SortableContext,
sortableKeyboardCoordinates,
rectSortingStrategy
} from '@dnd-kit/sortable'
import { useSession } from 'next-auth/react'
import React, { useEffect, useState } from 'react'
import { SortableItem } from './SortableItem'
import { DeleteAreaTrigger, AddAreaTrigger, AddAreaTriggerButtonMd, AddAreaTriggerButtonSm, DeleteAreaTriggerButtonSm } from './Triggers'
import { AreaSummaryType } from '../crag/cragSummary'
import { AreaEntityIcon } from '../EntityIcons'
import NetworkSquareIcon from '../../assets/icons/network-square-icon.svg'
import useUpdateAreasCmd from '../../js/hooks/useUpdateAreasCmd'
import { AreaType } from '../../js/types'
export type AreaCRUDProps = Pick<AreaType, 'uuid' | 'areaName'> & {
childAreas: AreaType[]
editMode: boolean
onChange?: () => void
}
/**
* Responsible for rendering child areas table (Read) and Create/Update/Delete operations.
* @param onChange notify parent of any changes
*/
export const AreaCRUD = ({ uuid: parentUuid, areaName: parentName, childAreas, editMode, onChange }: AreaCRUDProps): JSX.Element => {
const session = useSession()
const areaCount = childAreas.length
// Prepare {uuid: <AreaType>} mapping to avoid passing entire areas around.
const areaStore = new Map(childAreas.map(a => [a.uuid, a]))
const [areasSortedState, setAreasSortedState] = useState<string[]>(Array.from(areaStore.keys()))
const [draggedArea, setDraggedArea] = useState<string | null>(null)
useEffect(() => {
setAreasSortedState(Array.from(areaStore.keys()))
}, [childAreas])
const { updateAreasSortingOrderCmd } = useUpdateAreasCmd({
areaId: parentUuid,
accessToken: session?.data?.accessToken as string ?? ''
})
const sensors = useSensors(
useSensor(MouseSensor),
useSensor(KeyboardSensor, {
coordinateGetter: sortableKeyboardCoordinates
})
)
function handleDragEnd (event: DragEndEvent): void {
const { active, over } = event
setDraggedArea(null)
if (active.id != null && over?.id != null && active.id !== over.id) {
const oldIndex = areasSortedState.indexOf(active.id as string)
const newIndex = areasSortedState.indexOf(over.id as string)
const reorderedChildAreas = arrayMove(areasSortedState, oldIndex, newIndex)
void updateAreasSortingOrderCmd(reorderedChildAreas.map((uuid, idx) => ({ areaId: uuid, leftRightIndex: idx })))
setAreasSortedState(reorderedChildAreas)
}
}
function handleDragStart (event: DragStartEvent): void {
const { active } = event
if (active.id != null) {
setDraggedArea(active.id as string)
}
}
return (
<>
<div className='flex items-center justify-between'>
<div className='flex items-center gap-3'>
<h3 className='flex items-center gap-4'><AreaEntityIcon />Areas</h3>
<AddAreaTrigger parentName={parentName} parentUuid={parentUuid} onSuccess={onChange}>
<AddAreaTriggerButtonSm />
</AddAreaTrigger>
</div>
{/* eslint-disable-next-line @typescript-eslint/restrict-template-expressions */}
<span className='text-base-300 text-sm'>{areaCount > 0 && `Total: ${areaCount}`}</span>
</div>
<hr className='mt-4 border-1 border-base-content' />
{areaCount === 0 && (
<div>
<div className='mb-8 italic text-base-300'>This area doesn't have any child areas.</div>
{editMode && <AddAreaTrigger parentName={parentName} parentUuid={parentUuid} onSuccess={onChange} />}
</div>)}
{areaCount > 0 && (
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragEnd={handleDragEnd}
onDragStart={handleDragStart}
>
<div
className={`two-column-table ${editMode ? '' : 'xl:grid-cols-2 lg:grid-cols-2 md:grid-cols-2'
} fr-2`}
>
<SortableContext
items={areasSortedState}
strategy={rectSortingStrategy}
>
{areasSortedState.map((uuid, idx) => {
const areaProps = areaStore.get(uuid)
if (areaProps == null || Object.keys(areaProps).length === 0) return null
return (
<SortableItem id={uuid} key={uuid} disabled={!editMode}>
<AreaItem
index={idx}
borderBottom={[Math.ceil(areaCount / 2) - 1, areaCount - 1].includes(idx)}
parentUuid={parentUuid}
{/* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */
...areaProps}
editMode={editMode}
onChange={onChange}
/>
</SortableItem>
)
})}
</SortableContext>
</div>
<DragOverlay>
{draggedArea != null
? (
<div className='bg-purple-100'>
<AreaItem
index={areasSortedState.indexOf(draggedArea)}
borderBottom
parentUuid={parentUuid}
{/* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */
...areaStore.get(draggedArea)!}
editMode={editMode}
onChange={onChange}
/>
</div>
)
: null}
</DragOverlay>
</DndContext>
)}
{areaCount > 0 && editMode && (
<div className='mt-8 md:text-right'>
<AddAreaTrigger data-no-dnd='true' parentName={parentName} parentUuid={parentUuid} onSuccess={onChange}>
<AddAreaTriggerButtonMd data-no-dnd='true' />
</AddAreaTrigger>
</div>)}
</>
)
}
type AreaItemProps = AreaSummaryType & {
index: number
borderBottom: boolean
parentUuid: string
editMode?: boolean
onChange?: () => void
}
/**
* Individual area entry
* @param borderBottom true add a bottom border
*/
export const AreaItem = ({ index, borderBottom, areaName, uuid, parentUuid, onChange, editMode = false, climbs, children, ...props }: AreaItemProps): JSX.Element | null => {
// undefined array can mean we forget to include the field in GQL so let's make it not editable
const canEdit = (children?.length ?? 1) === 0 && (climbs?.length ?? 1) === 0
const { totalClimbs, metadata: { leaf, isBoulder } } = props
const isLeaf = leaf || isBoulder
return (
<div className={clx('area-row', borderBottom ? 'border-b' : '')}>
<a href={`/crag/${uuid}`} className='area-entity-box' data-no-dnd='true'>
{index + 1}
</a>
<a href={`/crag/${uuid}`} className='flex flex-col items-start items-stretch grow gap-y-1' data-no-dnd='true'>
<div className='font-semibold uppercase thick-link'>
{areaName}
</div>
<div className='flex gap-2 items-center'>
{!isLeaf && <NetworkSquareIcon className='stroke-base-200 w-6 h-6' />}
<span className='mt-0.5 text-sm text-base-200'>
<span>{totalClimbs ?? 0} climbs • {children?.length ?? 0} areas</span>
</span>
</div>
</a>
{editMode && (
<div className='text-base-300'>
<DeleteAreaTrigger
areaName={areaName}
areaUuid={uuid}
parentUuid={parentUuid}
returnToParentPageAfterDelete={false}
onSuccess={onChange}
>
<DeleteAreaTriggerButtonSm disabled={!canEdit} />
</DeleteAreaTrigger>
</div>)}
</div>
)
}
/**
* A custom MouseSensor for DnD to ignore elements with `data-no-dnd='true'` attribute.
* Without this handler the DnD component will capture all mouse events on its items.
* See https://github.com/clauderic/dnd-kit/pull/377#issuecomment-991842782
*/
export class MouseSensor extends LibMouseSensor {
static activators = [
{
eventName: 'onMouseDown' as const,
handler: ({ nativeEvent: event }: MouseEvent) => {
return shouldHandleEvent(event.target as HTMLElement)
}
}
]
}
function shouldHandleEvent (element: HTMLElement | null): boolean {
let cur = element
while (cur != null) {
if (cur.dataset?.noDnd === 'true') {
return false
}
cur = cur.parentElement
}
return true
}
export const DynamicAreaCRUD = dynamic<AreaCRUDProps>(async () => await Promise.resolve(AreaCRUD))