Compare commits
4 Commits
ANDROID_1.
...
ANDROID_1.
| Author | SHA1 | Date | |
|---|---|---|---|
|
dcc3f9cc9d
|
|||
|
2a48908dd2
|
|||
|
5d1748765f
|
|||
|
298ba6149b
|
@@ -16,8 +16,8 @@ android {
|
||||
applicationId = "com.atridad.openclimb"
|
||||
minSdk = 31
|
||||
targetSdk = 36
|
||||
versionCode = 24
|
||||
versionName = "1.5.0"
|
||||
versionCode = 26
|
||||
versionName = "1.5.1"
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
|
||||
@@ -7,62 +7,58 @@ import kotlinx.coroutines.flow.Flow
|
||||
|
||||
@Dao
|
||||
interface ProblemDao {
|
||||
|
||||
|
||||
@Query("SELECT * FROM problems ORDER BY updatedAt DESC")
|
||||
fun getAllProblems(): Flow<List<Problem>>
|
||||
|
||||
@Query("SELECT * FROM problems WHERE id = :id")
|
||||
suspend fun getProblemById(id: String): Problem?
|
||||
|
||||
|
||||
@Query("SELECT * FROM problems WHERE id = :id") suspend fun getProblemById(id: String): Problem?
|
||||
|
||||
@Query("SELECT * FROM problems WHERE gymId = :gymId ORDER BY updatedAt DESC")
|
||||
fun getProblemsByGym(gymId: String): Flow<List<Problem>>
|
||||
|
||||
|
||||
@Query("SELECT * FROM problems WHERE climbType = :climbType ORDER BY updatedAt DESC")
|
||||
fun getProblemsByClimbType(climbType: ClimbType): Flow<List<Problem>>
|
||||
|
||||
@Query("SELECT * FROM problems WHERE gymId = :gymId AND climbType = :climbType ORDER BY updatedAt DESC")
|
||||
|
||||
@Query(
|
||||
"SELECT * FROM problems WHERE gymId = :gymId AND climbType = :climbType ORDER BY updatedAt DESC"
|
||||
)
|
||||
fun getProblemsByGymAndType(gymId: String, climbType: ClimbType): Flow<List<Problem>>
|
||||
|
||||
|
||||
@Query("SELECT * FROM problems WHERE isActive = 1 ORDER BY updatedAt DESC")
|
||||
fun getActiveProblems(): Flow<List<Problem>>
|
||||
|
||||
|
||||
@Query("SELECT * FROM problems WHERE gymId = :gymId AND isActive = 1 ORDER BY updatedAt DESC")
|
||||
fun getActiveProblemsByGym(gymId: String): Flow<List<Problem>>
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertProblem(problem: Problem)
|
||||
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertProblem(problem: Problem)
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertProblems(problems: List<Problem>)
|
||||
|
||||
@Update
|
||||
suspend fun updateProblem(problem: Problem)
|
||||
|
||||
@Delete
|
||||
suspend fun deleteProblem(problem: Problem)
|
||||
|
||||
@Query("DELETE FROM problems WHERE id = :id")
|
||||
suspend fun deleteProblemById(id: String)
|
||||
|
||||
|
||||
@Update suspend fun updateProblem(problem: Problem)
|
||||
|
||||
@Delete suspend fun deleteProblem(problem: Problem)
|
||||
|
||||
@Query("DELETE FROM problems WHERE id = :id") suspend fun deleteProblemById(id: String)
|
||||
|
||||
@Query("SELECT COUNT(*) FROM problems WHERE gymId = :gymId")
|
||||
suspend fun getProblemsCountByGym(gymId: String): Int
|
||||
|
||||
|
||||
@Query("SELECT COUNT(*) FROM problems WHERE isActive = 1")
|
||||
suspend fun getActiveProblemsCount(): Int
|
||||
|
||||
@Query("""
|
||||
SELECT * FROM problems
|
||||
WHERE (name LIKE '%' || :searchQuery || '%'
|
||||
|
||||
@Query(
|
||||
"""
|
||||
SELECT * FROM problems
|
||||
WHERE (name LIKE '%' || :searchQuery || '%'
|
||||
OR description LIKE '%' || :searchQuery || '%'
|
||||
OR location LIKE '%' || :searchQuery || '%'
|
||||
OR setter LIKE '%' || :searchQuery || '%')
|
||||
OR location LIKE '%' || :searchQuery || '%')
|
||||
ORDER BY updatedAt DESC
|
||||
""")
|
||||
"""
|
||||
)
|
||||
fun searchProblems(searchQuery: String): Flow<List<Problem>>
|
||||
|
||||
@Query("SELECT COUNT(*) FROM problems")
|
||||
suspend fun getProblemsCount(): Int
|
||||
|
||||
@Query("DELETE FROM problems")
|
||||
suspend fun deleteAllProblems()
|
||||
|
||||
@Query("SELECT COUNT(*) FROM problems") suspend fun getProblemsCount(): Int
|
||||
|
||||
@Query("DELETE FROM problems") suspend fun deleteAllProblems()
|
||||
}
|
||||
|
||||
@@ -4,71 +4,67 @@ import androidx.room.Entity
|
||||
import androidx.room.ForeignKey
|
||||
import androidx.room.Index
|
||||
import androidx.room.PrimaryKey
|
||||
import kotlinx.serialization.Serializable
|
||||
import java.time.LocalDateTime
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Entity(
|
||||
tableName = "problems",
|
||||
foreignKeys = [
|
||||
ForeignKey(
|
||||
entity = Gym::class,
|
||||
parentColumns = ["id"],
|
||||
childColumns = ["gymId"],
|
||||
onDelete = ForeignKey.CASCADE
|
||||
)
|
||||
],
|
||||
indices = [Index(value = ["gymId"])]
|
||||
tableName = "problems",
|
||||
foreignKeys =
|
||||
[
|
||||
ForeignKey(
|
||||
entity = Gym::class,
|
||||
parentColumns = ["id"],
|
||||
childColumns = ["gymId"],
|
||||
onDelete = ForeignKey.CASCADE
|
||||
)],
|
||||
indices = [Index(value = ["gymId"])]
|
||||
)
|
||||
@Serializable
|
||||
data class Problem(
|
||||
@PrimaryKey
|
||||
val id: String,
|
||||
val gymId: String,
|
||||
val name: String? = null,
|
||||
val description: String? = null,
|
||||
val climbType: ClimbType,
|
||||
val difficulty: DifficultyGrade,
|
||||
val setter: String? = null,
|
||||
val tags: List<String> = emptyList(),
|
||||
val location: String? = null,
|
||||
val imagePaths: List<String> = emptyList(),
|
||||
val isActive: Boolean = true,
|
||||
val dateSet: String? = null,
|
||||
val notes: String? = null,
|
||||
val createdAt: String,
|
||||
val updatedAt: String
|
||||
@PrimaryKey val id: String,
|
||||
val gymId: String,
|
||||
val name: String? = null,
|
||||
val description: String? = null,
|
||||
val climbType: ClimbType,
|
||||
val difficulty: DifficultyGrade,
|
||||
val tags: List<String> = emptyList(),
|
||||
val location: String? = null,
|
||||
val imagePaths: List<String> = emptyList(),
|
||||
val isActive: Boolean = true,
|
||||
val dateSet: String? = null,
|
||||
val notes: String? = null,
|
||||
val createdAt: String,
|
||||
val updatedAt: String
|
||||
) {
|
||||
companion object {
|
||||
fun create(
|
||||
gymId: String,
|
||||
name: String? = null,
|
||||
description: String? = null,
|
||||
climbType: ClimbType,
|
||||
difficulty: DifficultyGrade,
|
||||
setter: String? = null,
|
||||
tags: List<String> = emptyList(),
|
||||
location: String? = null,
|
||||
imagePaths: List<String> = emptyList(),
|
||||
dateSet: String? = null,
|
||||
notes: String? = null
|
||||
gymId: String,
|
||||
name: String? = null,
|
||||
description: String? = null,
|
||||
climbType: ClimbType,
|
||||
difficulty: DifficultyGrade,
|
||||
tags: List<String> = emptyList(),
|
||||
location: String? = null,
|
||||
imagePaths: List<String> = emptyList(),
|
||||
dateSet: String? = null,
|
||||
notes: String? = null
|
||||
): Problem {
|
||||
val now = LocalDateTime.now().toString()
|
||||
return Problem(
|
||||
id = java.util.UUID.randomUUID().toString(),
|
||||
gymId = gymId,
|
||||
name = name,
|
||||
description = description,
|
||||
climbType = climbType,
|
||||
difficulty = difficulty,
|
||||
setter = setter,
|
||||
tags = tags,
|
||||
location = location,
|
||||
imagePaths = imagePaths,
|
||||
isActive = true,
|
||||
dateSet = dateSet,
|
||||
notes = notes,
|
||||
createdAt = now,
|
||||
updatedAt = now
|
||||
id = java.util.UUID.randomUUID().toString(),
|
||||
gymId = gymId,
|
||||
name = name,
|
||||
description = description,
|
||||
climbType = climbType,
|
||||
difficulty = difficulty,
|
||||
tags = tags,
|
||||
location = location,
|
||||
imagePaths = imagePaths,
|
||||
isActive = true,
|
||||
dateSet = dateSet,
|
||||
notes = notes,
|
||||
createdAt = now,
|
||||
updatedAt = now
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,7 +82,7 @@ class ClimbRepository(database: OpenClimbDatabase, private val context: Context)
|
||||
val exportData =
|
||||
ClimbDataExport(
|
||||
exportedAt = LocalDateTime.now().toString(),
|
||||
version = "1.0",
|
||||
version = "2.0",
|
||||
gyms = allGyms,
|
||||
problems = allProblems,
|
||||
sessions = allSessions,
|
||||
@@ -141,7 +141,7 @@ class ClimbRepository(database: OpenClimbDatabase, private val context: Context)
|
||||
val exportData =
|
||||
ClimbDataExport(
|
||||
exportedAt = LocalDateTime.now().toString(),
|
||||
version = "1.0",
|
||||
version = "2.0",
|
||||
gyms = allGyms,
|
||||
problems = allProblems,
|
||||
sessions = allSessions,
|
||||
@@ -343,7 +343,7 @@ class ClimbRepository(database: OpenClimbDatabase, private val context: Context)
|
||||
@kotlinx.serialization.Serializable
|
||||
data class ClimbDataExport(
|
||||
val exportedAt: String,
|
||||
val version: String = "1.0",
|
||||
val version: String = "2.0",
|
||||
val gyms: List<Gym>,
|
||||
val problems: List<Problem>,
|
||||
val sessions: List<ClimbSession>,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -21,181 +21,181 @@ import com.atridad.openclimb.ui.viewmodel.ClimbViewModel
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun ProblemsScreen(
|
||||
viewModel: ClimbViewModel,
|
||||
onNavigateToProblemDetail: (String) -> Unit
|
||||
) {
|
||||
fun ProblemsScreen(viewModel: ClimbViewModel, onNavigateToProblemDetail: (String) -> Unit) {
|
||||
val problems by viewModel.problems.collectAsState()
|
||||
val gyms by viewModel.gyms.collectAsState()
|
||||
var showImageViewer by remember { mutableStateOf(false) }
|
||||
var selectedImagePaths by remember { mutableStateOf<List<String>>(emptyList()) }
|
||||
var selectedImageIndex by remember { mutableIntStateOf(0) }
|
||||
|
||||
|
||||
// Filter state
|
||||
var selectedClimbType by remember { mutableStateOf<ClimbType?>(null) }
|
||||
var selectedGym by remember { mutableStateOf<Gym?>(null) }
|
||||
|
||||
|
||||
// Apply filters
|
||||
val filteredProblems = problems.filter { problem ->
|
||||
val climbTypeMatch = selectedClimbType?.let { it == problem.climbType } != false
|
||||
val gymMatch = selectedGym?.let { it.id == problem.gymId } != false
|
||||
climbTypeMatch && gymMatch
|
||||
}
|
||||
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(16.dp)
|
||||
) {
|
||||
val filteredProblems =
|
||||
problems.filter { problem ->
|
||||
val climbTypeMatch = selectedClimbType?.let { it == problem.climbType } != false
|
||||
val gymMatch = selectedGym?.let { it.id == problem.gymId } != false
|
||||
climbTypeMatch && gymMatch
|
||||
}
|
||||
|
||||
// Separate active and inactive problems
|
||||
val activeProblems = filteredProblems.filter { it.isActive }
|
||||
val inactiveProblems = filteredProblems.filter { !it.isActive }
|
||||
val sortedProblems = activeProblems + inactiveProblems
|
||||
|
||||
Column(modifier = Modifier.fillMaxSize().padding(16.dp)) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp)
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp)
|
||||
) {
|
||||
Icon(
|
||||
painter = painterResource(id = R.drawable.ic_mountains),
|
||||
contentDescription = "OpenClimb Logo",
|
||||
modifier = Modifier.size(32.dp),
|
||||
tint = MaterialTheme.colorScheme.primary
|
||||
painter = painterResource(id = R.drawable.ic_mountains),
|
||||
contentDescription = "OpenClimb Logo",
|
||||
modifier = Modifier.size(32.dp),
|
||||
tint = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
Text(
|
||||
text = "Problems & Routes",
|
||||
style = MaterialTheme.typography.headlineMedium,
|
||||
fontWeight = FontWeight.Bold
|
||||
text = "Problems & Routes",
|
||||
style = MaterialTheme.typography.headlineMedium,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
|
||||
// Filters Section
|
||||
if (problems.isNotEmpty()) {
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(16.dp)
|
||||
) {
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Text(
|
||||
text = "Filters",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold
|
||||
text = "Filters",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
|
||||
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
|
||||
|
||||
// Climb Type Filter
|
||||
Text(
|
||||
text = "Climb Type",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.Medium
|
||||
text = "Climb Type",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.Medium
|
||||
)
|
||||
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
LazyRow(
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
|
||||
LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
item {
|
||||
FilterChip(
|
||||
onClick = { selectedClimbType = null },
|
||||
label = { Text("All Types") },
|
||||
selected = selectedClimbType == null
|
||||
onClick = { selectedClimbType = null },
|
||||
label = { Text("All Types") },
|
||||
selected = selectedClimbType == null
|
||||
)
|
||||
}
|
||||
items(ClimbType.entries) { climbType ->
|
||||
FilterChip(
|
||||
onClick = { selectedClimbType = climbType },
|
||||
label = { Text(climbType.getDisplayName()) },
|
||||
selected = selectedClimbType == climbType
|
||||
onClick = { selectedClimbType = climbType },
|
||||
label = { Text(climbType.getDisplayName()) },
|
||||
selected = selectedClimbType == climbType
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
|
||||
|
||||
// Gym Filter
|
||||
Text(
|
||||
text = "Gym",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.Medium
|
||||
text = "Gym",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.Medium
|
||||
)
|
||||
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
LazyRow(
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
|
||||
LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
item {
|
||||
FilterChip(
|
||||
onClick = { selectedGym = null },
|
||||
label = { Text("All Gyms") },
|
||||
selected = selectedGym == null
|
||||
onClick = { selectedGym = null },
|
||||
label = { Text("All Gyms") },
|
||||
selected = selectedGym == null
|
||||
)
|
||||
}
|
||||
items(gyms) { gym ->
|
||||
FilterChip(
|
||||
onClick = { selectedGym = gym },
|
||||
label = { Text(gym.name) },
|
||||
selected = selectedGym?.id == gym.id
|
||||
onClick = { selectedGym = gym },
|
||||
label = { Text(gym.name) },
|
||||
selected = selectedGym?.id == gym.id
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Filter result count
|
||||
if (selectedClimbType != null || selectedGym != null) {
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
Text(
|
||||
text = "Showing ${filteredProblems.size} of ${problems.size} problems",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
text =
|
||||
"Showing ${filteredProblems.size} of ${problems.size} problems (${activeProblems.size} active, ${inactiveProblems.size} reset)",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
}
|
||||
|
||||
|
||||
if (filteredProblems.isEmpty()) {
|
||||
EmptyStateMessage(
|
||||
title = if (problems.isEmpty()) {
|
||||
if (gyms.isEmpty()) "No Gyms Available" else "No Problems Yet"
|
||||
} else {
|
||||
"No Problems Match Filters"
|
||||
},
|
||||
message = if (problems.isEmpty()) {
|
||||
if (gyms.isEmpty()) "Add a gym first to start tracking problems and routes!" else "Start tracking your favorite problems and routes!"
|
||||
} else {
|
||||
"Try adjusting your filters to see more problems."
|
||||
},
|
||||
onActionClick = { },
|
||||
actionText = ""
|
||||
title =
|
||||
if (problems.isEmpty()) {
|
||||
if (gyms.isEmpty()) "No Gyms Available" else "No Problems Yet"
|
||||
} else {
|
||||
"No Problems Match Filters"
|
||||
},
|
||||
message =
|
||||
if (problems.isEmpty()) {
|
||||
if (gyms.isEmpty())
|
||||
"Add a gym first to start tracking problems and routes!"
|
||||
else "Start tracking your favorite problems and routes!"
|
||||
} else {
|
||||
"Try adjusting your filters to see more problems."
|
||||
},
|
||||
onActionClick = {},
|
||||
actionText = ""
|
||||
)
|
||||
} else {
|
||||
LazyColumn {
|
||||
items(filteredProblems) { problem ->
|
||||
items(sortedProblems) { problem ->
|
||||
ProblemCard(
|
||||
problem = problem,
|
||||
gymName = gyms.find { it.id == problem.gymId }?.name ?: "Unknown Gym",
|
||||
onClick = { onNavigateToProblemDetail(problem.id) },
|
||||
onImageClick = { imagePaths, index ->
|
||||
selectedImagePaths = imagePaths
|
||||
selectedImageIndex = index
|
||||
showImageViewer = true
|
||||
}
|
||||
problem = problem,
|
||||
gymName = gyms.find { it.id == problem.gymId }?.name ?: "Unknown Gym",
|
||||
onClick = { onNavigateToProblemDetail(problem.id) },
|
||||
onImageClick = { imagePaths, index ->
|
||||
selectedImagePaths = imagePaths
|
||||
selectedImageIndex = index
|
||||
showImageViewer = true
|
||||
},
|
||||
onToggleActive = {
|
||||
val updatedProblem = problem.copy(isActive = !problem.isActive)
|
||||
viewModel.updateProblem(updatedProblem)
|
||||
}
|
||||
)
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Fullscreen Image Viewer
|
||||
if (showImageViewer && selectedImagePaths.isNotEmpty()) {
|
||||
FullscreenImageViewer(
|
||||
imagePaths = selectedImagePaths,
|
||||
initialIndex = selectedImageIndex,
|
||||
onDismiss = { showImageViewer = false }
|
||||
imagePaths = selectedImagePaths,
|
||||
initialIndex = selectedImageIndex,
|
||||
onDismiss = { showImageViewer = false }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -203,97 +203,117 @@ fun ProblemsScreen(
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun ProblemCard(
|
||||
problem: Problem,
|
||||
gymName: String,
|
||||
onClick: () -> Unit,
|
||||
onImageClick: ((List<String>, Int) -> Unit)? = null
|
||||
problem: Problem,
|
||||
gymName: String,
|
||||
onClick: () -> Unit,
|
||||
onImageClick: ((List<String>, Int) -> Unit)? = null,
|
||||
onToggleActive: (() -> Unit)? = null
|
||||
) {
|
||||
Card(
|
||||
onClick = onClick,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(16.dp)
|
||||
) {
|
||||
Card(onClick = onClick, modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.Top
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.Top
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = problem.name ?: "Unnamed Problem",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold
|
||||
text = problem.name ?: "Unnamed Problem",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color =
|
||||
if (problem.isActive) MaterialTheme.colorScheme.onSurface
|
||||
else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)
|
||||
)
|
||||
|
||||
|
||||
Text(
|
||||
text = gymName,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
text = gymName,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color =
|
||||
MaterialTheme.colorScheme.onSurfaceVariant.copy(
|
||||
alpha = if (problem.isActive) 1f else 0.6f
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
Column(horizontalAlignment = Alignment.End) {
|
||||
Text(
|
||||
text = problem.difficulty.grade,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = MaterialTheme.colorScheme.primary
|
||||
text = problem.difficulty.grade,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
|
||||
|
||||
Text(
|
||||
text = problem.climbType.getDisplayName(),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
text = problem.climbType.getDisplayName(),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
problem.location?.let { location ->
|
||||
Spacer(modifier = Modifier.height(4.dp))
|
||||
Text(
|
||||
text = "Location: $location",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
text = "Location: $location",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
if (problem.tags.isNotEmpty()) {
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
Row {
|
||||
problem.tags.take(3).forEach { tag ->
|
||||
AssistChip(
|
||||
onClick = { },
|
||||
label = { Text(tag) },
|
||||
modifier = Modifier.padding(end = 4.dp)
|
||||
onClick = {},
|
||||
label = { Text(tag) },
|
||||
modifier = Modifier.padding(end = 4.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Display images if any
|
||||
if (problem.imagePaths.isNotEmpty()) {
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
ImageDisplay(
|
||||
imagePaths = problem.imagePaths.take(3), // Show max 3 images in list
|
||||
imageSize = 60,
|
||||
onImageClick = { index ->
|
||||
onImageClick?.invoke(problem.imagePaths, index)
|
||||
}
|
||||
imagePaths = problem.imagePaths.take(3), // Show max 3 images in list
|
||||
imageSize = 60,
|
||||
onImageClick = { index -> onImageClick?.invoke(problem.imagePaths, index) }
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
if (!problem.isActive) {
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
Text(
|
||||
text = "Inactive",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.error
|
||||
text = "Reset / No Longer Set",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.tertiary,
|
||||
fontWeight = FontWeight.Medium
|
||||
)
|
||||
}
|
||||
|
||||
// Toggle active button
|
||||
if (onToggleActive != null) {
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
OutlinedButton(
|
||||
onClick = onToggleActive,
|
||||
colors =
|
||||
ButtonDefaults.outlinedButtonColors(
|
||||
contentColor =
|
||||
if (problem.isActive)
|
||||
MaterialTheme.colorScheme.tertiary
|
||||
else MaterialTheme.colorScheme.primary
|
||||
),
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Text(
|
||||
text = if (problem.isActive) "Mark as Reset" else "Mark as Active",
|
||||
style = MaterialTheme.typography.bodySmall
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -324,12 +324,17 @@ class ClimbViewModel(private val repository: ClimbRepository) : ViewModel() {
|
||||
fun exportDataToZipUri(context: Context, uri: android.net.Uri) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
_uiState.value = _uiState.value.copy(isLoading = true)
|
||||
_uiState.value =
|
||||
_uiState.value.copy(
|
||||
isLoading = true,
|
||||
message = "Creating ZIP file with images..."
|
||||
)
|
||||
repository.exportAllDataToZipUri(context, uri)
|
||||
_uiState.value =
|
||||
_uiState.value.copy(
|
||||
isLoading = false,
|
||||
message = "Data with images exported successfully"
|
||||
message =
|
||||
"Export complete! Your climbing data and images have been saved."
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
_uiState.value =
|
||||
|
||||
@@ -5,139 +5,146 @@ import android.content.Intent
|
||||
import android.graphics.*
|
||||
import android.graphics.drawable.GradientDrawable
|
||||
import androidx.core.content.FileProvider
|
||||
import androidx.core.graphics.createBitmap
|
||||
import androidx.core.graphics.toColorInt
|
||||
import com.atridad.openclimb.data.model.*
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import java.time.LocalDateTime
|
||||
import java.time.format.DateTimeFormatter
|
||||
import kotlin.math.roundToInt
|
||||
import androidx.core.graphics.createBitmap
|
||||
import androidx.core.graphics.toColorInt
|
||||
|
||||
object SessionShareUtils {
|
||||
|
||||
|
||||
data class SessionStats(
|
||||
val totalAttempts: Int,
|
||||
val successfulAttempts: Int,
|
||||
val problems: List<Problem>,
|
||||
val uniqueProblemsAttempted: Int,
|
||||
val uniqueProblemsCompleted: Int,
|
||||
val averageGrade: String?,
|
||||
val sessionDuration: String,
|
||||
val topResult: AttemptResult?,
|
||||
val topGrade: String?
|
||||
val totalAttempts: Int,
|
||||
val successfulAttempts: Int,
|
||||
val problems: List<Problem>,
|
||||
val uniqueProblemsAttempted: Int,
|
||||
val uniqueProblemsCompleted: Int,
|
||||
val averageGrade: String?,
|
||||
val sessionDuration: String,
|
||||
val topResult: AttemptResult?,
|
||||
val topGrade: String?
|
||||
)
|
||||
|
||||
|
||||
fun calculateSessionStats(
|
||||
session: ClimbSession,
|
||||
attempts: List<Attempt>,
|
||||
problems: List<Problem>
|
||||
session: ClimbSession,
|
||||
attempts: List<Attempt>,
|
||||
problems: List<Problem>
|
||||
): SessionStats {
|
||||
val successfulResults = listOf(
|
||||
AttemptResult.SUCCESS,
|
||||
AttemptResult.FLASH
|
||||
)
|
||||
|
||||
val successfulResults = listOf(AttemptResult.SUCCESS, AttemptResult.FLASH)
|
||||
|
||||
val successfulAttempts = attempts.filter { it.result in successfulResults }
|
||||
val uniqueProblems = attempts.map { it.problemId }.distinct()
|
||||
val uniqueCompletedProblems = successfulAttempts.map { it.problemId }.distinct()
|
||||
|
||||
|
||||
val attemptedProblems = problems.filter { it.id in uniqueProblems }
|
||||
|
||||
|
||||
// Calculate separate averages for different climbing types and difficulty systems
|
||||
val boulderProblems = attemptedProblems.filter { it.climbType == ClimbType.BOULDER }
|
||||
val ropeProblems = attemptedProblems.filter { it.climbType == ClimbType.ROPE }
|
||||
|
||||
|
||||
val boulderAverage = calculateAverageGrade(boulderProblems, "Boulder")
|
||||
val ropeAverage = calculateAverageGrade(ropeProblems, "Rope")
|
||||
|
||||
|
||||
// Combine averages for display
|
||||
val averageGrade = when {
|
||||
boulderAverage != null && ropeAverage != null -> "$boulderAverage / $ropeAverage"
|
||||
boulderAverage != null -> boulderAverage
|
||||
ropeAverage != null -> ropeAverage
|
||||
else -> null
|
||||
}
|
||||
|
||||
val averageGrade =
|
||||
when {
|
||||
boulderAverage != null && ropeAverage != null ->
|
||||
"$boulderAverage / $ropeAverage"
|
||||
boulderAverage != null -> boulderAverage
|
||||
ropeAverage != null -> ropeAverage
|
||||
else -> null
|
||||
}
|
||||
|
||||
// Determine highest achieved grade (only from completed problems: SUCCESS or FLASH)
|
||||
val completedProblems = problems.filter { it.id in uniqueCompletedProblems }
|
||||
val completedBoulder = completedProblems.filter { it.climbType == ClimbType.BOULDER }
|
||||
val completedRope = completedProblems.filter { it.climbType == ClimbType.ROPE }
|
||||
val topBoulder = highestGradeForProblems(completedBoulder)
|
||||
val topRope = highestGradeForProblems(completedRope)
|
||||
val topGrade = when {
|
||||
topBoulder != null && topRope != null -> "$topBoulder / $topRope"
|
||||
topBoulder != null -> topBoulder
|
||||
topRope != null -> topRope
|
||||
else -> null
|
||||
}
|
||||
|
||||
val topGrade =
|
||||
when {
|
||||
topBoulder != null && topRope != null -> "$topBoulder / $topRope"
|
||||
topBoulder != null -> topBoulder
|
||||
topRope != null -> topRope
|
||||
else -> null
|
||||
}
|
||||
|
||||
val duration = if (session.duration != null) "${session.duration}m" else "Unknown"
|
||||
val topResult = attempts.maxByOrNull {
|
||||
when (it.result) {
|
||||
AttemptResult.FLASH -> 3
|
||||
AttemptResult.SUCCESS -> 2
|
||||
AttemptResult.FALL -> 1
|
||||
else -> 0
|
||||
}
|
||||
}?.result
|
||||
|
||||
val topResult =
|
||||
attempts
|
||||
.maxByOrNull {
|
||||
when (it.result) {
|
||||
AttemptResult.FLASH -> 3
|
||||
AttemptResult.SUCCESS -> 2
|
||||
AttemptResult.FALL -> 1
|
||||
else -> 0
|
||||
}
|
||||
}
|
||||
?.result
|
||||
|
||||
return SessionStats(
|
||||
totalAttempts = attempts.size,
|
||||
successfulAttempts = successfulAttempts.size,
|
||||
problems = attemptedProblems,
|
||||
uniqueProblemsAttempted = uniqueProblems.size,
|
||||
uniqueProblemsCompleted = uniqueCompletedProblems.size,
|
||||
averageGrade = averageGrade,
|
||||
sessionDuration = duration,
|
||||
topResult = topResult,
|
||||
topGrade = topGrade
|
||||
totalAttempts = attempts.size,
|
||||
successfulAttempts = successfulAttempts.size,
|
||||
problems = attemptedProblems,
|
||||
uniqueProblemsAttempted = uniqueProblems.size,
|
||||
uniqueProblemsCompleted = uniqueCompletedProblems.size,
|
||||
averageGrade = averageGrade,
|
||||
sessionDuration = duration,
|
||||
topResult = topResult,
|
||||
topGrade = topGrade
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Calculate average grade for a specific set of problems, respecting their difficulty systems
|
||||
*/
|
||||
private fun calculateAverageGrade(problems: List<Problem>, climbingType: String): String? {
|
||||
if (problems.isEmpty()) return null
|
||||
|
||||
|
||||
// Group problems by difficulty system
|
||||
val problemsBySystem = problems.groupBy { it.difficulty.system }
|
||||
|
||||
|
||||
val averages = mutableListOf<String>()
|
||||
|
||||
|
||||
problemsBySystem.forEach { (system, systemProblems) ->
|
||||
when (system) {
|
||||
DifficultySystem.V_SCALE -> {
|
||||
val gradeValues = systemProblems.mapNotNull { problem ->
|
||||
when {
|
||||
problem.difficulty.grade == "VB" -> 0
|
||||
else -> problem.difficulty.grade.removePrefix("V").toIntOrNull()
|
||||
}
|
||||
}
|
||||
val gradeValues =
|
||||
systemProblems.mapNotNull { problem ->
|
||||
when {
|
||||
problem.difficulty.grade == "VB" -> 0
|
||||
else -> problem.difficulty.grade.removePrefix("V").toIntOrNull()
|
||||
}
|
||||
}
|
||||
if (gradeValues.isNotEmpty()) {
|
||||
val avg = gradeValues.average().roundToInt()
|
||||
averages.add(if (avg == 0) "VB" else "V$avg")
|
||||
}
|
||||
}
|
||||
DifficultySystem.FONT -> {
|
||||
val gradeValues = systemProblems.mapNotNull { problem ->
|
||||
// Extract numeric part from Font grades (e.g., "6A" -> 6, "7C+" -> 7)
|
||||
problem.difficulty.grade.filter { it.isDigit() }.toIntOrNull()
|
||||
}
|
||||
val gradeValues =
|
||||
systemProblems.mapNotNull { problem ->
|
||||
// Extract numeric part from Font grades (e.g., "6A" -> 6, "7C+" ->
|
||||
// 7)
|
||||
problem.difficulty.grade.filter { it.isDigit() }.toIntOrNull()
|
||||
}
|
||||
if (gradeValues.isNotEmpty()) {
|
||||
val avg = gradeValues.average().roundToInt()
|
||||
averages.add("$avg")
|
||||
}
|
||||
}
|
||||
DifficultySystem.YDS -> {
|
||||
val gradeValues = systemProblems.mapNotNull { problem ->
|
||||
// Extract numeric part from YDS grades (e.g., "5.10a" -> 5.10)
|
||||
val grade = problem.difficulty.grade
|
||||
if (grade.startsWith("5.")) {
|
||||
grade.substring(2).toDoubleOrNull()
|
||||
} else null
|
||||
}
|
||||
val gradeValues =
|
||||
systemProblems.mapNotNull { problem ->
|
||||
// Extract numeric part from YDS grades (e.g., "5.10a" -> 5.10)
|
||||
val grade = problem.difficulty.grade
|
||||
if (grade.startsWith("5.")) {
|
||||
grade.substring(2).toDoubleOrNull()
|
||||
} else null
|
||||
}
|
||||
if (gradeValues.isNotEmpty()) {
|
||||
val avg = gradeValues.average()
|
||||
averages.add("5.${String.format("%.1f", avg)}")
|
||||
@@ -145,9 +152,13 @@ object SessionShareUtils {
|
||||
}
|
||||
DifficultySystem.CUSTOM -> {
|
||||
// For custom systems, try to extract numeric values
|
||||
val gradeValues = systemProblems.mapNotNull { problem ->
|
||||
problem.difficulty.grade.filter { it.isDigit() || it == '.' || it == '-' }.toDoubleOrNull()
|
||||
}
|
||||
val gradeValues =
|
||||
systemProblems.mapNotNull { problem ->
|
||||
problem.difficulty
|
||||
.grade
|
||||
.filter { it.isDigit() || it == '.' || it == '-' }
|
||||
.toDoubleOrNull()
|
||||
}
|
||||
if (gradeValues.isNotEmpty()) {
|
||||
val avg = gradeValues.average()
|
||||
averages.add(String.format("%.1f", avg))
|
||||
@@ -155,7 +166,7 @@ object SessionShareUtils {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return if (averages.isNotEmpty()) {
|
||||
if (averages.size == 1) {
|
||||
averages.first()
|
||||
@@ -166,185 +177,262 @@ object SessionShareUtils {
|
||||
}
|
||||
|
||||
fun generateShareCard(
|
||||
context: Context,
|
||||
session: ClimbSession,
|
||||
gym: Gym,
|
||||
stats: SessionStats
|
||||
context: Context,
|
||||
session: ClimbSession,
|
||||
gym: Gym,
|
||||
stats: SessionStats
|
||||
): File? {
|
||||
return try {
|
||||
val width = 1242 // 3:4 aspect at higher resolution for better fit
|
||||
val height = 1656
|
||||
|
||||
|
||||
val bitmap = createBitmap(width, height)
|
||||
val canvas = Canvas(bitmap)
|
||||
|
||||
val gradientDrawable = GradientDrawable(
|
||||
GradientDrawable.Orientation.TOP_BOTTOM,
|
||||
intArrayOf(
|
||||
"#667eea".toColorInt(),
|
||||
"#764ba2".toColorInt()
|
||||
)
|
||||
)
|
||||
|
||||
val gradientDrawable =
|
||||
GradientDrawable(
|
||||
GradientDrawable.Orientation.TOP_BOTTOM,
|
||||
intArrayOf("#667eea".toColorInt(), "#764ba2".toColorInt())
|
||||
)
|
||||
gradientDrawable.setBounds(0, 0, width, height)
|
||||
gradientDrawable.draw(canvas)
|
||||
|
||||
|
||||
// Setup paint objects
|
||||
val titlePaint = Paint().apply {
|
||||
color = Color.WHITE
|
||||
textSize = 72f
|
||||
typeface = Typeface.DEFAULT_BOLD
|
||||
isAntiAlias = true
|
||||
textAlign = Paint.Align.CENTER
|
||||
}
|
||||
|
||||
val subtitlePaint = Paint().apply {
|
||||
color = "#E8E8E8".toColorInt()
|
||||
textSize = 48f
|
||||
typeface = Typeface.DEFAULT
|
||||
isAntiAlias = true
|
||||
textAlign = Paint.Align.CENTER
|
||||
}
|
||||
|
||||
val statLabelPaint = Paint().apply {
|
||||
color = "#B8B8B8".toColorInt()
|
||||
textSize = 36f
|
||||
typeface = Typeface.DEFAULT
|
||||
isAntiAlias = true
|
||||
textAlign = Paint.Align.CENTER
|
||||
}
|
||||
|
||||
val statValuePaint = Paint().apply {
|
||||
color = Color.WHITE
|
||||
textSize = 64f
|
||||
typeface = Typeface.DEFAULT_BOLD
|
||||
isAntiAlias = true
|
||||
textAlign = Paint.Align.CENTER
|
||||
}
|
||||
|
||||
val cardPaint = Paint().apply {
|
||||
color = "#40FFFFFF".toColorInt()
|
||||
isAntiAlias = true
|
||||
}
|
||||
|
||||
val titlePaint =
|
||||
Paint().apply {
|
||||
color = Color.WHITE
|
||||
textSize = 72f
|
||||
typeface = Typeface.DEFAULT_BOLD
|
||||
isAntiAlias = true
|
||||
textAlign = Paint.Align.CENTER
|
||||
}
|
||||
|
||||
val subtitlePaint =
|
||||
Paint().apply {
|
||||
color = "#E8E8E8".toColorInt()
|
||||
textSize = 48f
|
||||
typeface = Typeface.DEFAULT
|
||||
isAntiAlias = true
|
||||
textAlign = Paint.Align.CENTER
|
||||
}
|
||||
|
||||
val statLabelPaint =
|
||||
Paint().apply {
|
||||
color = "#B8B8B8".toColorInt()
|
||||
textSize = 36f
|
||||
typeface = Typeface.DEFAULT
|
||||
isAntiAlias = true
|
||||
textAlign = Paint.Align.CENTER
|
||||
}
|
||||
|
||||
val statValuePaint =
|
||||
Paint().apply {
|
||||
color = Color.WHITE
|
||||
textSize = 64f
|
||||
typeface = Typeface.DEFAULT_BOLD
|
||||
isAntiAlias = true
|
||||
textAlign = Paint.Align.CENTER
|
||||
}
|
||||
|
||||
val cardPaint =
|
||||
Paint().apply {
|
||||
color = "#40FFFFFF".toColorInt()
|
||||
isAntiAlias = true
|
||||
}
|
||||
|
||||
// Draw main card background
|
||||
val cardRect = RectF(60f, 200f, width - 60f, height - 120f)
|
||||
canvas.drawRoundRect(cardRect, 40f, 40f, cardPaint)
|
||||
|
||||
|
||||
// Draw content
|
||||
var yPosition = 300f
|
||||
|
||||
|
||||
// Title
|
||||
canvas.drawText("Climbing Session", width / 2f, yPosition, titlePaint)
|
||||
yPosition += 80f
|
||||
|
||||
|
||||
// Gym and date
|
||||
canvas.drawText(gym.name, width / 2f, yPosition, subtitlePaint)
|
||||
yPosition += 60f
|
||||
|
||||
|
||||
val dateText = formatSessionDate(session.date)
|
||||
canvas.drawText(dateText, width / 2f, yPosition, subtitlePaint)
|
||||
yPosition += 120f
|
||||
|
||||
|
||||
// Stats grid
|
||||
val statsStartY = yPosition
|
||||
val columnWidth = width / 2f
|
||||
val columnMaxTextWidth = columnWidth - 120f
|
||||
|
||||
|
||||
// Left column stats
|
||||
var leftY = statsStartY
|
||||
drawStatItemFitting(canvas, columnWidth / 2f, leftY, "Attempts", stats.totalAttempts.toString(), statLabelPaint, statValuePaint, columnMaxTextWidth)
|
||||
drawStatItemFitting(
|
||||
canvas,
|
||||
columnWidth / 2f,
|
||||
leftY,
|
||||
"Attempts",
|
||||
stats.totalAttempts.toString(),
|
||||
statLabelPaint,
|
||||
statValuePaint,
|
||||
columnMaxTextWidth
|
||||
)
|
||||
leftY += 120f
|
||||
drawStatItemFitting(canvas, columnWidth / 2f, leftY, "Problems", stats.uniqueProblemsAttempted.toString(), statLabelPaint, statValuePaint, columnMaxTextWidth)
|
||||
drawStatItemFitting(
|
||||
canvas,
|
||||
columnWidth / 2f,
|
||||
leftY,
|
||||
"Problems",
|
||||
stats.uniqueProblemsAttempted.toString(),
|
||||
statLabelPaint,
|
||||
statValuePaint,
|
||||
columnMaxTextWidth
|
||||
)
|
||||
leftY += 120f
|
||||
drawStatItemFitting(canvas, columnWidth / 2f, leftY, "Duration", stats.sessionDuration, statLabelPaint, statValuePaint, columnMaxTextWidth)
|
||||
|
||||
drawStatItemFitting(
|
||||
canvas,
|
||||
columnWidth / 2f,
|
||||
leftY,
|
||||
"Duration",
|
||||
stats.sessionDuration,
|
||||
statLabelPaint,
|
||||
statValuePaint,
|
||||
columnMaxTextWidth
|
||||
)
|
||||
|
||||
// Right column stats
|
||||
var rightY = statsStartY
|
||||
drawStatItemFitting(canvas, width - columnWidth / 2f, rightY, "Successful", stats.successfulAttempts.toString(), statLabelPaint, statValuePaint, columnMaxTextWidth)
|
||||
drawStatItemFitting(
|
||||
canvas,
|
||||
width - columnWidth / 2f,
|
||||
rightY,
|
||||
"Completed",
|
||||
stats.uniqueProblemsCompleted.toString(),
|
||||
statLabelPaint,
|
||||
statValuePaint,
|
||||
columnMaxTextWidth
|
||||
)
|
||||
rightY += 120f
|
||||
drawStatItemFitting(canvas, width - columnWidth / 2f, rightY, "Completed", stats.uniqueProblemsCompleted.toString(), statLabelPaint, statValuePaint, columnMaxTextWidth)
|
||||
rightY += 120f
|
||||
|
||||
|
||||
var rightYAfter = rightY
|
||||
stats.topGrade?.let { grade ->
|
||||
drawStatItemFitting(canvas, width - columnWidth / 2f, rightY, "Top Grade", grade, statLabelPaint, statValuePaint, columnMaxTextWidth)
|
||||
drawStatItemFitting(
|
||||
canvas,
|
||||
width - columnWidth / 2f,
|
||||
rightY,
|
||||
"Top Grade",
|
||||
grade,
|
||||
statLabelPaint,
|
||||
statValuePaint,
|
||||
columnMaxTextWidth
|
||||
)
|
||||
rightYAfter += 120f
|
||||
}
|
||||
|
||||
|
||||
// Grade range(s)
|
||||
val boulderRange = gradeRangeForProblems(stats.problems.filter { it.climbType == ClimbType.BOULDER })
|
||||
val ropeRange = gradeRangeForProblems(stats.problems.filter { it.climbType == ClimbType.ROPE })
|
||||
val boulderRange =
|
||||
gradeRangeForProblems(
|
||||
stats.problems.filter { it.climbType == ClimbType.BOULDER }
|
||||
)
|
||||
val ropeRange =
|
||||
gradeRangeForProblems(stats.problems.filter { it.climbType == ClimbType.ROPE })
|
||||
val rangesY = kotlin.math.max(leftY, rightYAfter) + 120f
|
||||
if (boulderRange != null && ropeRange != null) {
|
||||
// Two evenly spaced items
|
||||
drawStatItemFitting(canvas, columnWidth / 2f, rangesY, "Boulder Range", boulderRange, statLabelPaint, statValuePaint, columnMaxTextWidth)
|
||||
drawStatItemFitting(canvas, width - columnWidth / 2f, rangesY, "Rope Range", ropeRange, statLabelPaint, statValuePaint, columnMaxTextWidth)
|
||||
drawStatItemFitting(
|
||||
canvas,
|
||||
columnWidth / 2f,
|
||||
rangesY,
|
||||
"Boulder Range",
|
||||
boulderRange,
|
||||
statLabelPaint,
|
||||
statValuePaint,
|
||||
columnMaxTextWidth
|
||||
)
|
||||
drawStatItemFitting(
|
||||
canvas,
|
||||
width - columnWidth / 2f,
|
||||
rangesY,
|
||||
"Rope Range",
|
||||
ropeRange,
|
||||
statLabelPaint,
|
||||
statValuePaint,
|
||||
columnMaxTextWidth
|
||||
)
|
||||
} else if (boulderRange != null || ropeRange != null) {
|
||||
// Single centered item
|
||||
val singleRange = boulderRange ?: ropeRange ?: ""
|
||||
drawStatItemFitting(canvas, width / 2f, rangesY, "Grade Range", singleRange, statLabelPaint, statValuePaint, width - 200f)
|
||||
drawStatItemFitting(
|
||||
canvas,
|
||||
width / 2f,
|
||||
rangesY,
|
||||
"Grade Range",
|
||||
singleRange,
|
||||
statLabelPaint,
|
||||
statValuePaint,
|
||||
width - 200f
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
|
||||
// App branding
|
||||
val brandingPaint = Paint().apply {
|
||||
color = "#80FFFFFF".toColorInt()
|
||||
textSize = 32f
|
||||
typeface = Typeface.DEFAULT
|
||||
isAntiAlias = true
|
||||
textAlign = Paint.Align.CENTER
|
||||
}
|
||||
val brandingPaint =
|
||||
Paint().apply {
|
||||
color = "#80FFFFFF".toColorInt()
|
||||
textSize = 32f
|
||||
typeface = Typeface.DEFAULT
|
||||
isAntiAlias = true
|
||||
textAlign = Paint.Align.CENTER
|
||||
}
|
||||
canvas.drawText("OpenClimb", width / 2f, height - 40f, brandingPaint)
|
||||
|
||||
|
||||
// Save to file
|
||||
val shareDir = File(context.cacheDir, "shares")
|
||||
if (!shareDir.exists()) {
|
||||
shareDir.mkdirs()
|
||||
}
|
||||
|
||||
|
||||
val filename = "session_${session.id}_${System.currentTimeMillis()}.png"
|
||||
val file = File(shareDir, filename)
|
||||
|
||||
|
||||
val outputStream = FileOutputStream(file)
|
||||
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
|
||||
outputStream.flush()
|
||||
outputStream.close()
|
||||
|
||||
|
||||
bitmap.recycle()
|
||||
|
||||
|
||||
file
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private fun drawStatItem(
|
||||
canvas: Canvas,
|
||||
x: Float,
|
||||
y: Float,
|
||||
label: String,
|
||||
value: String,
|
||||
labelPaint: Paint,
|
||||
valuePaint: Paint
|
||||
canvas: Canvas,
|
||||
x: Float,
|
||||
y: Float,
|
||||
label: String,
|
||||
value: String,
|
||||
labelPaint: Paint,
|
||||
valuePaint: Paint
|
||||
) {
|
||||
canvas.drawText(value, x, y, valuePaint)
|
||||
canvas.drawText(label, x, y + 50f, labelPaint)
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Draws a stat item while fitting the value text to a max width by reducing text size if needed.
|
||||
* Draws a stat item while fitting the value text to a max width by reducing text size if
|
||||
* needed.
|
||||
*/
|
||||
private fun drawStatItemFitting(
|
||||
canvas: Canvas,
|
||||
x: Float,
|
||||
y: Float,
|
||||
label: String,
|
||||
value: String,
|
||||
labelPaint: Paint,
|
||||
valuePaint: Paint,
|
||||
maxTextWidth: Float
|
||||
canvas: Canvas,
|
||||
x: Float,
|
||||
y: Float,
|
||||
label: String,
|
||||
value: String,
|
||||
labelPaint: Paint,
|
||||
valuePaint: Paint,
|
||||
maxTextWidth: Float
|
||||
) {
|
||||
val tempPaint = Paint(valuePaint)
|
||||
var textSize = tempPaint.textSize
|
||||
@@ -357,7 +445,7 @@ object SessionShareUtils {
|
||||
canvas.drawText(value, x, y, tempPaint)
|
||||
canvas.drawText(label, x, y + 50f, labelPaint)
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns a range string like "X - Y" for the given problems, based on their difficulty grades.
|
||||
*/
|
||||
@@ -367,9 +455,7 @@ object SessionShareUtils {
|
||||
val sorted = grades.sortedWith { a, b -> a.compareTo(b) }
|
||||
return "${sorted.first().grade} - ${sorted.last().grade}"
|
||||
}
|
||||
|
||||
|
||||
|
||||
private fun formatSessionDate(dateString: String): String {
|
||||
return try {
|
||||
val formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME
|
||||
@@ -380,23 +466,28 @@ object SessionShareUtils {
|
||||
dateString.take(10)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
fun shareSessionCard(context: Context, imageFile: File) {
|
||||
try {
|
||||
val uri = FileProvider.getUriForFile(
|
||||
context,
|
||||
"${context.packageName}.fileprovider",
|
||||
imageFile
|
||||
)
|
||||
|
||||
val shareIntent = Intent().apply {
|
||||
action = Intent.ACTION_SEND
|
||||
type = "image/png"
|
||||
putExtra(Intent.EXTRA_STREAM, uri)
|
||||
putExtra(Intent.EXTRA_TEXT, "Check out my climbing session! 🧗♀️ #OpenClimb")
|
||||
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
}
|
||||
|
||||
val uri =
|
||||
FileProvider.getUriForFile(
|
||||
context,
|
||||
"${context.packageName}.fileprovider",
|
||||
imageFile
|
||||
)
|
||||
|
||||
val shareIntent =
|
||||
Intent().apply {
|
||||
action = Intent.ACTION_SEND
|
||||
type = "image/png"
|
||||
putExtra(Intent.EXTRA_STREAM, uri)
|
||||
putExtra(
|
||||
Intent.EXTRA_TEXT,
|
||||
"Check out my climbing session! 🧗♀️ #OpenClimb"
|
||||
)
|
||||
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
}
|
||||
|
||||
val chooser = Intent.createChooser(shareIntent, "Share Session")
|
||||
chooser.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
context.startActivity(chooser)
|
||||
@@ -406,16 +497,18 @@ object SessionShareUtils {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the highest grade string among the given problems, respecting their difficulty system.
|
||||
* Returns the highest grade string among the given problems, respecting their difficulty
|
||||
* system.
|
||||
*/
|
||||
private fun highestGradeForProblems(problems: List<Problem>): String? {
|
||||
if (problems.isEmpty()) return null
|
||||
return problems.maxByOrNull { p -> gradeRank(p.difficulty.system, p.difficulty.grade) }?.difficulty?.grade
|
||||
return problems
|
||||
.maxByOrNull { p -> gradeRank(p.difficulty.system, p.difficulty.grade) }
|
||||
?.difficulty
|
||||
?.grade
|
||||
}
|
||||
|
||||
/**
|
||||
* Produces a comparable numeric rank for grades across supported systems.
|
||||
*/
|
||||
/** Produces a comparable numeric rank for grades across supported systems. */
|
||||
private fun gradeRank(system: DifficultySystem, grade: String): Double {
|
||||
return when (system) {
|
||||
DifficultySystem.V_SCALE -> {
|
||||
@@ -424,7 +517,8 @@ object SessionShareUtils {
|
||||
DifficultySystem.FONT -> {
|
||||
val list = DifficultySystem.FONT.getAvailableGrades()
|
||||
val idx = list.indexOf(grade.uppercase())
|
||||
if (idx >= 0) idx.toDouble() else grade.filter { it.isDigit() }.toDoubleOrNull() ?: -1.0
|
||||
if (idx >= 0) idx.toDouble()
|
||||
else grade.filter { it.isDigit() }.toDoubleOrNull() ?: -1.0
|
||||
}
|
||||
DifficultySystem.YDS -> {
|
||||
// Parse 5.X with optional letter a-d
|
||||
@@ -434,13 +528,14 @@ object SessionShareUtils {
|
||||
val numberPart = tail.takeWhile { it.isDigit() || it == '.' }
|
||||
val letterPart = tail.drop(numberPart.length).firstOrNull()
|
||||
val base = numberPart.toDoubleOrNull() ?: return -1.0
|
||||
val letterWeight = when (letterPart) {
|
||||
'a' -> 0.0
|
||||
'b' -> 0.1
|
||||
'c' -> 0.2
|
||||
'd' -> 0.3
|
||||
else -> 0.0
|
||||
}
|
||||
val letterWeight =
|
||||
when (letterPart) {
|
||||
'a' -> 0.0
|
||||
'b' -> 0.1
|
||||
'c' -> 0.2
|
||||
'd' -> 0.3
|
||||
else -> 0.0
|
||||
}
|
||||
base + letterWeight
|
||||
}
|
||||
DifficultySystem.CUSTOM -> {
|
||||
|
||||
@@ -394,7 +394,7 @@
|
||||
CODE_SIGN_ENTITLEMENTS = OpenClimb/OpenClimb.entitlements;
|
||||
CODE_SIGN_IDENTITY = "Apple Development";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 7;
|
||||
CURRENT_PROJECT_VERSION = 9;
|
||||
DEVELOPMENT_TEAM = 4BC9Y2LL4B;
|
||||
ENABLE_PREVIEWS = YES;
|
||||
GENERATE_INFOPLIST_FILE = YES;
|
||||
@@ -414,7 +414,7 @@
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
MARKETING_VERSION = 1.0.2;
|
||||
MARKETING_VERSION = 1.0.3;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.atridad.OpenClimb;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
@@ -437,7 +437,7 @@
|
||||
CODE_SIGN_ENTITLEMENTS = OpenClimb/OpenClimb.entitlements;
|
||||
CODE_SIGN_IDENTITY = "Apple Development";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 7;
|
||||
CURRENT_PROJECT_VERSION = 9;
|
||||
DEVELOPMENT_TEAM = 4BC9Y2LL4B;
|
||||
ENABLE_PREVIEWS = YES;
|
||||
GENERATE_INFOPLIST_FILE = YES;
|
||||
@@ -457,7 +457,7 @@
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
MARKETING_VERSION = 1.0.2;
|
||||
MARKETING_VERSION = 1.0.3;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.atridad.OpenClimb;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
@@ -479,7 +479,7 @@
|
||||
ASSETCATALOG_COMPILER_WIDGET_BACKGROUND_COLOR_NAME = WidgetBackground;
|
||||
CODE_SIGN_ENTITLEMENTS = SessionStatusLiveExtension.entitlements;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 7;
|
||||
CURRENT_PROJECT_VERSION = 9;
|
||||
DEVELOPMENT_TEAM = 4BC9Y2LL4B;
|
||||
GENERATE_INFOPLIST_FILE = YES;
|
||||
INFOPLIST_FILE = SessionStatusLive/Info.plist;
|
||||
@@ -490,7 +490,7 @@
|
||||
"@executable_path/Frameworks",
|
||||
"@executable_path/../../Frameworks",
|
||||
);
|
||||
MARKETING_VERSION = 1.0.2;
|
||||
MARKETING_VERSION = 1.0.3;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.atridad.OpenClimb.SessionStatusLive;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SKIP_INSTALL = YES;
|
||||
@@ -509,7 +509,7 @@
|
||||
ASSETCATALOG_COMPILER_WIDGET_BACKGROUND_COLOR_NAME = WidgetBackground;
|
||||
CODE_SIGN_ENTITLEMENTS = SessionStatusLiveExtension.entitlements;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 7;
|
||||
CURRENT_PROJECT_VERSION = 9;
|
||||
DEVELOPMENT_TEAM = 4BC9Y2LL4B;
|
||||
GENERATE_INFOPLIST_FILE = YES;
|
||||
INFOPLIST_FILE = SessionStatusLive/Info.plist;
|
||||
@@ -520,7 +520,7 @@
|
||||
"@executable_path/Frameworks",
|
||||
"@executable_path/../../Frameworks",
|
||||
);
|
||||
MARKETING_VERSION = 1.0.2;
|
||||
MARKETING_VERSION = 1.0.3;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.atridad.OpenClimb.SessionStatusLive;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SKIP_INSTALL = YES;
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,114 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "2600"
|
||||
wasCreatedForAppExtension = "YES"
|
||||
version = "2.0">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES"
|
||||
buildArchitectures = "Automatic">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D2FE948A2E78FEE0008CDB25"
|
||||
BuildableName = "SessionStatusLiveExtension.appex"
|
||||
BlueprintName = "SessionStatusLiveExtension"
|
||||
ReferencedContainer = "container:OpenClimb.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D24C19672E75002A0045894C"
|
||||
BuildableName = "OpenClimb.app"
|
||||
BlueprintName = "OpenClimb"
|
||||
ReferencedContainer = "container:OpenClimb.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
shouldAutocreateTestPlan = "YES">
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = ""
|
||||
selectedLauncherIdentifier = "Xcode.IDEFoundation.Launcher.PosixSpawn"
|
||||
launchStyle = "0"
|
||||
askForAppToLaunch = "Yes"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES"
|
||||
launchAutomaticallySubstyle = "2">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D24C19672E75002A0045894C"
|
||||
BuildableName = "OpenClimb.app"
|
||||
BlueprintName = "OpenClimb"
|
||||
ReferencedContainer = "container:OpenClimb.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
<EnvironmentVariables>
|
||||
<EnvironmentVariable
|
||||
key = "_XCWidgetKind"
|
||||
value = ""
|
||||
isEnabled = "YES">
|
||||
</EnvironmentVariable>
|
||||
<EnvironmentVariable
|
||||
key = "_XCWidgetDefaultView"
|
||||
value = "timeline"
|
||||
isEnabled = "YES">
|
||||
</EnvironmentVariable>
|
||||
<EnvironmentVariable
|
||||
key = "_XCWidgetFamily"
|
||||
value = "systemMedium"
|
||||
isEnabled = "YES">
|
||||
</EnvironmentVariable>
|
||||
</EnvironmentVariables>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
askForAppToLaunch = "Yes"
|
||||
launchAutomaticallySubstyle = "2">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D24C19672E75002A0045894C"
|
||||
BuildableName = "OpenClimb.app"
|
||||
BlueprintName = "OpenClimb"
|
||||
ReferencedContainer = "container:OpenClimb.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -7,12 +7,25 @@
|
||||
<key>OpenClimb.xcscheme_^#shared#^_</key>
|
||||
<dict>
|
||||
<key>orderHint</key>
|
||||
<integer>0</integer>
|
||||
<integer>1</integer>
|
||||
</dict>
|
||||
<key>SessionStatusLiveExtension.xcscheme_^#shared#^_</key>
|
||||
<dict>
|
||||
<key>orderHint</key>
|
||||
<integer>1</integer>
|
||||
<integer>0</integer>
|
||||
</dict>
|
||||
</dict>
|
||||
<key>SuppressBuildableAutocreation</key>
|
||||
<dict>
|
||||
<key>D24C19672E75002A0045894C</key>
|
||||
<dict>
|
||||
<key>primary</key>
|
||||
<true/>
|
||||
</dict>
|
||||
<key>D2FE948A2E78FEE0008CDB25</key>
|
||||
<dict>
|
||||
<key>primary</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</dict>
|
||||
</dict>
|
||||
|
||||
@@ -4,6 +4,7 @@ struct ContentView: View {
|
||||
@StateObject private var dataManager = ClimbingDataManager()
|
||||
@State private var selectedTab = 0
|
||||
@Environment(\.scenePhase) private var scenePhase
|
||||
@State private var notificationObservers: [NSObjectProtocol] = []
|
||||
|
||||
var body: some View {
|
||||
TabView(selection: $selectedTab) {
|
||||
@@ -43,11 +44,23 @@ struct ContentView: View {
|
||||
.tag(4)
|
||||
}
|
||||
.environmentObject(dataManager)
|
||||
.onChange(of: scenePhase) {
|
||||
if scenePhase == .active {
|
||||
dataManager.onAppBecomeActive()
|
||||
.onChange(of: scenePhase) { oldPhase, newPhase in
|
||||
if newPhase == .active {
|
||||
// Add slight delay to ensure app is fully loaded
|
||||
Task {
|
||||
try? await Task.sleep(nanoseconds: 200_000_000) // 0.2 seconds
|
||||
dataManager.onAppBecomeActive()
|
||||
}
|
||||
} else if newPhase == .background {
|
||||
dataManager.onAppEnterBackground()
|
||||
}
|
||||
}
|
||||
.onAppear {
|
||||
setupNotificationObservers()
|
||||
}
|
||||
.onDisappear {
|
||||
removeNotificationObservers()
|
||||
}
|
||||
.overlay(alignment: .top) {
|
||||
if let message = dataManager.successMessage {
|
||||
SuccessMessageView(message: message)
|
||||
@@ -62,6 +75,44 @@ struct ContentView: View {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func setupNotificationObservers() {
|
||||
// Listen for when the app will enter foreground
|
||||
let willEnterForegroundObserver = NotificationCenter.default.addObserver(
|
||||
forName: UIApplication.willEnterForegroundNotification,
|
||||
object: nil,
|
||||
queue: .main
|
||||
) { _ in
|
||||
print("📱 App will enter foreground - preparing Live Activity check")
|
||||
Task {
|
||||
// Small delay to ensure app is fully active
|
||||
try? await Task.sleep(nanoseconds: 800_000_000) // 0.8 seconds
|
||||
await dataManager.onAppBecomeActive()
|
||||
}
|
||||
}
|
||||
|
||||
// Listen for when the app becomes active
|
||||
let didBecomeActiveObserver = NotificationCenter.default.addObserver(
|
||||
forName: UIApplication.didBecomeActiveNotification,
|
||||
object: nil,
|
||||
queue: .main
|
||||
) { _ in
|
||||
print("📱 App did become active - checking Live Activity status")
|
||||
Task {
|
||||
try? await Task.sleep(nanoseconds: 300_000_000) // 0.3 seconds
|
||||
dataManager.onAppBecomeActive()
|
||||
}
|
||||
}
|
||||
|
||||
notificationObservers = [willEnterForegroundObserver, didBecomeActiveObserver]
|
||||
}
|
||||
|
||||
private func removeNotificationObservers() {
|
||||
for observer in notificationObservers {
|
||||
NotificationCenter.default.removeObserver(observer)
|
||||
}
|
||||
notificationObservers.removeAll()
|
||||
}
|
||||
}
|
||||
|
||||
struct SuccessMessageView: View {
|
||||
|
||||
@@ -260,7 +260,7 @@ struct Problem: Identifiable, Codable, Hashable {
|
||||
let description: String?
|
||||
let climbType: ClimbType
|
||||
let difficulty: DifficultyGrade
|
||||
let setter: String?
|
||||
|
||||
let tags: [String]
|
||||
let location: String?
|
||||
let imagePaths: [String]
|
||||
@@ -272,7 +272,7 @@ struct Problem: Identifiable, Codable, Hashable {
|
||||
|
||||
init(
|
||||
gymId: UUID, name: String? = nil, description: String? = nil, climbType: ClimbType,
|
||||
difficulty: DifficultyGrade, setter: String? = nil, tags: [String] = [],
|
||||
difficulty: DifficultyGrade, tags: [String] = [],
|
||||
location: String? = nil, imagePaths: [String] = [], dateSet: Date? = nil,
|
||||
notes: String? = nil
|
||||
) {
|
||||
@@ -282,7 +282,7 @@ struct Problem: Identifiable, Codable, Hashable {
|
||||
self.description = description
|
||||
self.climbType = climbType
|
||||
self.difficulty = difficulty
|
||||
self.setter = setter
|
||||
|
||||
self.tags = tags
|
||||
self.location = location
|
||||
self.imagePaths = imagePaths
|
||||
@@ -296,7 +296,7 @@ struct Problem: Identifiable, Codable, Hashable {
|
||||
|
||||
func updated(
|
||||
name: String? = nil, description: String? = nil, climbType: ClimbType? = nil,
|
||||
difficulty: DifficultyGrade? = nil, setter: String? = nil, tags: [String]? = nil,
|
||||
difficulty: DifficultyGrade? = nil, tags: [String]? = nil,
|
||||
location: String? = nil, imagePaths: [String]? = nil, isActive: Bool? = nil,
|
||||
dateSet: Date? = nil, notes: String? = nil
|
||||
) -> Problem {
|
||||
@@ -307,7 +307,7 @@ struct Problem: Identifiable, Codable, Hashable {
|
||||
description: description ?? self.description,
|
||||
climbType: climbType ?? self.climbType,
|
||||
difficulty: difficulty ?? self.difficulty,
|
||||
setter: setter ?? self.setter,
|
||||
|
||||
tags: tags ?? self.tags,
|
||||
location: location ?? self.location,
|
||||
imagePaths: imagePaths ?? self.imagePaths,
|
||||
@@ -321,7 +321,7 @@ struct Problem: Identifiable, Codable, Hashable {
|
||||
|
||||
private init(
|
||||
id: UUID, gymId: UUID, name: String?, description: String?, climbType: ClimbType,
|
||||
difficulty: DifficultyGrade, setter: String?, tags: [String], location: String?,
|
||||
difficulty: DifficultyGrade, tags: [String], location: String?,
|
||||
imagePaths: [String], isActive: Bool, dateSet: Date?, notes: String?, createdAt: Date,
|
||||
updatedAt: Date
|
||||
) {
|
||||
@@ -331,7 +331,7 @@ struct Problem: Identifiable, Codable, Hashable {
|
||||
self.description = description
|
||||
self.climbType = climbType
|
||||
self.difficulty = difficulty
|
||||
self.setter = setter
|
||||
|
||||
self.tags = tags
|
||||
self.location = location
|
||||
self.imagePaths = imagePaths
|
||||
@@ -344,7 +344,7 @@ struct Problem: Identifiable, Codable, Hashable {
|
||||
|
||||
static func fromImport(
|
||||
id: UUID, gymId: UUID, name: String?, description: String?, climbType: ClimbType,
|
||||
difficulty: DifficultyGrade, setter: String?, tags: [String], location: String?,
|
||||
difficulty: DifficultyGrade, tags: [String], location: String?,
|
||||
imagePaths: [String], isActive: Bool, dateSet: Date?, notes: String?, createdAt: Date,
|
||||
updatedAt: Date
|
||||
) -> Problem {
|
||||
@@ -355,7 +355,7 @@ struct Problem: Identifiable, Codable, Hashable {
|
||||
description: description,
|
||||
climbType: climbType,
|
||||
difficulty: difficulty,
|
||||
setter: setter,
|
||||
|
||||
tags: tags,
|
||||
location: location,
|
||||
imagePaths: imagePaths,
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
|
||||
import Foundation
|
||||
import SwiftUI
|
||||
|
||||
@@ -522,7 +521,7 @@ class ImageManager {
|
||||
}
|
||||
}
|
||||
|
||||
private func getFullPath(from relativePath: String) -> String {
|
||||
func getFullPath(from relativePath: String) -> String {
|
||||
// If it's already a full path, check if it's legacy and needs migration
|
||||
if relativePath.hasPrefix("/") {
|
||||
// If it's pointing to legacy Documents directory, redirect to new location
|
||||
|
||||
@@ -7,6 +7,10 @@ import UniformTypeIdentifiers
|
||||
import WidgetKit
|
||||
#endif
|
||||
|
||||
#if canImport(ActivityKit)
|
||||
import ActivityKit
|
||||
#endif
|
||||
|
||||
@MainActor
|
||||
class ClimbingDataManager: ObservableObject {
|
||||
|
||||
@@ -23,6 +27,7 @@ class ClimbingDataManager: ObservableObject {
|
||||
private let sharedUserDefaults = UserDefaults(suiteName: "group.com.atridad.OpenClimb")
|
||||
private let encoder = JSONEncoder()
|
||||
private let decoder = JSONDecoder()
|
||||
private var liveActivityObserver: NSObjectProtocol?
|
||||
|
||||
private enum Keys {
|
||||
static let gyms = "openclimb_gyms"
|
||||
@@ -57,6 +62,7 @@ class ClimbingDataManager: ObservableObject {
|
||||
_ = ImageManager.shared
|
||||
loadAllData()
|
||||
migrateImagePaths()
|
||||
setupLiveActivityNotifications()
|
||||
|
||||
Task {
|
||||
try? await Task.sleep(nanoseconds: 2_000_000_000)
|
||||
@@ -67,6 +73,12 @@ class ClimbingDataManager: ObservableObject {
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
if let observer = liveActivityObserver {
|
||||
NotificationCenter.default.removeObserver(observer)
|
||||
}
|
||||
}
|
||||
|
||||
private func loadAllData() {
|
||||
loadGyms()
|
||||
loadProblems()
|
||||
@@ -463,6 +475,7 @@ class ClimbingDataManager: ObservableObject {
|
||||
|
||||
let exportData = ClimbDataExport(
|
||||
exportedAt: dateFormatter.string(from: Date()),
|
||||
version: "2.0",
|
||||
gyms: gyms.map { AndroidGym(from: $0) },
|
||||
problems: problems.map { AndroidProblem(from: $0) },
|
||||
sessions: sessions.map { AndroidClimbSession(from: $0) },
|
||||
@@ -471,13 +484,21 @@ class ClimbingDataManager: ObservableObject {
|
||||
|
||||
// Collect referenced image paths
|
||||
let referencedImagePaths = collectReferencedImagePaths()
|
||||
print("🎯 Starting export with \(referencedImagePaths.count) images")
|
||||
|
||||
return try ZipUtils.createExportZip(
|
||||
let zipData = try ZipUtils.createExportZip(
|
||||
exportData: exportData,
|
||||
referencedImagePaths: referencedImagePaths
|
||||
)
|
||||
|
||||
print("✅ Export completed successfully")
|
||||
successMessage = "Export completed with \(referencedImagePaths.count) images"
|
||||
clearMessageAfterDelay()
|
||||
return zipData
|
||||
} catch {
|
||||
setError("Export failed: \(error.localizedDescription)")
|
||||
let errorMessage = "Export failed: \(error.localizedDescription)"
|
||||
print("❌ \(errorMessage)")
|
||||
setError(errorMessage)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -565,16 +586,18 @@ class ClimbingDataManager: ObservableObject {
|
||||
|
||||
struct ClimbDataExport: Codable {
|
||||
let exportedAt: String
|
||||
let version: String
|
||||
let gyms: [AndroidGym]
|
||||
let problems: [AndroidProblem]
|
||||
let sessions: [AndroidClimbSession]
|
||||
let attempts: [AndroidAttempt]
|
||||
|
||||
init(
|
||||
exportedAt: String, gyms: [AndroidGym], problems: [AndroidProblem],
|
||||
exportedAt: String, version: String = "2.0", gyms: [AndroidGym], problems: [AndroidProblem],
|
||||
sessions: [AndroidClimbSession], attempts: [AndroidAttempt]
|
||||
) {
|
||||
self.exportedAt = exportedAt
|
||||
self.version = version
|
||||
self.gyms = gyms
|
||||
self.problems = problems
|
||||
self.sessions = sessions
|
||||
@@ -588,6 +611,7 @@ struct AndroidGym: Codable {
|
||||
let location: String?
|
||||
let supportedClimbTypes: [ClimbType]
|
||||
let difficultySystems: [DifficultySystem]
|
||||
let customDifficultyGrades: [String]
|
||||
let notes: String?
|
||||
let createdAt: String
|
||||
let updatedAt: String
|
||||
@@ -598,6 +622,7 @@ struct AndroidGym: Codable {
|
||||
self.location = gym.location
|
||||
self.supportedClimbTypes = gym.supportedClimbTypes
|
||||
self.difficultySystems = gym.difficultySystems
|
||||
self.customDifficultyGrades = gym.customDifficultyGrades
|
||||
self.notes = gym.notes
|
||||
let formatter = DateFormatter()
|
||||
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS"
|
||||
@@ -607,13 +632,15 @@ struct AndroidGym: Codable {
|
||||
|
||||
init(
|
||||
id: String, name: String, location: String?, supportedClimbTypes: [ClimbType],
|
||||
difficultySystems: [DifficultySystem], notes: String?, createdAt: String, updatedAt: String
|
||||
difficultySystems: [DifficultySystem], customDifficultyGrades: [String] = [],
|
||||
notes: String?, createdAt: String, updatedAt: String
|
||||
) {
|
||||
self.id = id
|
||||
self.name = name
|
||||
self.location = location
|
||||
self.supportedClimbTypes = supportedClimbTypes
|
||||
self.difficultySystems = difficultySystems
|
||||
self.customDifficultyGrades = customDifficultyGrades
|
||||
self.notes = notes
|
||||
self.createdAt = createdAt
|
||||
self.updatedAt = updatedAt
|
||||
@@ -633,7 +660,7 @@ struct AndroidGym: Codable {
|
||||
location: location,
|
||||
supportedClimbTypes: supportedClimbTypes,
|
||||
difficultySystems: difficultySystems,
|
||||
customDifficultyGrades: [],
|
||||
customDifficultyGrades: customDifficultyGrades,
|
||||
notes: notes,
|
||||
createdAt: createdDate,
|
||||
updatedAt: updatedDate
|
||||
@@ -648,7 +675,12 @@ struct AndroidProblem: Codable {
|
||||
let description: String?
|
||||
let climbType: ClimbType
|
||||
let difficulty: DifficultyGrade
|
||||
let tags: [String]
|
||||
let location: String?
|
||||
let imagePaths: [String]?
|
||||
let isActive: Bool
|
||||
let dateSet: String?
|
||||
let notes: String?
|
||||
let createdAt: String
|
||||
let updatedAt: String
|
||||
|
||||
@@ -659,16 +691,25 @@ struct AndroidProblem: Codable {
|
||||
self.description = problem.description
|
||||
self.climbType = problem.climbType
|
||||
self.difficulty = problem.difficulty
|
||||
self.tags = problem.tags
|
||||
self.location = problem.location
|
||||
self.imagePaths = problem.imagePaths.isEmpty ? nil : problem.imagePaths
|
||||
self.isActive = problem.isActive
|
||||
self.notes = problem.notes
|
||||
let formatter = DateFormatter()
|
||||
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS"
|
||||
self.dateSet = problem.dateSet != nil ? formatter.string(from: problem.dateSet!) : nil
|
||||
self.createdAt = formatter.string(from: problem.createdAt)
|
||||
self.updatedAt = formatter.string(from: problem.updatedAt)
|
||||
}
|
||||
|
||||
init(
|
||||
id: String, gymId: String, name: String?, description: String?, climbType: ClimbType,
|
||||
difficulty: DifficultyGrade, imagePaths: [String]?, createdAt: String, updatedAt: String
|
||||
difficulty: DifficultyGrade, tags: [String] = [],
|
||||
location: String? = nil,
|
||||
imagePaths: [String]? = nil, isActive: Bool = true, dateSet: String? = nil,
|
||||
notes: String? = nil,
|
||||
createdAt: String, updatedAt: String
|
||||
) {
|
||||
self.id = id
|
||||
self.gymId = gymId
|
||||
@@ -676,7 +717,12 @@ struct AndroidProblem: Codable {
|
||||
self.description = description
|
||||
self.climbType = climbType
|
||||
self.difficulty = difficulty
|
||||
self.tags = tags
|
||||
self.location = location
|
||||
self.imagePaths = imagePaths
|
||||
self.isActive = isActive
|
||||
self.dateSet = dateSet
|
||||
self.notes = notes
|
||||
self.createdAt = createdAt
|
||||
self.updatedAt = updatedAt
|
||||
}
|
||||
@@ -697,13 +743,12 @@ struct AndroidProblem: Codable {
|
||||
description: description,
|
||||
climbType: climbType,
|
||||
difficulty: difficulty,
|
||||
setter: nil,
|
||||
tags: [],
|
||||
location: nil,
|
||||
tags: tags,
|
||||
location: location,
|
||||
imagePaths: imagePaths ?? [],
|
||||
isActive: true,
|
||||
dateSet: nil,
|
||||
notes: nil,
|
||||
isActive: isActive,
|
||||
dateSet: dateSet != nil ? formatter.date(from: dateSet!) : nil,
|
||||
notes: notes,
|
||||
createdAt: createdDate,
|
||||
updatedAt: updatedDate
|
||||
)
|
||||
@@ -717,7 +762,12 @@ struct AndroidProblem: Codable {
|
||||
description: self.description,
|
||||
climbType: self.climbType,
|
||||
difficulty: self.difficulty,
|
||||
tags: self.tags,
|
||||
location: self.location,
|
||||
imagePaths: newImagePaths.isEmpty ? nil : newImagePaths,
|
||||
isActive: self.isActive,
|
||||
dateSet: self.dateSet,
|
||||
notes: self.notes,
|
||||
createdAt: self.createdAt,
|
||||
updatedAt: self.updatedAt
|
||||
)
|
||||
@@ -730,8 +780,9 @@ struct AndroidClimbSession: Codable {
|
||||
let date: String
|
||||
let startTime: String?
|
||||
let endTime: String?
|
||||
let duration: Int?
|
||||
let duration: Int64?
|
||||
let status: SessionStatus
|
||||
let notes: String?
|
||||
let createdAt: String
|
||||
let updatedAt: String
|
||||
|
||||
@@ -743,15 +794,17 @@ struct AndroidClimbSession: Codable {
|
||||
self.date = formatter.string(from: session.date)
|
||||
self.startTime = session.startTime != nil ? formatter.string(from: session.startTime!) : nil
|
||||
self.endTime = session.endTime != nil ? formatter.string(from: session.endTime!) : nil
|
||||
self.duration = session.duration
|
||||
self.duration = session.duration != nil ? Int64(session.duration!) : nil
|
||||
self.status = session.status
|
||||
self.notes = session.notes
|
||||
self.createdAt = formatter.string(from: session.createdAt)
|
||||
self.updatedAt = formatter.string(from: session.updatedAt)
|
||||
}
|
||||
|
||||
init(
|
||||
id: String, gymId: String, date: String, startTime: String?, endTime: String?,
|
||||
duration: Int?, status: SessionStatus, createdAt: String, updatedAt: String
|
||||
duration: Int64?, status: SessionStatus, notes: String? = nil, createdAt: String,
|
||||
updatedAt: String
|
||||
) {
|
||||
self.id = id
|
||||
self.gymId = gymId
|
||||
@@ -760,6 +813,7 @@ struct AndroidClimbSession: Codable {
|
||||
self.endTime = endTime
|
||||
self.duration = duration
|
||||
self.status = status
|
||||
self.notes = notes
|
||||
self.createdAt = createdAt
|
||||
self.updatedAt = updatedAt
|
||||
}
|
||||
@@ -783,9 +837,9 @@ struct AndroidClimbSession: Codable {
|
||||
date: sessionDate,
|
||||
startTime: sessionStartTime,
|
||||
endTime: sessionEndTime,
|
||||
duration: duration,
|
||||
duration: duration != nil ? Int(duration!) : nil,
|
||||
status: status,
|
||||
notes: nil,
|
||||
notes: notes,
|
||||
createdAt: createdDate,
|
||||
updatedAt: updatedDate
|
||||
)
|
||||
@@ -799,8 +853,8 @@ struct AndroidAttempt: Codable {
|
||||
let result: AttemptResult
|
||||
let highestHold: String?
|
||||
let notes: String?
|
||||
let duration: Int?
|
||||
let restTime: Int?
|
||||
let duration: Int64?
|
||||
let restTime: Int64?
|
||||
let timestamp: String
|
||||
let createdAt: String
|
||||
|
||||
@@ -811,8 +865,8 @@ struct AndroidAttempt: Codable {
|
||||
self.result = attempt.result
|
||||
self.highestHold = attempt.highestHold
|
||||
self.notes = attempt.notes
|
||||
self.duration = attempt.duration
|
||||
self.restTime = attempt.restTime
|
||||
self.duration = attempt.duration != nil ? Int64(attempt.duration!) : nil
|
||||
self.restTime = attempt.restTime != nil ? Int64(attempt.restTime!) : nil
|
||||
let formatter = DateFormatter()
|
||||
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS"
|
||||
self.timestamp = formatter.string(from: attempt.timestamp)
|
||||
@@ -821,7 +875,7 @@ struct AndroidAttempt: Codable {
|
||||
|
||||
init(
|
||||
id: String, sessionId: String, problemId: String, result: AttemptResult,
|
||||
highestHold: String?, notes: String?, duration: Int?, restTime: Int?,
|
||||
highestHold: String?, notes: String?, duration: Int64?, restTime: Int64?,
|
||||
timestamp: String, createdAt: String
|
||||
) {
|
||||
self.id = id
|
||||
@@ -853,8 +907,8 @@ struct AndroidAttempt: Codable {
|
||||
result: result,
|
||||
highestHold: highestHold,
|
||||
notes: notes,
|
||||
duration: duration,
|
||||
restTime: restTime,
|
||||
duration: duration != nil ? Int(duration!) : nil,
|
||||
restTime: restTime != nil ? Int(restTime!) : nil,
|
||||
timestamp: attemptTimestamp,
|
||||
createdAt: createdDate
|
||||
)
|
||||
@@ -864,9 +918,33 @@ struct AndroidAttempt: Codable {
|
||||
extension ClimbingDataManager {
|
||||
private func collectReferencedImagePaths() -> Set<String> {
|
||||
var imagePaths = Set<String>()
|
||||
print("🖼️ Starting image path collection...")
|
||||
print("📊 Total problems: \(problems.count)")
|
||||
|
||||
for problem in problems {
|
||||
imagePaths.formUnion(problem.imagePaths)
|
||||
if !problem.imagePaths.isEmpty {
|
||||
print(
|
||||
"📸 Problem '\(problem.name ?? "Unnamed")' has \(problem.imagePaths.count) images"
|
||||
)
|
||||
for imagePath in problem.imagePaths {
|
||||
print(" - Relative path: \(imagePath)")
|
||||
let fullPath = ImageManager.shared.getFullPath(from: imagePath)
|
||||
print(" - Full path: \(fullPath)")
|
||||
|
||||
// Check if file exists
|
||||
if FileManager.default.fileExists(atPath: fullPath) {
|
||||
print(" ✅ File exists")
|
||||
imagePaths.insert(fullPath)
|
||||
} else {
|
||||
print(" ❌ File does NOT exist")
|
||||
// Still add it to let ZipUtils handle the error logging
|
||||
imagePaths.insert(fullPath)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
print("🖼️ Collected \(imagePaths.count) total image paths for export")
|
||||
return imagePaths
|
||||
}
|
||||
|
||||
@@ -1046,23 +1124,111 @@ extension ClimbingDataManager {
|
||||
}
|
||||
|
||||
private func checkAndRestartLiveActivity() async {
|
||||
guard let activeSession = activeSession else { return }
|
||||
guard let activeSession = activeSession else {
|
||||
// No active session, make sure all Live Activities are cleaned up
|
||||
await LiveActivityManager.shared.endLiveActivity()
|
||||
return
|
||||
}
|
||||
|
||||
// Only restart if session is actually active
|
||||
guard activeSession.status == .active else {
|
||||
print(
|
||||
"⚠️ Session exists but is not active (status: \(activeSession.status)), ending Live Activity"
|
||||
)
|
||||
await LiveActivityManager.shared.endLiveActivity()
|
||||
return
|
||||
}
|
||||
|
||||
if let gym = gym(withId: activeSession.gymId) {
|
||||
print("🔍 Checking Live Activity for active session at \(gym.name)")
|
||||
|
||||
// First cleanup any dismissed activities
|
||||
await LiveActivityManager.shared.cleanupDismissedActivities()
|
||||
|
||||
// Then attempt to restart if needed
|
||||
await LiveActivityManager.shared.restartLiveActivityIfNeeded(
|
||||
activeSession: activeSession,
|
||||
gymName: gym.name
|
||||
)
|
||||
|
||||
// Update with current session data
|
||||
await updateLiveActivityData()
|
||||
}
|
||||
}
|
||||
|
||||
/// Call this when app becomes active to check for Live Activity restart
|
||||
func onAppBecomeActive() {
|
||||
print("📱 App became active - checking Live Activity status")
|
||||
Task {
|
||||
await checkAndRestartLiveActivity()
|
||||
}
|
||||
}
|
||||
|
||||
/// Call this when app enters background to update Live Activity
|
||||
func onAppEnterBackground() {
|
||||
print("📱 App entering background - updating Live Activity if needed")
|
||||
Task {
|
||||
await updateLiveActivityData()
|
||||
}
|
||||
}
|
||||
|
||||
/// Setup notifications for Live Activity events
|
||||
private func setupLiveActivityNotifications() {
|
||||
liveActivityObserver = NotificationCenter.default.addObserver(
|
||||
forName: .liveActivityDismissed,
|
||||
object: nil,
|
||||
queue: .main
|
||||
) { [weak self] _ in
|
||||
print("🔔 Received Live Activity dismissed notification - attempting restart")
|
||||
Task { @MainActor in
|
||||
await self?.handleLiveActivityDismissed()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle Live Activity being dismissed by user
|
||||
private func handleLiveActivityDismissed() async {
|
||||
guard let activeSession = activeSession,
|
||||
activeSession.status == .active,
|
||||
let gym = gym(withId: activeSession.gymId)
|
||||
else {
|
||||
return
|
||||
}
|
||||
|
||||
print("🔄 Attempting to restart dismissed Live Activity for \(gym.name)")
|
||||
|
||||
// Wait a bit before restarting to avoid frequency limits
|
||||
try? await Task.sleep(nanoseconds: 2_000_000_000) // 2 seconds
|
||||
|
||||
await LiveActivityManager.shared.startLiveActivity(
|
||||
for: activeSession,
|
||||
gymName: gym.name
|
||||
)
|
||||
|
||||
// Update with current data
|
||||
await updateLiveActivityData()
|
||||
}
|
||||
|
||||
/// Update Live Activity with current session statistics
|
||||
private func updateLiveActivityData() async {
|
||||
guard let activeSession = activeSession,
|
||||
activeSession.status == .active
|
||||
else { return }
|
||||
|
||||
let elapsed = Date().timeIntervalSince(activeSession.startTime ?? activeSession.date)
|
||||
let sessionAttempts = attempts.filter { $0.sessionId == activeSession.id }
|
||||
let totalAttempts = sessionAttempts.count
|
||||
let completedProblems = Set(
|
||||
sessionAttempts.filter { $0.result.isSuccessful }.map { $0.problemId }
|
||||
).count
|
||||
|
||||
await LiveActivityManager.shared.updateLiveActivity(
|
||||
elapsed: elapsed,
|
||||
totalAttempts: totalAttempts,
|
||||
completedProblems: completedProblems
|
||||
)
|
||||
}
|
||||
|
||||
/// Update Live Activity with current session data
|
||||
private func updateLiveActivityForActiveSession() {
|
||||
guard let activeSession = activeSession,
|
||||
@@ -1160,7 +1326,6 @@ extension ClimbingDataManager {
|
||||
description: "Technical overhang with small holds",
|
||||
climbType: .boulder,
|
||||
difficulty: DifficultyGrade(system: .vScale, grade: "V4"),
|
||||
setter: "John Doe",
|
||||
tags: ["technical", "overhang"],
|
||||
location: "Cave area"
|
||||
)
|
||||
|
||||
@@ -1,12 +1,22 @@
|
||||
import ActivityKit
|
||||
import Foundation
|
||||
|
||||
extension Notification.Name {
|
||||
static let liveActivityDismissed = Notification.Name("liveActivityDismissed")
|
||||
}
|
||||
|
||||
@MainActor
|
||||
final class LiveActivityManager {
|
||||
static let shared = LiveActivityManager()
|
||||
private init() {}
|
||||
|
||||
private var currentActivity: Activity<SessionActivityAttributes>?
|
||||
private var healthCheckTimer: Timer?
|
||||
private var lastHealthCheck: Date = Date()
|
||||
|
||||
deinit {
|
||||
healthCheckTimer?.invalidate()
|
||||
}
|
||||
|
||||
/// Check if there's an active session and restart Live Activity if needed
|
||||
func restartLiveActivityIfNeeded(activeSession: ClimbSession?, gymName: String?) async {
|
||||
@@ -18,13 +28,31 @@ final class LiveActivityManager {
|
||||
return
|
||||
}
|
||||
|
||||
// Check if we already have a running Live Activity
|
||||
if currentActivity != nil {
|
||||
print("ℹ️ Live Activity already running")
|
||||
// Check if we have a tracked Live Activity that's still actually running
|
||||
if let currentActivity = currentActivity {
|
||||
let activities = Activity<SessionActivityAttributes>.activities
|
||||
let isStillActive = activities.contains { $0.id == currentActivity.id }
|
||||
|
||||
if isStillActive {
|
||||
print("ℹ️ Live Activity still running: \(currentActivity.id)")
|
||||
return
|
||||
} else {
|
||||
print(
|
||||
"⚠️ Tracked Live Activity \(currentActivity.id) was dismissed, clearing reference"
|
||||
)
|
||||
self.currentActivity = nil
|
||||
}
|
||||
}
|
||||
|
||||
// Check if there are ANY active Live Activities for this session
|
||||
let existingActivities = Activity<SessionActivityAttributes>.activities
|
||||
if let existingActivity = existingActivities.first {
|
||||
print("ℹ️ Found existing Live Activity: \(existingActivity.id), using it")
|
||||
self.currentActivity = existingActivity
|
||||
return
|
||||
}
|
||||
|
||||
print("🔄 Restarting Live Activity for existing session")
|
||||
print("🔄 No Live Activity found, restarting for existing session")
|
||||
await startLiveActivity(for: activeSession, gymName: gymName)
|
||||
}
|
||||
|
||||
@@ -34,10 +62,17 @@ final class LiveActivityManager {
|
||||
|
||||
await endLiveActivity()
|
||||
|
||||
// Start health checks once we have an active session
|
||||
startHealthChecks()
|
||||
|
||||
// Calculate elapsed time if session already started
|
||||
let startTime = session.startTime ?? session.date
|
||||
let elapsed = Date().timeIntervalSince(startTime)
|
||||
|
||||
let attributes = SessionActivityAttributes(
|
||||
gymName: gymName, startTime: session.startTime ?? session.date)
|
||||
gymName: gymName, startTime: startTime)
|
||||
let initialContentState = SessionActivityAttributes.ContentState(
|
||||
elapsed: 0,
|
||||
elapsed: elapsed,
|
||||
totalAttempts: 0,
|
||||
completedProblems: 0
|
||||
)
|
||||
@@ -59,6 +94,8 @@ final class LiveActivityManager {
|
||||
print("Authorization error - check Live Activity permissions in Settings")
|
||||
} else if error.localizedDescription.contains("content") {
|
||||
print("Content error - check ActivityAttributes structure")
|
||||
} else if error.localizedDescription.contains("frequencyLimited") {
|
||||
print("Frequency limited - too many Live Activities started recently")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -66,11 +103,23 @@ final class LiveActivityManager {
|
||||
/// Call this to update the Live Activity with new session progress
|
||||
func updateLiveActivity(elapsed: TimeInterval, totalAttempts: Int, completedProblems: Int) async
|
||||
{
|
||||
guard let currentActivity else {
|
||||
guard let currentActivity = currentActivity else {
|
||||
print("⚠️ No current activity to update")
|
||||
return
|
||||
}
|
||||
|
||||
// Verify the activity is still valid before updating
|
||||
let activities = Activity<SessionActivityAttributes>.activities
|
||||
let isStillActive = activities.contains { $0.id == currentActivity.id }
|
||||
|
||||
if !isStillActive {
|
||||
print(
|
||||
"⚠️ Tracked Live Activity \(currentActivity.id) is no longer active, clearing reference"
|
||||
)
|
||||
self.currentActivity = nil
|
||||
return
|
||||
}
|
||||
|
||||
print(
|
||||
"🔄 Updating Live Activity - Attempts: \(totalAttempts), Completed: \(completedProblems)"
|
||||
)
|
||||
@@ -81,12 +130,21 @@ final class LiveActivityManager {
|
||||
completedProblems: completedProblems
|
||||
)
|
||||
|
||||
await currentActivity.update(.init(state: updatedContentState, staleDate: nil))
|
||||
print("✅ Live Activity updated successfully")
|
||||
do {
|
||||
await currentActivity.update(.init(state: updatedContentState, staleDate: nil))
|
||||
print("✅ Live Activity updated successfully")
|
||||
} catch {
|
||||
print("❌ Failed to update Live Activity: \(error)")
|
||||
// If update fails, the activity might have been dismissed
|
||||
self.currentActivity = nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Call this when a ClimbSession ends to end the Live Activity
|
||||
func endLiveActivity() async {
|
||||
// Stop health checks first
|
||||
stopHealthChecks()
|
||||
|
||||
// First end the tracked activity if it exists
|
||||
if let currentActivity {
|
||||
print("🔴 Ending tracked Live Activity: \(currentActivity.id)")
|
||||
@@ -115,18 +173,92 @@ final class LiveActivityManager {
|
||||
func checkLiveActivityAvailability() -> String {
|
||||
let authorizationInfo = ActivityAuthorizationInfo()
|
||||
let status = authorizationInfo.areActivitiesEnabled
|
||||
let allActivities = Activity<SessionActivityAttributes>.activities
|
||||
|
||||
let message = """
|
||||
Live Activity Status:
|
||||
• Enabled: \(status)
|
||||
• Authorization: \(authorizationInfo.areActivitiesEnabled ? "Granted" : "Denied/Unknown")
|
||||
• Current Activity: \(currentActivity?.id.description ?? "None")
|
||||
• Tracked Activity: \(currentActivity?.id.description ?? "None")
|
||||
• All Active Activities: \(allActivities.count)
|
||||
"""
|
||||
|
||||
print(message)
|
||||
return message
|
||||
}
|
||||
|
||||
/// Force check and cleanup dismissed Live Activities
|
||||
func cleanupDismissedActivities() async {
|
||||
let activities = Activity<SessionActivityAttributes>.activities
|
||||
|
||||
if let currentActivity = currentActivity {
|
||||
let isStillActive = activities.contains { $0.id == currentActivity.id }
|
||||
if !isStillActive {
|
||||
print("🧹 Cleaning up dismissed Live Activity: \(currentActivity.id)")
|
||||
self.currentActivity = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Start periodic health checks for Live Activity
|
||||
func startHealthChecks() {
|
||||
stopHealthChecks() // Stop any existing timer
|
||||
|
||||
print("🩺 Starting Live Activity health checks")
|
||||
healthCheckTimer = Timer.scheduledTimer(withTimeInterval: 30.0, repeats: true) {
|
||||
[weak self] _ in
|
||||
Task { @MainActor in
|
||||
await self?.performHealthCheck()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stop periodic health checks
|
||||
func stopHealthChecks() {
|
||||
healthCheckTimer?.invalidate()
|
||||
healthCheckTimer = nil
|
||||
print("🛑 Stopped Live Activity health checks")
|
||||
}
|
||||
|
||||
/// Perform a health check on the current Live Activity
|
||||
private func performHealthCheck() async {
|
||||
guard let currentActivity = currentActivity else { return }
|
||||
|
||||
let now = Date()
|
||||
let timeSinceLastCheck = now.timeIntervalSince(lastHealthCheck)
|
||||
|
||||
// Only perform health check if it's been at least 25 seconds
|
||||
guard timeSinceLastCheck >= 25 else { return }
|
||||
|
||||
print("🩺 Performing Live Activity health check")
|
||||
lastHealthCheck = now
|
||||
|
||||
let activities = Activity<SessionActivityAttributes>.activities
|
||||
let isStillActive = activities.contains { $0.id == currentActivity.id }
|
||||
|
||||
if !isStillActive {
|
||||
print("💔 Health check failed - Live Activity was dismissed")
|
||||
self.currentActivity = nil
|
||||
|
||||
// Notify that we need to restart
|
||||
NotificationCenter.default.post(
|
||||
name: .liveActivityDismissed,
|
||||
object: nil
|
||||
)
|
||||
} else {
|
||||
print("✅ Live Activity health check passed")
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the current activity status for debugging
|
||||
func getCurrentActivityStatus() -> String {
|
||||
let activities = Activity<SessionActivityAttributes>.activities
|
||||
let trackedStatus = currentActivity != nil ? "Tracked" : "None"
|
||||
let actualCount = activities.count
|
||||
|
||||
return "Status: \(trackedStatus) | Active Count: \(actualCount)"
|
||||
}
|
||||
|
||||
/// Start periodic updates for Live Activity
|
||||
func startPeriodicUpdates(for session: ClimbSession, totalAttempts: Int, completedProblems: Int)
|
||||
{
|
||||
|
||||
@@ -635,12 +635,6 @@ struct ProblemExpandedView: View {
|
||||
.foregroundColor(.secondary)
|
||||
}
|
||||
|
||||
if let setter = problem.setter, !setter.isEmpty {
|
||||
Label(setter, systemImage: "person")
|
||||
.font(.subheadline)
|
||||
.foregroundColor(.secondary)
|
||||
}
|
||||
|
||||
if let description = problem.description, !description.isEmpty {
|
||||
Text(description)
|
||||
.font(.body)
|
||||
|
||||
@@ -13,7 +13,6 @@ struct AddEditProblemView: View {
|
||||
@State private var selectedClimbType: ClimbType = .boulder
|
||||
@State private var selectedDifficultySystem: DifficultySystem = .vScale
|
||||
@State private var difficultyGrade = ""
|
||||
@State private var setter = ""
|
||||
@State private var location = ""
|
||||
@State private var tags = ""
|
||||
@State private var notes = ""
|
||||
@@ -63,7 +62,7 @@ struct AddEditProblemView: View {
|
||||
PhotosSection()
|
||||
ClimbTypeSection()
|
||||
DifficultySection()
|
||||
LocationAndSetterSection()
|
||||
LocationSection()
|
||||
TagsSection()
|
||||
AdditionalInfoSection()
|
||||
}
|
||||
@@ -158,7 +157,6 @@ struct AddEditProblemView: View {
|
||||
)
|
||||
}
|
||||
|
||||
TextField("Route Setter (Optional)", text: $setter)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -281,7 +279,7 @@ struct AddEditProblemView: View {
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private func LocationAndSetterSection() -> some View {
|
||||
private func LocationSection() -> some View {
|
||||
Section("Location & Details") {
|
||||
TextField(
|
||||
"Location (Optional)", text: $location, prompt: Text("e.g., 'Cave area', 'Wall 3'"))
|
||||
@@ -334,25 +332,28 @@ struct AddEditProblemView: View {
|
||||
HStack(spacing: 12) {
|
||||
ForEach(imageData.indices, id: \.self) { index in
|
||||
if let uiImage = UIImage(data: imageData[index]) {
|
||||
Image(uiImage: uiImage)
|
||||
.resizable()
|
||||
.aspectRatio(contentMode: .fill)
|
||||
.frame(width: 80, height: 80)
|
||||
.clipped()
|
||||
.cornerRadius(8)
|
||||
.overlay(alignment: .topTrailing) {
|
||||
Button(action: {
|
||||
imageData.remove(at: index)
|
||||
if index < imagePaths.count {
|
||||
imagePaths.remove(at: index)
|
||||
}
|
||||
}) {
|
||||
Image(systemName: "xmark.circle.fill")
|
||||
.foregroundColor(.red)
|
||||
.background(Circle().fill(.white))
|
||||
ZStack(alignment: .topTrailing) {
|
||||
Image(uiImage: uiImage)
|
||||
.resizable()
|
||||
.aspectRatio(contentMode: .fill)
|
||||
.frame(width: 80, height: 80)
|
||||
.clipped()
|
||||
.cornerRadius(8)
|
||||
|
||||
Button(action: {
|
||||
imageData.remove(at: index)
|
||||
if index < imagePaths.count {
|
||||
imagePaths.remove(at: index)
|
||||
}
|
||||
.offset(x: 8, y: -8)
|
||||
}) {
|
||||
Image(systemName: "xmark.circle.fill")
|
||||
.foregroundColor(.red)
|
||||
.background(Circle().fill(.white))
|
||||
.font(.system(size: 18))
|
||||
}
|
||||
.offset(x: 4, y: -4)
|
||||
}
|
||||
.frame(width: 88, height: 88) // Extra space for button
|
||||
} else {
|
||||
RoundedRectangle(cornerRadius: 8)
|
||||
.fill(.gray.opacity(0.3))
|
||||
@@ -365,6 +366,7 @@ struct AddEditProblemView: View {
|
||||
}
|
||||
}
|
||||
.padding(.horizontal, 1)
|
||||
.padding(.vertical, 8)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -410,7 +412,7 @@ struct AddEditProblemView: View {
|
||||
selectedClimbType = problem.climbType
|
||||
selectedDifficultySystem = problem.difficulty.system
|
||||
difficultyGrade = problem.difficulty.grade
|
||||
setter = problem.setter ?? ""
|
||||
|
||||
location = problem.location ?? ""
|
||||
tags = problem.tags.joined(separator: ", ")
|
||||
notes = problem.notes ?? ""
|
||||
@@ -420,7 +422,7 @@ struct AddEditProblemView: View {
|
||||
// Load image data for preview
|
||||
imageData = []
|
||||
for imagePath in problem.imagePaths {
|
||||
if let data = try? Data(contentsOf: URL(fileURLWithPath: imagePath)) {
|
||||
if let data = ImageManager.shared.loadImageData(fromPath: imagePath) {
|
||||
imageData.append(data)
|
||||
}
|
||||
}
|
||||
@@ -479,7 +481,7 @@ struct AddEditProblemView: View {
|
||||
|
||||
let trimmedName = name.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
let trimmedDescription = description.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
let trimmedSetter = setter.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
|
||||
let trimmedLocation = location.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
let trimmedNotes = notes.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
let trimmedTags = tags.split(separator: ",").map {
|
||||
@@ -494,7 +496,7 @@ struct AddEditProblemView: View {
|
||||
description: trimmedDescription.isEmpty ? nil : trimmedDescription,
|
||||
climbType: selectedClimbType,
|
||||
difficulty: difficulty,
|
||||
setter: trimmedSetter.isEmpty ? nil : trimmedSetter,
|
||||
|
||||
tags: trimmedTags,
|
||||
location: trimmedLocation.isEmpty ? nil : trimmedLocation,
|
||||
imagePaths: imagePaths,
|
||||
@@ -510,7 +512,7 @@ struct AddEditProblemView: View {
|
||||
description: trimmedDescription.isEmpty ? nil : trimmedDescription,
|
||||
climbType: selectedClimbType,
|
||||
difficulty: difficulty,
|
||||
setter: trimmedSetter.isEmpty ? nil : trimmedSetter,
|
||||
|
||||
tags: trimmedTags,
|
||||
location: trimmedLocation.isEmpty ? nil : trimmedLocation,
|
||||
imagePaths: imagePaths,
|
||||
|
||||
@@ -105,9 +105,26 @@ struct ProgressChartSection: View {
|
||||
@EnvironmentObject var dataManager: ClimbingDataManager
|
||||
@State private var selectedSystem: DifficultySystem = .vScale
|
||||
@State private var showAllTime: Bool = true
|
||||
@State private var cachedGradeCountData: [GradeCount] = []
|
||||
@State private var lastCalculationDate: Date = Date.distantPast
|
||||
@State private var lastDataHash: Int = 0
|
||||
|
||||
private var gradeCountData: [GradeCount] {
|
||||
calculateGradeCounts()
|
||||
let currentHash =
|
||||
dataManager.problems.count + dataManager.attempts.count + (showAllTime ? 1 : 0)
|
||||
let now = Date()
|
||||
|
||||
// Recalculate only if data changed or cache is older than 30 seconds
|
||||
if currentHash != lastDataHash || now.timeIntervalSince(lastCalculationDate) > 30 {
|
||||
let newData = calculateGradeCounts()
|
||||
DispatchQueue.main.async {
|
||||
self.cachedGradeCountData = newData
|
||||
self.lastCalculationDate = now
|
||||
self.lastDataHash = currentHash
|
||||
}
|
||||
}
|
||||
|
||||
return cachedGradeCountData.isEmpty ? calculateGradeCounts() : cachedGradeCountData
|
||||
}
|
||||
|
||||
private var usedSystems: [DifficultySystem] {
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
|
||||
import SwiftUI
|
||||
|
||||
struct GymDetailView: View {
|
||||
@@ -60,8 +59,10 @@ struct GymDetailView: View {
|
||||
ToolbarItemGroup(placement: .navigationBarTrailing) {
|
||||
if gym != nil {
|
||||
Menu {
|
||||
Button("Edit Gym") {
|
||||
Button {
|
||||
// Navigate to edit view
|
||||
} label: {
|
||||
Label("Edit Gym", systemImage: "pencil")
|
||||
}
|
||||
|
||||
Button(role: .destructive) {
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
|
||||
import SwiftUI
|
||||
|
||||
struct ProblemDetailView: View {
|
||||
@@ -64,8 +63,10 @@ struct ProblemDetailView: View {
|
||||
ToolbarItemGroup(placement: .navigationBarTrailing) {
|
||||
if problem != nil {
|
||||
Menu {
|
||||
Button("Edit Problem") {
|
||||
Button {
|
||||
showingEditProblem = true
|
||||
} label: {
|
||||
Label("Edit Problem", systemImage: "pencil")
|
||||
}
|
||||
|
||||
Button(role: .destructive) {
|
||||
@@ -167,12 +168,6 @@ struct ProblemHeaderCard: View {
|
||||
.font(.body)
|
||||
}
|
||||
|
||||
if let setter = problem.setter, !setter.isEmpty {
|
||||
Text("Set by: \(setter)")
|
||||
.font(.subheadline)
|
||||
.foregroundColor(.secondary)
|
||||
}
|
||||
|
||||
if !problem.tags.isEmpty {
|
||||
ScrollView(.horizontal, showsIndicators: false) {
|
||||
HStack(spacing: 8) {
|
||||
|
||||
@@ -15,6 +15,18 @@ struct SessionDetailView: View {
|
||||
dataManager.session(withId: sessionId)
|
||||
}
|
||||
|
||||
private func startTimer() {
|
||||
// Update every 5 seconds instead of 1 second for better performance
|
||||
timer = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) { _ in
|
||||
currentTime = Date()
|
||||
}
|
||||
}
|
||||
|
||||
private func stopTimer() {
|
||||
timer?.invalidate()
|
||||
timer = nil
|
||||
}
|
||||
|
||||
private var gym: Gym? {
|
||||
guard let session = session else { return nil }
|
||||
return dataManager.gym(withId: session.gymId)
|
||||
@@ -35,7 +47,7 @@ struct SessionDetailView: View {
|
||||
calculateSessionStats()
|
||||
}
|
||||
|
||||
private let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
|
||||
@State private var timer: Timer?
|
||||
|
||||
var body: some View {
|
||||
ScrollView {
|
||||
@@ -57,8 +69,11 @@ struct SessionDetailView: View {
|
||||
}
|
||||
.padding()
|
||||
}
|
||||
.onReceive(timer) { _ in
|
||||
currentTime = Date()
|
||||
.onAppear {
|
||||
startTimer()
|
||||
}
|
||||
.onDisappear {
|
||||
stopTimer()
|
||||
}
|
||||
.navigationTitle("Session Details")
|
||||
.navigationBarTitleDisplayMode(.inline)
|
||||
@@ -153,46 +168,14 @@ struct SessionDetailView: View {
|
||||
let uniqueProblems = Set(attempts.map { $0.problemId })
|
||||
let completedProblems = Set(successfulAttempts.map { $0.problemId })
|
||||
|
||||
let attemptedProblems = uniqueProblems.compactMap { dataManager.problem(withId: $0) }
|
||||
let boulderProblems = attemptedProblems.filter { $0.climbType == .boulder }
|
||||
let ropeProblems = attemptedProblems.filter { $0.climbType == .rope }
|
||||
|
||||
let boulderRange = gradeRange(for: boulderProblems)
|
||||
let ropeRange = gradeRange(for: ropeProblems)
|
||||
|
||||
return SessionStats(
|
||||
totalAttempts: attempts.count,
|
||||
successfulAttempts: successfulAttempts.count,
|
||||
uniqueProblemsAttempted: uniqueProblems.count,
|
||||
uniqueProblemsCompleted: completedProblems.count,
|
||||
boulderRange: boulderRange,
|
||||
ropeRange: ropeRange
|
||||
uniqueProblemsCompleted: completedProblems.count
|
||||
)
|
||||
}
|
||||
|
||||
private func gradeRange(for problems: [Problem]) -> String? {
|
||||
guard !problems.isEmpty else { return nil }
|
||||
let difficulties = problems.map { $0.difficulty }
|
||||
|
||||
// Group by difficulty system first
|
||||
let groupedBySystem = Dictionary(grouping: difficulties) { $0.system }
|
||||
|
||||
// For each system, find the range
|
||||
let ranges = groupedBySystem.compactMap { (system, difficulties) -> String? in
|
||||
let sortedDifficulties = difficulties.sorted()
|
||||
guard let min = sortedDifficulties.first, let max = sortedDifficulties.last else {
|
||||
return nil
|
||||
}
|
||||
|
||||
if min == max {
|
||||
return min.grade
|
||||
} else {
|
||||
return "\(min.grade) - \(max.grade)"
|
||||
}
|
||||
}
|
||||
|
||||
return ranges.joined(separator: ", ")
|
||||
}
|
||||
}
|
||||
|
||||
struct SessionHeaderCard: View {
|
||||
@@ -297,22 +280,8 @@ struct SessionStatsCard: View {
|
||||
LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: 2), spacing: 16) {
|
||||
StatItem(label: "Total Attempts", value: "\(stats.totalAttempts)")
|
||||
StatItem(label: "Problems", value: "\(stats.uniqueProblemsAttempted)")
|
||||
StatItem(label: "Successful", value: "\(stats.successfulAttempts)")
|
||||
StatItem(label: "Completed", value: "\(stats.uniqueProblemsCompleted)")
|
||||
}
|
||||
|
||||
// Grade ranges
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
if let boulderRange = stats.boulderRange, let ropeRange = stats.ropeRange {
|
||||
HStack {
|
||||
StatItem(label: "Boulder Range", value: boulderRange)
|
||||
StatItem(label: "Rope Range", value: ropeRange)
|
||||
}
|
||||
} else if let singleRange = stats.boulderRange ?? stats.ropeRange {
|
||||
StatItem(label: "Grade Range", value: singleRange)
|
||||
.frame(maxWidth: .infinity, alignment: .center)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding()
|
||||
@@ -504,8 +473,6 @@ struct SessionStats {
|
||||
let successfulAttempts: Int
|
||||
let uniqueProblemsAttempted: Int
|
||||
let uniqueProblemsCompleted: Int
|
||||
let boulderRange: String?
|
||||
let ropeRange: String?
|
||||
}
|
||||
|
||||
#Preview {
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
|
||||
import SwiftUI
|
||||
|
||||
struct GymsView: View {
|
||||
@@ -49,7 +48,10 @@ struct GymsList: View {
|
||||
Button {
|
||||
gymToEdit = gym
|
||||
} label: {
|
||||
Label("Edit", systemImage: "pencil")
|
||||
HStack {
|
||||
Image(systemName: "pencil")
|
||||
Text("Edit")
|
||||
}
|
||||
}
|
||||
.tint(.blue)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
|
||||
import SwiftUI
|
||||
|
||||
struct ProblemsView: View {
|
||||
@@ -14,10 +13,9 @@ struct ProblemsView: View {
|
||||
// Apply search filter
|
||||
if !searchText.isEmpty {
|
||||
filtered = filtered.filter { problem in
|
||||
(problem.name?.localizedCaseInsensitiveContains(searchText) ?? false)
|
||||
return problem.name?.localizedCaseInsensitiveContains(searchText) ?? false
|
||||
|| (problem.description?.localizedCaseInsensitiveContains(searchText) ?? false)
|
||||
|| (problem.location?.localizedCaseInsensitiveContains(searchText) ?? false)
|
||||
|| (problem.setter?.localizedCaseInsensitiveContains(searchText) ?? false)
|
||||
|| problem.tags.contains { $0.localizedCaseInsensitiveContains(searchText) }
|
||||
}
|
||||
}
|
||||
@@ -32,7 +30,11 @@ struct ProblemsView: View {
|
||||
filtered = filtered.filter { $0.gymId == gym.id }
|
||||
}
|
||||
|
||||
return filtered.sorted { $0.updatedAt > $1.updatedAt }
|
||||
// Separate active and inactive problems
|
||||
let active = filtered.filter { $0.isActive }.sorted { $0.updatedAt > $1.updatedAt }
|
||||
let inactive = filtered.filter { !$0.isActive }.sorted { $0.updatedAt > $1.updatedAt }
|
||||
|
||||
return active + inactive
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
@@ -196,10 +198,23 @@ struct ProblemsList: View {
|
||||
Label("Delete", systemImage: "trash")
|
||||
}
|
||||
|
||||
Button {
|
||||
let updatedProblem = problem.updated(isActive: !problem.isActive)
|
||||
dataManager.updateProblem(updatedProblem)
|
||||
} label: {
|
||||
Label(
|
||||
problem.isActive ? "Mark as Reset" : "Mark as Active",
|
||||
systemImage: problem.isActive ? "xmark.circle" : "checkmark.circle")
|
||||
}
|
||||
.tint(.orange)
|
||||
|
||||
Button {
|
||||
problemToEdit = problem
|
||||
} label: {
|
||||
Label("Edit", systemImage: "pencil")
|
||||
HStack {
|
||||
Image(systemName: "pencil")
|
||||
Text("Edit")
|
||||
}
|
||||
}
|
||||
.tint(.blue)
|
||||
}
|
||||
@@ -240,6 +255,7 @@ struct ProblemRow: View {
|
||||
Text(problem.name ?? "Unnamed Problem")
|
||||
.font(.headline)
|
||||
.fontWeight(.semibold)
|
||||
.foregroundColor(problem.isActive ? .primary : .secondary)
|
||||
|
||||
Text(gym?.name ?? "Unknown Gym")
|
||||
.font(.subheadline)
|
||||
@@ -286,7 +302,7 @@ struct ProblemRow: View {
|
||||
|
||||
if !problem.imagePaths.isEmpty {
|
||||
ScrollView(.horizontal, showsIndicators: false) {
|
||||
HStack(spacing: 8) {
|
||||
LazyHStack(spacing: 8) {
|
||||
ForEach(problem.imagePaths.prefix(3), id: \.self) { imagePath in
|
||||
ProblemImageView(imagePath: imagePath)
|
||||
}
|
||||
@@ -296,9 +312,9 @@ struct ProblemRow: View {
|
||||
}
|
||||
|
||||
if !problem.isActive {
|
||||
Text("Inactive")
|
||||
Text("Reset / No Longer Set")
|
||||
.font(.caption)
|
||||
.foregroundColor(.red)
|
||||
.foregroundColor(.orange)
|
||||
.fontWeight(.medium)
|
||||
}
|
||||
}
|
||||
@@ -372,6 +388,13 @@ struct ProblemImageView: View {
|
||||
@State private var isLoading = true
|
||||
@State private var hasFailed = false
|
||||
|
||||
private static var imageCache: NSCache<NSString, UIImage> = {
|
||||
let cache = NSCache<NSString, UIImage>()
|
||||
cache.countLimit = 100
|
||||
cache.totalCostLimit = 50 * 1024 * 1024 // 50MB
|
||||
return cache
|
||||
}()
|
||||
|
||||
var body: some View {
|
||||
Group {
|
||||
if let uiImage = uiImage {
|
||||
@@ -412,10 +435,22 @@ struct ProblemImageView: View {
|
||||
return
|
||||
}
|
||||
|
||||
let cacheKey = NSString(string: imagePath)
|
||||
|
||||
// Check cache first
|
||||
if let cachedImage = Self.imageCache.object(forKey: cacheKey) {
|
||||
self.uiImage = cachedImage
|
||||
self.isLoading = false
|
||||
return
|
||||
}
|
||||
|
||||
DispatchQueue.global(qos: .userInitiated).async {
|
||||
if let data = ImageManager.shared.loadImageData(fromPath: imagePath),
|
||||
let image = UIImage(data: data)
|
||||
{
|
||||
// Cache the image
|
||||
Self.imageCache.setObject(image, forKey: cacheKey)
|
||||
|
||||
DispatchQueue.main.async {
|
||||
self.uiImage = image
|
||||
self.isLoading = false
|
||||
|
||||
@@ -114,7 +114,7 @@ struct ActiveSessionBanner: View {
|
||||
@State private var currentTime = Date()
|
||||
@State private var navigateToDetail = false
|
||||
|
||||
private let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
|
||||
@State private var timer: Timer?
|
||||
|
||||
var body: some View {
|
||||
HStack {
|
||||
@@ -162,8 +162,11 @@ struct ActiveSessionBanner: View {
|
||||
.fill(.green.opacity(0.1))
|
||||
.stroke(.green.opacity(0.3), lineWidth: 1)
|
||||
)
|
||||
.onReceive(timer) { _ in
|
||||
currentTime = Date()
|
||||
.onAppear {
|
||||
startTimer()
|
||||
}
|
||||
.onDisappear {
|
||||
stopTimer()
|
||||
}
|
||||
.background(
|
||||
NavigationLink(
|
||||
@@ -190,6 +193,17 @@ struct ActiveSessionBanner: View {
|
||||
return String(format: "%ds", seconds)
|
||||
}
|
||||
}
|
||||
|
||||
private func startTimer() {
|
||||
timer = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) { _ in
|
||||
currentTime = Date()
|
||||
}
|
||||
}
|
||||
|
||||
private func stopTimer() {
|
||||
timer?.invalidate()
|
||||
timer = nil
|
||||
}
|
||||
}
|
||||
|
||||
struct SessionRow: View {
|
||||
|
||||
@@ -164,60 +164,70 @@ struct ExportDataView: View {
|
||||
let data: Data
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
@State private var tempFileURL: URL?
|
||||
@State private var isCreatingFile = true
|
||||
|
||||
var body: some View {
|
||||
NavigationView {
|
||||
VStack(spacing: 20) {
|
||||
Image(systemName: "square.and.arrow.up")
|
||||
.font(.system(size: 60))
|
||||
.foregroundColor(.blue)
|
||||
VStack(spacing: 30) {
|
||||
if isCreatingFile {
|
||||
// Loading state - more prominent
|
||||
VStack(spacing: 20) {
|
||||
ProgressView()
|
||||
.scaleEffect(1.5)
|
||||
.tint(.blue)
|
||||
|
||||
Text("Export Data")
|
||||
.font(.title)
|
||||
.fontWeight(.bold)
|
||||
Text("Preparing Your Export")
|
||||
.font(.title2)
|
||||
.fontWeight(.semibold)
|
||||
|
||||
Text(
|
||||
"Your climbing data has been prepared for export. Use the share button below to save or send your data."
|
||||
)
|
||||
.multilineTextAlignment(.center)
|
||||
.padding(.horizontal)
|
||||
|
||||
if let fileURL = tempFileURL {
|
||||
ShareLink(
|
||||
item: fileURL,
|
||||
preview: SharePreview(
|
||||
"OpenClimb Data Export",
|
||||
image: Image("MountainsIcon"))
|
||||
) {
|
||||
Label("Share Data", systemImage: "square.and.arrow.up")
|
||||
.font(.headline)
|
||||
.foregroundColor(.white)
|
||||
.frame(maxWidth: .infinity)
|
||||
.padding()
|
||||
.background(
|
||||
RoundedRectangle(cornerRadius: 12)
|
||||
.fill(.blue)
|
||||
)
|
||||
Text("Creating ZIP file with your climbing data and images...")
|
||||
.font(.body)
|
||||
.foregroundColor(.secondary)
|
||||
.multilineTextAlignment(.center)
|
||||
.padding(.horizontal)
|
||||
}
|
||||
.padding(.horizontal)
|
||||
.buttonStyle(.plain)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
} else {
|
||||
Button(action: {}) {
|
||||
Label("Preparing Export...", systemImage: "hourglass")
|
||||
.font(.headline)
|
||||
.foregroundColor(.white)
|
||||
.frame(maxWidth: .infinity)
|
||||
.padding()
|
||||
.background(
|
||||
RoundedRectangle(cornerRadius: 12)
|
||||
.fill(.gray)
|
||||
)
|
||||
}
|
||||
.disabled(true)
|
||||
.padding(.horizontal)
|
||||
}
|
||||
// Ready state
|
||||
VStack(spacing: 20) {
|
||||
Image(systemName: "checkmark.circle.fill")
|
||||
.font(.system(size: 60))
|
||||
.foregroundColor(.green)
|
||||
|
||||
Spacer()
|
||||
Text("Export Ready!")
|
||||
.font(.title)
|
||||
.fontWeight(.bold)
|
||||
|
||||
Text(
|
||||
"Your climbing data has been prepared for export. Use the share button below to save or send your data."
|
||||
)
|
||||
.multilineTextAlignment(.center)
|
||||
.padding(.horizontal)
|
||||
|
||||
if let fileURL = tempFileURL {
|
||||
ShareLink(
|
||||
item: fileURL,
|
||||
preview: SharePreview(
|
||||
"OpenClimb Data Export",
|
||||
image: Image("MountainsIcon"))
|
||||
) {
|
||||
Label("Share Data", systemImage: "square.and.arrow.up")
|
||||
.font(.headline)
|
||||
.foregroundColor(.white)
|
||||
.frame(maxWidth: .infinity)
|
||||
.padding()
|
||||
.background(
|
||||
RoundedRectangle(cornerRadius: 12)
|
||||
.fill(.blue)
|
||||
)
|
||||
}
|
||||
.padding(.horizontal)
|
||||
.buttonStyle(.plain)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer()
|
||||
}
|
||||
}
|
||||
.padding()
|
||||
.navigationTitle("Export")
|
||||
@@ -259,6 +269,9 @@ struct ExportDataView: View {
|
||||
).first
|
||||
else {
|
||||
print("Could not access Documents directory")
|
||||
DispatchQueue.main.async {
|
||||
self.isCreatingFile = false
|
||||
}
|
||||
return
|
||||
}
|
||||
let fileURL = documentsURL.appendingPathComponent(filename)
|
||||
@@ -268,9 +281,13 @@ struct ExportDataView: View {
|
||||
|
||||
DispatchQueue.main.async {
|
||||
self.tempFileURL = fileURL
|
||||
self.isCreatingFile = false
|
||||
}
|
||||
} catch {
|
||||
print("Failed to create export file: \(error)")
|
||||
DispatchQueue.main.async {
|
||||
self.isCreatingFile = false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user