Cotton code
578 lines · 20.1 KB · KotlinRaw
package com.cottondb.android.ui.activityimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.PaddingValuesimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.Spacerimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.heightimport androidx.compose.foundation.layout.offsetimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.safeDrawingPaddingimport androidx.compose.foundation.layout.sizeimport androidx.compose.foundation.layout.widthimport androidx.compose.foundation.lazy.LazyColumnimport androidx.compose.foundation.lazy.itemsimport androidx.compose.foundation.lazy.itemsIndexedimport androidx.compose.material3.HorizontalDividerimport androidx.compose.material3.Textimport androidx.compose.material3.TextButtonimport androidx.compose.runtime.Composableimport androidx.compose.runtime.rememberimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.rotateimport androidx.compose.ui.semantics.contentDescriptionimport androidx.compose.ui.semantics.semanticsimport androidx.compose.ui.text.font.FontWeightimport androidx.compose.ui.unit.dpimport com.cottondb.android.activity.ActivityPresentationFactsimport com.cottondb.android.activitybin.ActivityAuditEntryimport com.cottondb.android.activitybin.ActivityReadimport com.cottondb.android.activitybin.ActivityReplicaimport com.cottondb.android.activitybin.AssistantRunimport com.cottondb.android.design.CottonFontsimport com.cottondb.android.design.CottonMetricsimport com.cottondb.android.design.CottonTextStylesimport com.cottondb.android.generated.CottonPaletteimport com.cottondb.android.ui.paper.MemoryPaperDyeimport com.cottondb.android.ui.paper.PaperEdgeimport com.cottondb.android.ui.paper.TornPaperimport java.time.Clock/** * Controlled `/activity` presentation. The host owns reading, refresh, admission, cancellation, * and navigation. Server-written task, receipt, error, and audit argument summary are rendered * verbatim and never reconstructed here. */@Composablefun ActivityScreen(    read: ActivityRead?,    loading: Boolean,    readProblem: String?,    writeProblem: String?,    canWrite: Boolean,    onRetry: () -> Unit,    onCancel: (AssistantRun) -> Unit,    onOpenNote: (String) -> Unit,    onBack: () -> Unit,    modifier: Modifier = Modifier,    clock: Clock = Clock.systemDefaultZone(),) {    val frozenClock = remember { Clock.fixed(clock.instant(), clock.zone) }    Column(        modifier            .fillMaxSize()            .background(CottonPalette.groundMuted)            .safeDrawingPadding(),    ) {        ActivityHeader(onBack)        when {            read == null && (loading || readProblem == null) -> ActivitySkeleton()            read == null -> ActivityUnreadable(readProblem, onRetry)            else -> ActivityList(                read = read,                readProblem = readProblem,                writeProblem = writeProblem,                canWrite = canWrite,                clock = frozenClock,                onRetry = onRetry,                onCancel = onCancel,                onOpenNote = onOpenNote,            )        }    }}@Composableprivate fun ActivityHeader(onBack: () -> Unit) {    Row(        modifier = Modifier            .fillMaxWidth()            .padding(horizontal = 12.dp, vertical = 8.dp),        verticalAlignment = Alignment.CenterVertically,    ) {        TextButton(            onClick = onBack,            modifier = Modifier.semantics { contentDescription = "Back" },        ) {            Text("Back")        }        Text(            text = "Activity",            modifier = Modifier.padding(start = 8.dp),            style = CottonTextStyles.screenTitle.copy(fontFamily = CottonFonts.serif),            color = CottonPalette.ink,        )    }}@Composableprivate fun ActivityList(    read: ActivityRead,    readProblem: String?,    writeProblem: String?,    canWrite: Boolean,    clock: Clock,    onRetry: () -> Unit,    onCancel: (AssistantRun) -> Unit,    onOpenNote: (String) -> Unit,) {    LazyColumn(        modifier = Modifier.fillMaxSize(),        contentPadding = PaddingValues(            horizontal = CottonMetrics.contentMargin,            vertical = 8.dp,        ),        verticalArrangement = Arrangement.spacedBy(12.dp),    ) {        if (readProblem != null) {            item(key = "read-problem") {                CachedReadProblem(readProblem, onRetry)            }        }        item(key = "database-section") {            ActivitySection("This database")        }        item(key = "replica") {            ReplicaSlip(read.replica)        }        item(key = "runs-section") {            ActivitySection(                title = "What the assistant did",                count = read.runs.takeIf { it.isNotEmpty() }?.size?.toString(),            )        }        when {            read.runs.isEmpty() -> item(key = "runs-empty") {                ActivityEmpty(                    title = "No runs yet.",                    message = "When you ask something that needs work, the run shows up here.",                )            }            else -> items(read.runs, key = { run -> run.id }) { run ->                RunSlip(                    run = run,                    canWrite = canWrite,                    clock = clock,                    onCancel = onCancel,                    onOpenNote = onOpenNote,                )            }        }        if (writeProblem != null) {            item(key = "write-problem") {                Text(                    writeProblem,                    style = CottonTextStyles.caption,                    color = CottonPalette.statusError,                )            }        }        item(key = "audit-section") {            ActivitySection(                title = "What assistants did here",                count = read.audit.takeIf { it.isNotEmpty() }?.size?.toString(),            )        }        when {            read.audit.isEmpty() -> item(key = "audit-empty") {                ActivityEmpty(                    title = "Nothing yet.",                    message = "Every call a connected assistant makes to this database is listed here.",                )            }            else -> {                val ledgerRows = auditLedgerRows(read.audit, clock)                itemsIndexed(ledgerRows, key = { _, row -> row.key }) { index, row ->                    AuditLedgerRow(                        row = row,                        clock = clock,                        overlapsPrevious = index > 0,                    )                }                if (read.auditTruncated) {                    item(key = "audit-truncated") {                        AuditLedgerTruncated(overlapsPrevious = ledgerRows.isNotEmpty())                    }                }            }        }    }}@Composableprivate fun ActivitySection(title: String, count: String? = null) {    Row(        modifier = Modifier            .fillMaxWidth()            .padding(top = 8.dp),        verticalAlignment = Alignment.CenterVertically,    ) {        Text(title, style = CottonTextStyles.sectionLabel, color = CottonPalette.inkSecondary)        count?.let {            Spacer(Modifier.width(8.dp))            Text(it, style = CottonTextStyles.caption, color = CottonPalette.inkTertiary)        }    }}@Composableprivate fun ReplicaSlip(replica: ActivityReplica) {    TornPaper(        id = "activity-replica",        dye = MemoryPaperDye.Cream,        modifier = Modifier.fillMaxWidth(),        edge = PaperEdge.Cut,    ) {        Column(            modifier = Modifier.padding(16.dp),            verticalArrangement = Arrangement.spacedBy(10.dp),        ) {            ReplicaLine("Project", replica.workspaceId)            ReplicaLine("This device", replica.deviceId)            ReplicaLine("File", ActivityPresentationFacts.heldLine(replica.held))            ReplicaLine("Waiting to sync", ActivityPresentationFacts.pendingLine(replica.pending))        }    }}@Composableprivate fun ReplicaLine(label: String, value: String) {    Row(Modifier.fillMaxWidth()) {        Text(            text = label,            modifier = Modifier.width(120.dp),            style = CottonTextStyles.caption,            color = CottonPalette.inkSecondary,        )        Text(            text = value,            modifier = Modifier.weight(1f),            style = CottonTextStyles.caption,            color = CottonPalette.ink,        )    }}@Composableprivate fun RunSlip(    run: AssistantRun,    canWrite: Boolean,    clock: Clock,    onCancel: (AssistantRun) -> Unit,    onOpenNote: (String) -> Unit,) {    val stateInk = when (ActivityPresentationFacts.stateInk(run.state)) {        ActivityPresentationFacts.StateInk.Green -> CottonPalette.statusSuccess        ActivityPresentationFacts.StateInk.Red -> CottonPalette.statusError        ActivityPresentationFacts.StateInk.Pencil -> CottonPalette.inkSecondary    }    val canCancel = ActivityPresentationFacts.canCancel(run.id, run.state)    val noteId = run.resultNoteId?.takeUnless(String::isBlank)    val stamp = ActivityPresentationFacts.stampDone(run.state)    TornPaper(        id = run.id,        dye = MemoryPaperDye.Cream,        modifier = Modifier.fillMaxWidth(),        edge = PaperEdge.Cut,    ) {        Box(Modifier.fillMaxWidth()) {            Column(Modifier.padding(16.dp)) {                Row(verticalAlignment = Alignment.CenterVertically) {                    if (ActivityPresentationFacts.isUnfinished(run.state)) {                        Box(                            modifier = Modifier                                .size(7.dp)                                .background(CottonPalette.statusSuccess, androidx.compose.foundation.shape.CircleShape)                                .semantics { contentDescription = "Run in progress" },                        )                        Spacer(Modifier.width(8.dp))                    }                    Text(                        text = run.task,                        modifier = Modifier.weight(1f),                        style = CottonTextStyles.rowTitleCompact.copy(fontFamily = CottonFonts.serif),                        color = CottonPalette.ink,                    )                }                Text(                    text = ActivityPresentationFacts.caption(                        state = run.state,                        stamp = run.finishedAt ?: run.startedAt ?: run.queuedAt,                        turns = run.turns,                        clock = clock,                        zone = clock.zone,                    ),                    modifier = Modifier.padding(top = 4.dp),                    style = CottonTextStyles.preview.copy(fontFamily = CottonFonts.hand),                    color = stateInk,                )                run.receipt.takeIf(String::isNotEmpty)?.let { receipt ->                    Text(                        text = receipt,                        modifier = Modifier.padding(top = 8.dp),                        style = CottonTextStyles.caption,                        color = CottonPalette.ink,                    )                }                ActivityPresentationFacts.spentLine(run.stoppedReason, run.costUsd)?.let { spent ->                    Text(                        text = spent,                        modifier = Modifier.padding(top = 6.dp),                        style = CottonTextStyles.caption,                        color = CottonPalette.inkSecondary,                    )                }                ActivityPresentationFacts.failureSentence(run.state, run.error)?.let { failure ->                    Text(                        text = failure,                        modifier = Modifier.padding(top = 8.dp),                        style = CottonTextStyles.caption,                        color = CottonPalette.statusError,                    )                }                if (canCancel || noteId != null) {                    Row(Modifier.padding(top = 8.dp)) {                        if (canCancel) {                            TextButton(                                onClick = { onCancel(run) },                                enabled = canWrite,                                modifier = Modifier.semantics { contentDescription = "Cancel ${run.task}" },                            ) {                                Text("Cancel")                            }                        }                        if (noteId != null) {                            TextButton(                                onClick = { onOpenNote(noteId) },                                modifier = Modifier.semantics { contentDescription = "Open the note" },                            ) {                                Text("Open the note")                            }                        }                    }                }            }            if (stamp) {                Text(                    text = "DONE",                    modifier = Modifier                        .align(Alignment.TopEnd)                        .padding(top = 10.dp, end = 12.dp)                        .rotate(-9f),                    style = CottonTextStyles.sectionLabel.copy(fontWeight = FontWeight.Bold),                    color = CottonPalette.statusSuccess,                )            }        }    }}private sealed interface ActivityLedgerRow {    val key: String    data class Day(        override val key: String,        val label: String,    ) : ActivityLedgerRow    data class Entry(        override val key: String,        val entry: ActivityAuditEntry,    ) : ActivityLedgerRow}private fun auditLedgerRows(    entries: List<ActivityAuditEntry>,    clock: Clock,): List<ActivityLedgerRow> = buildList {    ActivityPresentationFacts.ledgerDays(        entries = entries,        createdAt = ActivityAuditEntry::createdAt,        clock = clock,        zone = clock.zone,    ).forEachIndexed { dayIndex, day ->        add(ActivityLedgerRow.Day("activity-ledger-day-$dayIndex-${day.key}", day.label))        day.entries.forEachIndexed { entryIndex, entry ->            add(ActivityLedgerRow.Entry("activity-ledger-entry-$dayIndex-$entryIndex-${entry.id}", entry))        }    }}@Composableprivate fun AuditLedgerRow(    row: ActivityLedgerRow,    clock: Clock,    overlapsPrevious: Boolean,) {    TornPaper(        id = row.key,        dye = MemoryPaperDye.Cream,        modifier = Modifier            .fillMaxWidth()            .then(if (overlapsPrevious) Modifier.offset(y = (-12).dp) else Modifier),        elevation = 0.dp,        edge = PaperEdge.Cut,    ) {        when (row) {            is ActivityLedgerRow.Day -> {                Column(Modifier.padding(start = 18.dp, end = 18.dp, top = 12.dp, bottom = 4.dp)) {                    Text(row.label, style = CottonTextStyles.rowTitleCompact.copy(fontFamily = CottonFonts.serif))                    HorizontalDivider(                        modifier = Modifier.padding(top = 4.dp),                        thickness = CottonMetrics.hairline,                        color = CottonPalette.hairline,                    )                }            }            is ActivityLedgerRow.Entry -> AuditLine(row.entry, row.entry.ledgerFact(), clock)        }    }}@Composableprivate fun AuditLedgerTruncated(overlapsPrevious: Boolean) {    TornPaper(        id = "activity-ledger-truncated",        dye = MemoryPaperDye.Cream,        modifier = Modifier            .fillMaxWidth()            .then(if (overlapsPrevious) Modifier.offset(y = (-12).dp) else Modifier),        elevation = 0.dp,        edge = PaperEdge.Cut,    ) {        Text(            "There are more, not shown.",            modifier = Modifier.padding(18.dp),            style = CottonTextStyles.preview.copy(fontFamily = CottonFonts.hand),            color = CottonPalette.inkSecondary,        )    }}private fun ActivityAuditEntry.ledgerFact(): ActivityPresentationFacts.LedgerEntry =    ActivityPresentationFacts.LedgerEntry(        createdAt = createdAt,        tokenName = tokenName,        tool = tool,        argsSummary = argsSummary,        ok = ok,    )@Composableprivate fun AuditLine(    entry: ActivityAuditEntry,    fact: ActivityPresentationFacts.LedgerEntry,    clock: Clock,) {    Row(        modifier = Modifier.padding(horizontal = 18.dp, vertical = 7.dp),        verticalAlignment = Alignment.Top,    ) {        Text(            text = ActivityPresentationFacts.ledgerTime(entry.createdAt, clock.zone),            modifier = Modifier.width(58.dp),            style = CottonTextStyles.caption,            color = CottonPalette.inkSecondary,        )        Column(Modifier.weight(1f)) {            Row(verticalAlignment = Alignment.CenterVertically) {                Text(entry.tool, style = CottonTextStyles.preview, color = CottonPalette.ink)                if (ActivityPresentationFacts.refused(fact)) {                    Spacer(Modifier.width(8.dp))                    Text("refused", style = CottonTextStyles.preview, color = CottonPalette.statusError)                }            }            ActivityPresentationFacts.ledgerDetail(fact).takeIf(String::isNotEmpty)?.let { detail ->                Text(detail, style = CottonTextStyles.caption, color = CottonPalette.inkSecondary)            }        }    }}@Composableprivate fun ActivitySkeleton() {    LazyColumn(        modifier = Modifier.fillMaxSize(),        contentPadding = PaddingValues(CottonMetrics.contentMargin),        verticalArrangement = Arrangement.spacedBy(12.dp),    ) {        items(listOf("activity-loading-1", "activity-loading-2", "activity-loading-3")) { id ->            TornPaper(                id = id,                dye = MemoryPaperDye.Cream,                modifier = Modifier.fillMaxWidth().height(96.dp),                edge = PaperEdge.Cut,            ) {}        }    }}@Composableprivate fun ActivityEmpty(title: String, message: String) {    TornPaper(        id = "activity-empty-$title",        dye = MemoryPaperDye.Cream,        modifier = Modifier.fillMaxWidth(),        edge = PaperEdge.Cut,    ) {        Column(            modifier = Modifier.padding(16.dp),            verticalArrangement = Arrangement.spacedBy(6.dp),        ) {            Text(title, style = CottonTextStyles.rowTitleCompact, color = CottonPalette.ink)            Text(message, style = CottonTextStyles.caption, color = CottonPalette.inkSecondary)        }    }}@Composableprivate fun ActivityUnreadable(problem: String?, onRetry: () -> Unit) {    Column(        modifier = Modifier.padding(CottonMetrics.contentMargin),        verticalArrangement = Arrangement.spacedBy(8.dp),    ) {        Text("Activity could not be read.", style = CottonTextStyles.body, color = CottonPalette.statusError)        Text(            "This phone could not read its own database just now.",            style = CottonTextStyles.caption,            color = CottonPalette.inkSecondary,        )        problem?.takeIf(String::isNotEmpty)?.let {            Text(it, style = CottonTextStyles.caption, color = CottonPalette.statusError)        }        TextButton(            onClick = onRetry,            modifier = Modifier.semantics { contentDescription = "Try again" },        ) {            Text("Try again")        }    }}@Composableprivate fun CachedReadProblem(problem: String, onRetry: () -> Unit) {    Row(        modifier = Modifier.fillMaxWidth(),        verticalAlignment = Alignment.CenterVertically,    ) {        Text(            problem,            modifier = Modifier.weight(1f),            style = CottonTextStyles.caption,            color = CottonPalette.statusError,        )        TextButton(            onClick = onRetry,            modifier = Modifier.semantics { contentDescription = "Try again" },        ) {            Text("Try again")        }    }}