Add a Templates gallery and detail view to the app

The server's template catalog (the list_templates command) had no surface in
the app. This adds a Templates destination to the shared SlidingPaneStack: a
measured card gallery (name, short description, stage count and its own glyph;
one column narrow, a fitting grid wide) and a detail pane that reuses the
pipeline detail's Summary/Graph/Source tabs, plus a create-from-template action
that submits a create-only draft. Stage counts come from a source the server
parsed (validate); a source that does not parse is still viewable as raw
markdown.

Added: Templates.kt (TemplateEntry/TemplateCard, the grid-column and
stage-count mapping), components/GalleryGrid.kt (the shared measured-gallery
fitting, extracted from the artifact gallery), graph/SourceView.kt
(PipelineSourceView, the one rendered-definition view, extracted from
PipelineDetailScreen), screens/TemplateGalleryScreen.kt,
screens/TemplateDetailScreen.kt, TemplatesTest.kt.
Changed: PipelinesApp.kt (the Templates destination), AppViewModel.kt
(refreshTemplates/createFromTemplate), data/PipelinesRepository.kt
(listTemplates/validateSource/createPipeline), graph/Artifacts.kt (use the
shared galleryGrid), PipelineDetailScreen.kt (use the shared
PipelineSourceView), ArtifactGalleryTest.kt (exercise galleryGrid).

