4 Commits
1.0.0 ... 1.1

Author SHA1 Message Date
d4d886c91f feat: enhance Dockerfile and entrypoint for user permissions and environment variable handling
All checks were successful
Build and publish Docker image / build-and-push (release) Successful in 1m50s
2025-11-16 01:16:53 +01:00
0eccf479e6 feat: improve drag-and-drop functionality and fix counter layout 2025-11-16 00:02:28 +01:00
00da4d2abc feat: add example usage of docker-compose.yml to README
All checks were successful
Build and publish Docker image / build-and-push (release) Successful in 9s
2025-11-13 04:06:04 +01:00
1bc4b0fb50 feat: forgot to define some runtime environment variables in Dockerfile 2025-11-13 04:01:26 +01:00
6 changed files with 296 additions and 152 deletions

View File

@@ -9,6 +9,10 @@ RUN npm run build
# Final runtime image # Final runtime image
FROM node:24-alpine FROM node:24-alpine
WORKDIR /app WORKDIR /app
# ensure su-exec present to drop privileges later
RUN apk add --no-cache ca-certificates su-exec
# copy package manifests and install deps (leverage Docker cache) # copy package manifests and install deps (leverage Docker cache)
COPY backend/package*.json backend/package-lock*.json ./backend/ COPY backend/package*.json backend/package-lock*.json ./backend/
RUN cd backend && npm ci --silent RUN cd backend && npm ci --silent
@@ -26,6 +30,11 @@ RUN chmod +x /usr/local/bin/entrypoint.sh
# Copy built frontend into the expected location: /app/frontend/dist # Copy built frontend into the expected location: /app/frontend/dist
COPY --from=frontend-build /app/frontend/dist ./frontend/dist COPY --from=frontend-build /app/frontend/dist ./frontend/dist
# runtime environment (DATA_DIR used at runtime; DATABASE_URL points to it)
ENV NODE_ENV=production
ENV DATA_DIR=/data
ENV DATABASE_URL="file:${DATA_DIR}/sqlite.db"
WORKDIR /app/backend WORKDIR /app/backend
EXPOSE 3000 EXPOSE 3000

31
README.md Normal file
View File

@@ -0,0 +1,31 @@
# Tally Counter
Run the app with Docker Compose (recommended). The container startup/entrypoint will create the runtime folders and apply migrations; pass numeric PUID/PGID via environment to run as a non-root user.
```yaml
services:
tally-counter:
image: gitea.kanawave.net/sebastas/tally-counter:latest #this image
container_name: tally-counter
restart: unless-stopped
networks:
- proxy # connect any proxy networks (for traefik)
environment:
- PUID=1000 # host uid forwarded to container
- PGID=1000 # host gid forwarded to container
ports:
- "3000:3000" # Set whatever port you want on the left side (host)
volumes:
- ./tally-counter:/data # persistent DB + uploads (bind mount)
```
Add any `labels` for traefik
### Notes & tips
The entrypoint will:
- ensure `$DATA_DIR` exists,
- create `sqlite.db` if missing,
- run `prisma migrate deploy` (if CLI available and migrations exist),
- then drop privileges to the provided `PUID:PGID` and exec the app.

View File

@@ -3,27 +3,50 @@ set -eu
DATA_DIR="${DATA_DIR:-/data}" DATA_DIR="${DATA_DIR:-/data}"
SCHEMA_PATH="./prisma/schema.prisma" SCHEMA_PATH="./prisma/schema.prisma"
PUID="${PUID:-}"
PGID="${PGID:-$PUID}"
# ensure data dir exists and is writable
mkdir -p "$DATA_DIR" mkdir -p "$DATA_DIR"
chmod 0775 "$DATA_DIR" || true chmod 0775 "$DATA_DIR" || true
# ensure DATABASE_URL is set to the runtime DATA_DIR
: "${DATABASE_URL:=file:${DATA_DIR}/sqlite.db}" : "${DATABASE_URL:=file:${DATA_DIR}/sqlite.db}"
export DATABASE_URL export DATABASE_URL
# create sqlite file if missing
SQLITE_DB_PATH="${DATA_DIR}/sqlite.db" SQLITE_DB_PATH="${DATA_DIR}/sqlite.db"
if [ ! -f "$SQLITE_DB_PATH" ]; then if [ ! -f "$SQLITE_DB_PATH" ]; then
touch "$SQLITE_DB_PATH" touch "$SQLITE_DB_PATH"
chmod 0664 "$SQLITE_DB_PATH" || true chmod 0664 "$SQLITE_DB_PATH" || true
fi fi
# run non-interactive migrations if CLI available # run migrations if prisma CLI available
if command -v npx >/dev/null 2>&1 && [ -f "$SCHEMA_PATH" ]; then if command -v npx >/dev/null 2>&1 && [ -f "$SCHEMA_PATH" ]; then
echo "Running prisma migrate deploy..." echo "Running prisma migrate deploy..."
npx prisma migrate deploy --schema="$SCHEMA_PATH" || echo "prisma migrate deploy failed or no migrations to apply" npx prisma migrate deploy --schema="$SCHEMA_PATH" || echo "prisma migrate deploy failed or no migrations to apply"
fi fi
# exec main process # If root and numeric PUID supplied, create/reuse group by GID then create user and chown
if [ "$(id -u)" = "0" ] && [ -n "$PUID" ]; then
# try find an existing group with this GID
existing_group="$(getent group | awk -F: -v gid="$PGID" '$3==gid{print $1; exit}')"
if [ -n "$existing_group" ]; then
grp="$existing_group"
else
grp="appgroup"
addgroup -g "${PGID}" "$grp" 2>/dev/null || true
fi
if ! id -u app >/dev/null 2>&1; then
adduser -D -u "${PUID}" -G "$grp" -s /bin/sh app 2>/dev/null || true
fi
# ensure runtime paths writable by numeric ids
chown -R "${PUID}:${PGID}" "$DATA_DIR" /app/backend /app/frontend/dist 2>/dev/null || true
# drop privileges and run command
echo "Running as user: "${PUID}""
echo "Running as group: "${PGID}""
exec su-exec "${PUID}:${PGID}" "$@"
fi
# otherwise run as current user
exec "$@" exec "$@"

