feat: improve drag-and-drop functionality and fix counter layout
This commit is contained in:
@@ -415,6 +415,37 @@ html, body, #root {
|
|||||||
outline-offset: 8px;
|
outline-offset: 8px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* container grid */
|
||||||
|
.counters-grid {
|
||||||
|
display: grid;
|
||||||
|
gap: 16px;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
|
||||||
|
max-width: var(--max-width);
|
||||||
|
margin: 0 auto;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: start;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* keep each card centered in its cell and center its inner content */
|
||||||
|
.counters-grid > .counter-card {
|
||||||
|
justify-self: center;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 460px;
|
||||||
|
box-sizing: border-box;
|
||||||
|
padding: 12px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ensure the actual counter element stays centered and doesn't stretch awkwardly */
|
||||||
|
.counter-card .counter {
|
||||||
|
width: 100%;
|
||||||
|
max-width: 420px;
|
||||||
|
margin: 0 auto;
|
||||||
|
display: flex;
|
||||||
|
}
|
||||||
|
|
||||||
/* ---------------------------
|
/* ---------------------------
|
||||||
Utilities / footer
|
Utilities / footer
|
||||||
--------------------------- */
|
--------------------------- */
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import React, { useEffect, useState, useCallback } from 'react'
|
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||||
import Counter from './components/Counter'
|
import Counter from './components/Counter'
|
||||||
import CreateCounter from './components/CreateCounter'
|
import CreateCounter from './components/CreateCounter'
|
||||||
import { apiUrl } from './utils/api'
|
import { apiUrl } from './utils/api'
|
||||||
@@ -6,6 +6,13 @@ import './App.css'
|
|||||||
|
|
||||||
type CounterRecord = { id: number; value: number; name?: string; imageUrl?: string; position?: number }
|
type CounterRecord = { id: number; value: number; name?: string; imageUrl?: string; position?: number }
|
||||||
|
|
||||||
|
// small pure helper kept outside the component so it's stable
|
||||||
|
const swapInArray = (arr: CounterRecord[], i: number, j: number) => {
|
||||||
|
const copy = arr.slice()
|
||||||
|
;[copy[i], copy[j]] = [copy[j], copy[i]]
|
||||||
|
return copy
|
||||||
|
}
|
||||||
|
|
||||||
export default function App() {
|
export default function App() {
|
||||||
const [counters, setCounters] = useState<CounterRecord[]>([])
|
const [counters, setCounters] = useState<CounterRecord[]>([])
|
||||||
const [loading, setLoading] = useState(true)
|
const [loading, setLoading] = useState(true)
|
||||||
@@ -13,33 +20,46 @@ export default function App() {
|
|||||||
const [draggingId, setDraggingId] = useState<number | null>(null)
|
const [draggingId, setDraggingId] = useState<number | null>(null)
|
||||||
const [dragOverId, setDragOverId] = useState<number | null>(null)
|
const [dragOverId, setDragOverId] = useState<number | null>(null)
|
||||||
|
|
||||||
|
// track which modal ids are currently open (idempotent)
|
||||||
|
const [modalOpenSet, setModalOpenSet] = useState<Set<number>>(new Set())
|
||||||
|
const draggingEnabled = useMemo(() => modalOpenSet.size === 0, [modalOpenSet])
|
||||||
|
|
||||||
|
// helper: idempotently add/remove modal id
|
||||||
|
const handleEditingChange = useCallback((id: number, editing: boolean) => {
|
||||||
|
setModalOpenSet((prev) => {
|
||||||
|
const next = new Set(prev)
|
||||||
|
if (editing) next.add(id)
|
||||||
|
else next.delete(id)
|
||||||
|
return next
|
||||||
|
})
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
// mounted ref to avoid setting state on unmounted component
|
||||||
|
const mountedRef = useRef(true)
|
||||||
|
useEffect(() => {
|
||||||
|
mountedRef.current = true
|
||||||
|
return () => {
|
||||||
|
mountedRef.current = false
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let mounted = true
|
|
||||||
;(async () => {
|
;(async () => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch(apiUrl('/api/counters'))
|
const res = await fetch(apiUrl('/api/counters'))
|
||||||
const list: CounterRecord[] = await res.json()
|
const list: CounterRecord[] = await res.json()
|
||||||
if (!mounted) return
|
if (!mountedRef.current) return
|
||||||
setCounters(Array.isArray(list) ? list : [])
|
setCounters(Array.isArray(list) ? list : [])
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
// keep minimal logging here
|
||||||
console.error('failed to load counters', err)
|
console.error('failed to load counters', err)
|
||||||
if (mounted) setCounters([])
|
if (mountedRef.current) setCounters([])
|
||||||
} finally {
|
} finally {
|
||||||
if (mounted) setLoading(false)
|
if (mountedRef.current) setLoading(false)
|
||||||
}
|
}
|
||||||
})()
|
})()
|
||||||
return () => {
|
|
||||||
mounted = false
|
|
||||||
}
|
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
// swap two items in an array (keeps array length and only swaps the two indexes)
|
|
||||||
const swapInArray = (arr: CounterRecord[], i: number, j: number) => {
|
|
||||||
const copy = arr.slice()
|
|
||||||
;[copy[i], copy[j]] = [copy[j], copy[i]]
|
|
||||||
return copy
|
|
||||||
}
|
|
||||||
|
|
||||||
const clearDragState = useCallback(() => {
|
const clearDragState = useCallback(() => {
|
||||||
setDraggingId(null)
|
setDraggingId(null)
|
||||||
setDragOverId(null)
|
setDragOverId(null)
|
||||||
@@ -121,7 +141,8 @@ export default function App() {
|
|||||||
clearDragState()
|
clearDragState()
|
||||||
}, [clearDragState])
|
}, [clearDragState])
|
||||||
|
|
||||||
const handleChange = async (id: number, next: number) => {
|
const handleChange = useCallback(
|
||||||
|
async (id: number, next: number) => {
|
||||||
// enforce non-negative values
|
// enforce non-negative values
|
||||||
const safeNext = Math.max(0, next)
|
const safeNext = Math.max(0, next)
|
||||||
|
|
||||||
@@ -159,14 +180,16 @@ export default function App() {
|
|||||||
return n
|
return n
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
|
[counters]
|
||||||
|
)
|
||||||
|
|
||||||
const handleCreated = (c: CounterRecord) => {
|
const handleCreated = useCallback((c: CounterRecord) => {
|
||||||
setCounters((prev) => [...prev, c])
|
setCounters((prev) => [...prev, c])
|
||||||
}
|
}, [])
|
||||||
|
|
||||||
// onUpdate: upload file (if present), then PATCH name/imageUrl for given id
|
const handleUpdate = useCallback(
|
||||||
const handleUpdate = async (id: number, payload: { name?: string; file?: File | null }) => {
|
async (id: number, payload: { name?: string; file?: File | null }) => {
|
||||||
setSavingIds((s) => {
|
setSavingIds((s) => {
|
||||||
const n = new Set(s)
|
const n = new Set(s)
|
||||||
n.add(id)
|
n.add(id)
|
||||||
@@ -219,10 +242,12 @@ export default function App() {
|
|||||||
return n
|
return n
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
|
[]
|
||||||
|
)
|
||||||
|
|
||||||
// added delete handler
|
const handleDelete = useCallback(
|
||||||
const handleDelete = async (id: number) => {
|
async (id: number) => {
|
||||||
setSavingIds((s) => {
|
setSavingIds((s) => {
|
||||||
const n = new Set(s)
|
const n = new Set(s)
|
||||||
n.add(id)
|
n.add(id)
|
||||||
@@ -244,7 +269,9 @@ export default function App() {
|
|||||||
return n
|
return n
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
|
[]
|
||||||
|
)
|
||||||
|
|
||||||
if (loading) return <div className="loading">Loading counters…</div>
|
if (loading) return <div className="loading">Loading counters…</div>
|
||||||
|
|
||||||
@@ -267,17 +294,18 @@ export default function App() {
|
|||||||
<p>Create your first counter to begin tracking.</p>
|
<p>Create your first counter to begin tracking.</p>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="counters-grid" style={{ display: 'grid', gap: 16, gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))' }}>
|
<div className="counters-grid">
|
||||||
{counters.map((c) => (
|
{counters.map((c) => {
|
||||||
|
return (
|
||||||
<div
|
<div
|
||||||
key={c.id}
|
key={c.id}
|
||||||
className={`counter-card card ${draggingId === c.id ? 'dragging' : ''} ${dragOverId === c.id ? 'drag-over' : ''}`}
|
className={`counter-card card ${draggingId === c.id ? 'dragging' : ''} ${dragOverId === c.id ? 'drag-over' : ''}`}
|
||||||
draggable={true}
|
draggable={draggingEnabled}
|
||||||
onDragStart={(e) => handleDragStart(e, c.id)}
|
onDragStart={draggingEnabled ? (e) => handleDragStart(e, c.id) : undefined}
|
||||||
onDragEnter={(e) => handleDragOver(e, c.id)}
|
onDragEnter={draggingEnabled ? (e) => handleDragOver(e, c.id) : undefined}
|
||||||
onDragOver={(e) => handleDragOver(e, c.id)}
|
onDragOver={draggingEnabled ? (e) => handleDragOver(e, c.id) : undefined}
|
||||||
onDrop={(e) => handleDropOnCard(e, c.id)}
|
onDrop={draggingEnabled ? (e) => handleDropOnCard(e, c.id) : undefined}
|
||||||
onDragEnd={handleDragEnd}
|
onDragEnd={draggingEnabled ? handleDragEnd : undefined}
|
||||||
>
|
>
|
||||||
<Counter
|
<Counter
|
||||||
id={String(c.id)}
|
id={String(c.id)}
|
||||||
@@ -289,9 +317,11 @@ export default function App() {
|
|||||||
onChange={(next) => handleChange(c.id, next)}
|
onChange={(next) => handleChange(c.id, next)}
|
||||||
onUpdate={(payload) => handleUpdate(c.id, payload)}
|
onUpdate={(payload) => handleUpdate(c.id, payload)}
|
||||||
onDelete={() => handleDelete(c.id)}
|
onDelete={() => handleDelete(c.id)}
|
||||||
|
onEditingChange={(editing: boolean) => handleEditingChange(c.id, editing)}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
))}
|
)
|
||||||
|
})}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</main>
|
</main>
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ interface CounterProps {
|
|||||||
|
|
||||||
onUpdate?: (payload: { name?: string; file?: File | null }) => Promise<void> | void
|
onUpdate?: (payload: { name?: string; file?: File | null }) => Promise<void> | void
|
||||||
onDelete?: () => Promise<void> | void // added delete prop
|
onDelete?: () => Promise<void> | void // added delete prop
|
||||||
|
onEditingChange?: (editing: boolean) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
const clamp = (v: number, min?: number, max?: number) => {
|
const clamp = (v: number, min?: number, max?: number) => {
|
||||||
@@ -36,6 +37,7 @@ const Counter: React.FC<CounterProps> = ({
|
|||||||
isSaving = false,
|
isSaving = false,
|
||||||
onUpdate,
|
onUpdate,
|
||||||
onDelete,
|
onDelete,
|
||||||
|
onEditingChange,
|
||||||
}) => {
|
}) => {
|
||||||
const setValue = useCallback(
|
const setValue = useCallback(
|
||||||
(next: number) => {
|
(next: number) => {
|
||||||
@@ -97,23 +99,26 @@ const Counter: React.FC<CounterProps> = ({
|
|||||||
setEditName(label ?? '')
|
setEditName(label ?? '')
|
||||||
setEditFile(null)
|
setEditFile(null)
|
||||||
setEditing(true)
|
setEditing(true)
|
||||||
}, [label])
|
}, [label, onEditingChange])
|
||||||
|
|
||||||
const closeEdit = useCallback(() => {
|
const closeEdit = useCallback(() => {
|
||||||
setEditing(false)
|
setEditing(false)
|
||||||
setEditFile(null)
|
setEditFile(null)
|
||||||
setPreviewUrl(null)
|
setPreviewUrl(null)
|
||||||
}, [])
|
}, [onEditingChange])
|
||||||
|
|
||||||
const handleSave = useCallback(async () => {
|
const handleSave = useCallback(async () => {
|
||||||
if (!onUpdate) {
|
if (!onUpdate) {
|
||||||
|
// close and notify parent
|
||||||
setEditing(false)
|
setEditing(false)
|
||||||
|
onEditingChange?.(false)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
setSavingLocal(true)
|
setSavingLocal(true)
|
||||||
await onUpdate({ name: editName || undefined, file: editFile })
|
await onUpdate({ name: editName || undefined, file: editFile })
|
||||||
setEditing(false)
|
setEditing(false)
|
||||||
|
onEditingChange?.(false)
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('update failed', err)
|
console.error('update failed', err)
|
||||||
} finally {
|
} finally {
|
||||||
@@ -128,6 +133,7 @@ const Counter: React.FC<CounterProps> = ({
|
|||||||
await onDelete()
|
await onDelete()
|
||||||
// close modal locally (parent will remove the card)
|
// close modal locally (parent will remove the card)
|
||||||
setEditing(false)
|
setEditing(false)
|
||||||
|
onEditingChange?.(false)
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('delete failed', err)
|
console.error('delete failed', err)
|
||||||
} finally {
|
} finally {
|
||||||
@@ -135,6 +141,20 @@ const Counter: React.FC<CounterProps> = ({
|
|||||||
}
|
}
|
||||||
}, [onDelete])
|
}, [onDelete])
|
||||||
|
|
||||||
|
// Call the latest onEditingChange but only re-run when `editing` toggles.
|
||||||
|
// This avoids re-running the effect when the parent's callback identity changes.
|
||||||
|
const onEditingChangeRef = useRef(onEditingChange)
|
||||||
|
useEffect(() => {
|
||||||
|
onEditingChangeRef.current = onEditingChange
|
||||||
|
}, [onEditingChange])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
onEditingChangeRef.current?.(editing)
|
||||||
|
return () => {
|
||||||
|
if (editing) onEditingChangeRef.current?.(false)
|
||||||
|
}
|
||||||
|
}, [editing])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className={className ?? 'counter'}
|
className={className ?? 'counter'}
|
||||||
|
|||||||
Reference in New Issue
Block a user