Doc/state check before committing:
- android/README.md (the app's topic doc): updated. Added a Features bullet for
  the Templates destination and a dated "Templates: a gallery and a detail view"
  section, matching the per-feature convention every prior android change uses.
- Packaged templates: not touched. The server's templates are Go-side and the
  brief forbids touching the Pipelines server; this change only renders the
  catalog the server already exposes.
- Packaged authoring skill references (internal/author/skill/references/): not
  updated. They document the Pipelines harness, not the Android app, and this
  change adds no harness runtime behaviour.
- Root README and docs/: not updated. They document the CLI/TUI/server, which
  are unchanged; the Android app is documented in android/README.md.

No conflict was present: no unmerged paths and no unfinished merge, rebase or
cherry-pick, so nothing needed resolving.
Deliberately left uncommitted (other work this run did not touch, not staged):
the worktree's other WIP - components/ListScroll.kt and screens/PaneStats.kt with
their tests, and the uncommitted edits to components/SlidingPaneStack.kt,
components/States.kt, theme/Dimens.kt and components/LoadPhaseTest.kt - plus the
untracked .ui-review-*/ capture artifacts.
This commit is contained in:
2026-10-17 01:30:27 +01:00
parent 0df0c278b0
commit 18db2f913a
13 changed files with 1175 additions and 132 deletions
+88
View File
@@ -104,6 +104,22 @@ stops it.
- Pipeline list (search/refresh, empty/error/loading states), pipeline details
(version list, content hash, source) and the workflow graph.
- A **Templates** destination (its own top-level pill between Pipelines and Runs,
with its own gallery glyph rather than the Pipelines workflow tree): a measured
gallery of cards, one per server template, each showing the template's name, its
short description and its stage count — `stage count unavailable` when the source
does not parse, never a claimed zero — with a single column on a narrow window
and as many equal-width cards as fit on a wide one, from the shared
`galleryGrid` fitting (the same rule the artifacts gallery uses) at the
`WIDE_RAIL_WIDTH_DP`/`SPACING_S` tokens, so the gallery widens by adding columns
instead of stretching cards. Tapping a card opens a detail pane that reuses the
pipeline detail's Summary / Graph / Source tabs (the stage list, the
`WorkflowGraph` and the shared `PipelineSourceView`), so the shape is readable
before choosing it; a source the server could not parse is still fully viewable
as raw markdown. A "create from this template" action submits the source as a
create-only draft pipeline (the app's equivalent of `pipelines new --template
KEY`) and never starts a run. Empty, loading and error states reuse the shared
state components.
- Workflow graph composable: content-sized stage nodes laid out in one row in
declaration order, with `#failure`/`#success` terminals sharing a lower row and
arrows entering their top borders (an `error -> #failure` route leaves its
@@ -3922,3 +3938,75 @@ Not verified in this pass: the on-device narrow/wide renders (a section opening
over the stage and returning, and the wide panel beside the stage pane) and any
screenshot of the former inline case — the brief keeps implementation
verification to the build and the unit tests, and visual review owns the device.
## Templates: a gallery and a detail view (17 Oct 2026)
The server's template catalog (`list_templates`, which `pipelines templates` and
`pipelines template <key> --source` already print) is now a first-class surface in
the app; before this change the app showed nothing for it. `android/` only:
nothing in the Pipelines server, its Go source, the Docker/compose files or the
installer was touched, no dependency was added (the destination glyph is the
already-declared material-icons-extended `Widgets`) and no run is started from the
app.
- **The destination.** `PipelinesApp`'s destination list gains a `Templates`
entry between `Pipelines` and `Runs` (`TemplatesIcon`, `Icons.Filled.Widgets`,
deliberately not the Pipelines workflow tree), and `TemplatesDestination` uses
the same shared `SlidingPaneStack` the other destinations use: pane 0 the
gallery, pane 1 the selected template's detail, with the selected key in
`rememberSaveable` so the open template survives rotation and process death.
- **The gallery.** `TemplateGalleryScreen` shows one card per template from
`vm.templates` (loaded by a new `AppViewModel.refreshTemplates`, backed by
`PipelinesRepository.listTemplates`): the name, the short description and the
stage count, with the card's own leading glyph. `templateGridColumns` decides
the layout — a single column on a narrow window, and on a wide one as many
`WIDE_RAIL_WIDTH_DP`-shaped cards as fit `SPACING_S` apart via the shared
`galleryGrid` fitting — so no new geometry constant is introduced.
- **Stage counts come from a parsed source, not a guess.** `list_templates`
carries only the source, so `refreshTemplates` parses each template's source on
the server (`validateSource`, the `validate` command) once and caches the graph
per key+source. A template whose source does not parse keeps a null graph: its
card reads `stage count unavailable` (never `0 stages`), its Graph tab says the
source could not be parsed, and its Source tab shows the raw markdown — the
template stays fully viewable.
- **The detail view reuses the pipeline-detail idiom.** `TemplateDetailScreen`
uses the same `DetailTabs` (`pipelineDetailTabs`: Summary / Graph / Source) and
the same tab body/width handling as `PipelineDetailScreen`: Summary lists the
stages, Graph renders the `WorkflowGraph` (with an explicit note when the source
did not parse), and Source renders the definition through the shared
`PipelineSourceView`.
- **One rendered-definition view, not two.** `PipelineSourceTab` moved out of
`PipelineDetailScreen` into `ui/graph/SourceView.kt` as `PipelineSourceView`, so
the pipeline detail and the template detail render a definition through exactly
one composable (per-stage collapsible sections, the Raw toggle, the copy action).
- **One gallery fitting, not two.** The artifact gallery's private
`ArtifactGrid`/`artifactGrid` fitting moved to the shared
`ui/components/GalleryGrid.kt` (`GalleryGrid`/`galleryGrid`), so the templates
gallery and the artifacts gallery share one measured-column rule and the
artefact gallery tests now exercise the shared function.
- **Create from a template.** A top-bar action on the detail opens a dialog that
submits the template's source as a create-only draft pipeline
(`AppViewModel.createFromTemplate` → `PipelinesRepository.createPipeline`, the
`submit` command with `create_only`): the app's equivalent of the CLI's
`pipelines new --template KEY` (that path writes a local draft file; the app has
no filesystem, so it stores the draft on the server, where it appears in the
Pipelines list). An existing name is never overwritten and no run is started.
- **States.** Empty, loading and error states reuse the shared `StateCrossfade`
state components; a covered pane shows only its compact identity.
Verification (this run's review stage, macOS, cached Gradle, `--no-daemon`): the
offline build and unit tests pass at **35 suites / 309 tests / 0 failures / 0
errors**, including the new `TemplatesTest` (the card/stage-count mapping, the
`stage count unavailable` label for an unparsed source, and the narrow-column /
wide-grid decision) and the relocated artifact-gallery cases now running against
the shared `galleryGrid`. The app's create path was checked against the repo's own
Go test for the server submit-with-`create_only` behaviour.
Visual review (this run, operator's Pixel 9 Pro XL, adb `47241FDAS00DLK`, built
from this tree and installed over the existing package) confirmed the gallery
renders 5 cards — a single column at the phone's ~448dp width and a 4-column
measured grid at `wm size 2000x2244` — and that each card opens a Summary / Graph
/ Source detail with the create dialog, consistent with the app's Material 3
language. The empty, loading, error and unparseable-source states were built from
the app's shared state components but could not be produced live without mutating
the operator's server.
@@ -5,12 +5,14 @@ import java.util.concurrent.ConcurrentHashMap
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.JsonElement
import net.awan.pipelines.data.protocol.Message
import net.awan.pipelines.data.protocol.Graph
import net.awan.pipelines.data.protocol.PipelineDetail
import net.awan.pipelines.data.protocol.PipelineSummary
import net.awan.pipelines.data.protocol.Protocol
import net.awan.pipelines.data.protocol.RunDetail
import net.awan.pipelines.data.protocol.RunSummary
import net.awan.pipelines.data.protocol.SessionEvidence
import net.awan.pipelines.data.protocol.Template
import net.awan.pipelines.data.protocol.UsageStats
import net.awan.pipelines.data.transport.NotConnectedException
import net.awan.pipelines.data.transport.PipelinesClient
@@ -65,6 +67,46 @@ class PipelinesRepository(
return RunHistory(response.runs ?: emptyList(), response.usage)
}
/**
* The server's template catalog: each template's name/description and its
* full, defaulted source, exactly as `pipelines templates` prints it.
*/
suspend fun listTemplates(): List<Template> =
client.call(Message(type = Protocol.LIST_TEMPLATES)).templates ?: emptyList()
/**
* Parses a definition source on the server (the `validate` command) and
* returns the resulting graph. Listing templates carries only the source, not
* its graph, so this is how the app learns a template's stages. A source the
* server cannot parse surfaces as a [ProtocolException], which the caller
* treats as "unparseable" and still shows the raw source.
*/
suspend fun validateSource(source: String): Graph =
client.call(Message(type = Protocol.VALIDATE, source = source)).graph
?: throw ProtocolException("The server returned no graph for the source.")
/**
* Creates a new pipeline from a definition [source] (the `submit` command).
* create-only, matching `pipelines new`: the name must not already exist, so
* this can only ever add a draft and never overwrite a retained pipeline. No
* run is started.
*/
suspend fun createPipeline(name: String, source: String): PipelineDetail {
if (name.isBlank()) throw ProtocolException("Enter a pipeline name.")
val response = client.call(
Message(
type = Protocol.SUBMIT,
name = name.trim(),
source = source,
createOnly = true,
),
)
// A successful submit can add a pipeline summary; the per-id detail cache
// is not affected, but keep it from serving a stale list-derived view.
clearCache()
return response.detail ?: throw ProtocolException("The server returned no pipeline detail.")
}
suspend fun getRun(id: Long): RunDetail = client.call(
Message(type = Protocol.GET_RUN, runId = id),
).runDetail ?: throw ProtocolException("The server returned no run detail.")
@@ -19,10 +19,12 @@ import net.awan.pipelines.data.PipelinesRepository
import net.awan.pipelines.data.RunHistory
import net.awan.pipelines.data.SettingsRepository
import net.awan.pipelines.data.protocol.BuildInfo
import net.awan.pipelines.data.protocol.Graph
import net.awan.pipelines.data.protocol.PipelineDetail
import net.awan.pipelines.data.protocol.PipelineSummary
import net.awan.pipelines.data.protocol.RunDetail
import net.awan.pipelines.data.protocol.SessionEvidence
import net.awan.pipelines.data.protocol.Template
import net.awan.pipelines.data.transport.ConnectionState
import net.awan.pipelines.data.transport.ServerUrl
@@ -92,6 +94,9 @@ class AppViewModel(
private val _evidence = MutableStateFlow(LoadState<List<SessionEvidence>>())
val evidence: StateFlow<LoadState<List<SessionEvidence>>> = _evidence.asStateFlow()
private val _templates = MutableStateFlow(LoadState<List<TemplateEntry>>())
val templates: StateFlow<LoadState<List<TemplateEntry>>> = _templates.asStateFlow()
private val startKeys = ConcurrentHashMap<Long, String>()
private val retryKeys = ConcurrentHashMap<Long, String>()
@@ -211,6 +216,63 @@ class AppViewModel(
fun refreshRuns() = load(_runs) { repository.listRuns() }
/**
* Loads the server's template catalog and, for each template, the graph the
* server parses from its source (the listing carries only the source). A
* template whose source does not parse keeps a null graph: it is still listed
* and its raw source still viewable. A previously loaded entry with the same
* key and source is reused, so a refresh does not re-validate unchanged
* templates.
*/
fun refreshTemplates() {
viewModelScope.launch {
_templates.value = _templates.value.copy(loading = true, error = null)
try {
val previous = _templates.value.data.orEmpty().associateBy { it.key }
val entries = repository.listTemplates().map { template ->
val cached = previous[template.key]?.takeIf { it.source == template.source }
if (cached != null) {
cached
} else {
TemplateEntry(
key = template.key,
name = template.name,
description = template.description,
source = template.source,
scheduled = template.scheduled,
graph = parseTemplateSource(template.source),
)
}
}
_templates.value = LoadState(loading = false, data = entries, loaded = true)
} catch (t: Throwable) {
if (t is CancellationException) throw t
_templates.value = _templates.value.copy(loading = false, error = ErrorMessages.describe(t))
}
}
}
/** The server-parsed graph for [source], or null when it cannot be parsed. */
private suspend fun parseTemplateSource(source: String): Graph? = try {
repository.validateSource(source)
} catch (c: CancellationException) {
throw c
} catch (_: Throwable) {
null
}
/** Creates a new create-only draft pipeline from a template's source. */
fun createFromTemplate(name: String, source: String, onResult: (Result<PipelineDetail>) -> Unit) {
viewModelScope.launch {
try {
onResult(Result.success(repository.createPipeline(name, source)))
} catch (t: Throwable) {
if (t is CancellationException) throw t
onResult(Result.failure(t))
}
}
}
fun loadEvidence(id: Long) = load(_evidence) { repository.getRunEvidence(id) }
/** Fetches an artifact's bytes for an inline image preview; null on failure. */
@@ -65,12 +65,15 @@ import net.awan.pipelines.ui.screens.PipelineListScreen
import net.awan.pipelines.ui.screens.RunDetailScreen
import net.awan.pipelines.ui.screens.RunHistoryScreen
import net.awan.pipelines.ui.screens.SettingsScreen
import net.awan.pipelines.ui.screens.TemplateDetailScreen
import net.awan.pipelines.ui.screens.TemplateGalleryScreen
import net.awan.pipelines.ui.theme.DESTINATION_PILL_RESERVE
private data class TopDestination(val route: String, val label: String, val icon: ImageVector)
private val destinations = listOf(
TopDestination("pipelines", "Pipelines", Icons.Default.AccountTree),
TopDestination("templates", "Templates", TemplatesIcon),
TopDestination("runs", "Runs", Icons.Default.History),
TopDestination("settings", "Settings", Icons.Default.Settings),
)
@@ -116,6 +119,7 @@ fun PipelinesApp(vm: AppViewModel) {
// the runs selection changes, as well as a configuration change and process
// death. The list screens only clamp it when the list changed underneath.
val pipelineListState = rememberSaveable(saver = LazyListState.Saver) { LazyListState() }
val templateListState = rememberSaveable(saver = LazyListState.Saver) { LazyListState() }
val runListState = rememberSaveable(saver = LazyListState.Saver) { LazyListState() }
val onNavigate: (TopDestination) -> Unit = { destination ->
@@ -186,6 +190,9 @@ fun PipelinesApp(vm: AppViewModel) {
listState = runListState,
)
}
composable("templates") {
TemplatesDestination(vm = vm, wide = wide, listState = templateListState)
}
composable("settings") {
SettingsScreen(vm)
}
@@ -446,6 +453,61 @@ private fun RunsDestination(
)
}
/**
* The Templates destination: the same shared pane stack, with the template
* gallery as pane 0 and the selected template's detail as pane 1. The selected
* template key is the saved state, so it survives rotation, configuration change
* and process death; Back/the peek pop one level. Nothing here starts a run.
*/
@Composable
private fun TemplatesDestination(
vm: AppViewModel,
wide: Boolean,
listState: LazyListState,
) {
var selectedKey by rememberSaveable { mutableStateOf<String?>(null) }
val depth = if (selectedKey == null) 0 else 1
val onBack: () -> Unit = { selectedKey = null }
PredictiveBackHandler(enabled = depth >= 1) { progress ->
progress.collect { }
onBack()
}
SlidingPaneStack(
depth = depth,
wide = wide,
onPopTo = { level -> if (level <= 0) selectedKey = null },
compactLabel = "Templates",
compactIcon = TemplatesIcon,
backContentDescription = { level ->
if (level == 0) "Back to templates" else "Back to template"
},
pane = { level, covered, paneModifier ->
when (level) {
0 -> TemplateGalleryScreen(
vm = vm,
wide = wide,
onOpen = { key -> selectedKey = key },
listState = listState,
modifier = paneModifier,
covered = covered,
)
1 -> rememberPaneContent(selectedKey)?.let { key ->
TemplateDetailScreen(
vm = vm,
templateKey = key,
onBack = onBack,
wide = wide,
modifier = paneModifier,
covered = covered,
)
}
}
},
)
}
/**
* The horizontal offset of the pill's travelling selection indicator for the
* destination at [index]: the pill's inner padding plus [index] item slots
@@ -0,0 +1,78 @@
package net.awan.pipelines.ui
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Widgets
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.unit.Dp
import net.awan.pipelines.data.protocol.Graph
import net.awan.pipelines.ui.components.galleryGrid
/**
* The Templates surface's own glyph (the destination pill's icon and a covered
* pane's compact identity), deliberately a gallery/grid glyph rather than the
* Pipelines destination's workflow tree.
*/
internal val TemplatesIcon: ImageVector = Icons.Filled.Widgets
/**
* One server template plus the graph the server parsed from its source (null when
* the source could not be parsed, or the server does not answer `validate`). The
* gallery and the detail view both read this one entry, so a card's stage count
* and the detail's stage list/graph can never disagree.
*/
data class TemplateEntry(
val key: String,
val name: String,
val description: String,
val source: String,
val scheduled: Boolean,
val graph: Graph?,
)
/**
* One gallery card's content: the template's name and description (from the
* catalog) and its stage count (from the graph parsed out of the source; null
* when the source could not be parsed, so the card says so rather than claiming
* zero stages). Pure, so the mapping is unit-tested without a device.
*/
internal data class TemplateCard(
val key: String,
val name: String,
val description: String,
val stageCount: Int?,
)
/** The card content for [entry]: name/description from the catalog, count from the parsed source. */
internal fun templateCard(entry: TemplateEntry): TemplateCard =
TemplateCard(
key = entry.key,
name = entry.name,
description = entry.description,
stageCount = entry.graph?.stages?.size,
)
/**
* How many columns the templates gallery lays out at a given window: a single
* column on a narrow window (the list form) and, on a wide one, as many
* [preferred]-width cards as fit [availableWidth] with their [spacing] gaps —
* the shared [galleryGrid] fitting, so the gallery widens by adding columns
* rather than stretching cards. Pure, so the grid/list decision is unit-tested
* without a device.
*/
internal fun templateGridColumns(
wide: Boolean,
availableWidth: Dp,
preferred: Dp,
spacing: Dp,
): Int = if (!wide) 1 else galleryGrid(availableWidth, preferred, spacing).columns
/**
* The card's stage-count line: the count from the parsed source, or an explicit
* "unavailable" when the source could not be parsed (never "0 stages", which
* would claim a count the app does not have). Pure, so it is unit-tested.
*/
internal fun templateStageCountLabel(stageCount: Int?): String = when (stageCount) {
null -> "stage count unavailable"
1 -> "1 stage"
else -> "$stageCount stages"
}
@@ -0,0 +1,26 @@
package net.awan.pipelines.ui.components
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
/**
* One row's gallery geometry: the number of [columns] that fit and the width each
* [cell] is stretched to. Shared by every measured gallery in the app (the
* artifacts gallery and the templates gallery), so the fitting rule lives in
* exactly one place and neither screen picks its own column count.
*/
internal data class GalleryGrid(val columns: Int, val cell: Dp)
/**
* The gallery geometry for [availableWidth]: the most [preferred]-shaped cells
* that fit with their [spacing] gaps, and each cell widened to fill the row
* exactly. A window narrower than one preferred cell falls back to a single,
* narrower cell; a non-positive preferred token never divides by zero. Pure, so
* the fitting is unit-tested without a device.
*/
internal fun galleryGrid(availableWidth: Dp, preferred: Dp, spacing: Dp): GalleryGrid {
if (preferred <= 0.dp) return GalleryGrid(columns = 1, cell = availableWidth.coerceAtLeast(0.dp))
val columns = ((availableWidth + spacing) / (preferred + spacing)).toInt().coerceAtLeast(1)
val cell = ((availableWidth - spacing * (columns - 1)) / columns).coerceAtLeast(0.dp)
return GalleryGrid(columns = columns, cell = cell)
}
@@ -53,6 +53,7 @@ import net.awan.pipelines.ui.artifactCaptureNotes
import net.awan.pipelines.ui.artifactMetaLine
import net.awan.pipelines.ui.artifactsSummary
import net.awan.pipelines.ui.components.copyText
import net.awan.pipelines.ui.components.galleryGrid
import net.awan.pipelines.ui.isImageContentType
import net.awan.pipelines.ui.theme.ARTIFACT_BADGE_DP
import net.awan.pipelines.ui.theme.ARTIFACT_THUMB_DP
@@ -120,7 +121,7 @@ internal fun ArtifactsSection(
* nests a scrollable inside the Summary [LazyColumn] or the pane's scroll.
*
* The grid geometry is derived from the measured width (one [BoxWithConstraints],
* see [artifactGrid]): as many cells as fit at the preferred [ARTIFACT_TILE_DP]
* see [galleryGrid]): as many cells as fit at the preferred [ARTIFACT_TILE_DP]
* shape, stretched to fill the row, so a wide window shows several thumbnails per
* row and a narrow one shows fewer, larger ones — never a fixed column count.
*/
@@ -136,7 +137,7 @@ internal fun ArtifactGallery(
) {
val text = pipelinesText()
BoxWithConstraints(modifier.fillMaxWidth()) {
val grid = artifactGrid(
val grid = galleryGrid(
availableWidth = maxWidth,
preferred = ARTIFACT_TILE_DP,
spacing = ARTIFACT_TILE_SPACING_DP,
@@ -186,26 +187,6 @@ internal fun ArtifactGallery(
}
}
/**
* One gallery row's geometry: the number of cells that fit the measured width at
* the preferred tile shape and the side each cell is stretched to. Pure, so the
* fitting is unit-tested without a device.
*/
internal data class ArtifactGrid(val columns: Int, val cell: Dp)
/**
* The gallery geometry for [availableWidth]: the most [preferred]-shaped cells
* that fit with their [spacing] gaps, and each cell widened to fill the row
* exactly. A window narrower than one preferred cell falls back to a single,
* narrower cell; a non-positive preferred token never divides by zero. Pure.
*/
internal fun artifactGrid(availableWidth: Dp, preferred: Dp, spacing: Dp): ArtifactGrid {
if (preferred <= 0.dp) return ArtifactGrid(columns = 1, cell = availableWidth.coerceAtLeast(0.dp))
val columns = ((availableWidth + spacing) / (preferred + spacing)).toInt().coerceAtLeast(1)
val cell = ((availableWidth - spacing * (columns - 1)) / columns).coerceAtLeast(0.dp)
return ArtifactGrid(columns = columns, cell = cell)
}
/**
* The absolute url a gallery artifact is previewed/opened at, or null when it
* cannot be resolved against the configured server (blank or invalid). The one
@@ -0,0 +1,130 @@
package net.awan.pipelines.ui.graph
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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalClipboardManager
import net.awan.pipelines.data.protocol.Graph
import net.awan.pipelines.ui.components.CodeBlock
import net.awan.pipelines.ui.components.collapsibleSection
import net.awan.pipelines.ui.components.copyText
import net.awan.pipelines.ui.components.rememberSectionExpansion
import net.awan.pipelines.ui.theme.ICON_INLINE_DP
import net.awan.pipelines.ui.theme.SPACING_L
import net.awan.pipelines.ui.theme.SPACING_S
import net.awan.pipelines.ui.theme.SPACING_XS
import net.awan.pipelines.ui.theme.pipelinesText
/**
* The one rendered-definition view: a source's parsed [graph] as collapsible
* per-stage sections built from the same [stageDefinitionFields] the stage pane
* uses, with the exact markdown one tap away behind the Raw toggle and a
* copy-whole-definition action. Shared by the pipeline detail's Source tab and
* the template detail, so a definition is rendered the same way wherever it is
* read.
*
* It fills the whole tab area (page-level scrolling, no cramped inner box); the
* caller supplies the single scroll owner. An empty graph says so explicitly.
*/
@Composable
internal fun PipelineSourceView(
source: String,
graph: Graph,
modifier: Modifier = Modifier,
) {
val text = pipelinesText()
val clipboard = LocalClipboardManager.current
var showRaw by rememberSaveable { mutableStateOf(false) }
val stages = graph.stages
// Derived once per definition change, not per recomposition.
val sections = remember(stages) {
stages.map { stage ->
// The heading already names the type, so drop the redundant row.
stage to stageDefinitionFields(stage).filterNot { it.label == "Type" }
}
}
val expansion = rememberSectionExpansion(stages)
LazyColumn(
modifier = modifier.fillMaxSize(),
contentPadding = PaddingValues(vertical = SPACING_L),
) {
item(key = "source-actions") {
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = SPACING_L),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(SPACING_S),
) {
OutlinedButton(onClick = { showRaw = !showRaw }) {
Text(if (showRaw) "Rendered" else "Raw")
}
OutlinedButton(onClick = { clipboard.copyText(source) }) {
Icon(
imageVector = Icons.Default.ContentCopy,
contentDescription = null,
modifier = Modifier.size(ICON_INLINE_DP),
)
Spacer(Modifier.width(SPACING_S))
Text("Copy definition")
}
}
}
when {
showRaw -> item(key = "source-raw") {
CodeBlock(
"Definition source",
source,
Modifier.padding(horizontal = SPACING_L, vertical = SPACING_XS),
maxHeight = null,
)
}
stages.isEmpty() -> item(key = "source-empty") {
Text(
"This definition has no stages.",
style = text.meta,
modifier = Modifier.padding(horizontal = SPACING_L, vertical = SPACING_S),
)
}
else -> sections.forEach { (stage, fields) ->
val sectionKey = "source-${stage.key}"
collapsibleSection(
title = "${stage.key} · ${effectiveStageType(stage.type)}",
key = sectionKey,
expanded = expansion.isExpanded(sectionKey),
onToggle = { expansion.toggle(sectionKey) },
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = SPACING_L, vertical = SPACING_S),
verticalArrangement = Arrangement.spacedBy(SPACING_XS),
) {
fields.forEach { field -> StageFieldRow(field) }
}
}
}
}
}
}
@@ -4,19 +4,15 @@ 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.WindowInsetsSides
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.AccountTree
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.AlertDialog
@@ -26,7 +22,6 @@ import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
@@ -39,16 +34,13 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import java.time.OffsetDateTime
import net.awan.pipelines.data.ErrorMessages
import net.awan.pipelines.data.protocol.PipelineDetail
import net.awan.pipelines.data.protocol.VersionSummary
import net.awan.pipelines.ui.AppViewModel
import net.awan.pipelines.ui.components.CodeBlock
import net.awan.pipelines.ui.components.DetailTabBody
import net.awan.pipelines.ui.components.DetailTabs
import net.awan.pipelines.ui.components.ErrorState
@@ -58,17 +50,12 @@ import net.awan.pipelines.ui.components.LoadingState
import net.awan.pipelines.ui.components.PaneIdentity
import net.awan.pipelines.ui.components.StateCrossfade
import net.awan.pipelines.ui.components.collapsibleSection
import net.awan.pipelines.ui.components.copyText
import net.awan.pipelines.ui.components.detailLoadPhase
import net.awan.pipelines.ui.components.paneSafeArea
import net.awan.pipelines.ui.components.pipelineDetailTabs
import net.awan.pipelines.ui.components.rememberPaneContent
import net.awan.pipelines.ui.components.rememberSectionExpansion
import net.awan.pipelines.ui.graph.StageFieldRow
import net.awan.pipelines.ui.graph.PipelineSourceView
import net.awan.pipelines.ui.graph.WorkflowGraph
import net.awan.pipelines.ui.graph.effectiveStageType
import net.awan.pipelines.ui.graph.stageDefinitionFields
import net.awan.pipelines.ui.theme.ICON_INLINE_DP
import net.awan.pipelines.ui.theme.SPACING_L
import net.awan.pipelines.ui.theme.SPACING_M
import net.awan.pipelines.ui.theme.SPACING_S
@@ -171,7 +158,11 @@ fun PipelineDetailScreen(
modifier = contentModifier,
onStageTap = onOpenStage,
)
else -> PipelineSourceTab(shownDetail, contentModifier)
else -> PipelineSourceView(
shownDetail.source,
shownDetail.graph,
contentModifier,
)
}
}
}
@@ -284,92 +275,6 @@ private fun PipelineGraphTab(
}
}
/**
* The Source tab fills the whole tab area (page-level scrolling, no cramped
* inner box) and renders the parsed definition: one collapsible section per
* stage (name · type) holding labelled blocks built from the same
* [stageDefinitionFields] the stage detail sheet uses, so the two cannot
* diverge. Absent fields are skipped. The exact markdown is one tap away behind
* the Raw toggle and a copy-whole-definition action.
*/
@Composable
private fun PipelineSourceTab(detail: PipelineDetail, modifier: Modifier) {
val text = pipelinesText()
val clipboard = LocalClipboardManager.current
var showRaw by rememberSaveable { mutableStateOf(false) }
val stages = detail.graph.stages
// Derived once per definition change, not per recomposition.
val sections = remember(stages) {
stages.map { stage ->
// The heading already names the type, so drop the redundant row.
stage to stageDefinitionFields(stage).filterNot { it.label == "Type" }
}
}
val expansion = rememberSectionExpansion(stages)
LazyColumn(
modifier = modifier.fillMaxSize(),
contentPadding = PaddingValues(vertical = SPACING_L),
) {
item(key = "source-actions") {
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = SPACING_L),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(SPACING_S),
) {
OutlinedButton(onClick = { showRaw = !showRaw }) {
Text(if (showRaw) "Rendered" else "Raw")
}
OutlinedButton(onClick = { clipboard.copyText(detail.source) }) {
Icon(
imageVector = Icons.Default.ContentCopy,
contentDescription = null,
modifier = Modifier.size(ICON_INLINE_DP),
)
Spacer(Modifier.width(SPACING_S))
Text("Copy definition")
}
}
}
when {
showRaw -> item(key = "source-raw") {
CodeBlock(
"Definition source",
detail.source,
Modifier.padding(horizontal = SPACING_L, vertical = SPACING_XS),
maxHeight = null,
)
}
stages.isEmpty() -> item(key = "source-empty") {
Text(
"This definition has no stages.",
style = text.meta,
modifier = Modifier.padding(horizontal = SPACING_L, vertical = SPACING_S),
)
}
else -> sections.forEach { (stage, fields) ->
val sectionKey = "source-${stage.key}"
collapsibleSection(
title = "${stage.key} · ${effectiveStageType(stage.type)}",
key = sectionKey,
expanded = expansion.isExpanded(sectionKey),
onToggle = { expansion.toggle(sectionKey) },
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = SPACING_L, vertical = SPACING_S),
verticalArrangement = Arrangement.spacedBy(SPACING_XS),
) {
fields.forEach { field -> StageFieldRow(field) }
}
}
}
}
}
}
@Composable
private fun VersionRow(v: VersionSummary, modifier: Modifier = Modifier) {
val text = pipelinesText()
@@ -0,0 +1,352 @@
package net.awan.pipelines.ui.screens
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.WindowInsetsSides
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import net.awan.pipelines.data.ErrorMessages
import net.awan.pipelines.ui.AppViewModel
import net.awan.pipelines.ui.TemplateEntry
import net.awan.pipelines.ui.TemplatesIcon
import net.awan.pipelines.ui.components.CodeBlock
import net.awan.pipelines.ui.components.DetailTabBody
import net.awan.pipelines.ui.components.DetailTabs
import net.awan.pipelines.ui.components.ErrorState
import net.awan.pipelines.ui.components.LoadPhase
import net.awan.pipelines.ui.components.LoadingState
import net.awan.pipelines.ui.components.PaneIdentity
import net.awan.pipelines.ui.components.StateCrossfade
import net.awan.pipelines.ui.components.clampTabIndex
import net.awan.pipelines.ui.components.detailLoadPhase
import net.awan.pipelines.ui.components.paneSafeArea
import net.awan.pipelines.ui.components.pipelineDetailTabs
import net.awan.pipelines.ui.graph.PipelineSourceView
import net.awan.pipelines.ui.graph.WorkflowGraph
import net.awan.pipelines.ui.graph.effectiveStageType
import net.awan.pipelines.ui.templateStageCountLabel
import net.awan.pipelines.ui.theme.SPACING_L
import net.awan.pipelines.ui.theme.SPACING_S
import net.awan.pipelines.ui.theme.SPACING_XS
import net.awan.pipelines.ui.theme.SPACING_XXS
import net.awan.pipelines.ui.theme.pipelinesText
/**
* One template's detail: the same Summary / Graph / Source tab idiom the pipeline
* detail uses, so a template is read the way a pipeline is. Summary carries the
* name, description and stage list; Graph renders the stage graph when the source
* parsed; Source renders the parsed definition through the shared
* [PipelineSourceView]. A source the server could not parse is still fully
* viewable: Graph says so and Source shows the raw markdown.
*
* The top-bar action creates a create-only draft pipeline from the template's
* source (see [CreateFromTemplateDialog]); it never starts a run.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TemplateDetailScreen(
vm: AppViewModel,
templateKey: String,
onBack: () -> Unit,
wide: Boolean = false,
modifier: Modifier = Modifier,
covered: Boolean = false,
) {
val state by vm.templates.collectAsStateWithLifecycle()
val entry = state.data?.firstOrNull { it.key == templateKey }
var selectedSection by rememberSaveable(templateKey) { mutableStateOf(0) }
var showCreate by remember { mutableStateOf(false) }
// A covered pane shows its compact identity only; the tab rail and body must
// never be drawn squeezed into the peek strip.
if (covered) {
PaneIdentity(
title = entry?.name ?: "Template",
icon = TemplatesIcon,
modifier = modifier.fillMaxSize(),
)
return
}
Scaffold(
modifier = modifier,
contentWindowInsets = paneSafeArea(),
topBar = {
TopAppBar(
title = { Text(entry?.name ?: "Template") },
navigationIcon = {
IconButton(onClick = onBack) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
}
},
windowInsets = paneSafeArea().only(WindowInsetsSides.Top + WindowInsetsSides.Horizontal),
actions = {
IconButton(onClick = vm::refreshTemplates) {
Icon(Icons.Default.Refresh, contentDescription = "Refresh templates")
}
IconButton(onClick = { showCreate = true }, enabled = entry != null) {
Icon(Icons.Default.Add, contentDescription = "Create pipeline from this template")
}
},
)
},
) { padding ->
StateCrossfade(
phase = detailLoadPhase(state.error, hasData = entry != null),
modifier = Modifier.fillMaxSize().padding(padding),
) { phase ->
when (phase) {
is LoadPhase.Error -> ErrorState(phase.message, onRetry = vm::refreshTemplates)
LoadPhase.Loading -> LoadingState("Loading template…")
else -> if (entry != null) {
val selected = clampTabIndex(selectedSection, pipelineDetailTabs.size)
DetailTabs(
tabs = pipelineDetailTabs,
selectedIndex = selected,
onSelect = { selectedSection = it },
wide = wide,
modifier = Modifier.fillMaxSize(),
) { tab, contentModifier ->
when (tab.key) {
"summary" -> TemplateSummaryTab(entry, wide, contentModifier)
"graph" -> TemplateGraphTab(entry, contentModifier)
else -> TemplateSourceTab(entry, contentModifier)
}
}
}
}
}
}
if (showCreate && entry != null) {
CreateFromTemplateDialog(vm = vm, entry = entry, onDismiss = { showCreate = false })
}
}
/** The template's identity and its stage list, or an explicit note when it did not parse. */
@Composable
private fun TemplateSummaryTab(entry: TemplateEntry, wide: Boolean, modifier: Modifier) {
val text = pipelinesText()
val stages = entry.graph?.stages.orEmpty()
DetailTabBody(wide, modifier) { columnModifier ->
LazyColumn(
modifier = columnModifier,
contentPadding = PaddingValues(vertical = SPACING_L),
) {
item(key = "template-summary") {
Column(
modifier = Modifier.fillMaxWidth().padding(horizontal = SPACING_L),
verticalArrangement = Arrangement.spacedBy(SPACING_XS),
) {
Text(entry.name.ifBlank { entry.key }, style = text.screenTitle)
if (entry.description.isNotBlank()) {
Text(entry.description, style = text.body)
}
Text("key ${entry.key}", style = text.meta)
Text(templateStageCountLabel(entry.graph?.stages?.size), style = text.meta)
if (entry.scheduled) {
Text("Includes a schedule", style = text.meta)
}
}
}
if (entry.graph == null) {
item(key = "template-unparsed") {
Text(
"This template's source could not be parsed, so its stages are not listed. See the Source tab for the raw definition.",
style = text.meta,
modifier = Modifier.padding(horizontal = SPACING_L, vertical = SPACING_S),
)
}
} else if (stages.isEmpty()) {
item(key = "template-no-stages") {
Text(
"This template has no stages.",
style = text.meta,
modifier = Modifier.padding(horizontal = SPACING_L, vertical = SPACING_S),
)
}
} else {
item(key = "template-stages-heading") {
Text(
"Stages",
style = text.sectionHeader,
modifier = Modifier.padding(horizontal = SPACING_L, vertical = SPACING_XS),
)
}
items(stages, key = { it.key }) { stage ->
Column(
modifier = Modifier.fillMaxWidth().padding(horizontal = SPACING_L, vertical = SPACING_XS),
verticalArrangement = Arrangement.spacedBy(SPACING_XXS),
) {
Text(stage.key, style = text.cardTitle)
Text(effectiveStageType(stage.type), style = text.meta)
}
}
}
}
}
}
/** The stage graph when the source parsed; an explicit note when it did not. */
@Composable
private fun TemplateGraphTab(entry: TemplateEntry, modifier: Modifier) {
val text = pipelinesText()
val graph = entry.graph
if (graph == null) {
Text(
"This template's source could not be parsed, so there is no graph. The Source tab shows the raw definition.",
style = text.meta,
modifier = modifier.fillMaxSize().padding(SPACING_L),
)
return
}
LazyColumn(
modifier = modifier,
contentPadding = PaddingValues(vertical = SPACING_L),
) {
item(key = "template-graph") {
Column(
modifier = Modifier.fillMaxWidth().padding(horizontal = SPACING_L),
verticalArrangement = Arrangement.spacedBy(SPACING_S),
) {
Text(
"Pinch to zoom and drag to pan. The graph is the parsed definition; nothing runs.",
style = text.meta,
)
WorkflowGraph(graph = graph, modifier = Modifier.fillMaxWidth())
}
}
}
}
/**
* The Source tab: the shared rendered definition when the source parsed, else the
* raw markdown with a note, so an unparseable template is still fully readable.
*/
@Composable
private fun TemplateSourceTab(entry: TemplateEntry, modifier: Modifier) {
val text = pipelinesText()
val graph = entry.graph
if (graph == null) {
Column(
modifier = modifier.fillMaxSize().padding(horizontal = SPACING_L, vertical = SPACING_L),
verticalArrangement = Arrangement.spacedBy(SPACING_S),
) {
Text(
"This source could not be parsed on the server; showing the raw definition.",
style = text.meta,
)
CodeBlock(
label = "Definition source",
text = entry.source,
modifier = Modifier.fillMaxWidth(),
maxHeight = null,
)
}
} else {
PipelineSourceView(entry.source, graph, modifier)
}
}
/**
* The "create from this template" action: submits the template's source as a new
* create-only draft pipeline. It is the app's equivalent of the CLI's
* `pipelines new --template KEY` (that CLI path writes a local draft file, which
* the app has no filesystem for); the server stores the draft and it appears in
* the Pipelines list. No run is started and an existing name is never overwritten.
*/
@Composable
private fun CreateFromTemplateDialog(
vm: AppViewModel,
entry: TemplateEntry,
onDismiss: () -> Unit,
) {
var name by remember { mutableStateOf(entry.name) }
var submitting by remember { mutableStateOf(false) }
var error by remember { mutableStateOf<String?>(null) }
var created by remember { mutableStateOf<String?>(null) }
AlertDialog(
onDismissRequest = { if (!submitting) onDismiss() },
title = { Text("Create from ${entry.name.ifBlank { entry.key }}") },
text = {
Column(verticalArrangement = Arrangement.spacedBy(SPACING_S)) {
OutlinedTextField(
value = name,
onValueChange = { name = it },
label = { Text("New pipeline name (required)") },
enabled = !submitting && created == null,
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
Text(
"Creates a new draft pipeline on the server from this template's source; it is not run.",
style = MaterialTheme.typography.bodySmall,
)
if (error != null) {
Text(
error!!,
color = MaterialTheme.colorScheme.error,
style = MaterialTheme.typography.bodySmall,
)
}
if (created != null) {
Text(
"Created \"$created\". It is in the Pipelines list.",
style = MaterialTheme.typography.bodySmall,
)
}
}
},
confirmButton = {
Button(
enabled = !submitting && created == null && name.isNotBlank(),
onClick = {
submitting = true
error = null
vm.createFromTemplate(name, entry.source) { result ->
submitting = false
result.onSuccess {
created = it.name.ifBlank { name.trim() }
vm.refreshPipelines()
}.onFailure { error = ErrorMessages.describe(it) }
}
},
) { Text(if (submitting) "Creating…" else "Create") }
},
dismissButton = {
TextButton(onClick = onDismiss, enabled = !submitting) {
Text(if (created != null) "Close" else "Cancel")
}
},
)
}
@@ -0,0 +1,232 @@
package net.awan.pipelines.ui.screens
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.BoxWithConstraints
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.WindowInsetsSides
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.clickable
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Description
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import net.awan.pipelines.ui.AppViewModel
import net.awan.pipelines.ui.TemplateCard
import net.awan.pipelines.ui.TemplateEntry
import net.awan.pipelines.ui.TemplatesIcon
import net.awan.pipelines.ui.components.EmptyState
import net.awan.pipelines.ui.components.ErrorState
import net.awan.pipelines.ui.components.LoadPhase
import net.awan.pipelines.ui.components.LoadingState
import net.awan.pipelines.ui.components.PaneIdentity
import net.awan.pipelines.ui.components.RestoreListScroll
import net.awan.pipelines.ui.components.StateCrossfade
import net.awan.pipelines.ui.components.animateListItem
import net.awan.pipelines.ui.components.listLoadPhase
import net.awan.pipelines.ui.components.paneSafeArea
import net.awan.pipelines.ui.templateCard
import net.awan.pipelines.ui.templateGridColumns
import net.awan.pipelines.ui.templateStageCountLabel
import net.awan.pipelines.ui.theme.SPACING_L
import net.awan.pipelines.ui.theme.SPACING_S
import net.awan.pipelines.ui.theme.SPACING_XXS
import net.awan.pipelines.ui.theme.WIDE_RAIL_WIDTH_DP
import net.awan.pipelines.ui.theme.pipelinesText
/**
* The Templates gallery: one card per server template with its name, a short
* description and its stage count, laid out as a measured gallery (the app's
* existing [templateGridColumns] fitting): a single column on a narrow window
* and as many equal-width cards as fit on a wide one. Tapping a card opens its
* detail pane.
*
* A covered pane shows its compact identity only; the grid must never be drawn
* squeezed into the peek strip.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TemplateGalleryScreen(
vm: AppViewModel,
wide: Boolean,
onOpen: (String) -> Unit,
listState: LazyListState,
modifier: Modifier = Modifier,
covered: Boolean = false,
) {
val state by vm.templates.collectAsStateWithLifecycle()
LaunchedEffect(Unit) { vm.refreshTemplates() }
if (covered) {
PaneIdentity(
title = "Templates",
icon = TemplatesIcon,
modifier = modifier.fillMaxSize(),
)
return
}
Scaffold(
modifier = modifier,
contentWindowInsets = paneSafeArea(),
topBar = {
TopAppBar(
title = { Text("Templates") },
windowInsets = paneSafeArea().only(WindowInsetsSides.Top + WindowInsetsSides.Horizontal),
actions = {
IconButton(onClick = vm::refreshTemplates) {
Icon(Icons.Default.Refresh, contentDescription = "Refresh templates")
}
},
)
},
) { padding ->
val entries = state.data.orEmpty()
StateCrossfade(
phase = listLoadPhase(
loading = state.loading,
error = state.error,
hasData = state.data != null,
emptyMessage = if (entries.isEmpty()) {
"No templates are available on this server."
} else {
null
},
loaded = state.loaded,
),
modifier = Modifier.fillMaxSize().padding(padding),
) { phase ->
when (phase) {
LoadPhase.Loading -> LoadingState("Loading templates…")
is LoadPhase.Error -> ErrorState(phase.message, onRetry = vm::refreshTemplates)
is LoadPhase.Empty -> EmptyState(phase.message)
LoadPhase.Content -> TemplateGrid(entries, wide, onOpen, listState)
}
}
}
}
/** The measured gallery grid: [templateGridColumns] decides the column count, then cards fill each row. */
@Composable
private fun TemplateGrid(
entries: List<TemplateEntry>,
wide: Boolean,
onOpen: (String) -> Unit,
listState: LazyListState,
) {
BoxWithConstraints(Modifier.fillMaxSize()) {
val columns = templateGridColumns(
wide = wide,
availableWidth = maxWidth,
preferred = WIDE_RAIL_WIDTH_DP.dp,
spacing = SPACING_S,
)
val rows = entries.chunked(columns)
RestoreListScroll(listState, rows.size)
LazyColumn(
state = listState,
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(SPACING_L),
verticalArrangement = Arrangement.spacedBy(SPACING_S),
) {
items(rows, key = { it.first().key }) { row ->
Row(
modifier = animateListItem(Modifier.fillMaxWidth()),
horizontalArrangement = Arrangement.spacedBy(SPACING_S),
) {
row.forEach { entry ->
TemplateCardItem(
card = templateCard(entry),
onClick = { onOpen(entry.key) },
modifier = Modifier.weight(1f),
)
}
// Keep a partial last row's cards aligned to the grid.
repeat(columns - row.size) {
Spacer(Modifier.weight(1f))
}
}
}
}
}
}
/**
* One template card: a leading glyph of its own (a definition document, not the
* Pipelines destination's workflow tree), the name, the short description and the
* stage count derived from the source.
*/
@Composable
private fun TemplateCardItem(
card: TemplateCard,
onClick: () -> Unit,
modifier: Modifier = Modifier,
) {
val text = pipelinesText()
Card(
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainerHigh),
elevation = CardDefaults.cardElevation(defaultElevation = 0.dp),
modifier = modifier.clickable(onClick = onClick),
) {
Row(
modifier = Modifier.fillMaxWidth().padding(SPACING_L),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(SPACING_L),
) {
Icon(
imageVector = Icons.Default.Description,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
Column(
modifier = Modifier.weight(1f),
verticalArrangement = Arrangement.spacedBy(SPACING_XXS),
) {
Text(
card.name.ifBlank { "(unnamed template)" },
style = text.cardTitle,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
Text(
card.description,
style = text.meta,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
Text(
templateStageCountLabel(card.stageCount),
style = text.meta,
color = MaterialTheme.colorScheme.primary,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
}
}
@@ -0,0 +1,83 @@
package net.awan.pipelines.ui
import androidx.compose.ui.unit.dp
import net.awan.pipelines.data.protocol.Graph
import net.awan.pipelines.data.protocol.Stage
import net.awan.pipelines.ui.theme.SPACING_S
import net.awan.pipelines.ui.theme.WIDE_RAIL_WIDTH_DP
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* The templates mapping and the gallery grid/list decision, both pure: the card
* content comes from the catalog plus the graph parsed out of the source, and the
* column count comes from the window width.
*/
class TemplatesTest {
private val preferred = WIDE_RAIL_WIDTH_DP.dp
private val spacing = SPACING_S
private fun entry(graph: Graph?) = TemplateEntry(
key = "three-stage",
name = "Plan, implement, review",
description = "Plan a change, implement it, then review and verify it.",
source = "# stage plan\n…",
scheduled = false,
graph = graph,
)
@Test
fun cardCarriesTheNameDescriptionAndStageCountFromTheParsedSource() {
val graph = Graph(
stages = listOf(Stage(key = "plan"), Stage(key = "implement"), Stage(key = "review")),
)
val card = templateCard(entry(graph))
assertEquals("three-stage", card.key)
assertEquals("Plan, implement, review", card.name)
assertEquals("Plan a change, implement it, then review and verify it.", card.description)
assertEquals(3, card.stageCount)
}
@Test
fun cardReportsNoCountWhenTheSourceDidNotParse() {
// A null graph is "not parsed", never zero stages.
val card = templateCard(entry(graph = null))
assertNull(card.stageCount)
}
@Test
fun stageCountLabelSpellsOutUnknownRatherThanClaimingZero() {
assertEquals("stage count unavailable", templateStageCountLabel(null))
assertEquals("1 stage", templateStageCountLabel(1))
assertEquals("4 stages", templateStageCountLabel(4))
}
@Test
fun aNarrowWindowIsASingleColumn() {
// The list form: one column at every narrow width, even one that would fit
// several cards.
assertEquals(1, templateGridColumns(wide = false, availableWidth = 1200.dp, preferred = preferred, spacing = spacing))
assertEquals(1, templateGridColumns(wide = false, availableWidth = 360.dp, preferred = preferred, spacing = spacing))
assertEquals(1, templateGridColumns(wide = false, availableWidth = 0.dp, preferred = preferred, spacing = spacing))
}
@Test
fun aWideWindowBecomesAGridThatFitsTheAvailableWidth() {
val columns = templateGridColumns(wide = true, availableWidth = 666.dp, preferred = preferred, spacing = spacing)
assertTrue("expected more than one column, got $columns", columns > 1)
val used = columns * ((666f - spacing.value * (columns - 1)) / columns) +
(columns - 1) * spacing.value
assertTrue("row $used wider than the host", used <= 666f + 0.001f)
}
@Test
fun aWideWindowNarrowerThanOneCardStillYieldsOneColumn() {
assertEquals(
1,
templateGridColumns(wide = true, availableWidth = 40.dp, preferred = preferred, spacing = spacing),
)
}
}
@@ -3,6 +3,8 @@ package net.awan.pipelines.ui.graph
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import net.awan.pipelines.data.protocol.StageArtifact
import net.awan.pipelines.ui.components.GalleryGrid
import net.awan.pipelines.ui.components.galleryGrid
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
@@ -39,7 +41,7 @@ class ArtifactGalleryTest {
// A depth-2 phone stage pane is ~360dp less the peeks and side paddings
// ≈216dp: the grid fits two preferred-shaped cells (not a forced three)
// and stretches each to fill the row.
val grid = artifactGrid(availableWidth = 216.dp, preferred = preferred, spacing = spacing)
val grid = galleryGrid(availableWidth = 216.dp, preferred = preferred, spacing = spacing)
assertEquals(2, grid.columns)
assertEquals((216f - 8f) / 2f, grid.cell.value, 0.001f)
assertTrue(grid.cell >= preferred)
@@ -50,7 +52,7 @@ class ArtifactGalleryTest {
fun aWiderWindowFitsMoreColumnsOfThePreferredShape() {
// 328dp fits three preferred 96dp cells plus their gaps, so the grid adds
// a column instead of inflating the cells.
val grid = artifactGrid(availableWidth = 328.dp, preferred = preferred, spacing = spacing)
val grid = galleryGrid(availableWidth = 328.dp, preferred = preferred, spacing = spacing)
assertEquals(3, grid.columns)
assertEquals((328f - 2 * 8f) / 3f, grid.cell.value, 0.001f)
assertRowFits(grid, availableWidth = 328.dp)
@@ -60,7 +62,7 @@ class ArtifactGalleryTest {
fun aVeryWideWindowKeepsCellsNearThePreferredShape() {
// The cell never grows far past the preferred token; the width becomes
// more columns instead.
val grid = artifactGrid(availableWidth = 1200.dp, preferred = preferred, spacing = spacing)
val grid = galleryGrid(availableWidth = 1200.dp, preferred = preferred, spacing = spacing)
assertTrue(grid.columns > 3)
assertTrue(grid.cell.value in preferred.value..(preferred.value + spacing.value))
assertRowFits(grid, availableWidth = 1200.dp)
@@ -68,7 +70,7 @@ class ArtifactGalleryTest {
@Test
fun aHostNarrowerThanOnePreferredCellFallsBackToASingleCell() {
val grid = artifactGrid(availableWidth = 60.dp, preferred = preferred, spacing = spacing)
val grid = galleryGrid(availableWidth = 60.dp, preferred = preferred, spacing = spacing)
assertEquals(1, grid.columns)
assertEquals(60.dp, grid.cell)
assertRowFits(grid, availableWidth = 60.dp)
@@ -78,16 +80,16 @@ class ArtifactGalleryTest {
fun degenerateInputsReturnAValidGrid() {
// A tiny or zero host, or a non-positive preferred token, never yields a
// zero/negative column count or a negative cell.
assertEquals(1, artifactGrid(availableWidth = 4.dp, preferred = preferred, spacing = spacing).columns)
assertEquals(4.dp, artifactGrid(availableWidth = 4.dp, preferred = preferred, spacing = spacing).cell)
assertEquals(0.dp, artifactGrid(availableWidth = 0.dp, preferred = preferred, spacing = spacing).cell)
val noPreferred = artifactGrid(availableWidth = 300.dp, preferred = 0.dp, spacing = spacing)
assertEquals(1, galleryGrid(availableWidth = 4.dp, preferred = preferred, spacing = spacing).columns)
assertEquals(4.dp, galleryGrid(availableWidth = 4.dp, preferred = preferred, spacing = spacing).cell)
assertEquals(0.dp, galleryGrid(availableWidth = 0.dp, preferred = preferred, spacing = spacing).cell)
val noPreferred = galleryGrid(availableWidth = 300.dp, preferred = 0.dp, spacing = spacing)
assertEquals(1, noPreferred.columns)
assertEquals(300.dp, noPreferred.cell)
}
/** The one invariant every grid must hold: the row never overflows the host. */
private fun assertRowFits(grid: ArtifactGrid, availableWidth: Dp) {
private fun assertRowFits(grid: GalleryGrid, availableWidth: Dp) {
val used = grid.columns * grid.cell.value + (grid.columns - 1) * spacing.value
assertTrue("row $used wider than $availableWidth", used <= availableWidth.value + 0.001f)
}