Files
FocusBox/src/main/java/com/focusbox/app/ui/stats/PeriodDistributionCard.kt

328 lines
12 KiB
Kotlin
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package com.focusbox.app.ui.stats
import android.content.Context
import android.graphics.Typeface
import android.graphics.drawable.GradientDrawable
import android.util.AttributeSet
import android.util.TypedValue
import android.view.Gravity
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.focusbox.app.R
import com.focusbox.app.data.Store
import com.focusbox.app.util.Dates
import com.focusbox.app.util.col
import com.focusbox.app.util.dpi
import com.focusbox.app.widget.LabelDonutView
import kotlin.math.roundToInt
/**
* 「项目分布 / 任务分布」卡片:自带 日 / 周 / 月 / 年 四档与左右翻页。
*
* 为什么做成独立控件而不是在 Fragment 里堆代码:两张卡片结构完全一样,
* 只有数据源不同(按项目 / 按任务)。做成控件后各自持有自己的区间状态,
* 互不影响——看"本周的项目分布"和"这一年的任务分布"可以同时成立。
*/
class PeriodDistributionCard @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
) : LinearLayout(context, attrs) {
enum class Scale(val labelRes: Int) {
DAY(R.string.scale_day),
WEEK(R.string.scale_week),
MONTH(R.string.scale_month),
YEAR(R.string.scale_year),
}
private val tvTitle = TextView(context)
private val segItems = ArrayList<TextView>(4)
private val tvPeriod = TextView(context)
private val btnPrev = ImageView(context)
private val btnNext = ImageView(context)
private val donut = LabelDonutView(context)
/**
* 环下方明细列表:环只标占比最高的 6 条,剩下的全部在这里逐条列出。
* 不合并成「其他」——被合并掉的任务在页面上等于消失,用户根本不知道自己漏了什么。
*/
private val legend = LinearLayout(context)
/** 当前粒度,默认按天 */
var scale = Scale.DAY
private set
/** 锚点:落在目标周期内的任意时刻,实际区间由它推导 */
private var anchor = Dates.todayStart()
/** true = 按任务汇总,false = 按项目汇总 */
var byTask = false
set(value) {
field = value
refresh()
}
var cardTitle: String = ""
set(value) {
field = value
tvTitle.text = value
}
init {
orientation = VERTICAL
background = ContextCompat.getDrawable(context, R.drawable.bg_card)
setPadding(context.dpi(16f), context.dpi(15f), context.dpi(16f), context.dpi(10f))
build()
refresh()
}
// ------------------------------------------------------------------ 结构
private fun build() {
tvTitle.apply {
setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f)
setTextColor(context.col(R.color.title))
typeface = Typeface.DEFAULT_BOLD
includeFontPadding = false
}
addView(tvTitle)
val seg = LinearLayout(context).apply {
orientation = HORIZONTAL
background = ContextCompat.getDrawable(context, R.drawable.bg_segment_track)
setPadding(context.dpi(3f), context.dpi(3f), context.dpi(3f), context.dpi(3f))
}
addView(seg, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT).apply {
topMargin = context.dpi(13f)
})
Scale.entries.forEach { s ->
val tv = TextView(context).apply {
text = context.getString(s.labelRes)
setTextSize(TypedValue.COMPLEX_UNIT_SP, 13f)
gravity = Gravity.CENTER
setPadding(0, context.dpi(8f), 0, context.dpi(8f))
isClickable = true
setOnClickListener { switchScale(s) }
}
segItems.add(tv)
seg.addView(tv, LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f))
}
// 翻页行:左右箭头 + 居中周期文字(参考图的排布)
val periodRow = LinearLayout(context).apply {
orientation = HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
}
addView(periodRow, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT).apply {
topMargin = context.dpi(4f)
})
btnPrev.apply {
setImageResource(R.drawable.ic_chevron_right)
rotation = 180f
setColorFilter(context.col(R.color.text_secondary))
scaleType = ImageView.ScaleType.FIT_CENTER
setPadding(context.dpi(8f), context.dpi(8f), context.dpi(8f), context.dpi(8f))
isClickable = true
setOnClickListener { shift(-1) }
}
periodRow.addView(btnPrev, LayoutParams(context.dpi(36f), context.dpi(40f)))
tvPeriod.apply {
setTextSize(TypedValue.COMPLEX_UNIT_SP, 14f)
setTextColor(context.col(R.color.text))
typeface = Typeface.DEFAULT_BOLD
gravity = Gravity.CENTER
includeFontPadding = false
}
periodRow.addView(tvPeriod, LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f))
btnNext.apply {
setImageResource(R.drawable.ic_chevron_right)
setColorFilter(context.col(R.color.text_secondary))
scaleType = ImageView.ScaleType.FIT_CENTER
setPadding(context.dpi(8f), context.dpi(8f), context.dpi(8f), context.dpi(8f))
isClickable = true
setOnClickListener { shift(1) }
}
periodRow.addView(btnNext, LayoutParams(context.dpi(36f), context.dpi(40f)))
addView(donut, LayoutParams(LayoutParams.MATCH_PARENT, context.dpi(222f)).apply {
topMargin = context.dpi(2f)
})
legend.apply {
orientation = VERTICAL
visibility = GONE
}
addView(legend, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT).apply {
topMargin = context.dpi(6f)
})
}
// ------------------------------------------------------------------ 明细列表
/**
* 把环上没有牵线的切片按「圆点 + 名称 / 时长 · 占比」两列铺开(参考图版式)。
* 每格宽度均分,名称超长省略,保证列对齐不来回跳。
*/
private fun renderLegend(rest: List<LabelDonutView.Slice>, total: Int) {
legend.removeAllViews()
if (rest.isEmpty() || total <= 0) {
legend.visibility = GONE
return
}
legend.visibility = VISIBLE
rest.chunked(2).forEach { pair ->
val row = LinearLayout(context).apply { orientation = HORIZONTAL }
legend.addView(row, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT))
pair.forEach { slice ->
row.addView(buildLegendCell(slice, total), LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f))
}
// 单数时补一个空位,最后一行不会因为权重拉伸变成通栏
if (pair.size == 1) {
row.addView(android.view.View(context), LayoutParams(0, 1, 1f))
}
}
}
private fun buildLegendCell(slice: LabelDonutView.Slice, total: Int): LinearLayout {
val cell = LinearLayout(context).apply {
orientation = HORIZONTAL
setPadding(0, context.dpi(7f), context.dpi(8f), context.dpi(7f))
}
val dot = android.view.View(context).apply {
background = GradientDrawable().apply {
shape = GradientDrawable.OVAL
setColor(slice.color)
}
}
// 8dp 圆点,下移 5dp 与名称首行的视觉中心对齐
cell.addView(dot, LayoutParams(context.dpi(8f), context.dpi(8f)).apply {
topMargin = context.dpi(5f)
})
val text = LinearLayout(context).apply {
orientation = VERTICAL
setPadding(context.dpi(8f), 0, 0, 0)
}
cell.addView(text, LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f))
text.addView(TextView(context).apply {
this.text = slice.name
setTextSize(TypedValue.COMPLEX_UNIT_SP, 13f)
setTextColor(context.col(R.color.title))
maxLines = 1
ellipsize = android.text.TextUtils.TruncateAt.END
includeFontPadding = false
})
val pct = slice.seconds * 100f / total
val pctText = if (pct < 1f) "<1%" else "${pct.roundToInt()}%"
text.addView(TextView(context).apply {
this.text = context.getString(
R.string.legend_meta,
Dates.duration(slice.seconds),
pctText,
)
setTextSize(TypedValue.COMPLEX_UNIT_SP, 11f)
setTextColor(context.col(R.color.text_secondary))
maxLines = 1
includeFontPadding = false
})
return cell
}
// ------------------------------------------------------------------ 交互
private fun switchScale(s: Scale) {
if (scale == s) return
scale = s
// 换粒度回到"当前",否则从 2024 年的日视图切到年视图会落在 2024 年,容易困惑
anchor = Dates.todayStart()
refresh()
}
private fun shift(delta: Int) {
if (delta > 0 && !canNext()) return
val s = start()
anchor = when (scale) {
Scale.DAY -> Dates.addDays(s, delta)
Scale.WEEK -> Dates.addDays(s, 7 * delta)
Scale.MONTH -> Dates.addMonths(s, delta)
Scale.YEAR -> Dates.addYears(s, delta)
}
refresh()
}
private fun periodStart(ms: Long): Long = when (scale) {
Scale.DAY -> Dates.dayStart(ms)
Scale.WEEK -> Dates.weekStart(ms)
Scale.MONTH -> Dates.monthStart(ms)
Scale.YEAR -> Dates.yearStart(ms)
}
private fun start(): Long = periodStart(anchor)
private fun end(s: Long): Long = when (scale) {
Scale.DAY -> Dates.addDays(s, 1)
Scale.WEEK -> Dates.addDays(s, 7)
Scale.MONTH -> Dates.addMonths(s, 1)
Scale.YEAR -> Dates.addYears(s, 1)
}
/** 未来没有记录,往后翻到当前周期为止 */
private fun canNext(): Boolean = start() < periodStart(Dates.todayStart())
// ------------------------------------------------------------------ 渲染
fun refresh() {
val from = start()
val to = end(from)
val raw = if (byTask) Store.taskSlices(from, to) else Store.distribution(from, to)
donut.setSlices(
raw.map {
LabelDonutView.Slice(
name = it.name,
seconds = it.seconds,
color = if (it.color == -1) context.col(R.color.text_tertiary) else it.color,
)
}
)
val total = raw.sumOf { it.seconds }
donut.centerText = Dates.durationBrief(total)
renderLegend(donut.unlabeled, total)
tvPeriod.text = periodLabel(from, to)
applySegments()
btnNext.alpha = if (canNext()) 1f else 0.2f
}
private fun periodLabel(from: Long, to: Long): String = when (scale) {
Scale.DAY -> Dates.mdLong(from)
Scale.WEEK -> context.getString(R.string.period_week_range, Dates.md(from), Dates.md(to - 1))
Scale.MONTH -> context.getString(R.string.period_month, Dates.yearOf(from), Dates.monthOf(from))
Scale.YEAR -> context.getString(R.string.period_year, Dates.yearOf(from))
}
private fun applySegments() {
val onText = context.col(R.color.title)
val offText = context.col(R.color.text_secondary)
val onBg = ContextCompat.getDrawable(context, R.drawable.bg_segment_on)
Scale.entries.forEachIndexed { i, s ->
val tv = segItems[i]
val selected = s == scale
tv.background = if (selected) onBg else null
tv.setTextColor(if (selected) onText else offText)
tv.typeface = if (selected) Typeface.DEFAULT_BOLD else Typeface.DEFAULT
}
}
}