View File

@@ -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
--------------------------- */ --------------------------- */

View File

@@ -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,130 +141,137 @@ export default function App() {
clearDragState() clearDragState()
}, [clearDragState]) }, [clearDragState])
const handleChange = async (id: number, next: number) => { const handleChange = useCallback(
// enforce non-negative values async (id: number, next: number) => {
const safeNext = Math.max(0, next) // enforce non-negative values
const safeNext = Math.max(0, next)
const idx = counters.findIndex((c) => c.id === id) const idx = counters.findIndex((c) => c.id === id)
if (idx === -1) return if (idx === -1) return
const prev = counters[idx].value const prev = counters[idx].value
// optimistic update (use safeNext) // optimistic update (use safeNext)
setCounters((prevList) => prevList.map((c) => (c.id === id ? { ...c, value: safeNext } : c))) setCounters((prevList) => prevList.map((c) => (c.id === id ? { ...c, value: safeNext } : c)))
setSavingIds((s) => {
const n = new Set(s)
n.add(id)
return n
})
try {
const res = await fetch(apiUrl(`/api/counters/${id}`), {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ value: safeNext }),
})
if (!res.ok) throw new Error('patch failed')
const updated: CounterRecord = await res.json().catch(() => null)
if (updated) {
setCounters((prevList) => prevList.map((c) => (c.id === updated.id ? updated : c)))
}
} catch (err) {
console.error('save failed', err)
// revert
setCounters((prevList) => prevList.map((c) => (c.id === id ? { ...c, value: prev } : c)))
} finally {
setSavingIds((s) => { setSavingIds((s) => {
const n = new Set(s) const n = new Set(s)
n.delete(id) n.add(id)
return n return n
}) })
}
}
const handleCreated = (c: CounterRecord) => { try {
const res = await fetch(apiUrl(`/api/counters/${id}`), {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ value: safeNext }),
})
if (!res.ok) throw new Error('patch failed')
const updated: CounterRecord = await res.json().catch(() => null)
if (updated) {
setCounters((prevList) => prevList.map((c) => (c.id === updated.id ? updated : c)))
}
} catch (err) {
console.error('save failed', err)
// revert
setCounters((prevList) => prevList.map((c) => (c.id === id ? { ...c, value: prev } : c)))
} finally {
setSavingIds((s) => {
const n = new Set(s)
n.delete(id)
return n
})
}
},
[counters]
)
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) => {
const n = new Set(s)
n.add(id)
return n
})
try {
let imageUrl: string | null | undefined = undefined
if (payload.file) {
const fd = new FormData()
fd.append('file', payload.file)
const up = await fetch(apiUrl('/api/upload'), { method: 'POST', body: fd })
if (!up.ok) throw new Error('upload failed')
const body = await up.json().catch(() => null)
imageUrl = body?.url ?? null
}
const patchBody: any = {}
if (payload.name !== undefined) patchBody.name = payload.name
if (payload.file) patchBody.imageUrl = imageUrl
if (Object.keys(patchBody).length === 0) {
// nothing to do
return
}
const res = await fetch(apiUrl(`/api/counters/${id}`), {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(patchBody),
})
if (!res.ok) throw new Error(`update failed (${res.status})`)
const updated: CounterRecord = await res.json().catch(() => null)
if (updated) {
setCounters((prevList) => prevList.map((c) => (c.id === updated.id ? updated : c)))
} else {
// best-effort local apply if server didn't return the updated object
setCounters((prevList) =>
prevList.map((c) => (c.id === id ? { ...c, name: payload.name ?? c.name, imageUrl: imageUrl ?? c.imageUrl } : c))
)
}
} catch (err) {
console.error('update failed', err)
throw err
} finally {
setSavingIds((s) => { setSavingIds((s) => {
const n = new Set(s) const n = new Set(s)
n.delete(id) n.add(id)
return n return n
}) })
}
}
// added delete handler try {
const handleDelete = async (id: number) => { let imageUrl: string | null | undefined = undefined
setSavingIds((s) => {
const n = new Set(s)
n.add(id)
return n
})
try { if (payload.file) {
const res = await fetch(apiUrl(`/api/counters/${id}`), { method: 'DELETE' }) const fd = new FormData()
if (!res.ok) throw new Error(`delete failed (${res.status})`) fd.append('file', payload.file)
// remove locally const up = await fetch(apiUrl('/api/upload'), { method: 'POST', body: fd })
setCounters((prev) => prev.filter((c) => c.id !== id)) if (!up.ok) throw new Error('upload failed')
} catch (err) { const body = await up.json().catch(() => null)
console.error('delete failed', err) imageUrl = body?.url ?? null
throw err }
} finally {
const patchBody: any = {}
if (payload.name !== undefined) patchBody.name = payload.name
if (payload.file) patchBody.imageUrl = imageUrl
if (Object.keys(patchBody).length === 0) {
// nothing to do
return
}
const res = await fetch(apiUrl(`/api/counters/${id}`), {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(patchBody),
})
if (!res.ok) throw new Error(`update failed (${res.status})`)
const updated: CounterRecord = await res.json().catch(() => null)
if (updated) {
setCounters((prevList) => prevList.map((c) => (c.id === updated.id ? updated : c)))
} else {
// best-effort local apply if server didn't return the updated object
setCounters((prevList) =>
prevList.map((c) => (c.id === id ? { ...c, name: payload.name ?? c.name, imageUrl: imageUrl ?? c.imageUrl } : c))
)
}
} catch (err) {
console.error('update failed', err)
throw err
} finally {
setSavingIds((s) => {
const n = new Set(s)
n.delete(id)
return n
})
}
},
[]
)
const handleDelete = useCallback(
async (id: number) => {
setSavingIds((s) => { setSavingIds((s) => {
const n = new Set(s) const n = new Set(s)
n.delete(id) n.add(id)
return n return n
}) })
}
} try {
const res = await fetch(apiUrl(`/api/counters/${id}`), { method: 'DELETE' })
if (!res.ok) throw new Error(`delete failed (${res.status})`)
// remove locally
setCounters((prev) => prev.filter((c) => c.id !== id))
} catch (err) {
console.error('delete failed', err)
throw err
} finally {
setSavingIds((s) => {
const n = new Set(s)
n.delete(id)
return n
})
}
},
[]
)
if (loading) return <div className="loading">Loading counters</div> if (loading) return <div className="loading">Loading counters</div>
@@ -267,31 +294,34 @@ 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) => {
<div return (
key={c.id} <div
className={`counter-card card ${draggingId === c.id ? 'dragging' : ''} ${dragOverId === c.id ? 'drag-over' : ''}`} key={c.id}
draggable={true} className={`counter-card card ${draggingId === c.id ? 'dragging' : ''} ${dragOverId === c.id ? 'drag-over' : ''}`}
onDragStart={(e) => handleDragStart(e, c.id)} draggable={draggingEnabled}
onDragEnter={(e) => handleDragOver(e, c.id)} onDragStart={draggingEnabled ? (e) => handleDragStart(e, c.id) : undefined}
onDragOver={(e) => handleDragOver(e, c.id)} onDragEnter={draggingEnabled ? (e) => handleDragOver(e, c.id) : undefined}
onDrop={(e) => handleDropOnCard(e, c.id)} onDragOver={draggingEnabled ? (e) => handleDragOver(e, c.id) : undefined}
onDragEnd={handleDragEnd} onDrop={draggingEnabled ? (e) => handleDropOnCard(e, c.id) : undefined}
> onDragEnd={draggingEnabled ? handleDragEnd : undefined}
<Counter >
id={String(c.id)} <Counter
label={c.name ?? 'Counter'} id={String(c.id)}
value={c.value} label={c.name ?? 'Counter'}
min={0} value={c.value}
isSaving={savingIds.has(c.id)} min={0}
imageUrl={c.imageUrl} isSaving={savingIds.has(c.id)}
onChange={(next) => handleChange(c.id, next)} imageUrl={c.imageUrl}
onUpdate={(payload) => handleUpdate(c.id, payload)} onChange={(next) => handleChange(c.id, next)}
onDelete={() => handleDelete(c.id)} onUpdate={(payload) => handleUpdate(c.id, payload)}
/> onDelete={() => handleDelete(c.id)}
</div> onEditingChange={(editing: boolean) => handleEditingChange(c.id, editing)}
))} />
</div>
)
})}
</div> </div>
)} )}
</main> </main>

View File

@@ -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'}