Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 29 additions & 3 deletions core/materialize/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
plugins {
alias(libs.plugins.android.library)
alias(libs.plugins.kotlin.android)
alias(libs.plugins.kotlin.compose)
alias(libs.plugins.kotlin.serialization)
alias(libs.plugins.ksp)
alias(libs.plugins.hilt)
Expand All @@ -12,8 +13,11 @@ android {

defaultConfig {
minSdk = 26
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}

buildFeatures { compose = true }

compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
Expand All @@ -31,22 +35,44 @@ dependencies {
implementation(project(":core:common"))
// The shared authed Retrofit and `GET /api/user` (read by MaterializeGate).
implementation(project(":core:network"))
// The themed Compose surface the preview/confirm window is drawn on.
implementation(project(":core:designsystem"))

implementation(libs.retrofit.core)
implementation(libs.okhttp.core)
implementation(libs.kotlinx.serialization.json)

implementation(libs.hilt.android)
ksp(libs.hilt.compiler)
implementation(libs.androidx.hilt.navigation.compose)

// The preview/edit/confirm window lives here rather than in a feature module:
// five entry points (messages, lists, rows, documents, selections) open the
// same window, so re-implementing it per surface would let them drift apart.
implementation(platform(libs.androidx.compose.bom))
implementation(libs.androidx.compose.ui)
implementation(libs.androidx.compose.material3)
implementation(libs.androidx.compose.material.icons.extended)
implementation(libs.androidx.compose.ui.tooling.preview)
debugImplementation(libs.androidx.compose.ui.tooling)
implementation(libs.androidx.lifecycle.viewmodel.compose)
implementation(libs.androidx.lifecycle.runtime.compose)

// No Room cache and no Compose: `POST /api/materialize` is a one-shot write
// whose result is authoritative, and the preview/confirm UI is built by the
// feature surfaces that open it.
// No Room cache: `POST /api/materialize` is a one-shot write whose result is
// authoritative, so there is nothing to read back offline.

testImplementation(libs.junit)
testImplementation(libs.kotlinx.coroutines.test)
testImplementation(libs.truth)
// The repository tests drive a real Retrofit/OkHttp stack against MockWebServer.
testImplementation(libs.okhttp.mockwebserver)
testImplementation(libs.retrofit.kotlinx.serialization)

// Instrumented / UI tests
androidTestImplementation(libs.androidx.test.ext.junit)
androidTestImplementation(libs.androidx.test.runner)
androidTestImplementation(platform(libs.androidx.compose.bom))
androidTestImplementation(libs.androidx.compose.ui.test.junit4)
androidTestImplementation(libs.truth)
debugImplementation(libs.androidx.compose.ui.test.manifest)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
package com.interlinedlist.android.core.materialize.ui

import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.assertIsEnabled
import androidx.compose.ui.test.assertIsNotEnabled
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.common.truth.Truth.assertThat
import com.interlinedlist.android.core.designsystem.theme.InterlinedListTheme
import com.interlinedlist.android.core.materialize.domain.DocumentListStyle
import com.interlinedlist.android.core.materialize.domain.ListColumnType
import com.interlinedlist.android.core.materialize.domain.MaterializeColumn
import com.interlinedlist.android.core.materialize.domain.MaterializeSource
import com.interlinedlist.android.core.materialize.domain.MaterializeTarget
import com.interlinedlist.android.core.materialize.domain.MaterializedDocument
import com.interlinedlist.android.core.materialize.domain.MaterializedList
import com.interlinedlist.android.core.materialize.domain.RowDataStyle
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith

/**
* The window as the user sees it: the destination switcher, the list editor with
* its live table, the document editor with its rendered preview, and the success
* state's links into what was created.
*/
@RunWith(AndroidJUnit4::class)
class MaterializeWindowTest {

@get:Rule
val composeRule = createComposeRule()

private val preview = MaterializePreview(
suggestedTitle = "Books to Read",
suggestedDescription = "My reading backlog.",
suggestedFileName = "books-to-read.md",
columns = listOf(
MaterializeColumn("title", "Title", ListColumnType.TEXT, sourceKey = "title"),
MaterializeColumn("author", "Author", ListColumnType.TEXT, sourceKey = "author"),
),
rows = listOf(
MaterializePreviewRow(mapOf("title" to "The Dream Machine", "author" to "Waldrop")),
),
totalRowCount = 340,
)

private fun state(
target: MaterializeTarget = MaterializeTarget.LIST,
source: MaterializeSource = MaterializeSource.Lists(listOf("lst_1")),
) = MaterializeWindowUiState.from(MaterializeLaunch(source, target, preview))

private fun setWindow(
state: MaterializeWindowUiState,
onSelectTarget: (MaterializeTarget) -> Unit = {},
onOpenList: (MaterializedList) -> Unit = {},
onOpenDocument: (MaterializedDocument) -> Unit = {},
) {
composeRule.setContent {
InterlinedListTheme {
MaterializeWindowContent(
state = state,
onSelectTarget = onSelectTarget,
onTitleChange = {},
onDescriptionChange = {},
onPublicChange = {},
onAddColumn = {},
onRemoveColumn = {},
onColumnNameChange = { _, _ -> },
onColumnTypeChange = { _, _ -> },
onFileNameChange = {},
onListStyleChange = {},
onRowDataStyleChange = {},
onConfirm = {},
onDismiss = {},
onOpenList = onOpenList,
onOpenDocument = onOpenDocument,
onUseDraft = {},
)
}
}
}

@Test
fun theListEditorShowsItsColumnsAndALiveTable() {
val state = state()
setWindow(state)

composeRule.onNodeWithTag(MaterializeWindowTestTags.TITLE).assertIsDisplayed()
state.columns.forEach {
composeRule.onNodeWithTag(MaterializeWindowTestTags.column(it.uiId)).assertIsDisplayed()
}
composeRule.onNodeWithTag(MaterializeWindowTestTags.ADD_COLUMN).assertIsDisplayed()
composeRule.onNodeWithTag(MaterializeWindowTestTags.TABLE_PREVIEW).assertIsDisplayed()
// The preview is live data from the source, and says how much is coming.
composeRule.onNodeWithText("The Dream Machine").assertIsDisplayed()
composeRule.onNodeWithText("Showing 1 of 340 rows.").assertIsDisplayed()
}

@Test
fun theDestinationCanBeSwitchedFromInsideTheWindow() {
var selected: MaterializeTarget? = null
setWindow(state(), onSelectTarget = { selected = it })

MaterializeTarget.entries.forEach {
composeRule.onNodeWithTag(MaterializeWindowTestTags.destination(it)).assertIsDisplayed()
}
composeRule.onNodeWithTag(
MaterializeWindowTestTags.destination(MaterializeTarget.BOTH),
).performClick()

assertThat(selected).isEqualTo(MaterializeTarget.BOTH)
}

@Test
fun theDocumentEditorShowsItsStylesAndARenderedPreview() {
setWindow(state(target = MaterializeTarget.DOC))

composeRule.onNodeWithTag(MaterializeWindowTestTags.FILE_NAME).assertIsDisplayed()
composeRule.onNodeWithTag(
MaterializeWindowTestTags.listStyle(DocumentListStyle.NUMBERED),
).assertIsDisplayed()
composeRule.onNodeWithTag(
MaterializeWindowTestTags.rowDataStyle(RowDataStyle.SUB_ITEMS),
).assertIsDisplayed()
composeRule.onNodeWithTag(MaterializeWindowTestTags.DOCUMENT_PREVIEW).assertIsDisplayed()
// A document has no columns to edit.
composeRule.onNodeWithTag(MaterializeWindowTestTags.ADD_COLUMN).assertDoesNotExist()
}

@Test
fun aBlankListTitleDisablesCreate() {
setWindow(state().copy(title = " "))

composeRule.onNodeWithTag(MaterializeWindowTestTags.CONFIRM).assertIsNotEnabled()
composeRule.onNodeWithText("A list title is required").assertIsDisplayed()
}

@Test
fun aValidListCanBeCreated() {
setWindow(state())

composeRule.onNodeWithTag(MaterializeWindowTestTags.CONFIRM).assertIsEnabled()
}

@Test
fun bothOffersALinkToTheListAndToTheDocument() {
var openedList: MaterializedList? = null
var openedDocument: MaterializedDocument? = null
setWindow(
state(target = MaterializeTarget.BOTH).copy(
success = MaterializeSuccess(
list = MaterializedList("lst_new", "Books to Read"),
document = MaterializedDocument("doc_new", "Books to Read"),
),
),
onOpenList = { openedList = it },
onOpenDocument = { openedDocument = it },
)

composeRule.onNodeWithTag(MaterializeWindowTestTags.SUCCESS).assertIsDisplayed()
composeRule.onNodeWithTag(MaterializeWindowTestTags.OPEN_LIST).performClick()
composeRule.onNodeWithTag(MaterializeWindowTestTags.OPEN_DOCUMENT).performClick()

assertThat(openedList?.id).isEqualTo("lst_new")
assertThat(openedDocument?.id).isEqualTo("doc_new")
}

@Test
fun aMessagesSourceDoesNotOfferTheMessageDestination() {
setWindow(state(source = MaterializeSource.Messages(listOf("msg_1"))))

composeRule.onNodeWithTag(
MaterializeWindowTestTags.destination(MaterializeTarget.MESSAGE),
).assertDoesNotExist()
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package com.interlinedlist.android.core.materialize.ui

import com.interlinedlist.android.core.materialize.domain.DocumentListStyle
import com.interlinedlist.android.core.materialize.domain.RowDataStyle

/**
* Renders the markdown a document destination would produce, so the window can
* show it before anything is written.
*
* It renders the **source** columns from [preview], not the edited list columns:
* a document is derived server-side from the source, and `docConfig` carries no
* field list, so showing renamed list columns here would promise something the
* request does not ask for.
*
* The result is a preview, not the document: the server re-derives the real one
* from its own copy of the source.
*/
internal fun renderDocumentPreview(
title: String,
preview: MaterializePreview,
listStyle: DocumentListStyle,
rowDataStyle: RowDataStyle,
): String = buildString {
if (title.isNotBlank()) appendLine("# ${title.trim()}").appendLine()
preview.suggestedDescription?.takeIf { it.isNotBlank() }?.let {
appendLine(it.trim()).appendLine()
}

val headlineKey = preview.columns.firstOrNull()?.propertyKey
preview.rows.forEachIndexed { index, row ->
val marker = when (listStyle) {
DocumentListStyle.NUMBERED -> "${index + 1}. "
DocumentListStyle.BULLETED -> "- "
}
val headline = headlineKey?.let { row.values[it] }?.takeIf { it.isNotBlank() } ?: UNTITLED_ROW
val details = preview.columns.drop(1).mapNotNull { column ->
row.values[column.propertyKey]
?.takeIf { it.isNotBlank() }
?.let { column.propertyName to it }
}

when (rowDataStyle) {
RowDataStyle.INLINE -> {
append(marker).append(headline)
if (details.isNotEmpty()) {
append(" — ").append(details.joinToString(", ") { "${it.first}: ${it.second}" })
}
appendLine()
}

RowDataStyle.SUB_ITEMS -> {
appendLine("$marker$headline")
details.forEach { appendLine("$SUB_ITEM_INDENT- ${it.first}: ${it.second}") }
}
}
}

if (preview.hiddenRowCount > 0) {
appendLine().append("…and ${preview.hiddenRowCount} more")
}
}.trimEnd()

private const val UNTITLED_ROW = "(untitled)"
private const val SUB_ITEM_INDENT = " "
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.interlinedlist.android.core.materialize.ui

import com.interlinedlist.android.core.common.result.AppError

/**
* Maps a normalised [AppError] to what the window shows.
*
* `bad_request` / `validation_failed` arrive as [AppError.Unknown] carrying the
* server's own words ("A list title is required", "Field 'year' has invalid
* type"), which are far more useful than anything generic, so they are shown
* verbatim.
*/
fun AppError.toUserMessage(): String = when (this) {
is AppError.Network -> "No connection. Nothing was created."
is AppError.Unauthorized -> message ?: "Please sign in again."
is AppError.Forbidden -> message ?: "Your account cannot create this right now."
is AppError.NotFound ->
message ?: "Some of what you selected is no longer available."

is AppError.RateLimited -> "Too many requests. Please wait a moment and try again."
is AppError.SubscriptionRequired ->
message ?: "Creating lists and documents requires an active subscription."

is AppError.Server -> "InterlinedList is having trouble right now. Try again shortly."
else -> message ?: "Something went wrong. Nothing was created."
}

/** True when the error is the subscriber-only gate, so the UI can show an upsell. */
val AppError.isSubscriptionGate: Boolean get() = this is AppError.SubscriptionRequired
Loading
Loading