-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathExerciseCard.kt
More file actions
1098 lines (1060 loc) · 53.7 KB
/
Copy pathExerciseCard.kt
File metadata and controls
1098 lines (1060 loc) · 53.7 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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright (c) 2024-2026. The LibreFit Contributors
*
* LibreFit is subject to additional terms covering author attribution and trademark usage;
* see the ADDITIONAL_TERMS.md and TRADEMARK_POLICY.md files in the project root.
*/
package org.librefit.ui.components
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.AnimatedVisibilityScope
import androidx.compose.animation.ExperimentalSharedTransitionApi
import androidx.compose.animation.SharedTransitionLayout
import androidx.compose.animation.SharedTransitionScope
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.shape.CornerSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.text.input.TextFieldLineLimits
import androidx.compose.foundation.text.input.rememberTextFieldState
import androidx.compose.foundation.text.input.setTextAndPlaceCursorAtEnd
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Checkbox
import androidx.compose.material3.DropdownMenuGroup
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.DropdownMenuPopup
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
import androidx.compose.material3.ExposedDropdownMenuAnchorType
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.IconButtonDefaults
import androidx.compose.material3.IconToggleButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MenuDefaults
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.Slider
import androidx.compose.material3.SwipeToDismissBox
import androidx.compose.material3.SwipeToDismissBoxValue
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberSwipeToDismissBoxState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.tooling.preview.Wallpapers
import androidx.compose.ui.unit.dp
import coil3.compose.AsyncImage
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.toImmutableList
import kotlinx.coroutines.flow.collectLatest
import org.librefit.R
import org.librefit.enums.InfoMode
import org.librefit.enums.PreviousPerformanceSet
import org.librefit.enums.SetMode
import org.librefit.enums.userPreferences.ThemeMode
import org.librefit.models.Weight
import org.librefit.nav.LocalUnitSystem
import org.librefit.ui.components.modalBottomSheets.InputModalBottomSheet
import org.librefit.ui.models.InputModalBottomSheetState
import org.librefit.ui.models.UiExercise
import org.librefit.ui.models.UiExerciseDC
import org.librefit.ui.models.UiExerciseWithSets
import org.librefit.ui.models.UiSet
import org.librefit.ui.models.autoUnitSuffix
import org.librefit.ui.models.doubleValue
import org.librefit.ui.theme.LibreFitTheme
import org.librefit.util.Formatter
import org.librefit.util.Formatter.getDecimalDigitsAsInteger
import org.librefit.util.textFieldTransformations.TimeInputTransformation
import org.librefit.util.textFieldTransformations.TimeOutputTransformation
import kotlin.math.roundToInt
import kotlin.time.Duration.Companion.seconds
/**
* A custom [ElevatedCard] designed to display an [UiExerciseWithSets] with a uniform appearance across
* the app.
*
* @param modifier A [Modifier] that should be passed as `Modifier.animateItem` to enable
* animation for the card within the list.
* @param animatedVisibilityScope Used for image's animation transition
* @param exerciseWithSets An instance of [UiExerciseWithSets] containing all the relevant information
* required for the card display.
* @param previousPerformances When not null and not empty, it displays the performances of previous set next
* to the associated set. The strings should be already formatted and ready to be displayed.
* @param addSet A lambda function invoked when the "Add set" button is clicked.
* @param onDetail A lambda function triggered when the exercise's name or image is clicked, which should open
* the [org.librefit.ui.screens.infoExercise.InfoExerciseScreen].
* @param onDelete A lambda function executed when the *Delete* icon is clicked, it should result in
* the removal of the card.
* @param isCollapsed When `true`, the card collapses its editable body to provide clearer reorder feedback. So it's true only when reordering one of exercises in the list.
* @param dragHandleModifier Modifier applied to the optional drag handle.
* @param onReorderRequest A lambda triggered when the `reorder` option from dropdown menu is pressed.
* @param isDragging when `true`, it applies a shadow to further emphasize with a shadow that the card is dragged.
* @param useScrollWheelForInput If `true`, [InputModalBottomSheet] appears instead of keyboard
* @param dismissScrollWheelInputAutomatically If both this and [useScrollWheelForInput] are `true`, the [InputModalBottomSheet] will be dismissed automatically after first edit.
* @param showExercisesImages If `true`, it shows image of exercise
* @param updateExerciseNotes A function to update notes based on [UiExercise.id]. For more details, refer to
* [org.librefit.ui.screens.workout.WorkoutScreenViewModel.updateExerciseNotes] and
* [org.librefit.ui.screens.editWorkout.EditWorkoutScreenViewModel.updateExerciseNotes].
* @param updateExerciseRestTime A function to update rest time based on [UiExercise.id]. For more details, refer to
* [org.librefit.ui.screens.workout.WorkoutScreenViewModel.updateExerciseRestTime] and
* [org.librefit.ui.screens.editWorkout.EditWorkoutScreenViewModel.updateExerciseRestTime].
* @param updateExerciseSetMode A function to update the set mode based on.
* For more details, refer to [org.librefit.ui.screens.workout.WorkoutScreenViewModel.updateExerciseSetMode]
* and [org.librefit.ui.screens.editWorkout.EditWorkoutScreenViewModel.updateExerciseSetMode].
* @param updateSetLoad A function to update load based on [UiSet.id]. For more details, refer to
* [org.librefit.ui.screens.workout.WorkoutScreenViewModel.updateSetLoad] and
* [org.librefit.ui.screens.editWorkout.EditWorkoutScreenViewModel.updateSetLoad].
* @param updateSetReps A function to update reps based on [UiSet.id]. For more details, refer to
* [org.librefit.ui.screens.workout.WorkoutScreenViewModel.updateSetReps] and
* [org.librefit.ui.screens.editWorkout.EditWorkoutScreenViewModel.updateSetReps].
* @param updateSetTime A function to update time based on [UiSet.id].. For more details, refer to
* [org.librefit.ui.screens.workout.WorkoutScreenViewModel.updateSetTime] and
* [org.librefit.ui.screens.editWorkout.EditWorkoutScreenViewModel.updateSetTime].
* @param updateSetCompleted A function to update completed state based on [UiSet.id]. For more details, refer to
* [org.librefit.ui.screens.workout.WorkoutScreenViewModel.updateSetCompleted] and
* [org.librefit.ui.screens.editWorkout.EditWorkoutScreenViewModel.updateSetCompleted].
* @param deleteSet A function called when the user swipes the set to remove it.
* @param showInfo A lambda function executed when info icon next to "type of set" or "rest time" text
* is clicked. The passed parameter is used by [org.librefit.ui.components.modalBottomSheets.InfoModalBottomSheet] to show the relevant information.
* @param idSetWithRunningStopwatch The ID of the set whose stopwatch is currently active. This ensures
* only one timer runs at a time. The composable will display a running stopwatch for the
* set matching this ID. Pass null if no timer is active. This parameter is only used when [workout] is `true`.
* @param updateIdSetWithRunningStopwatch A callback invoked when the user interacts with a set with a
* running stopwatch. It provides the ID of the set that should become active, or null to stop the current timer.
* This parameter is only used when [workout] is `true`.
* @param workout A Boolean flag indicating whether a checkbox should be displayed next to each set.
* @param applyPreviousSetPerformance Triggered when the user clicks the previous set performance
* (on the left to the set counter) * and should update the current set with the values of the previous set.
*/
@OptIn(
ExperimentalMaterial3Api::class, ExperimentalSharedTransitionApi::class,
ExperimentalMaterial3ExpressiveApi::class
)
@Composable
fun SharedTransitionScope.ExerciseCard(
modifier: Modifier = Modifier,
animatedVisibilityScope: AnimatedVisibilityScope,
exerciseWithSets: UiExerciseWithSets,
previousPerformances: List<PreviousPerformanceSet>? = null,
workout: Boolean = false,
idSetWithRunningStopwatch: Long? = null,
addSet: (Long) -> Unit,
onDetail: (Long, String) -> Unit,
onDelete: (Long) -> Unit,
isCollapsed: Boolean = false,
dragHandleModifier: Modifier = Modifier,
isDragging: Boolean,
useScrollWheelForInput: Boolean,
dismissScrollWheelInputAutomatically: Boolean,
showExercisesImages: Boolean?,
onReorderRequest: () -> Unit,
deleteSet: (Long) -> Unit,
updateExerciseNotes: (String, Long) -> Unit,
updateExerciseRestTime: (Int, Long) -> Unit,
updateExerciseSetMode: (SetMode, Long) -> Unit,
updateSetTime: (Int, Long) -> Unit,
updateSetReps: (Int, Long) -> Unit,
updateSetLoad: (Weight, Long) -> Unit,
updateSetCompleted: (Boolean, Long) -> Unit,
showInfo: (InfoMode) -> Unit,
updateIdSetWithRunningStopwatch: (Long?) -> Unit = {},
applyPreviousSetPerformance: (Long) -> Unit = {}
) {
val unit = autoUnitSuffix()
var showMenu by rememberSaveable { mutableStateOf(false) }
val shape = MaterialTheme.shapes.extraLarge
ElevatedCard(
modifier = modifier.then(
if (isDragging) Modifier.shadow(
10.dp,
shape = shape
) else Modifier
),
shape = shape
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(15.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Row(
modifier = Modifier
.weight(1f)
.clip(MaterialTheme.shapes.medium)
.clickable(enabled = !isCollapsed) {
onDetail(exerciseWithSets.exercise.id, exerciseWithSets.exerciseDC.id)
},
verticalAlignment = Alignment.CenterVertically
) {
val model =
remember(exerciseWithSets.exerciseDC.images) { exerciseWithSets.exerciseDC.images.firstOrNull() }
if (showExercisesImages == true) {
AsyncImage(
model = model?.let { "file:///android_asset/${it}" },
fallback = painterResource(R.drawable.no_image),
contentDescription = exerciseWithSets.exerciseDC.name,
contentScale = ContentScale.Crop,
colorFilter = if (model == null) ColorFilter.tint(MaterialTheme.colorScheme.onSurfaceVariant) else null,
modifier = Modifier
.padding(end = 10.dp)
.sharedElement(
sharedContentState = rememberSharedContentState(
key = exerciseWithSets.exercise.id.toString() + exerciseWithSets.exerciseDC.id
),
animatedVisibilityScope = animatedVisibilityScope
)
.size(50.dp)
.clip(MaterialTheme.shapes.medium)
)
}
Text(
text = exerciseWithSets.exerciseDC.name,
style = MaterialTheme.typography.headlineSmall,
fontWeight = FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f)
)
}
Column {
AnimatedContent(
targetState = isCollapsed,
label = "DragHandleTransition",
) { isReordering ->
if (isReordering) {
IconButton(
modifier = dragHandleModifier,
onClick = {}
) {
Icon(
painter = painterResource(R.drawable.ic_drag_handle),
contentDescription = stringResource(R.string.reorder)
)
}
} else {
IconButton(
onClick = { showMenu = true }
) {
Icon(
painter = painterResource(R.drawable.ic_more_options),
contentDescription = stringResource(R.string.more_options)
)
}
DropdownMenuPopup(
expanded = showMenu,
onDismissRequest = { showMenu = false }) {
DropdownMenuGroup(
shapes = MenuDefaults.groupShape(0, 1) // Top-level group shape
) {
// MenuDefaults.Label { Text("Header") }
DropdownMenuItem(
text = { Text(stringResource(R.string.reorder)) },
leadingIcon = {
Icon(
painterResource(R.drawable.ic_reorder),
stringResource(R.string.reorder)
)
},
onClick = {
onReorderRequest()
showMenu = false
}
)
DropdownMenuItem(
text = { Text(stringResource(R.string.delete)) },
leadingIcon = {
Icon(
painterResource(R.drawable.ic_delete),
stringResource(R.string.delete)
)
},
onClick = {
onDelete(exerciseWithSets.exercise.id)
showMenu = false
}
)
}
}
}
}
}
}
AnimatedVisibility(visible = !isCollapsed) {
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
OutlinedTextField(
shape = MaterialTheme.shapes.large,
modifier = Modifier.fillMaxWidth(),
label = { Text(text = stringResource(id = R.string.notes)) },
value = exerciseWithSets.exercise.notes,
onValueChange = { updateExerciseNotes(it, exerciseWithSets.exercise.id) }
)
//Rest timer slider
Column {
var showSlider by rememberSaveable { mutableStateOf(false) }
var restTime by remember { mutableIntStateOf(exerciseWithSets.exercise.restTime) }
val haptic = LocalHapticFeedback.current
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceAround,
verticalAlignment = Alignment.CenterVertically
) {
Row(
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
IconButton(
// Read more at InfoModalBottomSheet
onClick = { showInfo(InfoMode.REST_TIMER) }
) {
Icon(
painter = painterResource(R.drawable.ic_info),
contentDescription = stringResource(R.string.info)
)
}
Text(
stringResource(R.string.rest_time) + ": " + restTime
+ " " + stringResource(R.string.seconds).replaceFirstChar { it.lowercase() })
}
IconToggleButton(
checked = showSlider,
onCheckedChange = {
showSlider = it
haptic.performHapticFeedback(if (it) HapticFeedbackType.ToggleOn else HapticFeedbackType.ToggleOff)
}
) {
Icon(
painter = painterResource(if (showSlider) R.drawable.ic_check else R.drawable.ic_edit),
contentDescription = stringResource(if (showSlider) R.string.save else R.string.edit)
)
}
}
AnimatedVisibility(visible = showSlider) {
Slider(
value = restTime.toFloat(),
onValueChange = {
// By dividing first and then multiplying by 5, it rounds to the closest number multiple of 5
restTime = (it / 5).roundToInt() * 5
haptic.performHapticFeedback(HapticFeedbackType.SegmentFrequentTick)
},
onValueChangeFinished = {
updateExerciseRestTime(
restTime,
exerciseWithSets.exercise.id
)
},
valueRange = 0f..300f,
// 19 steps means values multiple of 5
steps = 19
)
}
}
HorizontalDivider()
// Set mode selection
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceAround,
verticalAlignment = Alignment.CenterVertically
) {
Row(
modifier = Modifier.weight(0.5f),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) {
IconButton(
// Refer to InfoModalBottomSheet to know the reason behind this value.
// Do NOT change it.
onClick = { showInfo(InfoMode.TYPE_OF_SET) }
) {
Icon(
painter = painterResource(R.drawable.ic_info),
contentDescription = stringResource(R.string.info) + ":"
)
}
Text(stringResource(R.string.type_of_set))
}
var expanded by remember { mutableStateOf(false) }
val focusRequester = remember { FocusRequester() }
// Type of set selector
ExposedDropdownMenuBox(
expanded = expanded,
onExpandedChange = { expanded = it },
modifier = Modifier
.padding(start = 10.dp, end = 10.dp)
.weight(0.5f)
.clickable {
expanded = !expanded
focusRequester.requestFocus()
}
.focusRequester(focusRequester)
.focusable()
) {
OutlinedTextField(
shape = MaterialTheme.shapes.large,
readOnly = true,
value = stringResource(Formatter.setModeToStringId(exerciseWithSets.exercise.setMode)),
onValueChange = {},
singleLine = true,
trailingIcon = {
ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded)
},
modifier = Modifier.menuAnchor(ExposedDropdownMenuAnchorType.PrimaryNotEditable),
colors = ExposedDropdownMenuDefaults.outlinedTextFieldColors()
)
ExposedDropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false }
) {
SetMode.entries.forEachIndexed { _, mode ->
DropdownMenuItem(
onClick = {
updateExerciseSetMode(mode, exerciseWithSets.exercise.id)
expanded = false
},
text = {
Text(
text = stringResource(Formatter.setModeToStringId(mode))
)
},
trailingIcon = if (exerciseWithSets.exercise.setMode == mode) {
{
Icon(
painter = painterResource(R.drawable.ic_check),
contentDescription = stringResource(R.string.checkbox)
)
}
} else null,
modifier = Modifier.background(
if (exerciseWithSets.exercise.setMode == mode) MaterialTheme.colorScheme.inversePrimary.copy(
0.3f
) else Color.Unspecified
)
)
}
}
}
}
ElevatedCard(
shape = MaterialTheme.shapes.extraLarge,
colors = CardDefaults.elevatedCardColors(
containerColor = MaterialTheme.colorScheme.surfaceContainerHighest
)
) {
//Headline set
Row(
modifier = Modifier
.padding(10.dp)
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Spacer(Modifier)
if (previousPerformances != null) {
Text(
text = stringResource(R.string.previous),
color = MaterialTheme.colorScheme.secondary
)
}
if (exerciseWithSets.exercise.setMode == SetMode.DURATION) {
Text(
text = stringResource(R.string.time),
color = MaterialTheme.colorScheme.secondary
)
} else {
if (exerciseWithSets.exercise.setMode == SetMode.LOAD ||
exerciseWithSets.exercise.setMode == SetMode.BODYWEIGHT_WITH_LOAD
) {
Text(
text = stringResource(R.string.load) + " (" + unit + ")",
color = MaterialTheme.colorScheme.secondary
)
}
Text(
text = stringResource(id = R.string.reps),
color = MaterialTheme.colorScheme.secondary
)
}
if (workout) {
Icon(
painter = painterResource(R.drawable.ic_check),
contentDescription = stringResource(R.string.done)
)
}
}
//Sets
Column(modifier = Modifier.animateContentSize()) {
exerciseWithSets.sets.forEachIndexed { i, set ->
key(set.id) {
Set(
i = i,
set = set,
previousSet = previousPerformances?.getOrNull(i),
lastIndex = exerciseWithSets.sets.lastIndex,
setMode = exerciseWithSets.exercise.setMode,
isStopwatchRunning = idSetWithRunningStopwatch == null,
isThisSetStopwatchRunning = idSetWithRunningStopwatch == set.id,
workout = workout,
useScrollWheelForInput = useScrollWheelForInput,
dismissScrollWheelInputAutomatically = dismissScrollWheelInputAutomatically,
unit = unit,
deleteSet = deleteSet,
updateIdSetWithRunningStopwatch = updateIdSetWithRunningStopwatch,
updateSetTime = updateSetTime,
updateSetReps = updateSetReps,
updateSetLoad = updateSetLoad,
updateSetCompleted = updateSetCompleted,
applyPreviousSet = applyPreviousSetPerformance
)
}
}
}
}
//Add set button
LibreFitButton(
text = stringResource(id = R.string.add_set),
icon = painterResource(R.drawable.ic_add_circle),
onClick = { addSet(exerciseWithSets.exercise.id) },
elevated = false
)
}
}
}
}
}
@OptIn(ExperimentalMaterial3ExpressiveApi::class)
@Composable
private fun Set(
i: Int,
set: UiSet,
previousSet: PreviousPerformanceSet? = null,
lastIndex: Int,
setMode: SetMode,
isStopwatchRunning: Boolean,
isThisSetStopwatchRunning: Boolean,
workout: Boolean,
useScrollWheelForInput: Boolean,
dismissScrollWheelInputAutomatically: Boolean,
unit: String,
deleteSet: (Long) -> Unit,
updateSetTime: (Int, Long) -> Unit,
updateSetReps: (Int, Long) -> Unit,
updateSetLoad: (Weight, Long) -> Unit,
updateSetCompleted: (Boolean, Long) -> Unit,
updateIdSetWithRunningStopwatch: (Long?) -> Unit,
applyPreviousSet: (Long) -> Unit
) {
val unitSystem = LocalUnitSystem.current
val timeTextFieldState = rememberTextFieldState(
initialText = Formatter.formateSecondsInMinutesAndSeconds(set.elapsedTime)
.filter { it != ':' }
)
var repValue by rememberSaveable(set.reps) { mutableStateOf(set.reps.toString()) }
var weightValue by rememberSaveable(set.load) {
mutableStateOf(
set.load.doubleValue(unitSystem).toString()
)
}
// Sync elapsed time with time text field
LaunchedEffect(set.elapsedTime) {
val formatted =
Formatter.formateSecondsInMinutesAndSeconds(set.elapsedTime).filter { it != ':' }
if (timeTextFieldState.text.toString() != formatted) {
timeTextFieldState.setTextAndPlaceCursorAtEnd(formatted)
}
}
// Sync time text field with elapsed time
LaunchedEffect(timeTextFieldState) {
snapshotFlow { timeTextFieldState.text.toString() }.collectLatest { rawText ->
val padded = rawText.padStart(4, '0')
val seconds = padded.takeLast(2)
val minutes = padded.dropLast(2).takeLast(2)
val newValue = Formatter.parseTimeInputToSeconds(
input = "$minutes:$seconds"
)
if (newValue != set.elapsedTime) {
updateSetTime(newValue, set.id)
}
}
}
val swipeToDismissBoxState = rememberSwipeToDismissBoxState()
var inputModalBottomSheetState by remember { mutableStateOf<InputModalBottomSheetState?>(null) }
var inputSetId by rememberSaveable { mutableStateOf<Long?>(null) }
inputModalBottomSheetState?.let {
InputModalBottomSheet(
state = it,
onValueChange = { newState ->
inputModalBottomSheetState = newState
inputSetId?.let { id ->
when (newState) {
is InputModalBottomSheetState.Weight -> {
updateSetLoad(
Weight.auto(newState.totalWeight, unitSystem),
id
)
}
is InputModalBottomSheetState.Reps -> {
updateSetReps(newState.reps, id)
}
is InputModalBottomSheetState.MinutesSeconds -> {
updateSetTime(newState.totalSeconds, id)
}
else -> error("newState in ExerciseCard should not have this value: $newState")
}
}
},
onDismiss = {
inputModalBottomSheetState = null
inputSetId = null
},
dismissAutomatically = dismissScrollWheelInputAutomatically
)
}
val haptic = LocalHapticFeedback.current
LaunchedEffect(swipeToDismissBoxState.currentValue) {
if (swipeToDismissBoxState.currentValue != SwipeToDismissBoxValue.Settled) {
haptic.performHapticFeedback(HapticFeedbackType.GestureThresholdActivate)
}
}
SwipeToDismissBox(
state = swipeToDismissBoxState,
onDismiss = { deleteSet(set.id) },
backgroundContent = {
Row(
modifier = Modifier
.fillMaxSize()
.clip(
RoundedCornerShape(
topStart = CornerSize(if (i == 0) 45 else 0),
topEnd = CornerSize(if (i == 0) 45 else 0),
bottomEnd = CornerSize(
if (i == lastIndex) 45 else 0
),
bottomStart = CornerSize(
if (i == lastIndex) 45 else 0
),
)
)
.background(
when (swipeToDismissBoxState.dismissDirection) {
SwipeToDismissBoxValue.StartToEnd -> MaterialTheme.colorScheme.errorContainer
SwipeToDismissBoxValue.EndToStart -> MaterialTheme.colorScheme.errorContainer
SwipeToDismissBoxValue.Settled -> Color.Transparent
}
)
.padding(start = 10.dp, end = 10.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = when (swipeToDismissBoxState.dismissDirection) {
SwipeToDismissBoxValue.EndToStart -> Arrangement.End
SwipeToDismissBoxValue.Settled -> Arrangement.Start
SwipeToDismissBoxValue.StartToEnd -> Arrangement.Start
}
) {
Icon(
painter = painterResource(R.drawable.ic_delete),
contentDescription = stringResource(R.string.delete),
tint = MaterialTheme.colorScheme.onErrorContainer
)
}
}
) {
val backgroundColor by animateColorAsState(
targetValue = if (set.completed) {
MaterialTheme.colorScheme.tertiaryContainer
} else {
MaterialTheme.colorScheme.surfaceContainerHighest
},
label = "animated_color_for_set_background"
)
val contentColor by animateColorAsState(
targetValue = if (set.completed) {
MaterialTheme.colorScheme.onTertiaryContainer
} else {
MaterialTheme.colorScheme.onSurface
},
label = "animated_color_for_set_content"
)
Row(
modifier = Modifier
.clip(
RoundedCornerShape(
topStart = CornerSize(if (i == 0) 45 else 0),
topEnd = CornerSize(if (i == 0) 45 else 0),
bottomEnd = CornerSize(
if (i == lastIndex) 45 else 0
),
bottomStart = CornerSize(
if (i == lastIndex) 45 else 0
),
)
)
.background(backgroundColor)
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(
text = "${i + 1}",
color = contentColor,
modifier = Modifier.padding(start = 20.dp)
)
previousSet?.let { values ->
TextButton(
onClick = { applyPreviousSet(set.id) },
modifier = Modifier.wrapContentWidth()
) {
val (previousReps, previousLoad, previousTime) = values
val text = when (setMode) {
SetMode.LOAD -> "$previousLoad$unit\n* $previousReps"
SetMode.BODYWEIGHT -> "$previousReps"
SetMode.BODYWEIGHT_WITH_LOAD -> "$previousLoad$unit\n* $previousReps"
SetMode.DURATION -> Formatter.formateSecondsInMinutesAndSeconds(previousTime)
}
Text(
text = text,
color = contentColor,
textAlign = TextAlign.Center,
)
}
}
if (setMode == SetMode.DURATION) {
Row(verticalAlignment = Alignment.CenterVertically) {
if (workout) {
IconButton(
enabled = (isStopwatchRunning || isThisSetStopwatchRunning)
&& !set.completed,
colors = IconButtonDefaults.iconButtonColors(
contentColor = contentColor
),
onClick = {
val newId = if (isThisSetStopwatchRunning) null else set.id
updateIdSetWithRunningStopwatch(newId)
}
) {
Icon(
painter = painterResource(
if (isThisSetStopwatchRunning)
R.drawable.ic_pause else R.drawable.ic_play_arrow
),
contentDescription = if (isThisSetStopwatchRunning)
stringResource(R.string.resume) else
stringResource(R.string.pause)
)
}
}
//Time
Box {
OutlinedTextField(
shape = MaterialTheme.shapes.large,
modifier = Modifier.width(80.dp),
state = timeTextFieldState,
lineLimits = TextFieldLineLimits.SingleLine,
inputTransformation = TimeInputTransformation(),
outputTransformation = TimeOutputTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
colors = OutlinedTextFieldDefaults.colors(
unfocusedBorderColor = Color.Transparent,
focusedBorderColor = Color.Transparent,
disabledBorderColor = Color.Transparent,
focusedTextColor = contentColor,
unfocusedTextColor = contentColor,
),
readOnly = useScrollWheelForInput
)
if (useScrollWheelForInput) {
Box(
modifier = Modifier
.matchParentSize()
.clip(MaterialTheme.shapes.extraLarge)
.clickable {
set.elapsedTime.seconds.toComponents { _, minutes, seconds, _ ->
inputModalBottomSheetState =
InputModalBottomSheetState.MinutesSeconds(
minutes = minutes,
seconds = seconds
)
}
inputSetId = set.id
}
) { }
}
}
}
} else {
if (setMode == SetMode.LOAD || setMode == SetMode.BODYWEIGHT_WITH_LOAD) {
//Weight
Box {
OutlinedTextField(
shape = MaterialTheme.shapes.large,
modifier = Modifier.width(80.dp),
value = weightValue,
onValueChange = { string ->
weightValue = Formatter.normalizeNumericString(string)
updateSetLoad(
Weight.auto(
Formatter.parseDoubleFromString(weightValue) ?: 0.0,
unitSystem
),
set.id
)
},
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal),
colors = OutlinedTextFieldDefaults.colors(
unfocusedBorderColor = Color.Transparent,
focusedBorderColor = Color.Transparent,
disabledBorderColor = Color.Transparent,
focusedTextColor = contentColor,
unfocusedTextColor = contentColor,
),
readOnly = useScrollWheelForInput
)
if (useScrollWheelForInput) {
Box(
modifier = Modifier
.matchParentSize()
.clip(MaterialTheme.shapes.extraLarge)
.clickable {
val value = set.load.doubleValue(unitSystem)
inputModalBottomSheetState =
InputModalBottomSheetState.Weight(
integerWeight = value.toInt(),
decimalWeight = value.getDecimalDigitsAsInteger()
)
inputSetId = set.id
}
) { }
}
}
}
//Reps
Box {
OutlinedTextField(
shape = MaterialTheme.shapes.large,
modifier = Modifier.width(80.dp),
value = repValue,
onValueChange = { string ->
repValue = Formatter.normalizeNumericString(string)
Formatter.parseIntegerFromString(repValue)?.let {
updateSetReps(it, set.id)
}
},
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
colors = OutlinedTextFieldDefaults.colors(
unfocusedBorderColor = Color.Transparent,
focusedBorderColor = Color.Transparent,
disabledBorderColor = Color.Transparent,
focusedTextColor = contentColor,
unfocusedTextColor = contentColor,
),
readOnly = useScrollWheelForInput
)
if (useScrollWheelForInput) {
Box(
modifier = Modifier
.matchParentSize()
.clip(MaterialTheme.shapes.extraLarge)
.clickable {
inputModalBottomSheetState = InputModalBottomSheetState.Reps(
reps = repValue.toInt()
)
inputSetId = set.id
}
) { }
}
}
}
if (workout) {
Checkbox(
checked = set.completed,
onCheckedChange = { checked ->
if (isThisSetStopwatchRunning) {
updateIdSetWithRunningStopwatch(null)
}
updateSetCompleted(checked, set.id)
}
)
}
}
}
}
@OptIn(ExperimentalSharedTransitionApi::class)
@Preview(wallpaper = Wallpapers.RED_DOMINATED_EXAMPLE)
@Composable
private fun ExerciseCardPreview() {
val currentIdSetWithRunningSet = remember { mutableStateOf<Long?>(null) }
val e = remember {
mutableStateOf(
UiExerciseWithSets(
exercise = UiExercise(
notes = "This is a note!",
restTime = 90,
setMode = SetMode.DURATION
),
sets = persistentListOf(UiSet(completed = true), UiSet(elapsedTime = 100)),
exerciseDC = UiExerciseDC(
name = "Exercise name",
images = persistentListOf("3_4_Sit-Up/0.jpg")
)
)
)
}
val previousPerformances = e.value.sets.map { _ ->
when (e.value.exercise.setMode) {
SetMode.BODYWEIGHT -> PreviousPerformanceSet(reps = 10)
SetMode.DURATION -> PreviousPerformanceSet(time = 124)
SetMode.BODYWEIGHT_WITH_LOAD -> PreviousPerformanceSet(
reps = 10,