-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuse-workout-session.ts
More file actions
243 lines (218 loc) · 7.3 KB
/
Copy pathuse-workout-session.ts
File metadata and controls
243 lines (218 loc) · 7.3 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
'use client'
import { useEffect, useRef, useState } from 'react'
import { sdk } from '@/lib/sdk'
import type { MetricField } from '@/modules/training/exercises'
import {
getExerciseName,
type WorkoutExerciseTree,
type WorkoutTree,
} from '@/modules/training/plans'
import { toSetLogMetricData, type MetricFormValues } from '@/modules/training/logs'
import type { ExerciseLog, SetLog, WorkoutLog } from '@/payload-types'
const relationshipId = (
relationship: number | { id: number } | null | undefined,
): number | null =>
relationship && typeof relationship === 'object' ? relationship.id : (relationship ?? null)
export function useWorkoutSession(
workout: WorkoutTree,
options: { readOnly?: boolean; showResults?: boolean },
) {
const { readOnly, showResults } = options
const [session, setSession] = useState<WorkoutLog | null>(null)
const [sets, setSets] = useState<SetLog[]>([])
const [exerciseNotes, setExerciseNotes] = useState<ExerciseLog[]>([])
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
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)
setExerciseNotes(notesResult.docs)
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<WorkoutLog> | null>(null)
const ensureSession = async (): Promise<WorkoutLog> => {
if (displayedSession) return displayedSession
if (!creating.current) {
creating.current = sdk
.create({ collection: 'workout-logs', data: { workout: workout.id } })
.then((doc) => {
setSession(doc)
setLoadedWorkoutId(workout.id)
return doc
})
}
return creating.current
}
const setsForRow = (rowId: number) =>
displayedSets
.filter((set) => relationshipId(set.exerciseRow) === rowId)
.sort(
(firstSet, secondSet) => (firstSet.setNumber ?? 0) - (secondSet.setNumber ?? 0),
)
const noteForRow = (rowId: number): string =>
displayedNotes.find((entry) => relationshipId(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 } })
setSession(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 },
})
setSession(doc)
}, 'Błąd zapisu czasu')
const addSet = (
exercise: WorkoutExerciseTree,
fields: MetricField[],
values: MetricFormValues,
) =>
runMutation(async () => {
const s = await ensureSession()
const setNumber = setsForRow(exercise.id).length + 1
const exerciseName = getExerciseName(exercise)
const doc = await sdk.create({
collection: 'set-logs',
depth: 0,
data: {
session: s.id,
exercise: exercise.exercise?.id ?? undefined,
exerciseName,
exerciseRow: exercise.id,
setNumber,
...toSetLogMetricData(fields, values),
},
})
setSets((prev) => [...prev, doc])
}, 'Błąd zapisu serii')
const updateSet = (id: number, fields: MetricField[], values: MetricFormValues) =>
runMutation(async () => {
const doc = await sdk.update({
collection: 'set-logs',
id,
depth: 0,
data: toSetLogMetricData(fields, values),
})
setSets((prev) =>
prev.map((set) => (set.id === id ? 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() },
})
setSession(doc)
}, 'Błąd zapisu notatki')
const saveExerciseNote = (exercise: WorkoutExerciseTree, note: string) =>
runMutation(async () => {
const s = await ensureSession()
const rowId = exercise.id
const exerciseName = getExerciseName(exercise)
const existing = exerciseNotes.find(
(entry) => relationshipId(entry.exerciseRow) === rowId,
)
const trimmed = note.trim()
const doc = existing
? await sdk.update({
collection: 'exercise-logs',
id: existing.id,
depth: 0,
data: { note: trimmed },
})
: await sdk.create({
collection: 'exercise-logs',
depth: 0,
data: {
session: s.id,
exercise: exercise.exercise?.id ?? undefined,
exerciseName,
exerciseRow: rowId,
note: trimmed,
},
})
setExerciseNotes((prev) =>
existing ? prev.map((entry) => (entry.id === doc.id ? doc : entry)) : [...prev, doc],
)
}, 'Błąd zapisu notatki')
return {
session: displayedSession,
hasLoaded,
error,
clearError: () => setError(null),
setsForRow,
noteForRow,
setTime,
saveTimes,
addSet,
updateSet,
deleteSet,
saveExerciseNote,
saveSessionNote,
}
}