diff --git a/app/src/main/kotlin/org/openstrap/app/presentation/RewardsCopy.kt b/app/src/main/kotlin/org/openstrap/app/presentation/RewardsCopy.kt index 2bcc9191..c6a99034 100644 --- a/app/src/main/kotlin/org/openstrap/app/presentation/RewardsCopy.kt +++ b/app/src/main/kotlin/org/openstrap/app/presentation/RewardsCopy.kt @@ -205,6 +205,10 @@ object RewardsCopy { return strings.format(part, t.format(Formatters.of("EEEE, d MMMM yyyy", locale)), sportName.lowercase(locale)) } + /** "Thursday, 30 October 2026": the day a badge was earned, or a best set by a day rather than a workout. */ + fun dayLong(date: Long, zone: ZoneId = ZoneId.systemDefault(), locale: Locale = Locale.getDefault()): String = + Instant.ofEpochSecond(date).atZone(zone).format(Formatters.of("EEEE, d MMMM yyyy", locale)) + /** "27 October to 2 November": a week from its first day. */ fun weekRange(first: LocalDate, locale: Locale = Locale.getDefault()): String { val f = Formatters.of("d MMMM", locale) diff --git a/app/src/main/kotlin/org/openstrap/app/ui/dashboard/DayViewModel.kt b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/DayViewModel.kt index d4d22d29..17775d68 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/dashboard/DayViewModel.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/DayViewModel.kt @@ -32,6 +32,7 @@ import org.openstrap.app.data.SleepHistory import org.openstrap.app.data.Summaries import org.openstrap.app.data.Today import org.openstrap.app.data.catching +import org.openstrap.app.data.db.DailyPai import org.openstrap.app.data.db.HealthAlertRow import org.openstrap.app.data.db.OsaEventRow import org.openstrap.app.data.db.OsaResultRow @@ -170,6 +171,11 @@ data class ActivityHistory( val steps: Map = emptyMap(), /** The most steps of any day before [date]: the stored personal best when it's older, else read from the history. */ val stepsBest: Int? = null, + /** + * The days with Heart points earned, from [STRIP_DAYS_BEFORE] days before [date] to the later of [date] and today: the + * days of a detail's strip, whichever of them is shown, so a day's dot is the same whichever day is open. + */ + val heartPointsDays: Set = emptySet(), ) { /** [heartPoints] when they're [day]'s, else none yet. */ fun heartPointsOn(day: LocalDate): Map = if (date == day) heartPoints else emptyMap() @@ -197,6 +203,9 @@ data class ActivityHistory( /** Heart points' month. */ const val HEART_POINTS_DAYS = 30 + /** A detail's strip starts this many days before its last day. */ + const val STRIP_DAYS_BEFORE = 6L + /** Calories' year and the year before it, for the change against it. */ val CALORIES_DAYS = 2 * Range.Year.days } @@ -347,22 +356,32 @@ class DayViewModel( /** Each day's Heart points and stored calories up to the day shown, for the Activity tab and its details. */ val activityHistory: StateFlow = selected.flatMapLatest { d -> combine( - repo.dailyPai(d.minusDays(ActivityHistory.HEART_POINTS_DAYS - 1L), d), + // The days after [d] up to today, for the strip's dots; nothing is read for today. + stripLater(d), repo.dailyCalories(d.minusDays(ActivityHistory.CALORIES_DAYS - 1L), d), stepsAndBest(d), - ) { pai, calories, (steps, best) -> + repo.dailyPai(d.minusDays(ActivityHistory.HEART_POINTS_DAYS - 1L), d), + ) { later, calories, (steps, best), pai -> ActivityHistory( date = d, heartPoints = pai.mapValues { (_, p) -> HeartPointsDay(p.daily, p.total) }, calories = calories.mapValues { (_, e) -> CaloriesDay(e.activeKcal, e.totalKcal, e.workoutKcal, e.partial) }, steps = steps, stepsBest = best, + heartPointsDays = (pai.filterKeys { it >= d.minusDays(ActivityHistory.STRIP_DAYS_BEFORE) } + later) + .filterValues { it.daily > 0 }.keys, ) } } .flowOn(work) .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ActivityHistory()) + /** The Heart points of the days after [d] up to today, for the strip's later days; none when [d] is today. */ + private fun stripLater(d: LocalDate): Flow> { + val today = Today.on(clock()) + return if (d < today) repo.dailyPai(d.plusDays(1), today) else flowOf(emptyMap()) + } + /** * [d]'s steps from [ActivityHistory.STEPS_DAYS] days before it to its week's end, and the most steps of a day * before it: the stored personal best when it's from an earlier day (with the loaded days, as it can lag a sync), diff --git a/app/src/main/kotlin/org/openstrap/app/ui/dashboard/Frame.kt b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/Frame.kt index 6d77f2ec..0d2edade 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/dashboard/Frame.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/Frame.kt @@ -40,7 +40,7 @@ fun peekDay(date: LocalDate, locale: Locale = Locale.getDefault()): String = * What the strap chip in the header shows: a [dot] and, only when they matter, a few words ([text] may be empty). * [description] is read out by a screen reader. */ -data class StrapChip(val text: String, val dot: Dot, val description: String) { +data class StrapChip(val text: String, val dot: Dot, val description: String, val battery: Int? = null) { enum class Dot { /** Connected and all is well. */ Fine, @@ -51,7 +51,10 @@ data class StrapChip(val text: String, val dot: Dot, val description: String) { /** Connected and charging. */ Charging, - /** Something needs a look: not synced, or not seen for a while. Amber. */ + /** The strap is there but its last sync failed. Orange. */ + Unsynced, + + /** The strap isn't connected: not seen for a while. Shown as the strap, broken. */ Warn, /** Nothing to report yet (connecting), or nothing paired. Dim. */ @@ -106,19 +109,20 @@ fun strapChip( when { connection.charging && battery != null -> StrapChip( strings.format(R.string.day_chip_charging, battery), StrapChip.Dot.Charging, - strings.plural(R.plurals.day_chip_charging_description, battery, battery), + strings.plural(R.plurals.day_chip_charging_description, battery, battery), battery, ) sync is SyncState.Failed -> StrapChip( - strings.get(R.string.day_chip_not_synced), StrapChip.Dot.Warn, strings.get(R.string.day_chip_not_synced_description), + strings.get(R.string.day_chip_not_synced), StrapChip.Dot.Unsynced, + strings.get(R.string.day_chip_not_synced_description), ) battery == null -> StrapChip("", StrapChip.Dot.Fine, strings.get(R.string.day_chip_connected_description)) StrapBands.lowBattery(battery, connection.charging) -> StrapChip( strings.format(R.string.day_chip_battery, battery), StrapChip.Dot.Low, - strings.plural(R.plurals.day_chip_battery_low_description, battery, battery), + strings.plural(R.plurals.day_chip_battery_low_description, battery, battery), battery, ) else -> StrapChip( strings.format(R.string.day_chip_battery, battery), StrapChip.Dot.Fine, - strings.plural(R.plurals.day_chip_battery_description, battery, battery), + strings.plural(R.plurals.day_chip_battery_description, battery, battery), battery, ) } } diff --git a/app/src/main/kotlin/org/openstrap/app/ui/dashboard/MomentHeader.kt b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/MomentHeader.kt index 7a10bb9d..bf90f940 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/dashboard/MomentHeader.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/MomentHeader.kt @@ -18,6 +18,7 @@ import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size +import org.openstrap.app.ui.theme.ControlSurface import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.shape.CircleShape @@ -103,7 +104,7 @@ fun MomentHeader( ) Spacer(Modifier.width(8.dp)) } - growClick(onOpenStrap).let { g -> StrapChipButton(chip, g.onClick, g.modifier) } + growClick(onOpenStrap).let { g -> StrapPill(chip, g.onClick, g.modifier) } } }, ) @@ -200,37 +201,6 @@ private fun Peek(text: String) { Text(text, Modifier.width(PeekWidth), color = Color.White.copy(alpha = 0.22f), style = GlowType.body, maxLines = 1, softWrap = false) } -/** The strap chip: a dot, and words only when they matter. */ -@Composable -private fun StrapChipButton(chip: StrapChip, onClick: () -> Unit, modifier: Modifier = Modifier) { - val shape = CircleShape - Row( - modifier.clip(shape).background(ChipSurface).border(1.dp, Color.White.copy(alpha = 0.07f), shape) - .clickable(onClickLabel = stringResource(R.string.day_header_open_strap), onClick = onClick) - .semantics { contentDescription = chip.description } - .padding(horizontal = 12.dp, vertical = 8.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Box(Modifier.size(7.dp).background(chipDotColor(chip.dot), CircleShape)) - if (chip.text.isNotEmpty()) { - Spacer(Modifier.width(7.dp)) - Text( - chip.text, maxLines = 1, softWrap = false, - color = if (chip.dot == StrapChip.Dot.Warn) MetricColors.warn else Color.White, - style = GlowType.secondary, - ) - } - } -} - -private fun chipDotColor(dot: StrapChip.Dot): Color = when (dot) { - StrapChip.Dot.Fine -> MetricColors.good - StrapChip.Dot.Low -> MetricColors.battery(StrapChip.LOW_BATTERY) - StrapChip.Dot.Charging -> MetricColors.good - StrapChip.Dot.Warn -> MetricColors.warn - StrapChip.Dot.Quiet -> Color.White.copy(alpha = 0.3f) -} - -private val Avatar = Color(0xFF1C1C1E) -private val ChipSurface = Color(0xFF16161A) +// The Control surface (spec 2.2): the avatar is a control. +private val Avatar = ControlSurface private val PeekWidth = 34.dp diff --git a/app/src/main/kotlin/org/openstrap/app/ui/dashboard/StrapPill.kt b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/StrapPill.kt new file mode 100644 index 00000000..8ef11dfb --- /dev/null +++ b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/StrapPill.kt @@ -0,0 +1,201 @@ +package org.openstrap.app.ui.dashboard + +import androidx.compose.animation.core.LinearEasing +import androidx.compose.animation.core.animateFloat +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.animation.core.infiniteRepeatable +import androidx.compose.animation.core.rememberInfiniteTransition +import androidx.compose.animation.core.tween +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.defaultMinSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material3.Icon +import androidx.compose.material3.Text +import androidx.compose.material3.minimumInteractiveComponentSize +import androidx.compose.runtime.Composable +import androidx.compose.runtime.State +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.drawBehind +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.TileMode +import androidx.compose.ui.graphics.drawscope.DrawScope +import androidx.compose.ui.graphics.drawscope.clipRect +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import org.openstrap.app.R +import org.openstrap.app.ui.components.Motion +import org.openstrap.app.ui.components.rememberAnimationsOn +import org.openstrap.app.ui.glow.GlowType +import org.openstrap.app.ui.glow.StrapDrawing +import org.openstrap.app.ui.theme.AppIcons +import org.openstrap.app.ui.theme.ControlSurface +import org.openstrap.app.ui.theme.MetricColors + +/* + * The strap pill in the header (spec 3.1). The pill is the strap's state, not a dot with words: + * - connected: green as far as the battery, fading out into the pill, the percent in the middle (amber when low) + * - charging: the same green, flowing, with a bolt before the number + * - not synced: orange all over, with the (i) + * - not connected, connecting or not paired: the strap as the Strap page draws it, dimmed, with its words ("2 h ago", + * "Not connected"), which tell the three apart. Not connected is mostly out of range or Bluetooth off and passes, so + * it isn't drawn as damage. + * Green and amber are for the strap and the sync only, never a health value (spec 2.2). + */ + +/** A fill's two colours: rich where it starts, softer where it runs out. */ +private class Tint(val rich: Color, val soft: Color) + +/** The orange of a sync that failed: the sync amber, deepened. */ +private val OrangeDeep = Color(0xFFE5672A) + +private fun tintOf(dot: StrapChip.Dot): Tint? = when (dot) { + StrapChip.Dot.Fine, StrapChip.Dot.Charging -> Tint(MetricColors.good.copy(alpha = 0.62f), MetricColors.good.copy(alpha = 0.3f)) + StrapChip.Dot.Low -> Tint(MetricColors.warn.copy(alpha = 0.62f), MetricColors.warn.copy(alpha = 0.3f)) + StrapChip.Dot.Unsynced -> Tint(MetricColors.warn.copy(alpha = 0.55f), OrangeDeep.copy(alpha = 0.85f)) + StrapChip.Dot.Warn, StrapChip.Dot.Quiet -> null +} + +/** How much of the pill is filled: the battery, or all of it when there's no reading or the colour is the point. */ +private fun fillOf(chip: StrapChip): Float = when (chip.dot) { + StrapChip.Dot.Fine, StrapChip.Dot.Low, StrapChip.Dot.Charging -> (chip.battery?.toFloat() ?: FULL) / FULL + StrapChip.Dot.Unsynced -> 1f + StrapChip.Dot.Warn, StrapChip.Dot.Quiet -> 0f +} + +private const val FULL = 100f + +@Composable +internal fun StrapPill(chip: StrapChip, onClick: () -> Unit, modifier: Modifier = Modifier) { + val tint = tintOf(chip.dot) + // A change of level moves the fill rather than cutting. + val fill by animateFloatAsState(fillOf(chip), tween(FILL_MS, easing = Motion.easing), label = "strap fill") + val flow = rememberChargeFlow(chip.dot == StrapChip.Dot.Charging) + Row( + // 48 dp tall to tap, the pill drawn 32 dp tall in the middle of it; the header row is 60 dp, so nothing moves. + // [modifier] comes after, so the Strap page grows out of the pill as drawn, not the room round it. + Modifier.minimumInteractiveComponentSize().then(modifier) + .clip(CircleShape).background(ControlSurface) + // Read where it is drawn, so the fill and its flow redraw without composing the pill again. + .drawBehind { if (tint != null) drawFill(tint, fill, flow.value) } + .border(1.dp, Color.White.copy(alpha = 0.07f), CircleShape) + .clickable(onClickLabel = stringResource(R.string.day_header_open_strap), onClick = onClick) + .semantics { contentDescription = chip.description } + .defaultMinSize(minWidth = MIN_WIDTH, minHeight = HEIGHT) + .padding(horizontal = 12.dp, vertical = 4.dp), + horizontalArrangement = Arrangement.Center, + verticalAlignment = Alignment.CenterVertically, + ) { PillContent(chip) } +} + +/** + * The colour from the left edge to [fill] of the width, then fading out into the pill's own surface over [FADE], so it + * ends in a soft edge like the lit cards, never a line. While charging ([flow] 0 to 1, -1 for still) the colour flows + * along the pill, swelling and thinning, and the fade holds it in. + */ +private fun DrawScope.drawFill(tint: Tint, fill: Float, flow: Float) { + val level = size.width * fill.coerceIn(0f, 1f) + if (level <= 0f) return + val full = fill >= 1f + val end = if (full) size.width else minOf(size.width, level + FADE.toPx()) + val body = if (flow < 0f) { + Brush.horizontalGradient(listOf(tint.rich, tint.soft), startX = 0f, endX = end) + } else { + // One swell is a period long and repeats, so sliding it along never shows a seam. + val period = size.width * FLOW_PERIOD + Brush.horizontalGradient( + listOf(tint.soft, tint.rich, tint.soft), startX = period * (flow - 1f), endX = period * flow, tileMode = TileMode.Repeated, + ) + } + clipRect(0f, 0f, end, size.height) { drawRect(body) } + if (!full) { + val from = maxOf(0f, level - FADE.toPx() * FADE_LEAD) + drawRect( + Brush.horizontalGradient(listOf(Color.Transparent, ControlSurface), startX = from, endX = end), + topLeft = Offset(from, 0f), size = Size(end - from, size.height), + ) + } +} + +/** How far along the pill the flow has come, 0 to 1, round and round while charging; -1 when it isn't flowing. */ +@Composable +private fun rememberChargeFlow(charging: Boolean): State { + val animate = rememberAnimationsOn() + if (!charging || !animate) return NoFlow + return rememberInfiniteTransition(label = "strap charge").animateFloat( + 0f, 1f, infiniteRepeatable(tween(FLOW_MS, easing = LinearEasing)), label = "strap charge flow", + ) +} + +private val NoFlow: State = mutableFloatStateOf(-1f) + +@Composable +private fun PillContent(chip: StrapChip) { + when (chip.dot) { + StrapChip.Dot.Fine, StrapChip.Dot.Low -> + if (chip.text.isNotEmpty()) PillText(chip.text) else Box(Modifier.size(6.dp).background(Color.White, CircleShape)) + StrapChip.Dot.Charging -> Row(verticalAlignment = Alignment.CenterVertically) { + Icon(AppIcons.Bolt, null, Modifier.size(13.dp), tint = Color.White) + Spacer(Modifier.width(2.dp)) + PillText(chip.battery?.toString() ?: chip.text) + } + StrapChip.Dot.Unsynced -> Row(verticalAlignment = Alignment.CenterVertically) { + Icon(AppIcons.Info, null, Modifier.size(15.dp), tint = Color.White) + Spacer(Modifier.width(6.dp)) + PillText(chip.text) + } + StrapChip.Dot.Warn, StrapChip.Dot.Quiet -> StrapAndWords(chip.text) + } +} + +/** The Strap page's strap drawing, small (its light out and the drawing dimmed, as it is when the strap isn't there). */ +@Composable +private fun StrapAndWords(text: String) { + Row(verticalAlignment = Alignment.CenterVertically) { + StrapDrawing( + led = Color.White, lit = false, syncing = false, modifier = Modifier.size(width = MARK_WIDTH, height = MARK_HEIGHT), + lineScale = MARK_LINES, + ) + if (text.isNotEmpty()) { + Spacer(Modifier.width(7.dp)) + PillText(text) + } + } +} + +@Composable +private fun PillText(text: String) { + Text( + text, maxLines = 1, softWrap = false, color = Color.White, + style = GlowType.secondary.copy(fontWeight = FontWeight.SemiBold, fontFeatureSettings = "tnum"), + ) +} + +private const val FILL_MS = 600 +private const val FLOW_MS = 2600 +private const val FLOW_PERIOD = 0.9f +private const val FADE_LEAD = 0.5f +private const val MARK_LINES = 4f +private val MIN_WIDTH = 56.dp +private val HEIGHT = 32.dp +private val FADE = 22.dp +private val MARK_WIDTH = 19.dp +private val MARK_HEIGHT = 24.dp diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/ActivityDetail.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/ActivityDetail.kt index a6cac4eb..6822fcb1 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/ActivityDetail.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/ActivityDetail.kt @@ -92,6 +92,8 @@ internal class ActivityDetailContext( val onEditProfile: () -> Unit, val contentPadding: PaddingValues, val onBack: () -> Unit, + /** The day picked, which the strip shows at once while [state] and [r] may still be the last day's. */ + val stripDate: LocalDate = state.date, ) { val today: LocalDate get() = LocalDate.now() val isToday: Boolean get() = state.date == today @@ -121,9 +123,9 @@ private fun weekOf(end: LocalDate): List = (6 downTo 0).map { end.min /** The strip under the value, with a dot under days that have steps. */ @Composable private fun stepsStrip(ctx: ActivityDetailContext, metric: DailyMetric = DailyMetric.Steps): List { - val strip = DetailCopy.strip(ctx.state.date, ctx.today, emptySet()) + val strip = DetailCopy.strip(ctx.stripDate, ctx.today, emptySet()) val withData = daysWithData(metric, strip.first().date.minusDays(1), strip.last().date, ctx.history) - return DetailCopy.strip(ctx.state.date, ctx.today, withData) + return DetailCopy.strip(ctx.stripDate, ctx.today, withData) } /* -------------------------------------------- Heart points ------------------------------------------ */ @@ -161,7 +163,9 @@ private fun HeartPointsDetail(ctx: ActivityDetailContext) { DetailHeadline(total.toString(), stringResource(R.string.glow_activity_points_last_7_days), ActivityCopy.heartPointsWord(total)) else -> DetailHeadline.none(stringResource(R.string.glow_activity_no_points_yet), AFTER_NEXT_SYNC) } - val strip = DetailCopy.strip(date, ctx.today, stored.keys) + // A dot only under a day the strap recorded points for: read for the whole strip, so it doesn't change with the day + // shown, and not for a day it wasn't worn. + val strip = DetailCopy.strip(date, ctx.today, ctx.activity.heartPointsDays) DetailTemplate( Score.HeartPoints.title, color, siblings(Detail.OfScore(Score.HeartPoints), ctx.onSwitch), onInfo = { info = true }, onBack = ctx.onBack, @@ -270,6 +274,8 @@ private fun ActiveMinutesDetail(ctx: ActivityDetailContext) { Score.ActiveMinutes.title, color, siblings(Detail.OfScore(Score.ActiveMinutes), ctx.onSwitch), onInfo = { info = true }, onBack = ctx.onBack, contentPadding = ctx.contentPadding, headline = headline, strip = stepsStrip(ctx), onDay = ctx.onSelectDay, ranges = ranges, range = range, onRange = { rangeIndex = ranges.indexOf(it) }, scrubbed = { scrub }, + // The figures are the held day's ([ActivityDetailContext.stripDate]), so they move when it does. + headlineDay = date, // The card's picture: the week's minutes as blocks toward the 150 to aim for. It's the week's number the card // shows, so the blocks belong to Week, over the days that make them. heroPicture = if (a != null && range == Range.Week) { @@ -364,6 +370,8 @@ private fun LoadDetail(ctx: ActivityDetailContext) { Score.Load.title, color, siblings(Detail.OfScore(Score.Load), ctx.onSwitch), onInfo = { info = true }, onBack = ctx.onBack, contentPadding = ctx.contentPadding, headline = headline, strip = stepsStrip(ctx, DailyMetric.HeartRate), onDay = ctx.onSelectDay, ranges = ranges, range = range, onRange = { rangeIndex = ranges.indexOf(it) }, scrubbed = { scrub }, + // The figures are the held day's ([ActivityDetailContext.stripDate]), so they move when it does. + headlineDay = ctx.state.date, // The Load card's picture: today's Load filling over your usual band, as on Today and Activity. heroPicture = if (r != null && range == Range.Day) { { DetailPicture(height = 40.dp) { m -> LevelFill(r.load, band, color, PictureSize.Wide, m) } } diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/BadgeParts.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/BadgeParts.kt new file mode 100644 index 00000000..6f401447 --- /dev/null +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/BadgeParts.kt @@ -0,0 +1,228 @@ +package org.openstrap.app.ui.glow + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.role +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import java.time.ZoneId +import org.openstrap.app.R +import org.openstrap.app.data.Rewards +import org.openstrap.app.data.db.PersonalBest +import org.openstrap.app.presentation.RewardsCopy +import org.openstrap.app.presentation.RewardsView +import org.openstrap.app.ui.components.pressClickable + +/* + * The parts of Goals and bests and All badges (ui/glow/GoalsAndBests.kt): the personal bests as rosettes, the next + * badge to earn, and the badges as medals. Each shows only its medal, its name and its figure; a tap opens its sheet + * (BadgeSheets.kt) with the rest. + */ + +/** What a badge's art reads on these pages: the first weekly goal shows the goal it was met at, or this week's while locked. */ +internal fun RewardsView.face(b: Rewards.Badge): String = + earned.firstOrNull { it.id == b.id }?.let { RewardsCopy.face(b, Rewards.goalAt(it, weeks, firstDay, ZoneId.systemDefault())) } + ?: RewardsCopy.face(b, goal) + +/** + * The personal bests as rosettes, three to a row, each with its figure and name. Before the first, the kinds there are + * to set, quiet, with a line on when they come. + */ +@Composable +internal fun BestsPanel(view: RewardsView, onOpen: (String) -> Unit) { + val shown = view.bests.sortedBy { order(it.kind) } + ListPanel(title = stringResource(R.string.glow_goals_personal_bests)) { + Column(Modifier.padding(vertical = 10.dp), verticalArrangement = Arrangement.spacedBy(14.dp)) { + if (shown.isEmpty()) { + Text( + stringResource(R.string.glow_goals_no_bests), color = Color.White.copy(alpha = GlowType.SECONDARY_ALPHA), + style = GlowType.secondary, + ) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(CELL_GAP)) { + FIRST_BESTS.forEach { kind -> BestCell(kind, null, onOpen, Modifier.weight(1f)) } + } + } + shown.chunked(BESTS_PER_ROW).forEach { row -> + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(CELL_GAP)) { + row.forEach { b -> BestCell(b.kind, b, onOpen, Modifier.weight(1f)) } + repeat(BESTS_PER_ROW - row.size) { Spacer(Modifier.weight(1f)) } + } + } + } + } +} + +/** + * The badge closest to done, as a picture card in its group's ink: its medal still to earn, its name, and how far along + * as a bar and in words. Opens its sheet. + */ +@Composable +internal fun NextBadgeCard(badge: Rewards.Badge, view: RewardsView, onOpen: (Rewards.Badge) -> Unit) { + val ink = badgeColor(badge.group) + val (have, need) = view.progress[badge.id] ?: (0L to 1L) + PictureCard(ink, Modifier.fillMaxWidth(), onClick = { onOpen(badge) }) { + Row(verticalAlignment = Alignment.CenterVertically) { + Medal(badgeLook(badge, view.face(badge)), NEXT_MEDAL, locked = true) + Spacer(Modifier.width(16.dp)) + Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(6.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text(stringResource(R.string.glow_goals_next_badge), color = Color.White, style = GlowType.cardTitle, maxLines = 1) + Spacer(Modifier.width(6.dp)) + TapCaret(CARD_CARET_ALPHA) + } + Text(badge.title, color = Color.White, style = GlowType.body, maxLines = 2) + ShareBar(have.toFloat() / need, ink, Modifier.fillMaxWidth().padding(top = 4.dp)) + Text( + RewardsCopy.progressLine(have, need, badge.unit), color = Color.White.copy(alpha = GlowType.SECONDARY_ALPHA), + style = GlowType.secondary, + ) + } + } + } +} + +/** + * The badges earned, newest first, as medals four to a row with only their names; before the first, the first ones to + * go for, quiet. The note opens All badges. + */ +@Composable +internal fun BadgesPanel(view: RewardsView, onOpen: (Rewards.Badge) -> Unit, onAllBadges: () -> Unit) { + val earned = view.earned.sortedByDescending { it.earnedAt }.mapNotNull { Rewards.badge(it.id) } + val shown = earned.ifEmpty { FIRST_BADGES.mapNotNull(Rewards::badge) }.take(PANEL_BADGES) + ListPanel( + title = stringResource(R.string.glow_goals_badges), + note = stringResource(R.string.glow_goals_earned_count, view.earned.size, Rewards.BADGES.size), + onNote = onAllBadges, + ) { + Column(Modifier.padding(vertical = 10.dp), verticalArrangement = Arrangement.spacedBy(14.dp)) { + shown.chunked(PANEL_PER_ROW).forEach { row -> + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(CELL_GAP)) { + row.forEach { b -> BadgeCell(b, view, onOpen, GlowType.caption, Modifier.weight(1f)) } + repeat(PANEL_PER_ROW - row.size) { Spacer(Modifier.weight(1f)) } + } + } + } + } +} + +/** + * A badge's medal and its name in [nameStyle], lit when earned; a locked one with a count shows how far along as a thin + * bar in its ink. Opens its sheet. + */ +@Composable +internal fun BadgeCell( + badge: Rewards.Badge, + view: RewardsView, + onOpen: (Rewards.Badge) -> Unit, + nameStyle: TextStyle, + modifier: Modifier = Modifier, +) { + val row = view.earned.firstOrNull { it.id == badge.id } + val share = view.progress[badge.id]?.let { (have, need) -> have.toFloat() / need }?.takeIf { row == null && it > 0f } + val state = row?.let { stringResource(R.string.glow_goals_earned_on, RewardsCopy.dayLong(it.earnedAt)) } + ?: stringResource(R.string.glow_goals_not_earned) + val described = stringResource(R.string.glow_goals_badge_described, badge.title, state) + Column( + modifier.clip(GlowLayout.TileShape).pressClickable({ onOpen(badge) }, GlowLayout.TileShape) + .clearAndSetSemantics { + contentDescription = described + role = Role.Button + } + .padding(vertical = 6.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Medal(badgeLook(badge, view.face(badge)), CELL_MEDAL, locked = row == null) + Text( + badge.title, color = Color.White.copy(alpha = if (row != null) 1f else LOCKED_NAME_ALPHA), style = nameStyle, + textAlign = TextAlign.Center, maxLines = 2, minLines = 2, + ) + if (share != null) ShareBar(share, badgeColor(badge.group), Modifier.width(CELL_BAR)) + } +} + +/** How far along, 0..1, as a thin rounded bar: [ink] over a faint track. */ +@Composable +internal fun ShareBar(share: Float, ink: Color, modifier: Modifier = Modifier) { + Box(modifier.height(4.dp).clip(CircleShape).background(Color.White.copy(alpha = TRACK_ALPHA))) { + Box(Modifier.fillMaxHeight().fillMaxWidth(share.coerceIn(0f, 1f)).clip(CircleShape).background(ink)) + } +} + +/** A best's rosette, its figure and its name; [best] null for one not set yet, quiet. Opens its sheet. */ +@Composable +private fun BestCell(kind: String, best: PersonalBest?, onOpen: (String) -> Unit, modifier: Modifier = Modifier) { + val title = RewardsCopy.bestTitle(kind) + val figure = best?.let { RewardsCopy.bestValue(kind, it.value) } ?: stringResource(R.string.glow_goals_not_set) + val described = stringResource(R.string.glow_goals_badge_described, title, figure) + Column( + modifier.clip(GlowLayout.TileShape).pressClickable({ onOpen(kind) }, GlowLayout.TileShape) + .clearAndSetSemantics { + contentDescription = described + role = Role.Button + } + .padding(vertical = 6.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { + Medal(bestLook(kind), CELL_MEDAL, locked = best == null) + Text( + figure, color = Color.White.copy(alpha = if (best != null) 1f else GlowType.CAPTION_ALPHA), + style = if (best != null) GlowType.cardTitle else GlowType.caption, maxLines = 1, + ) + Text( + title, color = Color.White.copy(alpha = if (best == null) LOCKED_NAME_ALPHA else GlowType.SECONDARY_ALPHA), + style = GlowType.caption, textAlign = TextAlign.Center, maxLines = 2, minLines = 2, + ) + } +} + +/** Bests in a fixed order: runs, then the longest workout, lifts, steps. */ +private fun order(kind: String): Int = Rewards.Kind.fastestMeters(kind) + ?: when { + kind == Rewards.Kind.LONGEST_RUN -> RUN_ORDER + kind == Rewards.Kind.LONGEST_WORKOUT -> RUN_ORDER + 1 + Rewards.Kind.liftName(kind) != null -> RUN_ORDER + 2 + else -> STEPS_ORDER + } + +/** Before any badge is earned, the first ones to go for: one of each kind of start. */ +private val FIRST_BADGES = listOf("first_workout", "goal_first", "first_run", "workouts_10") + +/** Before any best, the kinds there are to set: the ones any workout or day can set. */ +private val FIRST_BESTS = listOf(Rewards.Kind.LONGEST_WORKOUT, Rewards.Kind.MOST_STEPS, Rewards.Kind.fastest(FIVE_KM)) + +/** After every fastest stretch (their metres), the longest run, the longest workout, the lifts, then the steps. */ +private const val RUN_ORDER = 100_000 +private const val STEPS_ORDER = 100_003 +private const val FIVE_KM = 5000 +private const val BESTS_PER_ROW = 3 +private const val PANEL_PER_ROW = 4 +private const val PANEL_BADGES = 8 +private const val LOCKED_NAME_ALPHA = 0.55f +private const val TRACK_ALPHA = 0.12f +private val CELL_GAP = 8.dp +private val CELL_MEDAL = 64.dp +private val CELL_BAR = 44.dp +private val NEXT_MEDAL = 76.dp diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/BadgeSheets.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/BadgeSheets.kt new file mode 100644 index 00000000..3f0e8025 --- /dev/null +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/BadgeSheets.kt @@ -0,0 +1,195 @@ +package org.openstrap.app.ui.glow + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.ReadOnlyComposable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import org.openstrap.app.R +import org.openstrap.app.data.Rewards +import org.openstrap.app.data.Workouts +import org.openstrap.app.data.db.PersonalBest +import org.openstrap.app.presentation.RewardsCopy +import org.openstrap.app.presentation.RewardsView +import org.openstrap.app.presentation.Units + +/* + * A badge or a personal best on its own, in a sheet over Goals and bests or All badges: the medal large, lighting up as + * the sheet opens when it's earned, then what it is and how it's earned, and when it was, or how far along. The pages + * show only the medal and its name, so the words are here (spec 2.5: an explanation behind a tap, never on the page). + */ + +/** + * A badge on its own: its medal, its group and name, how it's earned, then when it was, or how far along with a bar, + * or that it's still to earn. Badges counted from workouts say which workouts count. + */ +@Composable +internal fun BadgeSheet(badge: Rewards.Badge, view: RewardsView, onDismiss: () -> Unit) { + val row = view.earned.firstOrNull { it.id == badge.id } + val progress = view.progress[badge.id] + val lit = rememberLightRise(row != null) + PageSheet(onDismiss) { + SheetColumn { + Medal(badgeLook(badge, view.face(badge)), SHEET_MEDAL, Modifier.padding(vertical = 12.dp), locked = row == null, lit = lit) + SheetText(groupName(badge.group)) + SheetTitle(badge.title) + howToEarn(badge)?.let { SheetText(it, Color.White.copy(alpha = LINE_ALPHA), GlowType.body) } + when { + row != null -> SheetText(stringResource(R.string.glow_goals_earned_on, RewardsCopy.dayLong(row.earnedAt)), Color.White) + progress != null -> Column( + Modifier.fillMaxWidth().padding(top = 8.dp, start = 24.dp, end = 24.dp), + horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + ShareBar(progress.first.toFloat() / progress.second, badgeColor(badge.group), Modifier.fillMaxWidth()) + SheetText(RewardsCopy.progressLine(progress.first, progress.second, badge.unit)) + } + else -> SheetText(stringResource(R.string.glow_goals_not_earned)) + } + if (countsWorkouts(badge)) { + SheetText( + stringResource(R.string.glow_goals_counts_rule), Color.White.copy(alpha = GlowType.CAPTION_ALPHA), GlowType.caption, + top = 8.dp, + ) + } + } + PageButton(stringResource(R.string.glow_done), onDismiss, Modifier.fillMaxWidth(), primary = true) + } +} + +/** + * A personal best on its own: its rosette, its name and figure, when it was set and in what, and what it measures. One + * not set yet says so, with what it will measure. + */ +@Composable +internal fun BestSheet(kind: String, view: RewardsView, onDismiss: () -> Unit) { + val best = view.bests.firstOrNull { it.kind == kind } + val lit = rememberLightRise(best != null) + PageSheet(onDismiss) { + SheetColumn { + Medal(bestLook(kind), SHEET_MEDAL, Modifier.padding(vertical = 12.dp), locked = best == null, lit = lit) + SheetText(stringResource(R.string.glow_goals_personal_bests)) + SheetTitle(RewardsCopy.bestTitle(kind)) + if (best != null) { + Text(RewardsCopy.bestValue(kind, best.value), color = Color.White, style = GlowType.goalValue, maxLines = 1) + SheetText(whenSet(best, view), Color.White) + } else { + SheetText(stringResource(R.string.glow_goals_not_set)) + } + SheetText(bestHow(kind), Color.White.copy(alpha = LINE_ALPHA), GlowType.body) + } + PageButton(stringResource(R.string.glow_done), onDismiss, Modifier.fillMaxWidth(), primary = true) + } +} + +/** A badge group's name: Firsts, Milestones, Weekly goal, Something new. */ +@Composable +@ReadOnlyComposable +internal fun groupName(group: Rewards.Group): String = stringResource( + when (group) { + Rewards.Group.Firsts -> R.string.glow_goals_group_firsts + Rewards.Group.Milestones -> R.string.glow_goals_group_milestones + Rewards.Group.Weekly -> R.string.glow_goals_weekly_goal + Rewards.Group.Kinds -> R.string.glow_goals_group_kinds + }, +) + +/** A sheet's centred column, its parts 8 dp apart. */ +@Composable +private fun SheetColumn(content: @Composable ColumnScope.() -> Unit) = Column( + Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp), + content = content, +) + +@Composable +private fun SheetTitle(text: String) = + Text(text, color = Color.White, style = GlowType.pageTitle, textAlign = TextAlign.Center, modifier = Modifier.fillMaxWidth()) + +/** A centred line of a sheet: the kicker over the title and the notes in Secondary, what it is in Body, the rule in Caption. */ +@Composable +private fun SheetText( + text: String, + color: Color = Color.White.copy(alpha = GlowType.SECONDARY_ALPHA), + style: TextStyle = GlowType.secondary, + top: Dp = 0.dp, +) = Text( + text, color = color, style = style, textAlign = TextAlign.Center, + modifier = Modifier.fillMaxWidth().padding(top = top, start = 8.dp, end = 8.dp), +) + +/** + * How [b] is earned, in a sentence, with its count for the milestones and the weeks in a row. Null for a badge with + * no sentence in [BADGE_HOW] yet: its sheet shows without one rather than crash. + */ +@Composable +@ReadOnlyComposable +private fun howToEarn(b: Rewards.Badge): String? { + val need = b.needs?.let { Units.count(it) }.orEmpty() + return when { + b.id.startsWith(WORKOUTS_PREFIX) -> stringResource(R.string.core_badge_how_workouts, need) + b.id.startsWith(KM_PREFIX) -> stringResource(R.string.core_badge_how_km, need) + b.id.startsWith(GOAL_PREFIX) && b.id != GOAL_FIRST_ID -> stringResource(R.string.core_badge_how_goal_run, need) + else -> BADGE_HOW[b.id]?.let { stringResource(it) } + } +} + +/** A best of [kind]'s measure, in a sentence. */ +@Composable +@ReadOnlyComposable +private fun bestHow(kind: String): String { + Rewards.Kind.fastestMeters(kind)?.let { return stringResource(R.string.glow_goals_best_fastest_how, RewardsCopy.distanceName(it)) } + return stringResource( + when { + Rewards.Kind.liftName(kind) != null -> R.string.glow_goals_best_lift_how + kind == Rewards.Kind.LONGEST_RUN -> R.string.glow_goals_best_longest_run_how + kind == Rewards.Kind.MOST_STEPS -> R.string.glow_goals_best_steps_how + else -> R.string.glow_goals_best_longest_workout_how + }, + ) +} + +/** When [best] was set, with the workout it was set in ("Thursday, 30 October 2026, morning run"), or its day alone. */ +private fun whenSet(best: PersonalBest, view: RewardsView): String { + val sport = best.workoutStart?.let { start -> view.all.firstOrNull { it.start == start } }?.sport + return if (sport != null) RewardsCopy.whenSet(best.date, Workouts.sportName(sport)) else RewardsCopy.dayLong(best.date) +} + +/** Whether [b] is counted from workouts, which count from 10 minutes when you start or keep them; not the steps or distance. */ +private fun countsWorkouts(b: Rewards.Badge): Boolean = !b.id.startsWith(KM_PREFIX) && b.id !in STEPS_BADGES + +/** Each badge earned by a single thing done, by id, with the sentence on how. */ +private val BADGE_HOW: Map = mapOf( + "first_workout" to R.string.core_badge_how_first_workout, + "first_10k_steps" to R.string.core_badge_how_first_10k_steps, + "steps_1m" to R.string.core_badge_how_steps_1m, + "goal_first" to R.string.core_badge_how_goal_first, + "first_run" to R.string.core_badge_how_first_run, + "first_5k" to R.string.core_badge_how_first_5k, + "first_10k" to R.string.core_badge_how_first_10k, + "first_indoor" to R.string.core_badge_how_first_indoor, + "first_log" to R.string.core_badge_how_first_log, + "first_tabata" to R.string.core_badge_how_first_tabata, + "first_reps" to R.string.core_badge_how_first_reps, + "first_mind" to R.string.core_badge_how_first_mind, + "first_game" to R.string.core_badge_how_first_game, +) + +/** The badges counted from the strap's steps, not from workouts. */ +private val STEPS_BADGES = setOf("first_10k_steps", "steps_1m") + +private const val WORKOUTS_PREFIX = "workouts_" +private const val KM_PREFIX = "km_" +private const val GOAL_PREFIX = "goal_" +private const val GOAL_FIRST_ID = "goal_first" +private const val LINE_ALPHA = 0.85f +private val SHEET_MEDAL = 156.dp diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/Celebrations.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/Celebrations.kt index b3e1f1aa..a11e52cf 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/Celebrations.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/Celebrations.kt @@ -4,8 +4,6 @@ import org.openstrap.app.R import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.pluralStringResource import androidx.activity.compose.BackHandler -import androidx.compose.foundation.background -import androidx.compose.foundation.border import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column @@ -14,18 +12,13 @@ import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.PaddingValues -import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.alpha -import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import org.openstrap.app.data.Rewards import org.openstrap.app.ui.theme.AppIcons @@ -51,39 +44,6 @@ internal fun badgeColor(group: Rewards.Group): Color = when (group) { /** A personal best's colour: the calories' gold. */ internal val BestColor = MetricColors.calories -/** - * A badge's art in the glow language: a round glow in [color] lit from below, a hairline rim, and its [short] text. - * [dots] puts the text in dots (the one dotted number on its screen); a [locked] badge is dim and unlit. - */ -@Composable -internal fun BadgeArt( - short: String, color: Color, size: Dp, modifier: Modifier = Modifier, locked: Boolean = false, dots: Boolean = false, under: String? = null, - /** Just a ring in the colour with the text in it (board AchievementsV1's row), no fill. */ - ring: Boolean = false, -) { - Box( - modifier.size(size).alpha(if (locked) 0.35f else 1f) - .let { m -> - if (ring) m else m.background( - if (locked) Brush.radialGradient(listOf(Color.White.copy(alpha = 0.06f), Color.White.copy(alpha = 0.02f))) - else Brush.verticalGradient(listOf(Color.Black, color.copy(alpha = 0.55f))), - CircleShape, - ) - } - .border(if (ring) 2.dp else 1.dp, if (locked) Color.White.copy(alpha = if (ring) 0.5f else 0.12f) else color.copy(alpha = if (ring) 1f else 0.8f), CircleShape), - contentAlignment = Alignment.Center, - ) { - Column(horizontalAlignment = Alignment.CenterHorizontally) { - if (dots) DotMatrixText(short, dot = DotSize.Hero) - else Text( - short, color = if (ring && !locked) color else Color.White, maxLines = 1, - style = if (size >= 80.dp) GlowType.pageTitle else GlowType.cardTitle, - ) - under?.let { Text(it, color = Color.White, style = GlowType.body, modifier = Modifier.padding(top = 6.dp)) } - } - } -} - /** The close button in a celebration's top corner. */ @Composable private fun CloseRow(title: String?, onClose: () -> Unit) { @@ -107,9 +67,10 @@ fun BestCardScreen(best: Rewards.NewBest, sportName: String, contentPadding: Pad ) { CloseRow(stringResource(R.string.glow_celebrate_personal_best), onContinue) Spacer(Modifier.height(24.dp)) - BadgeArt( - RewardsCopy.bestShort(best.best.kind), BestColor, 200.dp, Modifier.align(Alignment.CenterHorizontally), dots = true, - under = RewardsCopy.bestValue(best.best.kind, best.best.value), + Medal(bestLook(best.best.kind), 200.dp, Modifier.align(Alignment.CenterHorizontally), lit = rememberLightRise(true)) + Text( + RewardsCopy.bestValue(best.best.kind, best.best.value), color = Color.White, style = GlowType.goalValue, maxLines = 1, + textAlign = TextAlign.Center, modifier = Modifier.fillMaxWidth().padding(top = 16.dp), ) Spacer(Modifier.height(12.dp)) Text(RewardsCopy.bestTitle(best.best.kind), color = Color.White, style = GlowType.pageTitle, textAlign = TextAlign.Center, modifier = Modifier.fillMaxWidth()) @@ -202,49 +163,24 @@ fun HistoryBadgesScreen(badges: List, contentPadding: PaddingValu pluralStringResource(R.plurals.glow_celebrate_history_badges, badges.size, badges.size), color = Color.White.copy(alpha = GlowType.SECONDARY_ALPHA), style = GlowType.body, modifier = Modifier.padding(start = 4.dp), ) - BadgeGrid(badges.map { it to null }, face = face) - } -} - -/** - * The badges on Goals and bests (board AchievementsV1): up to four rings in a row, no panel, the badge's colour as the - * ring and its text, the name under and its date, or for the next one dim with how far along it is. - */ -@Composable -internal fun BadgeRow(badges: List>, locked: (Rewards.Badge) -> Boolean, face: (Rewards.Badge) -> String) { - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.Top) { - badges.take(4).forEach { (b, note) -> - val dim = locked(b) - Column(Modifier.weight(1f), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(6.dp)) { - BadgeArt(face(b), badgeColor(b.group), 64.dp, locked = dim, ring = true) - Text( - if (dim && note != null) note else b.title, color = Color.White.copy(alpha = if (dim) 0.5f else 1f), - style = GlowType.caption, textAlign = TextAlign.Center, maxLines = 2, - ) - } - } - repeat((4 - badges.size).coerceAtLeast(0)) { Box(Modifier.weight(1f)) } - } -} - -/** - * Badges three to a row, each its art and title; [note] under the title is the date earned or what it needs, [face] - * what its art reads ([RewardsCopy.face]). - */ -@Composable -internal fun BadgeGrid(badges: List>, locked: (Rewards.Badge) -> Boolean = { false }, face: (Rewards.Badge) -> String = { it.short }) { - QuietPanel { - badges.chunked(3).forEach { row -> - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) { - row.forEach { (b, note) -> - Column(Modifier.weight(1f), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(6.dp)) { - BadgeArt(face(b), badgeColor(b.group), 64.dp, locked = locked(b)) - Text(b.title, color = Color.White, style = GlowType.secondary, textAlign = TextAlign.Center, maxLines = 2) - note?.let { Text(it, color = Color.White.copy(alpha = GlowType.SECONDARY_ALPHA), style = GlowType.caption, textAlign = TextAlign.Center) } + QuietPanel { + badges.chunked(HISTORY_PER_ROW).forEach { row -> + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) { + row.forEach { b -> + Column( + Modifier.weight(1f), horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Medal(badgeLook(b, face(b)), 72.dp) + Text(b.title, color = Color.White, style = GlowType.secondary, textAlign = TextAlign.Center, maxLines = 2) + } } + repeat(HISTORY_PER_ROW - row.size) { Box(Modifier.weight(1f)) } } - repeat(3 - row.size) { Box(Modifier.weight(1f)) } } } } } + +/** The badges history earned, three to a row. */ +private const val HISTORY_PER_ROW = 3 diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/ChooseScreen.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/ChooseScreen.kt index 4729d3de..ff351b9f 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/ChooseScreen.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/ChooseScreen.kt @@ -26,6 +26,7 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState @@ -494,7 +495,8 @@ private fun SearchField(query: String, hint: String, modifier: Modifier = Modifi } if (query.isNotEmpty()) Icon( AppIcons.X, stringResource(R.string.glow_choose_clear), tint = Color.White.copy(alpha = GlowType.SECONDARY_ALPHA), - modifier = Modifier.size(28.dp).clip(CircleShape).clickable { onChange("") }.padding(6.dp), + // 48 dp to tap, the mark drawn 16 dp as before, and moved out so it stays where it was. + modifier = Modifier.offset(x = 10.dp).size(48.dp).clip(CircleShape).clickable { onChange("") }.padding(16.dp), ) } }, diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowMetricDetail.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowMetricDetail.kt index 21cbdb07..59209844 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowMetricDetail.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowMetricDetail.kt @@ -5,7 +5,25 @@ import org.openstrap.app.presentation.TimeOfDay import org.openstrap.app.presentation.DayWords import org.openstrap.app.presentation.Units import androidx.activity.compose.BackHandler +import androidx.compose.animation.AnimatedContent +import androidx.compose.animation.ContentTransform +import androidx.compose.animation.EnterTransition +import androidx.compose.animation.ExitTransition +import androidx.compose.animation.SizeTransform +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.slideInVertically +import androidx.compose.animation.slideOutVertically +import androidx.compose.runtime.SideEffect +import androidx.compose.ui.unit.IntOffset +import kotlin.math.abs +import androidx.compose.animation.animateColorAsState +import androidx.compose.animation.core.Animatable +import androidx.compose.animation.core.tween import androidx.compose.foundation.background +import androidx.compose.runtime.LaunchedEffect +import org.openstrap.app.ui.components.Motion +import org.openstrap.app.ui.components.rememberAnimationsOn import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box @@ -124,6 +142,8 @@ internal fun siblings(detail: Detail, onSwitch: (Detail) -> Unit): List Unit)? = null, heroPicture: (@Composable () -> Unit)? = null, scrubbed: () -> DetailHeadline? = { null }, + headlineDay: LocalDate? = strip.firstOrNull { it.selected }?.date, body: LazyListScope.() -> Unit, ) { BackHandler(onBack = onBack) @@ -180,11 +201,12 @@ internal fun DetailTemplate( style = GlowType.pageTitle, ) Text( - shown.label, color = Color.White.copy(alpha = GlowType.SECONDARY_ALPHA), style = GlowType.secondary, + shown.label, color = Color.White.copy(alpha = GlowType.SECONDARY_ALPHA), + style = GlowType.secondary, ) } else -> Row(verticalAlignment = Alignment.Bottom) { - DotMatrixText(shown.value, Modifier.detailNumber(shown.value), dot = DotSize.Detail) + DayNumber(shown.value, headlineDay, Modifier.detailNumber(shown.value)) Text( shown.label, color = Color.White.copy(alpha = GlowType.SECONDARY_ALPHA), style = GlowType.secondary, modifier = Modifier.padding(start = 10.dp, bottom = 2.dp), @@ -204,7 +226,8 @@ internal fun DetailTemplate( } if (ranges.size > 1) item { GlowSegments( - ranges.map { it.label }, ranges.indexOf(range), { onRange(ranges[it]) }, Modifier.padding(top = 6.dp), role = Role.Tab, + ranges.map { it.label }, ranges.indexOf(range), { onRange(ranges[it]) }, Modifier.padding(top = 6.dp), + role = Role.Tab, ) } body() @@ -213,6 +236,120 @@ internal fun DetailTemplate( if (switching) SwitcherSheet(siblings, color, onDismiss = { switching = false }) } +/** + * The hero's figure in dots, moving to the next day's rather than cutting. A figure that is a plain number counts from + * the one shown to the new one, and when the two are close (a few points, which a count would only step through) it + * rolls instead, the old one sliding out as the new one slides in. Never from zero, and not with the system's + * animations off. + * + * [day] is the day [value] is for, which on a page that holds the last day's figures while the next day is worked out + * (Energy, Load) is the held day, not the one just picked: the figure and its day arrive together, however late. Only + * a change that comes with another day moves; a scrub or a live reading lands at once, and so does the first change on + * a day whose figure came in the same as the last day's. + */ +@Composable +internal fun DayNumber(value: String, day: LocalDate?, modifier: Modifier = Modifier) { + val animate = rememberAnimationsOn() + val parsed = remember(value) { PlainNumber.parse(value) } + val count = remember { Animatable(parsed?.number ?: 0f) } + val shown = remember { Shown(value, day, parsed?.number) } + val moving = day != shown.day && value != shown.text + val from = if (count.isRunning) count.value else shown.number + val to = parsed?.number + val step = stepOf(animate && moving, from, to) + SideEffect { + shown.text = value + shown.day = day + shown.number = to + if (step == Step.Count) shown.countFrom = from + } + LaunchedEffect(value, day) { + if (to == null) return@LaunchedEffect + if (step == Step.Count && from != null) { + count.snapTo(from) + count.animateTo(to, tween(COUNT_MS, easing = Motion.easing)) + } else { + count.snapTo(to) + } + shown.countFrom = null + } + val up = (to ?: 0f) > (from ?: 0f) + AnimatedContent( + targetState = value, modifier = modifier, label = "day number", + transitionSpec = { + if (step == Step.Roll) roll(up) else ContentTransform(EnterTransition.None, ExitTransition.None, sizeTransform = null) + }, + ) { text -> DotMatrixText(countedText(text, value, parsed, count, step, from, shown.countFrom), dot = DotSize.Detail) } +} + +/** + * What the figure reads this frame: the count while it runs. Until it starts, its starting figure, so the new day's + * number never shows for a frame before the count runs back up to it (2,500 to 4,500 read 4, then 2, then 4). + */ +private fun countedText( + text: String, value: String, parsed: PlainNumber?, count: Animatable, step: Step, from: Float?, waiting: Float?, +): String { + if (parsed == null || text != value) return text + val at = when { + count.isRunning -> count.value + step == Step.Count -> from + else -> waiting + } + return at?.let(parsed::write) ?: text +} + +/** How a figure gets to the next day's: at once, counting through the numbers between, or rolling when they're close. */ +private enum class Step { Land, Count, Roll } + +private fun stepOf(moving: Boolean, from: Float?, to: Float?): Step = when { + !moving || from == null || to == null -> Step.Land + abs(to - from) < ROLL_BELOW -> Step.Roll + else -> Step.Count +} + +/** The figure last shown, the day it was for, and the figure a count starts from while it waits to run. */ +private class Shown(var text: String, var day: LocalDate?, var number: Float?, var countFrom: Float? = null) + +/** The old figure slides out one way and the new one in from the other, up for a higher one, with a fade. */ +private fun roll(up: Boolean): ContentTransform { + val slide = tween(ROLL_MS, easing = Motion.easing) + val fade = tween(ROLL_MS, easing = Motion.easing) + val sign = if (up) 1 else -1 + return ContentTransform( + slideInVertically(slide) { sign * it / ROLL_TRAVEL } + fadeIn(fade), + slideOutVertically(slide) { -sign * it / ROLL_TRAVEL } + fadeOut(fade), + sizeTransform = SizeTransform(clip = false), + ) +} + +/** How long a figure takes to count to the next day's, and to roll; and a change under [ROLL_BELOW] rolls. */ +private const val COUNT_MS = 600 +private const val ROLL_MS = 320 +private const val ROLL_BELOW = 25f + +/** A roll travels a third of the figure's height. */ +private const val ROLL_TRAVEL = 3 + +/** A figure written as a plain number ("72", "8,432", "14.6"): its value, and how to write another like it. */ +private class PlainNumber(val number: Float, decimals: Int, grouped: Boolean) { + /** Made once, not on every frame of a count. Only the composition writes with it, on the main thread. */ + private val format = java.text.NumberFormat.getNumberInstance(Units.DOT_LOCALE).apply { + minimumFractionDigits = decimals + maximumFractionDigits = decimals + isGroupingUsed = grouped + } + + fun write(n: Float): String = format.format(n.toDouble()) + + companion object { + private val SHAPE = Regex("""^(\d{1,3}(,\d{3})+|\d+)(\.\d+)?$""") + + fun parse(text: String): PlainNumber? = + if (!SHAPE.matches(text)) null + else PlainNumber(text.replace(",", "").toFloat(), text.substringAfter('.', "").length, ',' in text) + } +} + /** The hero's tint: the metric's colour at the top fading to black, rounded at the foot, as wide as the screen. */ @Composable private fun DetailHero(color: Color, gutter: Dp, content: @Composable () -> Unit) { @@ -269,16 +406,23 @@ private fun WeekStrip(days: List, color: Color, onDay: (Loc Row(modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { days.forEach { d -> val show = stringResource(R.string.glow_metrics_show_day, d.label) + // The pill moves to the day tapped, and its dot comes and goes, rather than cutting. + val quick = tween(Motion.QUICK) + val pill by animateColorAsState( + if (d.selected) Color.White.copy(alpha = 0.10f) else Color.Transparent, quick, label = "day pill", + ) + val ink by animateColorAsState(if (d.selected) Color.White else Color.White.copy(alpha = 0.5f), quick, label = "day ink") + val dot by animateColorAsState(if (d.hasData) color else Color.Transparent, quick, label = "day dot") Column( Modifier.width(40.dp).clip(RoundedCornerShape(14.dp)) - .background(if (d.selected) Color.White.copy(alpha = 0.10f) else Color.Transparent) + .background(pill) .clickable(onClickLabel = show, role = Role.Button) { onDay(d.date) } .padding(vertical = 8.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(6.dp), ) { - Text(d.label, color = if (d.selected) Color.White else Color.White.copy(alpha = 0.5f), style = GlowType.secondary, maxLines = 1) - Box(Modifier.size(5.dp).background(if (d.hasData) color else Color.Transparent, CircleShape)) + Text(d.label, color = ink, style = GlowType.secondary, maxLines = 1) + Box(Modifier.size(5.dp).background(dot, CircleShape)) } } } diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/GoalsAndBests.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/GoalsAndBests.kt index 11e07450..660dee66 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/GoalsAndBests.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/GoalsAndBests.kt @@ -8,6 +8,7 @@ import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.Text @@ -20,7 +21,6 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.runtime.remember -import androidx.compose.foundation.layout.height import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.contentDescription @@ -30,7 +30,7 @@ import androidx.compose.ui.unit.dp import java.time.Instant import java.time.LocalDate import java.time.ZoneId -import java.time.format.TextStyle +import java.time.format.TextStyle as DayStyle import java.util.Locale import org.openstrap.app.R import org.openstrap.app.data.Rewards @@ -45,21 +45,19 @@ import org.openstrap.app.ui.glow.draw.level /* * The Goals and bests page from You (workouts spec 3.5, board AchievementsV1), All badges, and the weekly recap the - * Monday notification opens (board WeeklyRecap). + * Monday notification opens (board WeeklyRecap). The pages show each best and badge as its medal ([Medal]) with only + * its name and figure; a tap opens its sheet, with what it is, when it was earned and how far along a locked one is. */ /** The goal colour: met weeks, the goal moment. */ private val GoalColor = MetricColors.good -/** What a badge's art reads on these pages: the first weekly goal shows the goal it was met at, or this week's while locked. */ -private fun RewardsView.face(b: Rewards.Badge): String = - earned.firstOrNull { it.id == b.id }?.let { RewardsCopy.face(b, Rewards.goalAt(it, weeks, firstDay, ZoneId.systemDefault())) } - ?: RewardsCopy.face(b, goal) - /** The days of [first]'s week, each a letter and whether a workout in [view] counted on it. */ private fun weekDots(view: RewardsView, first: LocalDate, zone: ZoneId = ZoneId.systemDefault()): List> { val days = view.counted.map { Instant.ofEpochSecond(it.shownStart).atZone(zone).toLocalDate() }.toSet() - return (0L until 7L).map { first.plusDays(it).let { d -> d.dayOfWeek.getDisplayName(TextStyle.NARROW, Locale.getDefault()) to (d in days) } } + return (0L until 7L).map { i -> + first.plusDays(i).let { d -> d.dayOfWeek.getDisplayName(DayStyle.NARROW, Locale.getDefault()) to (d in days) } + } } /** @@ -99,6 +97,10 @@ private const val MAX_GOAL_SHOWN = 14 /** A week's distance shows from a tenth of a km, the first the figure can write. */ private const val MIN_WEEK_METERS = 100f +/** All badges: three medals to a row, 8 dp apart. */ +private const val ALL_PER_ROW = 3 +private val ALL_GAP = 8.dp + /** * The share card for the week from [first]: the count against the goal, its days, the hours, km and active kcal, and * chips for the weeks in a row and the week's first best. @@ -156,7 +158,9 @@ fun WeeklyGoalSheet(goal: Int, onSave: (Int) -> Unit, onDismiss: () -> Unit) { /** * Goals and bests (board AchievementsV1): this week against the goal with the weeks in a row and the best run, the - * personal bests, the badges earned with the next one to earn, and the ways on. + * personal bests as rosettes, the next badge to earn and how far along, the badges earned as medals, and the ways on. + * Each best and badge opens its sheet. Before any workout there's still a page: the week at nought, the bests and + * badges there are to go for. */ @Composable fun GoalsAndBestsPage( @@ -169,6 +173,8 @@ fun GoalsAndBestsPage( onBack: () -> Unit, ) { BackHandler(onBack = onBack) + var openBadge by rememberSaveable { mutableStateOf(null) } + var openBest by rememberSaveable { mutableStateOf(null) } ScreenList(contentPadding, gutter = GlowLayout.Gutter) { item { PageHeader(stringResource(R.string.glow_goals_title), onBack) } if (view == null) { @@ -182,99 +188,58 @@ fun GoalsAndBestsPage( RewardsCopy.runLine(view.inARow, view.bestRun), bar = true, ) { PageButton(stringResource(R.string.glow_goals_goal_button, view.goal), onGoal, icon = AppIcons.PencilEdit) } } - item { - ListPanel(title = stringResource(R.string.glow_goals_personal_bests)) { - val shown = view.bests.sortedBy { order(it.kind) } - if (shown.isEmpty()) Text( - stringResource(R.string.glow_goals_no_bests), color = Color.White.copy(alpha = GlowType.SECONDARY_ALPHA), - style = GlowType.secondary, modifier = Modifier.padding(vertical = 10.dp), - ) - shown.forEachIndexed { i, b -> - ListRow( - RewardsCopy.bestTitle(b.kind), BestColor, RewardsCopy.bestValue(b.kind, b.value), shortDate(b.date), divider = i > 0, - icon = AppIcons.FlagCheckered, - ) - } - } - } - item { - val earned = view.earned.sortedByDescending { it.earnedAt }.take(5).mapNotNull { r -> Rewards.badge(r.id)?.let { it to shortDate(r.earnedAt) } } - val next = view.next?.let { b -> view.progress[b.id]?.let { (have, need) -> b to RewardsCopy.progressLine(have, need, b.unit) } } - Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { - Text( - stringResource(R.string.glow_goals_badges_count, view.earned.size, Rewards.BADGES.size), - color = Color.White.copy(alpha = GlowType.SECONDARY_ALPHA), style = GlowType.secondary, - modifier = Modifier.padding(start = 4.dp, top = 6.dp), - ) - // The last three earned and the next one, so the row is always four. - BadgeRow(earned.take(if (next != null) 3 else 4) + listOfNotNull(next), locked = { b -> view.earned.none { it.id == b.id } }, face = view::face) - } - } - item { - Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { - PageButton( - stringResource(R.string.glow_goals_all_badges), onAllBadges, Modifier.fillMaxWidth(), icon = AppIcons.CheckCircle, - ) - PageButton(stringResource(R.string.glow_goals_last_week), onRecap, Modifier.fillMaxWidth(), icon = AppIcons.CalendarBlank) - PageButton( - stringResource(R.string.glow_goals_celebrations), onCelebrations, Modifier.fillMaxWidth(), - icon = AppIcons.SlidersHorizontal, - ) - } - } + item { BestsPanel(view, onOpen = { openBest = it }) } + view.next?.let { next -> item { NextBadgeCard(next, view, onOpen = { openBadge = it.id }) } } + item { BadgesPanel(view, onOpen = { openBadge = it.id }, onAllBadges = onAllBadges) } + item { WaysOn(onAllBadges, onRecap, onCelebrations) } + } + if (view != null) { + openBadge?.let(Rewards::badge)?.let { b -> BadgeSheet(b, view, onDismiss = { openBadge = null }) } + openBest?.let { kind -> BestSheet(kind, view, onDismiss = { openBest = null }) } } } -/** Bests in a fixed order: runs, then the longest workout, lifts, steps. */ -private fun order(kind: String): Int = Rewards.Kind.fastestMeters(kind) - ?: when { - kind == Rewards.Kind.LONGEST_RUN -> 100_000 - kind == Rewards.Kind.LONGEST_WORKOUT -> 100_001 - Rewards.Kind.liftName(kind) != null -> 100_002 - else -> 100_003 +/** All badges, last week's recap and the celebration settings, as rows in one panel. */ +@Composable +private fun WaysOn(onAllBadges: () -> Unit, onRecap: () -> Unit, onCelebrations: () -> Unit) { + PageRows { + PageRow(stringResource(R.string.glow_goals_all_badges), onClick = onAllBadges, icon = AppIcons.CheckCircle, divider = false) + PageRow(stringResource(R.string.glow_goals_last_week), onClick = onRecap, icon = AppIcons.CalendarBlank) + PageRow(stringResource(R.string.glow_goals_celebrations), onClick = onCelebrations, icon = AppIcons.SlidersHorizontal) } - -/** "30 Oct", or "30 Oct 2025" in another year. */ -private fun shortDate(epoch: Long): String { - val d = Instant.ofEpochSecond(epoch).atZone(ZoneId.systemDefault()).toLocalDate() - return if (d.year == LocalDate.now().year) DayWords.dayMonth(d) else DayWords.dayMonthYear(d) } -/** Every badge by group: earned ones in colour with their date, locked ones dim with what they need. */ +/** + * Every badge by group, three medals to a row with only their names: earned ones lit, locked ones quiet with a bar for + * how far along. Each opens its sheet. + */ @Composable fun AllBadgesPage(view: RewardsView?, contentPadding: PaddingValues, onBack: () -> Unit) { BackHandler(onBack = onBack) + var open by rememberSaveable { mutableStateOf(null) } ScreenList(contentPadding, gutter = GlowLayout.Gutter) { item { val subtitle = view?.let { stringResource(R.string.glow_goals_earned_count, it.earned.size, Rewards.BADGES.size) } PageHeader(stringResource(R.string.glow_goals_all_badges), onBack, subtitle = subtitle) } if (view == null) return@ScreenList - val earned = view.earned.associateBy { it.id } Rewards.Group.entries.forEach { group -> item { Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { - Text( - stringResource( - when (group) { - Rewards.Group.Firsts -> R.string.glow_goals_group_firsts - Rewards.Group.Milestones -> R.string.glow_goals_group_milestones - Rewards.Group.Weekly -> R.string.glow_goals_weekly_goal - Rewards.Group.Kinds -> R.string.glow_goals_group_kinds - }, - ), - color = Color.White.copy(alpha = GlowType.SECONDARY_ALPHA), style = GlowType.secondary, modifier = Modifier.padding(start = 4.dp, top = 6.dp), - ) - BadgeGrid( - Rewards.BADGES.filter { it.group == group }.map { b -> - b to (earned[b.id]?.let { shortDate(it.earnedAt) } ?: view.progress[b.id]?.let { (have, need) -> RewardsCopy.progressLine(have, need, b.unit) }) - }, - locked = { it.id !in earned }, face = view::face, - ) + SectionLabel(groupName(group), Modifier.padding(top = 6.dp)) + QuietPanel { + Rewards.BADGES.filter { it.group == group }.chunked(ALL_PER_ROW).forEach { row -> + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(ALL_GAP)) { + row.forEach { b -> BadgeCell(b, view, { open = it.id }, GlowType.secondary, Modifier.weight(1f)) } + repeat(ALL_PER_ROW - row.size) { Spacer(Modifier.weight(1f)) } + } + } + } } } } } + if (view != null) open?.let(Rewards::badge)?.let { b -> BadgeSheet(b, view, onDismiss = { open = null }) } } /** diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/MedalDrawing.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/MedalDrawing.kt new file mode 100644 index 00000000..a37d1ddc --- /dev/null +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/MedalDrawing.kt @@ -0,0 +1,275 @@ +package org.openstrap.app.ui.glow + +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.StrokeCap +import androidx.compose.ui.graphics.StrokeJoin +import androidx.compose.ui.graphics.drawscope.DrawScope +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.graphics.drawscope.rotate +import androidx.compose.ui.graphics.drawscope.scale +import androidx.compose.ui.graphics.lerp +import androidx.compose.ui.graphics.vector.PathParser +import androidx.compose.ui.unit.dp +import org.openstrap.app.ui.glow.draw.GlowPalette +import org.openstrap.app.ui.glow.draw.GlowStyle +import kotlin.math.PI +import kotlin.math.cos +import kotlin.math.sin + +/* + * How a medal ([Medal]) is drawn: its outline for each group, the face lit from below as a glow card is, the laurel and + * the rosette's edge, and the line pictures. On a frame [FRAME] units across, the pictures on [EMBLEM_FRAME]. + */ + +/** A medal's outline: the group's shape, with where its face starts and ends on the frame, and its picture's room. */ +internal enum class MedalShape(val top: Float, val bottom: Float, val content: Float) { + /** Firsts: a round medal. */ + Round(ROUND_TOP, ROUND_BOTTOM, ROUND_CONTENT), + + /** Milestones: a hexagon, a count reached. */ + Hex(HEX_TOP, HEX_BOTTOM, HEX_CONTENT), + + /** The weekly goal: a round medal in a laurel, weeks kept up. */ + Laurel(LAUREL_TOP, LAUREL_BOTTOM, LAUREL_CONTENT), + + /** Something new: a soft square. */ + Soft(SOFT_TOP, SOFT_BOTTOM, SOFT_CONTENT), + + /** A personal best: a rosette, its edge scalloped. */ + Rosette(ROSETTE_TOP, ROSETTE_BOTTOM, ROSETTE_CONTENT), +} + +/** A medal's tones from its ink, by the glow cards' formula: the light at the foot, the body, the core, the picture. */ +internal class MedalTones(ink: Color) { + private val palette = GlowPalette(GlowStyle(color = ink)) + val light: Color = palette.light + val body: Color = palette.mid + val core: Color = palette.core + val mark: Color = lerp(Color.White, palette.light, MARK_TINT) +} + +/** The medal on the frame: the laurel or rosette's edge behind, then the face, lit or quiet, and its inner ring. */ +internal fun DrawScope.drawFrame(shape: MedalShape, tones: MedalTones, locked: Boolean, lit: Float) { + val face = faceOf(shape) + when (shape) { + MedalShape.Laurel -> drawLaurel(if (locked) LockedRim else tones.light) + MedalShape.Rosette -> drawRosetteEdge(tones, locked) + else -> Unit + } + if (locked) { + drawPath(face, LockedFill) + drawPath(face, LockedRim, style = Stroke(RIM_LINE)) + } else { + drawLitFace(shape, face, tones, lit.coerceIn(0f, 1f)) + } + // The second ring just inside the rim, as a struck medal has. + scale(INNER_RING, pivot = Offset(MID, MID)) { + drawPath(face, if (locked) LockedInner else tones.light.copy(alpha = INNER_ALPHA), style = Stroke(INNER_LINE / INNER_RING)) + } +} + +/** + * [e] filling this scope, in [color]: its filled parts, then its lines. The lines grow with the picture up to + * [EMBLEM_LINE_MAX], so a large medal (a sheet, the best card) keeps fine line art rather than heavy strokes. + */ +internal fun DrawScope.drawEmblem(e: Emblem, color: Color) { + val k = size.width / EMBLEM_FRAME + val line = Stroke(minOf(EMBLEM_LINE_WIDTH, EMBLEM_LINE_MAX.toPx() / k), cap = StrokeCap.Round, join = StrokeJoin.Round) + scale(k, pivot = Offset.Zero) { + e.fill?.let { drawPath(it, color) } + e.stroke?.let { drawPath(it, color, style = line) } + } +} + +/** SVG path data as a path. */ +internal fun parsePath(d: String): Path = PathParser().parsePathString(d).toPath() + +/** + * The face lit from below, as a glow card is: the light colour at the foot, melting into the body and on into the dark + * core at the top, a soft sheen at the upper left, and the hairline bright at the top (its gloss) and lit at the foot. + */ +private fun DrawScope.drawLitFace(shape: MedalShape, face: Path, tones: MedalTones, lit: Float) { + val height = shape.bottom - shape.top + drawPath( + face, + Brush.radialGradient( + 0f to lerp(tones.body, tones.light, lit), + LIGHT_REACH to tones.body, + CORE_FROM to tones.core, + center = Offset(MID, shape.bottom + LIGHT_BELOW), + radius = height + LIGHT_BELOW, + ), + ) + drawPath( + face, + Brush.radialGradient( + listOf(Color.White.copy(alpha = SHEEN_ALPHA), Color.Transparent), + center = Offset(SHEEN_X, shape.top + height * SHEEN_Y), + radius = height * SHEEN_RADIUS, + ), + ) + drawPath( + face, + Brush.verticalGradient( + 0f to Color.White.copy(alpha = GLOSS_ALPHA), 1f to tones.light.copy(alpha = lit), + startY = shape.top, endY = shape.bottom, + ), + style = Stroke(RIM_LINE), + ) +} + +/** The laurel round the weekly goal's medal: a stem up each side with its leaves, smaller toward the top. */ +private fun DrawScope.drawLaurel(color: Color) { + val stem = Stroke(STEM_LINE, cap = StrokeCap.Round) + val ring = Offset(MID - LAUREL_RADIUS, MID - LAUREL_RADIUS) + val across = Size(LAUREL_RADIUS * 2, LAUREL_RADIUS * 2) + drawArc(color, DOWN + LAUREL_FROM - STEM_LEAD, LAUREL_SPAN, false, ring, across, style = stem) + drawArc(color, DOWN - LAUREL_FROM + STEM_LEAD - LAUREL_SPAN, LAUREL_SPAN, false, ring, across, style = stem) + for (side in SIDES) { + for (i in 0 until LEAVES) { + val degrees = DOWN + side * (LAUREL_FROM + i * LAUREL_STEP) + val radians = degrees * PI / HALF_TURN + val c = Offset(MID + LAUREL_RADIUS * cos(radians).toFloat(), MID + LAUREL_RADIUS * sin(radians).toFloat()) + val k = 1f - i * LEAF_SHRINK + rotate(degrees + QUARTER_TURN + side * LEAF_TILT, pivot = c) { + drawOval(color, Offset(c.x - LEAF_LENGTH * k / 2, c.y - LEAF_WIDTH * k / 2), Size(LEAF_LENGTH * k, LEAF_WIDTH * k)) + } + } + } +} + +/** A best's rosette: the scalloped edge round its face, a step darker than the face's body. */ +private fun DrawScope.drawRosetteEdge(tones: MedalTones, locked: Boolean) { + if (locked) { + drawPath(RosetteEdge, LockedFill) + drawPath(RosetteEdge, LockedRim, style = Stroke(RIM_LINE)) + } else { + drawPath(RosetteEdge, lerp(tones.core, tones.body, EDGE_BODY)) + drawPath(RosetteEdge, tones.light.copy(alpha = EDGE_RIM), style = Stroke(RIM_LINE)) + } +} + +private fun faceOf(shape: MedalShape): Path = when (shape) { + MedalShape.Round -> RoundFace + MedalShape.Hex -> HexFace + MedalShape.Laurel -> LaurelFace + MedalShape.Soft -> SoftFace + MedalShape.Rosette -> RosetteFace +} + +private fun circle(radius: Float): Path = Path().apply { addOval(Rect(Offset(MID, MID), radius)) } + +/** The rosette's outline: a circle whose radius rises and falls [ROSETTE_POINTS] times round. */ +private fun rosette(): Path = Path().apply { + for (i in 0..ROSETTE_STEPS) { + val t = 2 * PI * i / ROSETTE_STEPS + val r = ROSETTE_RADIUS + ROSETTE_WAVE * cos(ROSETTE_POINTS * t) + val x = MID + (r * cos(t)).toFloat() + val y = MID + (r * sin(t)).toFloat() + if (i == 0) moveTo(x, y) else lineTo(x, y) + } + close() +} + +private val RoundFace: Path by lazy { circle(ROUND_RADIUS) } +private val LaurelFace: Path by lazy { circle(LAUREL_FACE_RADIUS) } +private val RosetteFace: Path by lazy { circle(ROSETTE_FACE_RADIUS) } +private val RosetteEdge: Path by lazy { rosette() } + +/** A hexagon standing on a point, its corners rounded. */ +private val HexFace: Path by lazy { + parsePath( + "M55.2 6 L85.5 23.5 Q90.7 26.5 90.7 32.5 V67.5 Q90.7 73.5 85.5 76.5 L55.2 94 Q50 97 44.8 94 L14.5 76.5 " + + "Q9.3 73.5 9.3 67.5 V32.5 Q9.3 26.5 14.5 23.5 L44.8 6 Q50 3 55.2 6 Z", + ) +} + +/** A square with its sides bowed out, between a square and a circle. */ +private val SoftFace: Path by lazy { + parsePath("M50 5 C82 5 95 18 95 50 C95 82 82 95 50 95 C18 95 5 82 5 50 C5 18 18 5 50 5 Z") +} + +/** A medal still to earn: a faint face and hairline, its inner ring fainter. */ +private val LockedFill = Color.White.copy(alpha = 0.045f) +private val LockedRim = Color.White.copy(alpha = 0.16f) +private val LockedInner = Color.White.copy(alpha = 0.07f) + +/** The laurel's two sides: right (toward lower angles from the foot) and left. */ +private val SIDES = intArrayOf(-1, 1) + +/** The frame a medal is drawn on, units across, and its middle. */ +internal const val FRAME = 100f +private const val MID = 50f +private const val EMBLEM_FRAME = 24f +private const val EMBLEM_LINE_WIDTH = 1.6f + +/** The picture's lines are never drawn thicker than this, however large the medal. */ +private val EMBLEM_LINE_MAX = 2.4.dp + +private const val ROUND_RADIUS = 46f +private const val ROUND_TOP = MID - ROUND_RADIUS +private const val ROUND_BOTTOM = MID + ROUND_RADIUS +private const val ROUND_CONTENT = 0.8f +private const val HEX_TOP = 3f +private const val HEX_BOTTOM = 97f +private const val HEX_CONTENT = 0.74f +private const val SOFT_TOP = 5f +private const val SOFT_BOTTOM = 95f +private const val SOFT_CONTENT = 0.78f +private const val LAUREL_FACE_RADIUS = 34f +private const val LAUREL_TOP = MID - LAUREL_FACE_RADIUS +private const val LAUREL_BOTTOM = MID + LAUREL_FACE_RADIUS +private const val LAUREL_CONTENT = 0.6f +private const val ROSETTE_FACE_RADIUS = 36f +private const val ROSETTE_TOP = MID - ROSETTE_FACE_RADIUS +private const val ROSETTE_BOTTOM = MID + ROSETTE_FACE_RADIUS +private const val ROSETTE_CONTENT = 0.58f + +/** The rosette's edge: its mean radius, how far it rises and falls, how many times round, and how finely drawn. */ +private const val ROSETTE_RADIUS = 46.5 +private const val ROSETTE_WAVE = 2.6 +private const val ROSETTE_POINTS = 16 +private const val ROSETTE_STEPS = 160 +private const val EDGE_BODY = 0.55f +private const val EDGE_RIM = 0.7f + +/** The laurel: its radius, the leaves from the foot up each side, their size and lean, and the stems under them. */ +private const val LAUREL_RADIUS = 42.5f +private const val LEAVES = 6 +private const val LAUREL_FROM = 26f +private const val LAUREL_STEP = 24f +private const val LAUREL_SPAN = 132f +private const val STEM_LEAD = 8f +private const val STEM_LINE = 1.1f +private const val LEAF_LENGTH = 10f +private const val LEAF_WIDTH = 4.4f +private const val LEAF_SHRINK = 0.07f +private const val LEAF_TILT = 22f +private const val DOWN = 90f +private const val QUARTER_TURN = 90f +private const val HALF_TURN = 180.0 + +/** + * The light: where it melts into the body and the core, and how far below the face it comes from. It reaches only the + * foot, so a label under the picture sits in the body, as text sits in the dark on a glow card (spec 2.1). + */ +private const val LIGHT_REACH = 0.27f +private const val CORE_FROM = 0.92f +private const val LIGHT_BELOW = 6f +private const val SHEEN_ALPHA = 0.09f +private const val SHEEN_X = 36f +private const val SHEEN_Y = 0.26f +private const val SHEEN_RADIUS = 0.42f +private const val GLOSS_ALPHA = 0.55f +private const val RIM_LINE = 1.6f +private const val INNER_RING = 0.87f +private const val INNER_LINE = 1f +private const val INNER_ALPHA = 0.32f + +/** How far the picture is from white toward the light colour: near white, with the medal's hue. */ +private const val MARK_TINT = 0.18f diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/Medals.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/Medals.kt new file mode 100644 index 00000000..08c9f678 --- /dev/null +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/Medals.kt @@ -0,0 +1,292 @@ +package org.openstrap.app.ui.glow + +import androidx.compose.animation.core.Animatable +import androidx.compose.animation.core.tween +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.size +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.Immutable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.drawscope.scale +import androidx.compose.ui.layout.layout +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.Constraints +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import kotlin.math.roundToInt +import org.openstrap.app.data.Rewards +import org.openstrap.app.presentation.RewardsCopy +import org.openstrap.app.ui.components.Motion +import org.openstrap.app.ui.components.rememberAnimationsOn + +/* + * The badges and personal bests as struck medals, in the glow language: the face lit from below like a glow card, + * melting from the light colour into the body and the dark core, with the 1 dp hairline and its gloss (spec 2.1). The + * tones come from the ink by the cards' own formula ([MedalTones]), so a badge reads as the same light as a card of + * its colour. Each group has its own outline as well as its colour, so a collection reads at a glance, and each badge + * its own line picture. A medal still to earn is drawn quiet: no light, the picture faint. How it's drawn is in + * MedalDrawing.kt. + */ + +/** A line picture on a 24 unit frame: [strokeData] drawn as lines, [fillData] filled, both SVG path data. */ +@Immutable +internal class Emblem(private val strokeData: String?, private val fillData: String? = null) { + val stroke: Path? by lazy { strokeData?.let(::parsePath) } + val fill: Path? by lazy { fillData?.let(::parsePath) } +} + +/** What a medal shows: its [shape] and [ink], the line picture in its middle and the few characters under it. */ +@Immutable +internal class MedalLook(val shape: MedalShape, val ink: Color, val emblem: Emblem?, val label: String?) + +/** The line pictures, one for each kind of badge and best. */ +internal object Emblems { + /** The first workout: the sun coming up. */ + val Sunrise = Emblem( + "M3 17 H21 M7.5 17 A4.5 4.5 0 0 1 16.5 17 M12 7.5 V9.5 M6.3 10.3 L7.7 11.7 M17.7 10.3 L16.3 11.7 " + + "M3.5 13.5 H5.5 M18.5 13.5 H20.5 M8.5 20 H15.5", + ) + + /** Steps: two footprints, one ahead of the other. */ + val Steps = Emblem( + null, + "M8 3.5 C9.9 3.5 10.7 5.5 10.5 7.9 C10.3 10.3 9.5 12 8 12 C6.5 12 5.7 10.3 5.5 7.9 C5.3 5.5 6.1 3.5 8 3.5 Z " + + "M8 13.6 C9.1 13.6 9.7 14.4 9.7 15.4 C9.7 16.4 9.1 17.1 8 17.1 C6.9 17.1 6.3 16.4 6.3 15.4 C6.3 14.4 6.9 13.6 8 13.6 Z " + + "M16 7 C17.9 7 18.7 9 18.5 11.4 C18.3 13.8 17.5 15.5 16 15.5 C14.5 15.5 13.7 13.8 13.5 11.4 C13.3 9 14.1 7 16 7 Z " + + "M16 17.1 C17.1 17.1 17.7 17.9 17.7 18.9 C17.7 19.9 17.1 20.6 16 20.6 C14.9 20.6 14.3 19.9 14.3 18.9 " + + "C14.3 17.9 14.9 17.1 16 17.1 Z", + ) + + /** The workout counts as ranks, one chevron more at each, and a star at the last. */ + val RankOne = Emblem("M6.5 13.5 L12 9.5 L17.5 13.5") + val RankTwo = Emblem("M6.5 11 L12 7 L17.5 11 M6.5 16 L12 12 L17.5 16") + val RankThree = Emblem("M6.5 8.5 L12 4.5 L17.5 8.5 M6.5 13.5 L12 9.5 L17.5 13.5 M6.5 18.5 L12 14.5 L17.5 18.5") + val Star = Emblem("M12 3.8 L14.5 9 L20.2 9.7 L16 13.6 L17.1 19.2 L12 16.4 L6.9 19.2 L8 13.6 L3.8 9.7 L9.5 9 Z") + + /** Distance: a road winding off to a flag. */ + val Road = Emblem("M7 21 C7 16.5 17 16.5 17 12 C17 8.5 12.5 7.5 12.5 5 M12.5 5 V1.8 M12.5 2 H16.5 L15.5 3.3 L16.5 4.6 H12.5") + + /** The first weekly goal: a tick. */ + val Check = Emblem("M5.5 12.5 L10 17 L18.5 7.5") + + /** The first run: a runner in stride. */ + val Runner = Emblem( + "M14 7.6 L11.6 13 M13.7 8.4 L16.6 10.6 L18.6 9.2 M13.7 8.4 L10.6 9.6 L8.6 11.8 M11.6 13 L14.6 15.6 L13.6 20.4 " + + "M11.6 13 L9.6 16.6 L6.2 16.2", + "M13.1 4.5 A1.9 1.9 0 1 0 16.9 4.5 A1.9 1.9 0 1 0 13.1 4.5 Z", + ) + + /** A distance run in one go: the chequered flag. */ + val Finish = Emblem("M6 21 V3.5 M6 4 H18 V12.5 H6", "M6 4 H10 V8.25 H6 Z M14 4 H18 V8.25 H14 Z M10 8.25 H14 V12.5 H10 Z") + + /** Indoors: a roof over a beating heart's line. */ + val Indoor = Emblem("M3.5 11 L12 4 L20.5 11 M5.5 9.5 V20 H18.5 V9.5 M7.5 15 H9.8 L11 12.4 L13 17.6 L14.2 15 H16.5") + + /** Strength: a barbell with its plates. */ + val Barbell = Emblem("M2.5 12 H21.5 M5.5 8.5 V15.5 M8 6.5 V17.5 M16 6.5 V17.5 M18.5 8.5 V15.5") + + /** Tabata: a stopwatch with its work slice lit. */ + val Interval = Emblem( + "M12 21 A7.5 7.5 0 1 0 12 6 A7.5 7.5 0 1 0 12 21 Z M10 2.5 H14 M12 2.5 V6", + "M12 13.5 L12 6 A7.5 7.5 0 0 1 18.5 9.75 Z", + ) + + /** Run intervals: laps of a track. */ + val Track = Emblem( + "M8 6 H16 A6 6 0 0 1 16 18 H8 A6 6 0 0 1 8 6 Z M8.5 9.5 H15.5 A2.5 2.5 0 0 1 15.5 14.5 H8.5 " + + "A2.5 2.5 0 0 1 8.5 9.5 Z M12 6 V9.5", + ) + + /** Yoga and calm: a lotus. */ + val Lotus = Emblem( + "M12 5 C14.6 8 14.6 13 12 16.5 C9.4 13 9.4 8 12 5 Z M12 16.5 C8.6 16.5 5.2 14.4 4.2 10.5 C7.8 10.5 10.6 12.6 12 16.5 Z " + + "M12 16.5 C15.4 16.5 18.8 14.4 19.8 10.5 C16.2 10.5 13.4 12.6 12 16.5 Z M6.5 19.5 H17.5", + ) + + /** Games and sports: a ball with its seams. */ + val Ball = Emblem( + "M12 20 A8 8 0 1 0 12 4 A8 8 0 1 0 12 20 Z M4 12 H20 M12 4 V20 M6.4 6.4 C8.9 9.4 8.9 14.6 6.4 17.6 " + + "M17.6 6.4 C15.1 9.4 15.1 14.6 17.6 17.6", + ) + + /** The longest workout: an hourglass, its sand fallen. */ + val Hourglass = Emblem( + "M6.5 3 H17.5 M6.5 21 H17.5 M8 3 C8 8 12 9.5 12 12 C12 14.5 8 16 8 21 M16 3 C16 8 12 9.5 12 12 C12 14.5 16 16 16 21", + "M9.4 19.6 C10.2 17.4 11.5 16.6 12 16.6 C12.5 16.6 13.8 17.4 14.6 19.6 Z M10.2 7 H13.8 C13.4 8.4 12.6 9.3 12 9.8 " + + "C11.4 9.3 10.6 8.4 10.2 7 Z", + ) + + /** The fastest stretches: a stopwatch. */ + val Stopwatch = Emblem( + "M12 21 A7.5 7.5 0 1 0 12 6 A7.5 7.5 0 1 0 12 21 Z M10 2.5 H14 M12 2.5 V6 M17.6 7.2 L19.2 5.6 M12 13.5 L15 10.5", + ) +} + +/** Each badge's line picture, by id. The weekly runs have none: their number, in the laurel, is the picture. */ +private val BADGE_EMBLEMS: Map = mapOf( + "first_workout" to Emblems.Sunrise, + "first_10k_steps" to Emblems.Steps, + "workouts_10" to Emblems.RankOne, + "workouts_50" to Emblems.RankTwo, + "workouts_100" to Emblems.RankThree, + "workouts_500" to Emblems.Star, + "km_100" to Emblems.Road, + "km_500" to Emblems.Road, + "km_1000" to Emblems.Road, + "steps_1m" to Emblems.Steps, + "goal_first" to Emblems.Check, + "first_run" to Emblems.Runner, + "first_5k" to Emblems.Finish, + "first_10k" to Emblems.Finish, + "first_indoor" to Emblems.Indoor, + "first_log" to Emblems.Barbell, + "first_tabata" to Emblems.Interval, + "first_reps" to Emblems.Track, + "first_mind" to Emblems.Lotus, + "first_game" to Emblems.Ball, +) + +/** The badges whose art carries their number or distance under the picture ("10", "1000", "5K"). */ +private val LABELLED_BADGES = setOf( + "first_10k_steps", "workouts_10", "workouts_50", "workouts_100", "workouts_500", "km_100", "km_500", "km_1000", + "steps_1m", "goal_4", "goal_12", "goal_26", "goal_52", "first_5k", "first_10k", +) + +private const val GOAL_FIRST = "goal_first" + +private fun shapeOf(group: Rewards.Group): MedalShape = when (group) { + Rewards.Group.Firsts -> MedalShape.Round + Rewards.Group.Milestones -> MedalShape.Hex + Rewards.Group.Weekly -> MedalShape.Laurel + Rewards.Group.Kinds -> MedalShape.Soft +} + +/** + * [b]'s medal, its art reading [face] ([RewardsCopy.face]). The first weekly goal shows the goal it was met at ("3/3") + * in place of its tick when there is one. + */ +internal fun badgeLook(b: Rewards.Badge, face: String): MedalLook { + val goalShown = b.id == GOAL_FIRST && '/' in face + val emblem = if (goalShown) null else BADGE_EMBLEMS[b.id] + val label = face.takeIf { goalShown || b.id in LABELLED_BADGES } + return MedalLook(shapeOf(b.group), badgeColor(b.group), emblem, label) +} + +/** A personal best of [kind] as a rosette in the best's gold, a fastest stretch with its distance under ("5K", "HM"). */ +internal fun bestLook(kind: String): MedalLook { + val fastest = Rewards.Kind.fastestMeters(kind) != null + val emblem = when { + fastest -> Emblems.Stopwatch + Rewards.Kind.liftName(kind) != null -> Emblems.Barbell + kind == Rewards.Kind.LONGEST_RUN -> Emblems.Road + kind == Rewards.Kind.MOST_STEPS -> Emblems.Steps + else -> Emblems.Hourglass + } + return MedalLook(MedalShape.Rosette, BestColor, emblem, RewardsCopy.bestShort(kind).takeIf { fastest }) +} + +/** + * A medal [diameter] across: the [look]'s outline and lit face, its picture and label. [locked] draws it quiet, still + * to earn. [lit] (0..1) is how far its light has risen, read only while drawing, so a medal can light up as its sheet + * opens ([rememberLightRise]) without composing again. + */ +@Composable +internal fun Medal(look: MedalLook, diameter: Dp, modifier: Modifier = Modifier, locked: Boolean = false, lit: () -> Float = { 1f }) { + val tones = remember(look.ink) { MedalTones(look.ink) } + Box(modifier.size(diameter), contentAlignment = Alignment.Center) { + Canvas(Modifier.matchParentSize()) { + scale(this.size.width / FRAME, pivot = Offset.Zero) { drawFrame(look.shape, tones, locked, lit()) } + } + MedalContent(look, diameter * look.shape.content, if (locked) LockedMark else tones.mark, if (locked) LockedLabel else Color.White) + } +} + +/** + * The picture over the label, centred on the face, the picture sized from the face's room [box]. The label takes a type + * role (spec 2.3) by the medal's size and whether it stands alone, and scales down to the face's width when it's + * longer than the face holds ("14/14"). + */ +@Composable +private fun MedalContent(look: MedalLook, box: Dp, mark: Color, text: Color) { + val emblemShare = if (look.label != null) EMBLEM_OVER_LABEL else EMBLEM_ALONE + val large = box >= LARGE_FACE + // Under a picture the label is a caption to it, a size down; on its own (the weeks in a row) it is the picture. + val style = when { + look.emblem == null -> if (large) GlowType.goalValue else GlowType.headerDate + else -> if (large) GlowType.smallValue else GlowType.secondary.copy(fontWeight = FontWeight.SemiBold) + } + // Under a picture the label sits low, where a round face narrows, so it keeps to less of the width there. + val room = box * if (look.emblem != null) LABEL_ROOM_UNDER else LABEL_ROOM_ALONE + Column( + Modifier.size(box), horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(box * LABEL_GAP, Alignment.CenterVertically), + ) { + look.emblem?.let { e -> Canvas(Modifier.size(box * emblemShare)) { drawEmblem(e, mark) } } + look.label?.let { label -> + Text( + label, Modifier.fitWidth(room), color = text, maxLines = 1, softWrap = false, + style = style.copy(fontFeatureSettings = "tnum", lineHeight = style.fontSize), + ) + } + } +} + +/** Lays the content out at its own width, then scales it down, about its centre, to fit [max] when it's wider. */ +private fun Modifier.fitWidth(max: Dp): Modifier = layout { measurable, _ -> + val p = measurable.measure(Constraints()) + val room = max.roundToPx() + val k = if (p.width > room) room.toFloat() / p.width else 1f + val w = (p.width * k).roundToInt() + val h = (p.height * k).roundToInt() + layout(w, h) { + p.placeWithLayer((w - p.width) / 2, (h - p.height) / 2) { + scaleX = k + scaleY = k + } + } +} + +/** + * How far a medal's light has risen: from [RISE_FROM] to full over [RISE_MS] when [on], as an earned medal's sheet + * opens, else full at once. Full with the system's animations off. + */ +@Composable +internal fun rememberLightRise(on: Boolean): () -> Float { + val animate = rememberAnimationsOn() + val level = remember { Animatable(if (on && animate) RISE_FROM else 1f) } + LaunchedEffect(on, animate) { + if (on && animate) level.animateTo(1f, tween(RISE_MS, easing = Motion.easing)) else level.snapTo(1f) + } + return remember(level) { { level.value } } +} + +/** A medal still to earn: its picture and label dim. */ +private val LockedMark = Color.White.copy(alpha = 0.34f) +private val LockedLabel = Color.White.copy(alpha = 0.42f) + +/** + * The picture's share of the face's room, alone or over a label; how much of the face's width a label may take, under + * a picture or on its own; and the space between the two. Every label keeps clear of the inner ring. + */ +private const val EMBLEM_ALONE = 0.56f +private const val EMBLEM_OVER_LABEL = 0.34f +private const val LABEL_ROOM_UNDER = 0.5f +private const val LABEL_ROOM_ALONE = 0.68f +private const val LABEL_GAP = 0.05f + +/** From this much room on the face, the label takes the large display roles: a sheet's medal, the best card's. */ +private val LARGE_FACE = 80.dp + +/** An earned medal's light rises from here as its sheet opens. */ +private const val RISE_FROM = 0.15f +private const val RISE_MS = 700 diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/ScoreDetail.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/ScoreDetail.kt index 9f791a69..3d19ba1d 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/ScoreDetail.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/ScoreDetail.kt @@ -16,6 +16,8 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.SideEffect import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue @@ -36,11 +38,13 @@ import org.openstrap.app.ui.dashboard.InfoCopy import org.openstrap.app.presentation.Metric import org.openstrap.app.ui.dashboard.Narrative import org.openstrap.app.presentation.Range +import org.openstrap.app.ui.dashboard.RecoveryFailure import org.openstrap.app.ui.dashboard.Score import org.openstrap.app.presentation.TabCopy import org.openstrap.app.presentation.TodayCopy import org.openstrap.app.ui.theme.MetricColors import java.time.LocalDate +import kotlinx.coroutines.delay import java.time.LocalTime import org.openstrap.app.ui.glow.draw.DotSize import org.openstrap.app.ui.glow.pictures.PictureSize @@ -74,17 +78,34 @@ fun GlowScoreDetailScreen( onEditProfile: () -> Unit = {}, /** For the Sleep score and Naps details: moving, deleting and restoring a sleep or nap. */ sleepEditing: SleepEditing = SleepEditing(), + /** The day's Recovery couldn't be worked out; null when it didn't fail, or failed for another day. */ + recoveryFailure: RecoveryFailure? = null, ) { val r = recovery?.takeIf { it.date == state.date } + // The day shown failed, so its result is never coming: nothing is held for it. + val failed = recoveryFailure?.date == state.date + // Recovery, Load and Active minutes are read from the day's result, which takes a moment to work out on another + // day. Until it comes, their page stays on the last day's, so it moves to the next instead of emptying and filling; + // the strip follows the tap at once. Energy holds its own, with its curve. The strap's score is held with its day, + // as it stands in for Recovery while the score is learning: else the held page would lose its number meanwhile. + val held = rememberHeld(r?.let { HeldDay(state, it, strapScore) }, state.date, failed) + val heldState = held?.state ?: state + val heldR = held?.result + val heldStrapScore = if (held != null) held.strapScore else strapScore + fun activityOf(s: DayUiState, result: RecoveryResult?) = ActivityDetailContext( + s, result, workouts, activity, history, onOpen, onSwitch, onSelectDay, onEditProfile, contentPadding, onBack, + stripDate = state.date, + ) when (score) { - Score.Recovery -> RecoveryDetail(state, r, strapScore, history, onOpen, onSwitch, onSelectDay, contentPadding, onBack) - Score.Energy -> ChargeDetail(state, r, history, onOpen, onSwitch, onSelectDay, contentPadding, onBack) + Score.Recovery -> RecoveryDetail( + heldState, heldR, heldStrapScore, history, onOpen, onSwitch, onSelectDay, contentPadding, onBack, state.date, + ) + Score.Energy -> ChargeDetail(state, r, failed, history, onOpen, onSwitch, onSelectDay, contentPadding, onBack) Score.Sleep -> SleepScoreDetail(state, r, history, onOpen, onSwitch, onSelectDay, contentPadding, onBack, sleepEditing) Score.Regularity -> RegularityDetail(state, r, history, onOpen, onSwitch, onSelectDay, contentPadding, onBack) Score.Naps -> NapsDetail(state, r, onOpen, onSwitch, onSelectDay, contentPadding, onBack, sleepEditing) - Score.HeartPoints, Score.ActiveMinutes, Score.Load, Score.Vo2Max, Score.Recover, Score.Calories, Score.Distance -> ActivityScoreDetail( - score, ActivityDetailContext(state, r, workouts, activity, history, onOpen, onSwitch, onSelectDay, onEditProfile, contentPadding, onBack), - ) + Score.ActiveMinutes, Score.Load -> ActivityScoreDetail(score, activityOf(heldState, heldR)) + Score.HeartPoints, Score.Vo2Max, Score.Recover, Score.Calories, Score.Distance -> ActivityScoreDetail(score, activityOf(state, r)) } } @@ -96,6 +117,17 @@ internal fun daysWithData(metric: DailyMetric, from: LocalDate, to: LocalDate, h return stats.map { it.date }.toSet() } +/** + * The days of [date]'s strip that have [metric], read for the whole strip at once ([DetailCopy.strip]'s window). A tap + * on another day in the same week asks nothing new, so the dots stay as they were while that day loads, and every day + * gets its dot from the same place whichever day is shown. + */ +@Composable +internal fun stripDaysWithData(metric: DailyMetric, date: LocalDate, today: LocalDate, history: DailyHistory): Set { + val strip = DetailCopy.strip(date, today, emptySet()) + return daysWithData(metric, strip.first().date.minusDays(1), strip.last().date, history) +} + /* ---------------------------------------------- Recovery -------------------------------------------- */ /** @@ -106,6 +138,8 @@ internal fun daysWithData(metric: DailyMetric, from: LocalDate, to: LocalDate, h private fun RecoveryDetail( state: DayUiState, r: RecoveryResult?, strapScore: Int?, history: DailyHistory, onOpen: (Detail) -> Unit, onSwitch: (Detail) -> Unit, onSelectDay: (LocalDate) -> Unit, contentPadding: PaddingValues, onBack: () -> Unit, + /** The day picked, which the strip shows at once while [state] and [r] may still be the last day's. */ + stripDate: LocalDate, ) { val ready = r?.readiness val score = debugRecoveryScore() ?: ready?.score @@ -122,9 +156,10 @@ private fun RecoveryDetail( val today = LocalDate.now() val isToday = state.date == today val week = r?.readinessTrend.orEmpty() - // The trend covers the week up to the day shown; for the days after it, a night's resting heart rate stands in. - val later = daysWithData(DailyMetric.RestingHr, state.date, today, history) - val withData = week.filter { it.second != null }.map { it.first }.toSet() + later + // A night's resting heart rate marks every day of the strip, so a day keeps its dot whichever day is shown and while + // the score is worked out; the trend adds the days it has a score for. + val nights = stripDaysWithData(DailyMetric.RestingHr, stripDate, today, history) + val withData = week.filter { it.second != null }.map { it.first }.toSet() + nights val known = week.mapNotNull { it.second } val headline = when { @@ -142,11 +177,14 @@ private fun RecoveryDetail( DetailTemplate( Score.Recovery.title, color, siblings(Detail.OfScore(Score.Recovery), onSwitch), onInfo = { info = true }, onBack = onBack, contentPadding = contentPadding, headline = headline, - strip = DetailCopy.strip(state.date, today, withData), onDay = onSelectDay, + strip = DetailCopy.strip(stripDate, today, withData), onDay = onSelectDay, ranges = ranges, range = range, onRange = { rangeIndex = ranges.indexOf(it) }, scrubbed = { scrub }, + // The figures are the held day's, so they move when it does, not with the strip. + headlineDay = state.date, // The arc gauge (chart kit, spec 2.7) holds the day's score, centred, the number inside the half circle. heroValue = (score ?: estimate)?.takeIf { range == Range.Day }?.let { shown -> - { ArcGauge(shown / 100f, color, key = state.date) { DetailScoreNumber(shown) } } + // One key for every day, so the arc sweeps from the score shown to the next day's instead of cutting. + { ArcGauge(shown / 100f, color, key = Score.Recovery) { DetailScoreNumber(shown, state.date) } } }, // The Recovery card's picture under the gauge: the week to this morning as dots through the band of your usual. heroPicture = week.map { it.second?.toFloat() }.takeIf { range == Range.Day && it.any { v -> v != null } }?.let { dots -> @@ -221,9 +259,14 @@ private const val SHORT_CURVE_HOURS = 3f */ @Composable private fun ChargeDetail( - state: DayUiState, r: RecoveryResult?, history: DailyHistory, + liveState: DayUiState, liveR: RecoveryResult?, failed: Boolean, history: DailyHistory, onOpen: (Detail) -> Unit, onSwitch: (Detail) -> Unit, onSelectDay: (LocalDate) -> Unit, contentPadding: PaddingValues, onBack: () -> Unit, ) { + // Another day's Energy takes a moment to work out. Until it is, the last one stays up, so the page moves from one day's + // to the next instead of emptying and filling; the strip follows the tap at once. A day that [failed] isn't waited for. + val held = rememberHeld(liveR?.let { liveState to it }, liveState.date, failed) + val state = held?.first ?: liveState + val r = held?.second val c = r?.charge val now = c?.latest?.let(::chargeShown) val atWake = c?.atWake?.toInt() @@ -233,7 +276,7 @@ private fun ChargeDetail( var scrub by remember(state.date) { mutableStateOf(null) } var info by rememberSaveable { mutableStateOf(false) } // Charge runs on heart rate, so the days with heart rate are the days with a Charge. - val strip = DetailCopy.strip(state.date, today, emptySet()) + val strip = DetailCopy.strip(liveState.date, today, emptySet()) val withData = daysWithData(DailyMetric.HeartRate, strip.first().date.minusDays(1), strip.last().date, history) // The latest Charge is where the curve ends, which can be well before now while the strap catches up. val lastAt = c?.points?.lastOrNull { it.state != Recovery.State.NoData }?.t @@ -262,8 +305,10 @@ private fun ChargeDetail( DetailTemplate( Score.Energy.title, color, siblings(Detail.OfScore(Score.Energy), onSwitch), onInfo = { info = true }, onBack = onBack, contentPadding = contentPadding, headline = headline, - strip = DetailCopy.strip(state.date, today, withData), onDay = onSelectDay, + strip = DetailCopy.strip(liveState.date, today, withData), onDay = onSelectDay, ranges = listOf(Range.Day), range = Range.Day, onRange = {}, scrubbed = { scrub }, + // The figures are the held day's, so they move when it does, not with the strip. + headlineDay = state.date, ) { item { if (c == null || now == null || c.points.size < 2) DetailEmpty(TabCopy.chargeLine(now, atWake, c?.anchored == true)) @@ -318,6 +363,33 @@ private fun ChargeDetail( ) } +/** + * [value] while there is one, else the last there was, so a day that is slow to work out is waited for. Not when the + * day [failed]: its value is never coming, so it lets go at once rather than leave another day's page up. Not past + * [HOLD_MS] either, for a day that never comes without a failure saying so. Null before the first. + */ +@Composable +private fun rememberHeld(value: T?, day: LocalDate, failed: Boolean): T? { + val last = remember { Last() } + var gaveUp by remember(day) { mutableStateOf(false) } + LaunchedEffect(day, value == null) { + gaveUp = false + if (value == null) { + delay(HOLD_MS) + gaveUp = true + } + } + SideEffect { if (value != null) last.value = value } + return value ?: last.value.takeUnless { gaveUp || failed } +} + +private const val HOLD_MS = 4_000L + +private class Last { var value: T? = null } + +/** A day's page as [rememberHeld] keeps it: the day, its result, and the strap's own score for its night. */ +private class HeldDay(val state: DayUiState, val result: RecoveryResult, val strapScore: Int?) + /* ---------------------------------------------- Related --------------------------------------------- */ /** @@ -347,5 +419,5 @@ private fun ScoreRelated(score: Score, state: DayUiState, r: RecoveryResult?, hi /** The score in a score gauge on a detail header ([ArcGauge], [HorizonArc]): the header's one dotted number. */ @Composable -internal fun DetailScoreNumber(score: Int) = - DotMatrixText(score.toString(), Modifier.detailNumber(score.toString()), dot = DotSize.Detail) +internal fun DetailScoreNumber(score: Int, day: LocalDate? = null) = + DayNumber(score.toString(), day, Modifier.detailNumber(score.toString())) diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/SleepDetail.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/SleepDetail.kt index e947036c..02c203e5 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/SleepDetail.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/SleepDetail.kt @@ -96,7 +96,7 @@ private fun sleepDays(state: DayUiState, history: DailyHistory): Set // shown goes by its own night, as the page says it, so a dot never stands beside "No sleep recorded". val loaded = state.nights.map { it.date }.toSet() val days = state.nights.filter { it.session != null }.map { it.date }.toSet() + - daysWithData(DailyMetric.Breathing, state.date, today, history).filter { it !in loaded } + stripDaysWithData(DailyMetric.Breathing, state.date, today, history).filter { it !in loaded } return if (state.loaded && state.sleep == null) days - state.date else days } @@ -175,7 +175,7 @@ internal fun SleepScoreDetail( // The horizon arc (chart kit, spec 2.7) holds the night's score, centred, the number under its crest. A // scrub takes its place in the hero alone, so the rest of the detail stays put (audit K4). heroValue = if (range == Range.Day && score != null) { - { HorizonArc(score / 100f, color, key = state.date) { DetailScoreNumber(score) } } + { HorizonArc(score / 100f, color, key = Score.Sleep) { DetailScoreNumber(score, state.date) } } } else null, scrubbed = { scrub }, ) { diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/StrapDrawing.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/StrapDrawing.kt index 9a4dc9a3..27cf1a42 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/StrapDrawing.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/StrapDrawing.kt @@ -24,16 +24,23 @@ import androidx.compose.ui.graphics.drawscope.rotate import androidx.compose.ui.graphics.graphicsLayer /* - * The strap as a line drawing, shared by the Strap page's card and Today's pairing stage. + * The strap as a line drawing, shared by the Strap page's card, Today's pairing stage and the header's strap pill. */ /** * The strap seen from the front, drawn in line: the band running off the top and bottom with a faint weave, the pod as * a rectangle a little wider than the band with its bevel, one highlight and the lugs, and its light in [led]. While it * syncs, an arc turns round the light. When it isn't connected the drawing dims and the light goes out to a ring. + * [lineScale] thickens every line, for a drawing too small for the hairlines of the card's. */ @Composable -internal fun StrapDrawing(led: Color, lit: Boolean, syncing: Boolean, modifier: Modifier) { +internal fun StrapDrawing( + led: Color, + lit: Boolean, + syncing: Boolean, + modifier: Modifier, + lineScale: Float = 1f, +) { // The turn is a State read only in draw, so a syncing strap redraws each frame without recomposing. val turn: State = if (syncing) { val t = rememberInfiniteTransition(label = "strap sync") @@ -46,6 +53,8 @@ internal fun StrapDrawing(led: Color, lit: Boolean, syncing: Boolean, modifier: modifier.graphicsLayer { alpha = if (lit) 1f else 0.45f }.drawWithCache { // Drawn on a 120 by 150 grid, the card slot's shape. val k = size.width / 120f + // Line widths, which [lineScale] thickens; positions stay on the grid. + val s = k * lineScale fun o(x: Float, y: Float) = Offset(x * k, y * k) val white = Color.White val edge = Brush.verticalGradient( @@ -67,23 +76,23 @@ internal fun StrapDrawing(led: Color, lit: Boolean, syncing: Boolean, modifier: for (x in WeaveOdd) drawLine(white.copy(alpha = 0.09f), o(x, y + 1.5f), o(x + 3f, y + 1.5f), k, StrokeCap.Round) for (x in WeaveEven) drawLine(white.copy(alpha = 0.09f), o(x, y + 4.5f), o(x + 3f, y + 4.5f), k, StrokeCap.Round) } - drawLine(edge, o(43f, 0f), o(43f, 150f), 1.4f * k) - drawLine(edge, o(77f, 0f), o(77f, 150f), 1.4f * k) + drawLine(edge, o(43f, 0f), o(43f, 150f), 1.4f * s) + drawLine(edge, o(77f, 0f), o(77f, 150f), 1.4f * s) // The lugs, where the band meets the pod. - for ((x, y) in Lugs) drawLine(white.copy(alpha = 0.5f), o(x, y), o(x, y + 4f), 1.2f * k, StrokeCap.Round) + for ((x, y) in Lugs) drawLine(white.copy(alpha = 0.5f), o(x, y), o(x, y + 4f), 1.2f * s, StrokeCap.Round) // The pod, its bevel and one highlight on the top left. drawRoundRect(Color(0xFF0C0F0E), o(34f, 40f), Size(52f * k, 70f * k), CornerRadius(9f * k)) - drawRoundRect(white.copy(alpha = 0.8f), o(34f, 40f), Size(52f * k, 70f * k), CornerRadius(9f * k), style = Stroke(1.5f * k)) - drawRoundRect(white.copy(alpha = 0.2f), o(39f, 45f), Size(42f * k, 60f * k), CornerRadius(5f * k), style = Stroke(k)) - drawPath(highlight, white.copy(alpha = 0.45f), style = Stroke(1.2f * k, cap = StrokeCap.Round)) + drawRoundRect(white.copy(alpha = 0.8f), o(34f, 40f), Size(52f * k, 70f * k), CornerRadius(9f * k), style = Stroke(1.5f * s)) + drawRoundRect(white.copy(alpha = 0.2f), o(39f, 45f), Size(42f * k, 60f * k), CornerRadius(5f * k), style = Stroke(s)) + drawPath(highlight, white.copy(alpha = 0.45f), style = Stroke(1.2f * s, cap = StrokeCap.Round)) // The light. if (lit) { drawCircle(glow, 14f * k, c) drawCircle(led, 3.2f * k, c) if (syncing) rotate(turn.value, c) { - drawArc(led, -90f, 75f, false, o(49f, 64f), Size(22f * k, 22f * k), style = Stroke(1.4f * k, cap = StrokeCap.Round)) + drawArc(led, -90f, 75f, false, o(49f, 64f), Size(22f * k, 22f * k), style = Stroke(1.4f * s, cap = StrokeCap.Round)) } - } else drawCircle(white.copy(alpha = 0.6f), 3.2f * k, c, style = Stroke(k)) + } else drawCircle(white.copy(alpha = 0.6f), 3.2f * k, c, style = Stroke(s)) } }, ) diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/live/LiveFrame.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/live/LiveFrame.kt index 1fc38c04..d265e806 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/live/LiveFrame.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/live/LiveFrame.kt @@ -42,6 +42,7 @@ import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.runtime.getValue import androidx.compose.ui.semantics.onClick import androidx.compose.ui.unit.Dp +import androidx.compose.ui.layout.layout import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.unit.dp import kotlinx.coroutines.coroutineScope @@ -480,7 +481,13 @@ internal fun PageDots(current: Int, count: Int, position: Float? = null, onSelec Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center) { repeat(count) { i -> Box( - Modifier.size(28.dp).clip(CircleShape).pressClickable({ onSelect(i) }, CircleShape), + // 48 dp square to tap, laid out as tall as before so the live screens keep their height: the 10 dp above + // and below reach into the bottom bar's 14 dp gaps, never over the controls. + Modifier.layout { measurable, constraints -> + val tap = measurable.measure(constraints) + val row = DotsRowHeight.roundToPx() + layout(tap.width, row) { tap.place(0, (row - tap.height) / 2) } + }.size(DotTap).clip(CircleShape).pressClickable({ onSelect(i) }, CircleShape), contentAlignment = Alignment.Center, ) { val lit = if (position != null) (1f - kotlin.math.abs(position - i)).coerceIn(0f, 1f) else if (i == current) 1f else 0f @@ -490,6 +497,10 @@ internal fun PageDots(current: Int, count: Int, position: Float? = null, onSelec } } +/** A page dot's tap target, and the height the dots' row takes in the bottom bar. */ +private val DotTap = 48.dp +private val DotsRowHeight = 28.dp + @Composable internal fun LiveStat(label: String, modifier: Modifier = Modifier, value: @Composable () -> Unit) { Column(modifier, horizontalAlignment = Alignment.CenterHorizontally) { diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/live/LiveSets.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/live/LiveSets.kt index 51cc0737..8576d75f 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/live/LiveSets.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/live/LiveSets.kt @@ -12,6 +12,7 @@ import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.CircleShape @@ -531,7 +532,9 @@ private fun ExerciseSheet(current: String?, used: List, onPick: (String? } if (typed.isNotBlank()) Icon( AppIcons.Tick02, stringResource(R.string.workout_live_exercise_use), tint = Color.White, - modifier = Modifier.size(28.dp).clip(CircleShape).pressClickable({ onPick(typed) }, CircleShape).padding(4.dp), + // 48 dp to tap, the mark drawn 20 dp as before, and moved out so it stays where it was. + modifier = Modifier.offset(x = 10.dp).size(48.dp).clip(CircleShape) + .pressClickable({ onPick(typed) }, CircleShape).padding(14.dp), ) } }, diff --git a/app/src/main/kotlin/org/openstrap/app/ui/root/AppRootViewModel.kt b/app/src/main/kotlin/org/openstrap/app/ui/root/AppRootViewModel.kt index 40217f41..eb192124 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/root/AppRootViewModel.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/root/AppRootViewModel.kt @@ -165,11 +165,16 @@ class AppRootViewModel( } }.state(null) - /** Goals and bests, All badges and the recap (workouts spec 3.5), once there are workouts. */ + /** + * Goals and bests, All badges and the recap (workouts spec 3.5). The workouts start as an empty list before they + * load, so an empty list waits, unless nothing is stored at all ([RewardsKeeper.refresh] tells the two apart the + * same way): a new user still gets the page, with the week at nought and the bests and badges to go for, rather + * than "Loading" for ever. + */ val rewardsView: StateFlow = combine(workouts, goals.map { it.workoutsPerWeek }, dao.personalBests(), dao.badges()) { list, goal, bests, earned -> RewardsInputs(list, goal, bests, earned) - }.filter { it.workouts.isNotEmpty() } + }.filter { it.workouts.isNotEmpty() || !dao.anyWorkoutOnce() } .mapLatest { i -> catching { rewards.view(i.workouts, i.goal, i.bests, i.earned) }.getOrNull() } .flowOn(work) .state(null) diff --git a/app/src/main/kotlin/org/openstrap/app/ui/root/DetailHost.kt b/app/src/main/kotlin/org/openstrap/app/ui/root/DetailHost.kt index 85d89fec..fe9ec415 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/root/DetailHost.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/root/DetailHost.kt @@ -79,6 +79,7 @@ internal fun DetailHost( contentPadding = padding, onBack = pop, workouts = workouts, activity = activity, onEditProfile = onOpenProfile, sleepEditing = SleepEditing(dayVm::setSleepTimes, dayVm::deleteSleep, dayVm::restoreSleep), + recoveryFailure = shown.recoveryFailure, ) Detail.Week -> WeekDetail( ActivityDetailContext( diff --git a/app/src/main/kotlin/org/openstrap/app/ui/theme/AppIcons.kt b/app/src/main/kotlin/org/openstrap/app/ui/theme/AppIcons.kt index 3072b91f..29cbaa94 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/theme/AppIcons.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/theme/AppIcons.kt @@ -65,6 +65,8 @@ object AppIcons { val TapCaret: ImageVector by lazy { hugeicon("TapCaret", arrayOf("M9.00005 6C9.00005 6 15 10.4189 15 12C15 13.5812 9 18 9 18"), CARET, false, true) } val CaretUpFill: ImageVector by lazy { solid("CaretUpFill", "M5.5 15.5L12 8.5L18.5 15.5Z") } val CaretDownFill: ImageVector by lazy { solid("CaretDownFill", "M5.5 8.5L12 15.5L18.5 8.5Z") } + /** A lightning bolt, solid, for a strap that is charging. */ + val Bolt: ImageVector by lazy { solid("BoltFill", "M13.5 2.5L5 13.5H11L10 21.5L19 10H13Z") } val User: ImageVector by lazy { line("User", "M20 21.0001C19.713 17.269 16.7289 14.3151 12.995 14.0662L12 13.9999C11.6446 14.0096 11.3134 14.0225 11.0008 14.0378C7.3 14.2192 4.28417 17.3057 4 21.0001", "M8 6.9999A4 4 0 1 0 16 6.9999A4 4 0 1 0 8 6.9999Z") } /** MinusSign and PlusSign, for a goal's step buttons. */ val Minus: ImageVector by lazy { line("Minus", "M20 12L4 12") } diff --git a/app/src/main/res/values-v31/themes.xml b/app/src/main/res/values-v31/themes.xml index b2428a88..daa617a0 100644 --- a/app/src/main/res/values-v31/themes.xml +++ b/app/src/main/res/values-v31/themes.xml @@ -1,7 +1,10 @@ + (docs/design/rebrand-unstrap.md). Android 11 keeps the plain theme in values/. The window is black as well, so + nothing grey shows between the splash and the first frame. --> diff --git a/app/src/main/res/values-zh-rCN/strings_core_badges.xml b/app/src/main/res/values-zh-rCN/strings_core_badges.xml index 2b198545..1a7cee75 100644 --- a/app/src/main/res/values-zh-rCN/strings_core_badges.xml +++ b/app/src/main/res/values-zh-rCN/strings_core_badges.xml @@ -31,4 +31,20 @@ 间歇 Om 球类 + 完成你的第一次运动。 + 单日步行 10,000 步。 + 完成 %1$s 次运动。 + 在你开始的运动中累计 %1$s km。 + 按天累计,步行满一百万步。 + 首次达成周目标。 + 连续 %1$s 周达成周目标。进行中的一周不会中断连续记录。 + 完成一次跑步,户外、越野或跑步机均可。 + 一次跑完 5 km,以 GPS 测量。 + 一次跑完 10 km,以 GPS 测量。 + 完成一次室内有氧运动,器械或泳池均可。 + 在力量训练中记录一组的重量和次数。 + 完成一次 Tabata,每轮 20 秒训练、10 秒休息。 + 完成一次间歇训练,按距离或时间重复,中间休息。 + 完成一次瑜伽或静心练习。 + 完成一次球类或竞技运动,例如网球、板式网球或攀岩。 diff --git a/app/src/main/res/values-zh-rCN/strings_glow_goals.xml b/app/src/main/res/values-zh-rCN/strings_glow_goals.xml index fbefa695..e5cafa0d 100644 --- a/app/src/main/res/values-zh-rCN/strings_glow_goals.xml +++ b/app/src/main/res/values-zh-rCN/strings_glow_goals.xml @@ -12,7 +12,18 @@ 个人最佳 完成首次运动后,你的最佳记录将显示在这里。 - 徽章,%1$d / %2$d + 徽章 + 下一枚徽章 + 尚未创下 + 尚未获得 + 获得于 %1$s + %1$s,%2$s + 由你开始或保留、且时长达到 10 分钟的运动才会计入。 + 所有 GPS 记录的跑步中,你最快的 %1$s。 + GPS 记录的单次最远跑步。 + 你开始的运动中最长的一次,按运动时间计。 + 你为这个动作记录过的最重一组,含次数。 + 手环在单日记录到的最多步数。 全部徽章 上周回顾 庆祝 diff --git a/app/src/main/res/values/strings_core_badges.xml b/app/src/main/res/values/strings_core_badges.xml index 26da637f..4f4ebc49 100644 --- a/app/src/main/res/values/strings_core_badges.xml +++ b/app/src/main/res/values/strings_core_badges.xml @@ -3,7 +3,7 @@ Badges (data/Rewards.kt): each badge's title under its art on the Goals and bests page, in celebrations and in a workout's summary, and the few letters drawn on the art itself. Tabata is a workout format, keep it as is. --> - + First workout @@ -67,4 +67,37 @@ Om Play + + + Finish your first workout. + + Walk 10,000 steps in a single day. + + Finish %1$s workouts. + + Cover %1$s km in all, across the workouts you started. + + Walk a million steps in all, counted day by day. + + Meet your weekly workout goal for the first time. + + Meet your weekly goal %1$s weeks in a row. A week still under way never breaks the run. + + Finish a run, outdoors, on a trail or on a treadmill. + + Run 5 km in one go, measured by GPS. + + Run 10 km in one go, measured by GPS. + + Finish an indoor cardio workout, on a machine or in the pool. + + Log the weight and reps of a set in a strength workout. + + Finish a Tabata, 20 seconds of work and 10 seconds of rest. + + Finish a workout of intervals, a distance or a time repeated with rest between. + + Finish a yoga or calm session. + + Finish a game or sport, such as tennis, padel or climbing. diff --git a/app/src/main/res/values/strings_glow_goals.xml b/app/src/main/res/values/strings_glow_goals.xml index d2ee5a6e..451f2b47 100644 --- a/app/src/main/res/values/strings_glow_goals.xml +++ b/app/src/main/res/values/strings_glow_goals.xml @@ -26,8 +26,30 @@ Personal bests Your bests show here after your first workouts. - - Badges, %1$d of %2$d + + Badges + + Next badge + + Not set yet + + Not earned yet + + Earned %1$s + + %1$s, %2$s + + Workouts count from 10 minutes, when you start them or keep them. + + Your quickest %1$s inside any run measured by GPS. + + Your farthest single run measured by GPS. + + The longest workout you started, in moving time. + + The heaviest set you logged for this exercise, with its reps. + + The most steps the strap counted in a single day. All badges diff --git a/app/src/main/res/values/themes.xml b/app/src/main/res/values/themes.xml index 483f1ba1..db3d1020 100644 --- a/app/src/main/res/values/themes.xml +++ b/app/src/main/res/values/themes.xml @@ -1,3 +1,8 @@ - diff --git a/app/src/test/kotlin/org/openstrap/app/ui/dashboard/FrameTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/dashboard/FrameTest.kt index af4f7fa5..d42c9f85 100644 --- a/app/src/test/kotlin/org/openstrap/app/ui/dashboard/FrameTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/ui/dashboard/FrameTest.kt @@ -60,7 +60,7 @@ class FrameTest { assertEquals(StrapChip.Dot.Charging, strapChip(true, connected(64, charging = true), SyncState.Idle, null, now).dot) val failed = strapChip(true, connected(), SyncState.Failed("timeout"), now, now) assertEquals("Not synced", failed.text) - assertEquals(StrapChip.Dot.Warn, failed.dot) + assertEquals(StrapChip.Dot.Unsynced, failed.dot) assertEquals("Not paired", strapChip(false, ConnectionState.NotPaired, SyncState.Idle, null, now).text) assertEquals("Not paired", strapChip(true, ConnectionState.NotPaired, SyncState.Idle, null, now).text) } diff --git a/app/src/test/kotlin/org/openstrap/app/ui/glow/DayNumberTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/glow/DayNumberTest.kt new file mode 100644 index 00000000..b20b0b75 --- /dev/null +++ b/app/src/test/kotlin/org/openstrap/app/ui/glow/DayNumberTest.kt @@ -0,0 +1,86 @@ +package org.openstrap.app.ui.glow + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.semantics.SemanticsProperties +import androidx.compose.ui.test.SemanticsMatcher +import java.time.LocalDate +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.openstrap.app.testing.ComposeRules +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** + * A detail's figure moves to another day's without jumping: a count runs one way from the figure shown to the new one + * (2,500 to 4,500 never reads 4,500, then 2,500, then climbs back), and a change that isn't a day's lands at once, even + * the first one on a day whose figure came in the same as the last day's. + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [35]) +class DayNumberTest { + @get:Rule val rules = ComposeRules() + + private var value by mutableStateOf("2,500") + private var day by mutableStateOf(DAY) + + /** The figures on screen this frame, as numbers. */ + private fun shown(): List = rules.compose.onAllNodes(SemanticsMatcher.keyIsDefined(SemanticsProperties.ContentDescription)) + .fetchSemanticsNodes().flatMap { it.config[SemanticsProperties.ContentDescription] } + .mapNotNull { it.replace(",", "").toFloatOrNull() } + + /** The largest figure on screen in each frame over [frames] frames from now. */ + private fun frames(frames: Int): List = List(frames) { + rules.compose.mainClock.advanceTimeByFrame() + shown().maxOrNull() ?: 0f + } + + private fun start() { + rules.compose.setContent { DayNumber(value, day) } + rules.compose.waitForIdle() + rules.compose.mainClock.autoAdvance = false + } + + @Test fun `another day's figure counts one way to it, never showing it first`() { + start() + value = "4,500" + day = DAY.plusDays(1) + val seen = frames(FRAMES) + assertTrue("the first frames read ${seen.take(3)}", seen.first() < END) + seen.zipWithNext().forEach { (a, b) -> assertTrue("went back from $a to $b in $seen", b >= a) } + assertEquals(END, seen.last(), 0f) + } + + @Test fun `a change after the next day came in the same as the last lands at once`() { + start() + // The next day's figure is the same as the last day's, so nothing moves; then a live reading changes it. + day = DAY.plusDays(1) + frames(LATE_FRAMES) + value = "4,500" + val seen = frames(2) + assertTrue("the live change read $seen", seen.all { it == START || it == END }) + assertEquals(END, seen.last(), 0f) + } + + @Test fun `a change on the same day lands at once`() { + start() + value = "4,500" + // The frame the change is applied in, then the new figure, with nothing between. + val seen = frames(2) + assertTrue("same day read $seen", seen.all { it == START || it == END }) + assertEquals(END, seen.last(), 0f) + } + + private companion object { + val DAY: LocalDate = LocalDate.of(2026, 11, 2) + const val START = 2500f + const val END = 4500f + /** Enough frames for the count to finish: 600 ms at 16 ms a frame, and some. */ + const val FRAMES = 50 + const val LATE_FRAMES = 5 + } +} diff --git a/app/src/test/kotlin/org/openstrap/app/ui/glow/MedalLabelTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/glow/MedalLabelTest.kt new file mode 100644 index 00000000..5a5ec7ea --- /dev/null +++ b/app/src/test/kotlin/org/openstrap/app/ui/glow/MedalLabelTest.kt @@ -0,0 +1,96 @@ +package org.openstrap.app.ui.glow + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.semantics.SemanticsNode +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import kotlin.math.hypot +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.openstrap.app.data.Rewards +import org.openstrap.app.testing.ComposeRules +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode + +/** + * A medal's number or distance ("1000", "14/14", "HM") keeps clear of its inner ring at every size it's drawn, the + * small cells and the sheet's large medal alike, rather than running into the edge. + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [35]) +@GraphicsMode(GraphicsMode.Mode.NATIVE) +class MedalLabelTest { + @get:Rule val rules = ComposeRules() + + /** The medals with the longest labels in each shape, each label once. */ + private val looks: List> = listOf( + "1000" to badgeLook(badge("km_1000"), "1000"), + "500" to badgeLook(badge("workouts_500"), "500"), + "1M" to badgeLook(badge("steps_1m"), "1M"), + "10K" to badgeLook(badge("first_10k"), "10K"), + "52" to badgeLook(badge("goal_52"), "52"), + "14/14" to badgeLook(badge("goal_first"), "14/14"), + "HM" to bestLook(Rewards.Kind.fastest(HALF_MARATHON)), + ) + + private fun badge(id: String) = Rewards.BADGES.first { it.id == id } + + @Test fun `labels keep inside the ring on a cell's medal`() = assertInside(64.dp) + + @Test fun `labels keep inside the ring on a sheet's medal`() = assertInside(156.dp) + + private fun assertInside(diameter: Dp) { + rules.compose.setContent { + Column { + looks.forEachIndexed { i, (_, look) -> Box(Modifier.testTag("medal$i")) { Medal(look, diameter) } } + } + } + val out = looks.mapIndexedNotNull { i, (label, look) -> + val medal = unclipped(rules.compose.onNodeWithTag("medal$i").fetchSemanticsNode()) + val text = unclipped(rules.compose.onNodeWithText(label, useUnmergedTree = true).fetchSemanticsNode()) + val cx = medal.center.x + val cy = medal.center.y + // The ring's radius on this medal, in px: the frame is 100 units across. + val ring = innerRing(look.shape) * medal.width / FRAME_UNITS + val corners = listOf(text.topLeft, text.topRight, text.bottomLeft, text.bottomRight) + val far = corners.maxOf { hypot(it.x - cx, it.y - cy) } + "$label on ${look.shape} at $diameter: reaches $far px, the ring is at $ring".takeIf { far > ring } + } + assertTrue(out.joinToString("\n"), out.isEmpty()) + } + + /** A node's bounds where it's laid out, even off the screen's edge, as its size scaled by any layer. */ + private fun unclipped(node: SemanticsNode): Rect { + val box = node.layoutInfo.coordinates + return Rect(box.localToRoot(Offset.Zero), box.localToRoot(Offset(box.size.width.toFloat(), box.size.height.toFloat()))) + } + + /** + * How far the inner ring is from the middle, in frame units, read safely: the ring at 0.87 of the face, and for the + * hexagon (its flats 40.7 from the middle) and the soft square the circle that fits inside them, so a pass means + * clear of every edge. + */ + private fun innerRing(shape: MedalShape): Float = INNER * when (shape) { + MedalShape.Round -> 46f + MedalShape.Hex -> 40.7f + MedalShape.Laurel -> 34f + MedalShape.Soft -> 45f + MedalShape.Rosette -> 36f + } + + private companion object { + const val HALF_MARATHON = 21097 + const val FRAME_UNITS = 100f + const val INNER = 0.87f + } +}