-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMapViews.tsx
More file actions
335 lines (306 loc) · 9.77 KB
/
MapViews.tsx
File metadata and controls
335 lines (306 loc) · 9.77 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
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
import {
DndContext,
KeyboardSensor,
PointerSensor,
closestCenter,
useSensor,
useSensors,
} from "@dnd-kit/core";
import {
restrictToHorizontalAxis,
restrictToParentElement,
} from "@dnd-kit/modifiers";
import {
SortableContext,
horizontalListSortingStrategy,
sortableKeyboardCoordinates,
} from "@dnd-kit/sortable";
import { useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { Check, Layers, Plus, X } from "lucide-react";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { v4 as uuidv4 } from "uuid";
import { useMapViews } from "@/app/map/[id]/hooks/useMapViews";
import ContextMenuContentWithFocus from "@/components/ContextMenuContentWithFocus";
import { Button } from "@/shadcn/ui/button";
import {
ContextMenu,
ContextMenuItem,
ContextMenuSeparator,
ContextMenuTrigger,
} from "@/shadcn/ui/context-menu";
import { Input } from "@/shadcn/ui/input";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/shadcn/ui/tooltip";
import { cn } from "@/shadcn/utils";
import { useMapId } from "../hooks/useMapCore";
import { useDirtyViewIds, useSetViewId } from "../hooks/useMapViews";
import { createNewViewConfig } from "../utils/mapView";
import {
compareByPositionAndId,
getNewPositionAfter,
getNewPositionBefore,
sortByPositionAndId,
} from "../utils/position";
import type { View } from "../types";
import type { DragEndEvent } from "@dnd-kit/core";
export default function MapViews() {
const mapId = useMapId();
const { views, insertView, updateView } = useMapViews();
const [isCreating, setIsCreating] = useState(false);
const [newViewName, setNewViewName] = useState("");
const [renamingViewId, setRenamingViewId] = useState<string | null>(null);
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
if (!isCreating) return;
setTimeout(() => {
inputRef.current?.focus();
}, 10);
}, [isCreating]);
// DnD sensors
const sensors = useSensors(
useSensor(PointerSensor, {
activationConstraint: {
distance: 8, // Only start dragging after moving 8px
},
}),
// Disable keyboard sensor while user is naming the view
useSensor(KeyboardSensor, {
coordinateGetter: sortableKeyboardCoordinates,
// Disable keyboard while text input is active
keyboardCodes:
renamingViewId || isCreating
? { start: [], cancel: [], end: [] }
: undefined,
}),
);
const handleCreateView = () => {
if (!newViewName.trim()) return;
if (!mapId) return;
const newView = {
id: uuidv4(),
name: newViewName.trim(),
config: createNewViewConfig(),
dataSourceViews: [],
mapId,
createdAt: new Date(),
};
insertView(newView);
setNewViewName("");
setIsCreating(false);
};
const handleDragEnd = (event: DragEndEvent) => {
const { active, over } = event;
if (active.id === over?.id || !over) return;
const activeView = views.find((v) => v.id === active.id.toString());
const overView = views.find((v) => v.id === over.id.toString());
if (!activeView || !overView) return;
let newPosition = 0;
const otherViews = views.filter((v) => v.id !== active.id);
const wasBefore = compareByPositionAndId(activeView, overView) < 0;
if (wasBefore) {
newPosition = getNewPositionAfter(overView.position, otherViews);
} else {
newPosition = getNewPositionBefore(overView.position, otherViews);
}
updateView({ ...activeView, position: newPosition });
};
const handleDragStart = () => {
if (!renamingViewId) return;
setRenamingViewId(null);
};
const sortedViews = useMemo(() => {
return sortByPositionAndId(views);
}, [views]);
return (
<>
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
modifiers={[restrictToHorizontalAxis, restrictToParentElement]}
>
<SortableContext
items={sortedViews.map((view) => view.id)}
strategy={horizontalListSortingStrategy}
>
<div className="flex flex-row gap-2 text-sm">
{sortedViews.map((view) => (
<SortableViewItem
key={view.id}
view={view}
renamingViewId={renamingViewId}
setRenamingViewId={setRenamingViewId}
/>
))}
{isCreating ? (
<div className="flex flex-row gap-2 items-center rounded border bg-white pr-2">
<Input
type="text"
value={newViewName}
onChange={(e) => setNewViewName(e.target.value)}
placeholder="View name..."
className="text-sm border-none outline-none bg-transparent w-auto"
onKeyDown={(e) => {
if (e.key === "Enter") handleCreateView();
if (e.key === "Escape") setIsCreating(false);
}}
ref={inputRef}
/>
<Check
onClick={handleCreateView}
className="text-green-600 hover:text-green-800 text-xs w-4 h-4"
/>
<X
onClick={() => setIsCreating(false)}
className="text-red-600 hover:text-red-800 text-xs w-4 h-4"
/>
</div>
) : (
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="outline"
size="sm"
className="rounded shadow-none"
onClick={() => setIsCreating(true)}
>
<Plus className="w-4 h-4" />
</Button>
</TooltipTrigger>
<TooltipContent>Create view</TooltipContent>
</Tooltip>
)}
</div>
</SortableContext>
</DndContext>
</>
);
}
// Sortable view item component
function SortableViewItem({
renamingViewId,
setRenamingViewId,
view,
}: {
renamingViewId: string | null;
setRenamingViewId: (id: string | null) => void;
view: View;
}) {
const setSelectedViewId = useSetViewId();
const dirtyViewIds = useDirtyViewIds();
const { views, deleteView, updateView, view: selectedView } = useMapViews();
const [editName, setEditName] = useState(view.name);
const isSelected = selectedView?.id === view.id;
const isRenaming = renamingViewId === view.id;
const isDirty = dirtyViewIds.includes(view.id);
// Focus management
const inputRef = useRef<HTMLInputElement>(null);
const isFocusing = useRef(false);
useEffect(() => {
if (isRenaming) {
// Prevent the blur handler triggering too fast
isFocusing.current = true;
setTimeout(() => {
isFocusing.current = false;
}, 500);
}
}, [isRenaming]);
const {
attributes,
listeners,
setNodeRef,
transform,
transition,
isDragging,
} = useSortable({ id: view.id });
const style = {
transform: CSS.Translate.toString(transform),
transition,
};
const handleViewSelect = () => {
// Auto-save handles persisting any changes automatically
setSelectedViewId(view.id);
};
const handleDoubleClick = () => {
setRenamingViewId(view.id);
};
const handleSaveRename = () => {
updateView({ ...view, name: editName });
setRenamingViewId(null);
};
const handleDeleteView = () => {
if (views.length <= 1) {
return;
}
deleteView(view.id);
if (view.id === selectedView?.id) {
const nextView = views.find((v) => v.id !== view.id);
if (nextView) {
setSelectedViewId(nextView.id);
}
}
};
return (
<ContextMenu>
<ContextMenuTrigger asChild>
<div
ref={setNodeRef}
style={style}
{...attributes}
{...listeners}
className={`flex flex-row gap-2 items-center px-2 py-1 rounded border transition-all ${
isRenaming ? "cursor-default" : "cursor-pointer"
} ${
isSelected ? "bg-muted" : "bg-transparent hover:border-action-hover"
} ${isDragging ? "opacity-50" : "opacity-100"}`}
onClick={() => !isRenaming && handleViewSelect()}
onDoubleClick={() => !isRenaming && handleDoubleClick()}
>
<Layers className="w-4 h-4 text-muted-foreground" />
{isRenaming ? (
<input
type="text"
value={editName}
onChange={(e) => setEditName(e.target.value)}
className="text-sm border-none outline-none bg-transparent min-w-0"
onKeyDown={(e) => {
if (e.key === "Enter") handleSaveRename();
if (e.key === "Escape") setRenamingViewId(null);
}}
onBlur={() => !isFocusing.current && handleSaveRename()}
ref={inputRef}
/>
) : (
<h2>{view.name}</h2>
)}
<div
className={cn(
"transition-all duration-300 bg-neutral-400 rounded-full",
isDirty ? "w-2 h-2" : "w-0 h-0",
)}
/>
</div>
</ContextMenuTrigger>
<ContextMenuContentWithFocus
shouldFocusTarget={isRenaming}
targetRef={inputRef}
>
<ContextMenuItem onClick={() => setRenamingViewId(view.id)}>
Rename
</ContextMenuItem>
{views.length > 1 && (
<>
<ContextMenuSeparator />
<ContextMenuItem
onClick={() => handleDeleteView()}
className="text-red-600 focus:text-red-600"
>
Delete
</ContextMenuItem>
</>
)}
</ContextMenuContentWithFocus>
</ContextMenu>
);
}