-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuse-workout-session.ts
More file actions
210 lines (184 loc) · 7.11 KB
/
Copy pathuse-workout-session.ts
File metadata and controls
210 lines (184 loc) · 7.11 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
'use client'
import { useEffect, useRef, useState } from 'react'
import type { MetricField } from '@/collections/exercises/types'
import { metricBody } from '@/lib/metrics'
import { sdk } from '@/lib/sdk'
import type { Session, SetLog, TExercise, TWorkout, Values } from '@/types/workout'
const toSession = (doc: unknown): Session => doc as unknown as Session
const toSetLog = (doc: unknown): SetLog => doc as unknown as SetLog
type ExerciseNote = { id: number; exerciseRow: number; note: string | null }
const toExerciseNote = (doc: unknown): ExerciseNote => doc as unknown as ExerciseNote
export function useWorkoutSession(
workout: TWorkout,
options: { readOnly?: boolean; showResults?: boolean },
) {
const { readOnly, showResults } = options
const [session, setSession] = useState<Session | null>(null)
const [sets, setSets] = useState<SetLog[]>([])
const [exerciseNotes, setExerciseNotes] = useState<ExerciseNote[]>([])
const [loadedWorkoutId, setLoadedWorkoutId] = useState<number | null>(null)
const [error, setError] = useState<string | null>(null)
const hasLoaded = loadedWorkoutId === workout.id
const displayedSession = hasLoaded ? session : null
const displayedSets = hasLoaded ? sets : []
const displayedNotes = hasLoaded ? exerciseNotes : []
useEffect(() => {
if (readOnly && !showResults) return
let active = true
sdk
.find({ collection: 'workout-logs', where: { workout: { equals: workout.id } }, limit: 1, depth: 0, sort: '-updatedAt' })
.then(async (result) => {
if (!active) return
const loadedSession = (result.docs[0] ?? null) as Session | null
if (!loadedSession) {
setSession(null)
setSets([])
setExerciseNotes([])
setLoadedWorkoutId(workout.id)
return
}
setSession(loadedSession)
const [setsResult, notesResult] = await Promise.all([
sdk.find({
collection: 'set-logs',
where: { session: { equals: loadedSession.id } },
limit: 500,
depth: 0,
sort: 'setNumber',
}),
sdk.find({
collection: 'exercise-logs',
where: { session: { equals: loadedSession.id } },
limit: 500,
depth: 0,
}),
])
if (!active) return
setSets(setsResult.docs as unknown as SetLog[])
setExerciseNotes(notesResult.docs.map(toExerciseNote))
setLoadedWorkoutId(workout.id)
})
.catch((loadError) => {
if (!active) return
setError(loadError instanceof Error ? loadError.message : 'Błąd ładowania sesji')
setLoadedWorkoutId(workout.id)
})
return () => {
active = false
}
}, [workout.id, readOnly, showResults])
const runMutation = async (fn: () => Promise<void>, fallback: string) => {
try {
await fn()
setError(null)
} catch (mutationError) {
setError(mutationError instanceof Error ? mutationError.message : fallback)
}
}
const creating = useRef<Promise<Session> | null>(null)
const ensureSession = async (): Promise<Session> => {
if (displayedSession) return displayedSession
if (!creating.current) {
creating.current = sdk
.create({ collection: 'workout-logs', data: { workout: workout.id } as never })
.then((doc) => {
const created = toSession(doc)
setSession(created)
setLoadedWorkoutId(workout.id)
return created
})
}
return creating.current
}
const setsForRow = (rowId: string) =>
displayedSets
.filter((set) => String(set.exerciseRow) === rowId)
.sort((a, b) => (a.setNumber ?? 0) - (b.setNumber ?? 0))
const noteForRow = (rowId: string): string =>
displayedNotes.find((entry) => String(entry.exerciseRow) === rowId)?.note ?? ''
const setTime = (field: 'startedAt' | 'finishedAt', iso: string | null) =>
runMutation(async () => {
const s = await ensureSession()
const doc = await sdk.update({ collection: 'workout-logs', id: s.id, data: { [field]: iso } as never })
setSession(toSession(doc))
}, 'Błąd zapisu czasu')
const saveTimes = (startedAt: string | null, finishedAt: string | null) =>
runMutation(async () => {
const s = await ensureSession()
const doc = await sdk.update({ collection: 'workout-logs', id: s.id, data: { startedAt, finishedAt } as never })
setSession(toSession(doc))
}, 'Błąd zapisu czasu')
const addSet = (ex: TExercise, fields: MetricField[], values: Values) =>
runMutation(async () => {
const s = await ensureSession()
const setNumber = setsForRow(ex.rowId).length + 1
const doc = await sdk.create({
collection: 'set-logs',
depth: 0,
data: {
session: s.id,
exercise: ex.exerciseId ?? undefined,
exerciseName: ex.exerciseName,
exerciseRow: Number(ex.rowId),
setNumber,
...metricBody(fields, values),
} as never,
})
setSets((prev) => [...prev, toSetLog(doc)])
}, 'Błąd zapisu serii')
const updateSet = (id: number, fields: MetricField[], values: Values) =>
runMutation(async () => {
const doc = await sdk.update({ collection: 'set-logs', id, depth: 0, data: metricBody(fields, values) as never })
setSets((prev) => prev.map((set) => (set.id === id ? { ...set, ...toSetLog(doc) } : set)))
}, 'Błąd aktualizacji serii')
const deleteSet = (id: number) =>
runMutation(async () => {
await sdk.delete({ collection: 'set-logs', id })
setSets((prev) => prev.filter((set) => set.id !== id))
}, 'Błąd usunięcia serii')
const saveSessionNote = (note: string) =>
runMutation(async () => {
const s = await ensureSession()
const doc = await sdk.update({ collection: 'workout-logs', id: s.id, depth: 0, data: { notes: note.trim() } as never })
setSession(toSession(doc))
}, 'Błąd zapisu notatki')
const saveExerciseNote = (ex: TExercise, note: string) =>
runMutation(async () => {
const s = await ensureSession()
const rowId = Number(ex.rowId)
const existing = exerciseNotes.find((entry) => entry.exerciseRow === rowId)
const trimmed = note.trim()
const doc = existing
? await sdk.update({ collection: 'exercise-logs', id: existing.id, depth: 0, data: { note: trimmed } as never })
: await sdk.create({
collection: 'exercise-logs',
depth: 0,
data: {
session: s.id,
exercise: ex.exerciseId ?? undefined,
exerciseName: ex.exerciseName,
exerciseRow: rowId,
note: trimmed,
} as never,
})
const saved = toExerciseNote(doc)
setExerciseNotes((prev) =>
existing ? prev.map((entry) => (entry.id === saved.id ? saved : entry)) : [...prev, saved],
)
}, 'Błąd zapisu notatki')
return {
session: displayedSession,
hasLoaded,
error,
clearError: () => setError(null),
setsForRow,
noteForRow,
setTime,
saveTimes,
addSet,
updateSet,
deleteSet,
saveExerciseNote,
saveSessionNote,
}
}