Android: the lists dressed up (docs/design/android-lists.md)
The owner approved the designer's «А» for the games list and «Б» for the databases screen: - Games: a thin line between games, a disc of each side, the winner's «1» on a tile (and the name a little heavier), «½» on quieter tiles, the ECO on its own tag that never gives way; the game last opened marked and in sight; search matches marked, the ECO tag too. Search finds by the ECO. - Databases: badges by kind in Catppuccin colours (Mocha dark, Latte light: PGN blue, ChessBase peach, archives mauve, online teal, own green, ♞ for the player's); the number of games stands out; groups as cards (16/4 dp corners, 2 dp apart); the game put aside with its position on a small board (no coordinates) and «Continue»; two equal, quiet buttons. - Settings as cards with icons; the add sheet's icons in tiles of the kind. - Fixed on the way (the tester): a list read anew after a quick new search could show another game's names in a row; clearing a search goes back to the top; tiles, tags and buttons grow with a large font. Reviewed by the designer and the tester on the emulator. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
95572c530b
commit
f120c49fd4
22 changed files with 813 additions and 131 deletions
|
|
@ -58,6 +58,9 @@ class ChessPenguinApp : Application() {
|
|||
/// The games shown on the list of each database (after a search), for paging
|
||||
/// games from the game screen: database id → game numbers.
|
||||
val shown = HashMap<String, List<UInt>>()
|
||||
/// The game last opened from a database's list: the search it was found with and its
|
||||
/// place there (android-lists.md §3.6; the list marks it and shows it again).
|
||||
val lastOpened = HashMap<String, Pair<String, Int>>()
|
||||
|
||||
/// Changes each time the app goes to the background, and in every new process: the
|
||||
/// engine button of a game holds only for the visit it was pressed in (§8.3).
|
||||
|
|
|
|||
|
|
@ -77,3 +77,29 @@ fun nagColor(nag: Int, dark: Boolean): Color? = if (dark) {
|
|||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
/// The kinds of databases, each in its own colour on its badge (android-lists.md §5.1).
|
||||
enum class DbKind { Pgn, ChessBase, Archive, Online, Own }
|
||||
|
||||
/// A badge's background and what is written on it.
|
||||
data class KindColor(val container: Color, val content: Color)
|
||||
|
||||
/// The colour of a kind of database, from Catppuccin (the owner's choice): Mocha in the
|
||||
/// dark theme, Latte in the light one, on a tint of the same hue (contrast at least 5:1).
|
||||
fun kindColor(kind: DbKind, dark: Boolean): KindColor = if (dark) {
|
||||
when (kind) {
|
||||
DbKind.Pgn -> KindColor(Color(0xFF384660), Color(0xFF89B4FA)) // blue
|
||||
DbKind.ChessBase -> KindColor(Color(0xFF55443B), Color(0xFFFAB387)) // peach
|
||||
DbKind.Archive -> KindColor(Color(0xFF4A3F5E), Color(0xFFCBA6F7)) // mauve
|
||||
DbKind.Online -> KindColor(Color(0xFF3A5250), Color(0xFF94E2D5)) // teal
|
||||
DbKind.Own -> KindColor(Color(0xFF3F523F), Color(0xFFA6E3A1)) // green
|
||||
}
|
||||
} else {
|
||||
when (kind) {
|
||||
DbKind.Pgn -> KindColor(Color(0xFFDFEAFE), Color(0xFF1957D0))
|
||||
DbKind.ChessBase -> KindColor(Color(0xFFFFE9DD), Color(0xFFA54107))
|
||||
DbKind.Archive -> KindColor(Color(0xFFEEE3FD), Color(0xFF7A33D7))
|
||||
DbKind.Online -> KindColor(Color(0xFFDFF0F1), Color(0xFF116D73))
|
||||
DbKind.Own -> KindColor(Color(0xFFE4F2E1), Color(0xFF2D701E))
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,8 @@
|
|||
package io.github.vrubelroman.chesspenguin.ui
|
||||
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.foundation.background
|
||||
import io.github.vrubelroman.chesspenguin.theme.DbKind
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
|
|
@ -53,6 +56,16 @@ import io.github.vrubelroman.chesspenguin.data.FolderScan
|
|||
import io.github.vrubelroman.chesspenguin.data.Found
|
||||
import io.github.vrubelroman.chesspenguin.data.Source
|
||||
|
||||
/// The icon of a way to add, in a round tile coloured as the database it brings
|
||||
/// (android-lists.md §6).
|
||||
@Composable
|
||||
private fun KindIcon(kind: DbKind, icon: androidx.compose.ui.graphics.vector.ImageVector) {
|
||||
val c = io.github.vrubelroman.chesspenguin.theme.kindColor(kind, io.github.vrubelroman.chesspenguin.theme.LocalChessColors.current.dark)
|
||||
Box(Modifier.size(40.dp).clip(androidx.compose.foundation.shape.CircleShape).background(c.container), contentAlignment = Alignment.Center) {
|
||||
Icon(icon, null, tint = c.content, modifier = Modifier.size(22.dp))
|
||||
}
|
||||
}
|
||||
|
||||
/// "Add a database": games in the clipboard, a file, every database in a folder, or a
|
||||
/// player's games from Lichess and Chess.com.
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
|
|
@ -71,7 +84,7 @@ fun AddSheet(onFile: () -> Unit, onFolder: () -> Unit, onPaste: (() -> Unit)?, o
|
|||
ListItem(
|
||||
headlineContent = { Text(stringResource(R.string.add_paste)) },
|
||||
supportingContent = { Text(stringResource(R.string.add_paste_hint)) },
|
||||
leadingContent = { Icon(Icons.Outlined.ContentPaste, null) },
|
||||
leadingContent = { KindIcon(DbKind.Pgn, Icons.Outlined.ContentPaste) },
|
||||
colors = ListItemDefaults.colors(containerColor = Color.Transparent),
|
||||
modifier = Modifier.clickable(role = Role.Button, onClick = onPaste).padding(horizontal = 8.dp),
|
||||
)
|
||||
|
|
@ -79,21 +92,21 @@ fun AddSheet(onFile: () -> Unit, onFolder: () -> Unit, onPaste: (() -> Unit)?, o
|
|||
ListItem(
|
||||
headlineContent = { Text(stringResource(R.string.online_title)) },
|
||||
supportingContent = { Text(stringResource(R.string.add_online_hint)) },
|
||||
leadingContent = { Icon(Icons.Outlined.CloudDownload, null) },
|
||||
leadingContent = { KindIcon(DbKind.Online, Icons.Outlined.CloudDownload) },
|
||||
colors = ListItemDefaults.colors(containerColor = Color.Transparent),
|
||||
modifier = Modifier.clickable(role = Role.Button, onClick = onOnline).padding(horizontal = 8.dp),
|
||||
)
|
||||
ListItem(
|
||||
headlineContent = { Text(stringResource(R.string.add_file)) },
|
||||
supportingContent = { Text(stringResource(R.string.add_file_hint)) },
|
||||
leadingContent = { Icon(Icons.Outlined.Description, null) },
|
||||
leadingContent = { KindIcon(DbKind.Pgn, Icons.Outlined.Description) },
|
||||
colors = ListItemDefaults.colors(containerColor = Color.Transparent),
|
||||
modifier = Modifier.clickable(role = Role.Button, onClick = onFile).padding(horizontal = 8.dp),
|
||||
)
|
||||
ListItem(
|
||||
headlineContent = { Text(stringResource(R.string.add_folder)) },
|
||||
supportingContent = { Text(stringResource(R.string.add_folder_hint)) },
|
||||
leadingContent = { Icon(Icons.Outlined.Folder, null) },
|
||||
leadingContent = { KindIcon(DbKind.Pgn, Icons.Outlined.Folder) },
|
||||
colors = ListItemDefaults.colors(containerColor = Color.Transparent),
|
||||
modifier = Modifier.clickable(role = Role.Button, onClick = onFolder).padding(horizontal = 8.dp),
|
||||
)
|
||||
|
|
@ -197,7 +210,7 @@ private fun FoundRow(f: Found, checked: Boolean, onChange: (Boolean) -> Unit) {
|
|||
) {
|
||||
Checkbox(checked = checked || f.added, onCheckedChange = null, enabled = enabled)
|
||||
Spacer(Modifier.size(12.dp))
|
||||
FormatBadge(label, error = f.incomplete)
|
||||
FormatBadge(label, error = f.incomplete, kind = when (label) { "CB" -> DbKind.ChessBase; "7Z", "ZIP" -> DbKind.Archive; else -> DbKind.Pgn })
|
||||
Column(Modifier.weight(1f).padding(start = 16.dp)) {
|
||||
Text(f.name, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
val where = if (f.path.isEmpty()) note else "${f.path} · $note"
|
||||
|
|
|
|||
|
|
@ -190,6 +190,8 @@ fun Board(
|
|||
input: BoardInput? = null,
|
||||
/// Two squares lit red: a wrong move of the trainer, shown for a moment (§32.2).
|
||||
alert: Pair<String, String>? = null,
|
||||
/// The files and ranks along the edges (none on a small board that only shows).
|
||||
coordinates: Boolean = true,
|
||||
) {
|
||||
val colors = LocalChessColors.current
|
||||
val context = LocalContext.current
|
||||
|
|
@ -372,7 +374,7 @@ fun Board(
|
|||
}
|
||||
// Over the pieces, so that b, c, f, g stay readable (as on Lichess).
|
||||
// Coordinates: files along the bottom edge, ranks along the left edge.
|
||||
for (k in 0 until 8) {
|
||||
for (k in 0 until (if (coordinates) 8 else 0)) {
|
||||
val fileIndex = if (flipped) 7 - k else k
|
||||
val rankIndex = if (flipped) k else 7 - k
|
||||
val bottomLight = (7 + k) % 2 == 0
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
package io.github.vrubelroman.chesspenguin.ui
|
||||
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
|
|
@ -33,6 +35,12 @@ import androidx.compose.ui.text.withStyle
|
|||
import io.github.vrubelroman.chesspenguin.ChessPenguinApp
|
||||
import io.github.vrubelroman.chesspenguin.R
|
||||
import io.github.vrubelroman.chesspenguin.theme.Tabular
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import io.github.vrubelroman.chesspenguin.theme.kindColor
|
||||
import io.github.vrubelroman.chesspenguin.theme.LocalChessColors
|
||||
import io.github.vrubelroman.chesspenguin.theme.DbKind
|
||||
import io.github.vrubelroman.chesspenguin.data.Notation
|
||||
import io.github.vrubelroman.chesspenguin.data.DbEntry
|
||||
import io.github.vrubelroman.chesspenguin.data.Source
|
||||
|
|
@ -73,21 +81,57 @@ fun formatName(e: DbEntry): String = when (e.fileName.substringAfterLast('.', ""
|
|||
else -> "PGN"
|
||||
}
|
||||
|
||||
/// What kind of database an entry is (its badge's colour, android-lists.md §5.1).
|
||||
fun kindOf(e: DbEntry): DbKind {
|
||||
return when {
|
||||
e.source == Source.Own -> DbKind.Own
|
||||
e.source == Source.Online -> DbKind.Online
|
||||
else -> when (badge(e)) {
|
||||
"CB" -> DbKind.ChessBase
|
||||
"7Z", "ZIP" -> DbKind.Archive
|
||||
else -> DbKind.Pgn
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A database's badge: 40 dp, the colour of its kind, a word or an icon on it.
|
||||
@Composable
|
||||
fun FormatBadge(text: String, error: Boolean = false) {
|
||||
fun KindBadge(
|
||||
kind: DbKind,
|
||||
error: Boolean = false,
|
||||
content: @Composable (Color) -> Unit,
|
||||
) {
|
||||
val c = kindColor(kind, LocalChessColors.current.dark)
|
||||
Box(
|
||||
Modifier
|
||||
.size(40.dp)
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.background(if (error) MaterialTheme.colorScheme.errorContainer else MaterialTheme.colorScheme.primaryContainer),
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(if (error) MaterialTheme.colorScheme.errorContainer else c.container),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(
|
||||
text,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = if (error) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onPrimaryContainer,
|
||||
)
|
||||
}
|
||||
) { content(if (error) MaterialTheme.colorScheme.error else c.content) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun FormatBadge(text: String, error: Boolean = false, kind: DbKind = DbKind.Pgn) {
|
||||
KindBadge(kind, error) { color -> Text(text, style = MaterialTheme.typography.labelSmall, color = color) }
|
||||
}
|
||||
|
||||
/// The shape of a card in a group of `count` (android-lists.md §5.3): 16 dp outside,
|
||||
/// 4 dp where it meets its neighbours.
|
||||
fun groupShape(index: Int, count: Int): RoundedCornerShape {
|
||||
val top = if (index == 0) 16.dp else 4.dp
|
||||
val bottom = if (index == count - 1) 16.dp else 4.dp
|
||||
return RoundedCornerShape(topStart = top, topEnd = top, bottomStart = bottom, bottomEnd = bottom)
|
||||
}
|
||||
|
||||
/// A row of a group drawn as its card: 12 dp from the screen's edges, 2 dp between cards.
|
||||
@Composable
|
||||
fun Modifier.groupCard(index: Int, count: Int): Modifier {
|
||||
val shape = groupShape(index, count)
|
||||
return this
|
||||
.padding(start = 12.dp, end = 12.dp, bottom = 2.dp)
|
||||
.clip(shape)
|
||||
.background(MaterialTheme.colorScheme.surfaceContainerLow, shape)
|
||||
}
|
||||
|
||||
/// "Carlsen, Magnus" → "Carlsen M."; other names stay as in the file (§6.2).
|
||||
|
|
@ -111,11 +155,57 @@ fun PlayerName(
|
|||
color: Color = Color.Unspecified,
|
||||
maxLines: Int = 1,
|
||||
abbreviate: Boolean = true,
|
||||
/// Words searched for: shown marked where they are in the name as shown.
|
||||
highlight: String? = null,
|
||||
) {
|
||||
val measurer = rememberTextMeasurer()
|
||||
BoxWithConstraints(modifier) {
|
||||
val text = if (abbreviate && measurer.measure(name, style, softWrap = false).size.width > constraints.maxWidth) shortName(name) else name
|
||||
Text(text, style = style, color = color, maxLines = maxLines, overflow = TextOverflow.Ellipsis)
|
||||
Text(highlighted(text, highlight), style = style, color = color, maxLines = maxLines, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
|
||||
/// `text` with the first place of each searched word marked (android-lists.md §3.7);
|
||||
/// case does not matter.
|
||||
@Composable
|
||||
fun highlighted(text: String, query: String?): AnnotatedString {
|
||||
val words = query?.split(' ')?.filter { it.isNotBlank() }.orEmpty()
|
||||
if (words.isEmpty()) return AnnotatedString(text)
|
||||
val mark = SpanStyle(
|
||||
background = MaterialTheme.colorScheme.primaryContainer,
|
||||
color = MaterialTheme.colorScheme.onPrimaryContainer,
|
||||
)
|
||||
return buildAnnotatedString {
|
||||
append(text)
|
||||
for (w in words) {
|
||||
val at = text.indexOf(w, ignoreCase = true)
|
||||
if (at >= 0) addStyle(mark, at, at + w.length)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A player's share of the result in the list of games (android-lists.md §3.3): the
|
||||
/// winner's «1» on a tile, «½» on a quieter one, a loss as a plain «0».
|
||||
@Composable
|
||||
fun ResultTile(result: String?) {
|
||||
// At least 24×20 dp; it grows with the font.
|
||||
Box(Modifier.widthIn(min = 24.dp).heightIn(min = 20.dp), contentAlignment = Alignment.Center) {
|
||||
when (result) {
|
||||
"1" -> Box(
|
||||
Modifier.widthIn(min = 24.dp).heightIn(min = 20.dp).clip(RoundedCornerShape(6.dp)).background(MaterialTheme.colorScheme.primaryContainer),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text("1", style = MaterialTheme.typography.labelLarge.merge(Tabular), fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onPrimaryContainer)
|
||||
}
|
||||
"½" -> Box(
|
||||
Modifier.widthIn(min = 24.dp).heightIn(min = 20.dp).clip(RoundedCornerShape(6.dp)).background(MaterialTheme.colorScheme.surfaceContainerHigh),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text("½", style = MaterialTheme.typography.labelLarge.merge(Tabular), color = MaterialTheme.colorScheme.onSurface)
|
||||
}
|
||||
null -> {}
|
||||
else -> Text(result, style = MaterialTheme.typography.labelLarge.merge(Tabular), color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -132,11 +222,14 @@ fun elo(value: String): String = value.trim().takeIf { v -> v.toIntOrNull()?.let
|
|||
|
||||
/// The colour of a side: a small disc (white with a rim, or black).
|
||||
@Composable
|
||||
fun SideDisc(white: Boolean) {
|
||||
fun SideDisc(white: Boolean, size: androidx.compose.ui.unit.Dp = 12.dp) {
|
||||
// Black darker than any background, white whiter; the ring in the text's muted colour
|
||||
// keeps either from reading as an empty circle (android-lists.md §3.2).
|
||||
val dark = LocalChessColors.current.dark
|
||||
Box(
|
||||
Modifier.size(12.dp).clip(CircleShape)
|
||||
.background(if (white) Color(0xFFF5F5F0) else Color(0xFF26282B))
|
||||
.border(1.dp, MaterialTheme.colorScheme.outline, CircleShape),
|
||||
Modifier.size(size).clip(CircleShape)
|
||||
.background(if (white) Color.White else if (dark) Color(0xFF0E0F10) else Color(0xFF1C1D1F))
|
||||
.border(1.dp, MaterialTheme.colorScheme.onSurfaceVariant, CircleShape),
|
||||
)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,15 @@
|
|||
package io.github.vrubelroman.chesspenguin.ui
|
||||
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import io.github.vrubelroman.chesspenguin.theme.DbKind
|
||||
import androidx.compose.material.icons.rounded.CloudDownload
|
||||
import androidx.compose.ui.text.buildAnnotatedString
|
||||
import androidx.compose.ui.text.withStyle
|
||||
import androidx.compose.ui.text.SpanStyle
|
||||
import android.content.ClipboardManager
|
||||
import android.text.format.DateUtils
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
|
|
@ -175,6 +185,8 @@ fun DatabasesScreen(onOpen: (String) -> Unit, onAdded: (DbEntry) -> Unit, onSett
|
|||
val own = entries.filter { it.source == Source.Own }
|
||||
val theApp = app()
|
||||
val adjourned by theApp.maiaGames.current.collectAsState()
|
||||
// Back on the list of databases, a list of games was left: its mark goes (android-lists.md §3.6).
|
||||
LaunchedEffect(Unit) { theApp.lastOpened.clear() }
|
||||
val playRemovedText = stringResource(R.string.play_removed)
|
||||
val keptText = stringResource(R.string.player_kept_unfinished)
|
||||
var playing by remember { mutableStateOf(false) }
|
||||
|
|
@ -264,18 +276,33 @@ fun DatabasesScreen(onOpen: (String) -> Unit, onAdded: (DbEntry) -> Unit, onSett
|
|||
// A game against Maia put aside (§31.7): go on with it, or let it go.
|
||||
adjourned?.takeIf { !it.over }?.let { m ->
|
||||
item(key = "adjourned") {
|
||||
// The game's position on a small board, the side and the move, and
|
||||
// «Continue» as the screen's main action while it waits (android-lists.md §5.4).
|
||||
val shownAt = remember(m) { adjournedPosition(theApp.maiaGames.pgn()) }
|
||||
val sideText = stringResource(if (m.userWhite) R.string.play_as_white else R.string.play_as_black)
|
||||
val sub = shownAt?.second?.let { sideText + " · " + stringResource(R.string.play_move_n, it) } ?: sideText
|
||||
val title = stringResource(R.string.play_adjourned_title, m.strength.toString())
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp)
|
||||
.background(MaterialTheme.colorScheme.secondaryContainer, RoundedCornerShape(12.dp))
|
||||
.padding(start = 16.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp)
|
||||
.clip(RoundedCornerShape(16.dp))
|
||||
.background(MaterialTheme.colorScheme.primaryContainer)
|
||||
.clickable(onClick = onPlay)
|
||||
.semantics(mergeDescendants = true) {}
|
||||
.padding(start = 12.dp, top = 12.dp, bottom = 12.dp, end = 4.dp),
|
||||
verticalAlignment = Alignment.Top,
|
||||
) {
|
||||
Text(
|
||||
stringResource(R.string.play_adjourned, m.strength.toString(), stringResource(if (m.userWhite) R.string.play_as_white else R.string.play_as_black)),
|
||||
Modifier.weight(1f),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
TextButton(onClick = onPlay) { Text(stringResource(R.string.play_continue)) }
|
||||
shownAt?.let { (fen, _) ->
|
||||
Box(Modifier.clip(RoundedCornerShape(6.dp))) { MiniBoard(fen, flipped = !m.userWhite, size = 72.dp) }
|
||||
Spacer(Modifier.width(12.dp))
|
||||
}
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, style = MaterialTheme.typography.bodyLarge, fontWeight = FontWeight.Medium, color = MaterialTheme.colorScheme.onPrimaryContainer)
|
||||
Text(sub, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onPrimaryContainer)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Button(onClick = onPlay, modifier = Modifier.heightIn(min = 32.dp), contentPadding = PaddingValues(horizontal = 16.dp, vertical = 4.dp)) {
|
||||
Text(stringResource(R.string.play_continue))
|
||||
}
|
||||
}
|
||||
IconButton(onClick = {
|
||||
// Played on both sides: kept in the player's database,
|
||||
// unfinished (no «Undo»: it is there to be deleted).
|
||||
|
|
@ -302,14 +329,20 @@ fun DatabasesScreen(onOpen: (String) -> Unit, onAdded: (DbEntry) -> Unit, onSett
|
|||
}
|
||||
}
|
||||
item(key = "actions") {
|
||||
Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
FilledTonalButton(onClick = { if (adjourned?.over == false) askingAdjourned = true else playing = true }, modifier = Modifier.height(48.dp)) {
|
||||
Icon(Icons.Rounded.SmartToy, null)
|
||||
// Two equal buttons over the whole width (android-lists.md §5.5).
|
||||
// Neutral, as the cards' edges: the blue stays for the game put aside and the FAB.
|
||||
val quiet = ButtonDefaults.filledTonalButtonColors(
|
||||
containerColor = MaterialTheme.colorScheme.surfaceContainerHigh,
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
)
|
||||
Row(Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 8.dp), horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
FilledTonalButton(onClick = { if (adjourned?.over == false) askingAdjourned = true else playing = true }, modifier = Modifier.weight(1f).heightIn(min = 56.dp), shape = RoundedCornerShape(16.dp), colors = quiet) {
|
||||
Icon(Icons.Rounded.SmartToy, null, tint = MaterialTheme.colorScheme.primary)
|
||||
Spacer(Modifier.size(8.dp))
|
||||
Text(stringResource(R.string.play_with_maia))
|
||||
}
|
||||
FilledTonalButton(onClick = onNewGame, modifier = Modifier.height(48.dp)) {
|
||||
Icon(Icons.Rounded.Add, null)
|
||||
FilledTonalButton(onClick = onNewGame, modifier = Modifier.weight(1f).heightIn(min = 56.dp), shape = RoundedCornerShape(16.dp), colors = quiet) {
|
||||
Icon(Icons.Rounded.Add, null, tint = MaterialTheme.colorScheme.primary)
|
||||
Spacer(Modifier.size(8.dp))
|
||||
Text(stringResource(R.string.new_game))
|
||||
}
|
||||
|
|
@ -331,7 +364,8 @@ fun DatabasesScreen(onOpen: (String) -> Unit, onAdded: (DbEntry) -> Unit, onSett
|
|||
)
|
||||
}
|
||||
}
|
||||
items(own, key = { it.id }) { e ->
|
||||
items(own.size, key = { own[it].id }) { k ->
|
||||
val e = own[k]
|
||||
OwnRow(
|
||||
e,
|
||||
player = theApp.playerGames.isPlayers(e.id),
|
||||
|
|
@ -360,7 +394,7 @@ fun DatabasesScreen(onOpen: (String) -> Unit, onAdded: (DbEntry) -> Unit, onSett
|
|||
deleting = e
|
||||
}
|
||||
},
|
||||
modifier = Modifier.animateItem(),
|
||||
modifier = Modifier.animateItem().groupCard(k, own.size),
|
||||
)
|
||||
}
|
||||
item(key = "files-head") {
|
||||
|
|
@ -371,7 +405,8 @@ fun DatabasesScreen(onOpen: (String) -> Unit, onAdded: (DbEntry) -> Unit, onSett
|
|||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
}
|
||||
items(files, key = { it.id }) { e ->
|
||||
items(files.size, key = { files[it].id }) { k ->
|
||||
val e = files[k]
|
||||
DatabaseRow(
|
||||
e,
|
||||
download = views[e.id],
|
||||
|
|
@ -404,7 +439,7 @@ fun DatabasesScreen(onOpen: (String) -> Unit, onAdded: (DbEntry) -> Unit, onSett
|
|||
}
|
||||
}
|
||||
},
|
||||
modifier = Modifier.animateItem(),
|
||||
modifier = Modifier.animateItem().groupCard(k, files.size),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
@ -549,24 +584,21 @@ private fun OwnRow(e: DbEntry, player: Boolean, onOpen: () -> Unit, onRename: ()
|
|||
.fillMaxWidth()
|
||||
.height(72.dp)
|
||||
.combinedClickable(onClick = onOpen, onLongClick = { menu = true })
|
||||
.padding(start = 16.dp, end = 4.dp),
|
||||
.padding(start = 12.dp, end = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Box(
|
||||
Modifier.size(40.dp).clip(RoundedCornerShape(8.dp)).background(MaterialTheme.colorScheme.primaryContainer),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
KindBadge(DbKind.Own) { color ->
|
||||
// A player's database (games against Maia written by themselves): a knight.
|
||||
if (player) {
|
||||
Text("♞", style = MaterialTheme.typography.titleLarge, color = MaterialTheme.colorScheme.onPrimaryContainer)
|
||||
Text("♞", style = MaterialTheme.typography.titleLarge, color = color)
|
||||
} else {
|
||||
Icon(Icons.Rounded.EditNote, null, tint = MaterialTheme.colorScheme.onPrimaryContainer)
|
||||
Icon(Icons.Rounded.EditNote, null, tint = color)
|
||||
}
|
||||
}
|
||||
Column(Modifier.weight(1f).padding(start = 16.dp)) {
|
||||
Column(Modifier.weight(1f).padding(start = 12.dp)) {
|
||||
Text(displayName(e), style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
pluralStringResource(R.plurals.games_count, n, groupDigits(n)) + " · " + stringResource(if (player) R.string.player_db_row else R.string.own_on_phone),
|
||||
countFirst(pluralStringResource(R.plurals.games_count, n, groupDigits(n)), stringResource(if (player) R.string.player_db_row else R.string.own_on_phone)),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
|
|
@ -641,6 +673,7 @@ private fun DatabaseRow(
|
|||
val subtitle = e.games?.let {
|
||||
stringResource(R.string.games_with_format, pluralStringResource(R.plurals.games_count, it, groupDigits(it)), e.format ?: format)
|
||||
} ?: stringResource(R.string.not_opened, formatName(e))
|
||||
val gamesText = e.games?.let { pluralStringResource(R.plurals.games_count, it, groupDigits(it)) }
|
||||
val shownSubtitle = when {
|
||||
// A copy kept in the app says so: removing it deletes it.
|
||||
e.source == Source.Copy -> subtitle + " · " + stringResource(R.string.db_copy)
|
||||
|
|
@ -664,14 +697,20 @@ private fun DatabaseRow(
|
|||
.fillMaxWidth()
|
||||
.height(72.dp)
|
||||
.combinedClickable(onClick = onOpen, onLongClick = { menu = true })
|
||||
.padding(start = 16.dp, end = 4.dp),
|
||||
.padding(start = 12.dp, end = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
FormatBadge(format)
|
||||
Column(Modifier.weight(1f).padding(start = 16.dp)) {
|
||||
// A downloaded database is told by where it comes from, not by its format.
|
||||
val kind = kindOf(e)
|
||||
KindBadge(kind) { color ->
|
||||
if (kind == DbKind.Online) Icon(Icons.Rounded.CloudDownload, null, tint = color, modifier = Modifier.size(22.dp))
|
||||
else Text(format, style = MaterialTheme.typography.labelSmall, color = color)
|
||||
}
|
||||
Column(Modifier.weight(1f).padding(start = 12.dp)) {
|
||||
Text(displayName(e), style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
shownSubtitle,
|
||||
// The number of games stands out (a big database from a small one).
|
||||
if (failure == null && gamesText != null && shownSubtitle.startsWith(gamesText)) countFirst(gamesText, shownSubtitle.removePrefix(gamesText).removePrefix(" · ")) else androidx.compose.ui.text.AnnotatedString(shownSubtitle),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = if (failure != null) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
|
|
@ -728,6 +767,31 @@ private fun RenameDialog(name: String, own: Boolean = false, onDismiss: () -> Un
|
|||
)
|
||||
}
|
||||
|
||||
/// «**267 games** · PGN»: the number of games heavier and in the text's colour.
|
||||
@Composable
|
||||
private fun countFirst(count: String, rest: String): androidx.compose.ui.text.AnnotatedString {
|
||||
val strong = SpanStyle(fontWeight = FontWeight.Medium, color = MaterialTheme.colorScheme.onSurface)
|
||||
return buildAnnotatedString {
|
||||
withStyle(strong) { append(count) }
|
||||
if (rest.isNotEmpty()) append(" · $rest")
|
||||
}
|
||||
}
|
||||
|
||||
/// The position on the board of a game put aside, and the number of its last move.
|
||||
private fun adjournedPosition(pgn: String?): Pair<String, Int>? {
|
||||
pgn ?: return null
|
||||
val s = runCatching { uniffi.mobile_api.GameSession.fromPgn(pgn) }.getOrNull() ?: return null
|
||||
return try {
|
||||
val d = s.data()
|
||||
val end = lineEnd(d)
|
||||
val node = d.nodes[end]
|
||||
// The move to be made: after White's, the same number; after Black's, the next.
|
||||
node.fen to (if (end == 0) 1 else node.moveNumber.toInt() + if (node.white) 0 else 1)
|
||||
} finally {
|
||||
s.close()
|
||||
}
|
||||
}
|
||||
|
||||
/// The name of pasted games: one game by its players, games of one event by it, others by
|
||||
/// when they were pasted (`dated`), so that two pastes differ.
|
||||
private fun pastedName(db: Database, dated: String): String {
|
||||
|
|
|
|||
|
|
@ -156,6 +156,8 @@ fun GameScreen(
|
|||
val dbEntry = libraryEntries.firstOrNull { it.id == db }
|
||||
var games by remember { mutableStateOf(app.shown[db]) }
|
||||
var place by rememberSaveable { mutableIntStateOf(startPlace) }
|
||||
// The list marks the game it comes back to (the one paged to with ‹ ›, too).
|
||||
LaunchedEffect(place) { if (db != NEW_GAME && db != PLAY_GAME) app.lastOpened[db] = query to place }
|
||||
// The game as changed on the board (android-play.md §29), kept while the phone turns:
|
||||
// a game of someone else's file is changed for analysis and never written there.
|
||||
val held: GameEdit = viewModel()
|
||||
|
|
|
|||
|
|
@ -1,7 +1,15 @@
|
|||
package io.github.vrubelroman.chesspenguin.ui
|
||||
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import kotlinx.coroutines.flow.first
|
||||
import androidx.compose.runtime.snapshotFlow
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
|
|
@ -99,8 +107,18 @@ fun GamesScreen(db: String, onBack: () -> Unit, onGame: (place: Int, query: Stri
|
|||
val found = withContext(Dispatchers.Default) { app.library.listed(db, d, query) }
|
||||
rows.clear()
|
||||
shown = found
|
||||
// New results start at the top.
|
||||
list.scrollToItem(0)
|
||||
// Once the new list is laid out (else the list keeps its place by a row's key).
|
||||
snapshotFlow { list.layoutInfo.totalItemsCount }.first { it == found.size }
|
||||
// Back from a game: it in sight; new results start at the top.
|
||||
val last = app.lastOpened[db]?.takeIf { it.first == query }?.second?.takeIf { it < found.size }
|
||||
val first = list.firstVisibleItemIndex
|
||||
val seen = list.layoutInfo.visibleItemsInfo.size.takeIf { it > 0 } ?: 6
|
||||
when {
|
||||
last == null -> list.scrollToItem(0)
|
||||
// Already on the screen (the list kept its place): it stays where it is.
|
||||
last in first until first + seen - 1 -> {}
|
||||
else -> list.scrollToItem((last - 3).coerceAtLeast(0))
|
||||
}
|
||||
app.shown[db] = found
|
||||
}
|
||||
val scroll = TopAppBarDefaults.pinnedScrollBehavior()
|
||||
|
|
@ -219,6 +237,7 @@ fun GamesScreen(db: String, onBack: () -> Unit, onGame: (place: Int, query: Stri
|
|||
else -> {
|
||||
// Wide enough for the database's largest number.
|
||||
val numberWidth = numberWidth(database?.len()?.toInt() ?: games.size)
|
||||
val last = app.lastOpened[db]?.takeIf { it.first == query }?.second
|
||||
LazyColumn(Modifier.fillMaxSize(), state = list) {
|
||||
items(games.size, key = { games[it].toLong() }) { place ->
|
||||
val chunk = place / CHUNK
|
||||
|
|
@ -227,10 +246,19 @@ fun GamesScreen(db: String, onBack: () -> Unit, onGame: (place: Int, query: Stri
|
|||
if (rows[chunk] == null) {
|
||||
val d = database ?: return@LaunchedEffect
|
||||
val part = games.subList(chunk * CHUNK, minOf(games.size, (chunk + 1) * CHUNK))
|
||||
rows[chunk] = withContext(Dispatchers.Default) { d.rowsOf(part) }
|
||||
val read = withContext(Dispatchers.Default) { d.rowsOf(part) }
|
||||
// Rows of a list replaced meanwhile (a new search) are not this one's.
|
||||
if (shown === games) rows[chunk] = read
|
||||
}
|
||||
}
|
||||
GameRowView(games[place].toInt() + 1, numberWidth, loaded?.getOrNull(place % CHUNK)) { onGame(place, query) }
|
||||
GameRowView(
|
||||
games[place].toInt() + 1,
|
||||
numberWidth,
|
||||
loaded?.getOrNull(place % CHUNK),
|
||||
lastOpened = place == last,
|
||||
divider = place < games.size - 1,
|
||||
query = query,
|
||||
) { onGame(place, query) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -277,67 +305,158 @@ private fun numberWidth(count: Int): androidx.compose.ui.unit.Dp {
|
|||
}
|
||||
}
|
||||
|
||||
/// One game (§6.2): its number, White and Black each on a line of their own (with the
|
||||
/// rating and the share of the result), then event · year · ECO. The row is read as one
|
||||
/// sentence by TalkBack.
|
||||
/// One game (§6.2, android-lists.md §3): its number, White and Black each on a line of
|
||||
/// their own (a disc of the side, the rating, the share of the result), then event · year
|
||||
/// and the ECO on a tag. A thin line under it; the game last opened is marked. The row
|
||||
/// is read as one sentence by TalkBack.
|
||||
@Composable
|
||||
private fun GameRowView(number: Int, numberWidth: androidx.compose.ui.unit.Dp, row: GameRow?, onClick: () -> Unit) {
|
||||
private fun GameRowView(
|
||||
number: Int,
|
||||
numberWidth: androidx.compose.ui.unit.Dp,
|
||||
row: GameRow?,
|
||||
lastOpened: Boolean,
|
||||
divider: Boolean,
|
||||
query: String,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
// 6 + 24 + 24 + 20 + 6 = 80 dp at the normal font size; the lines grow with a larger font.
|
||||
val nameLine = lineHeight(MaterialTheme.typography.bodyLarge, 24.dp)
|
||||
val detailsLine = lineHeight(MaterialTheme.typography.bodyMedium, 20.dp)
|
||||
val said = row?.let { rowDescription(number, it) } ?: ""
|
||||
Row(
|
||||
val lastText = stringResource(R.string.last_opened)
|
||||
val said = row?.let { rowDescription(number, it) + if (lastOpened) ". $lastText" else "" } ?: ""
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.height(12.dp + nameLine * 2 + detailsLine)
|
||||
.background(if (lastOpened) colors.surfaceContainer else Color.Transparent)
|
||||
.clickable(enabled = row != null, onClick = onClick)
|
||||
.clearAndSetSemantics { if (row != null) contentDescription = said }
|
||||
.padding(horizontal = 16.dp, vertical = 6.dp),
|
||||
verticalAlignment = Alignment.Top,
|
||||
.clearAndSetSemantics { if (row != null) contentDescription = said },
|
||||
) {
|
||||
// Level with White's line.
|
||||
Box(Modifier.width(numberWidth).height(nameLine), contentAlignment = Alignment.CenterEnd) {
|
||||
Text(
|
||||
groupDigits(number),
|
||||
style = MaterialTheme.typography.bodySmall.merge(Tabular),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
Row(Modifier.fillMaxSize().padding(horizontal = 16.dp, vertical = 6.dp), verticalAlignment = Alignment.Top) {
|
||||
// Level with White's line.
|
||||
Box(Modifier.width(numberWidth).height(nameLine), contentAlignment = Alignment.CenterEnd) {
|
||||
Text(
|
||||
groupDigits(number),
|
||||
style = MaterialTheme.typography.bodySmall.merge(Tabular),
|
||||
color = colors.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(12.dp))
|
||||
GameRowText(row, nameLine, detailsLine, query, Modifier.weight(1f))
|
||||
}
|
||||
if (lastOpened) {
|
||||
Box(
|
||||
Modifier.align(Alignment.CenterStart).width(3.dp).fillMaxHeight()
|
||||
.background(colors.primary, RoundedCornerShape(topEnd = 2.dp, bottomEnd = 2.dp)),
|
||||
)
|
||||
}
|
||||
// From the discs to 16 dp before the edge; the number stays in the margin.
|
||||
if (divider) {
|
||||
Box(
|
||||
Modifier.align(Alignment.BottomStart).padding(start = 16.dp + numberWidth + 12.dp, end = 16.dp)
|
||||
.fillMaxWidth().height(1.dp).background(colors.outlineVariant),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(12.dp))
|
||||
GameRowText(row, nameLine, detailsLine, Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GameRowText(row: GameRow?, nameLine: androidx.compose.ui.unit.Dp, detailsLine: androidx.compose.ui.unit.Dp, modifier: Modifier) {
|
||||
private fun GameRowText(row: GameRow?, nameLine: androidx.compose.ui.unit.Dp, detailsLine: androidx.compose.ui.unit.Dp, query: String, modifier: Modifier) {
|
||||
Column(modifier) {
|
||||
if (row == null) return@Column
|
||||
val style = MaterialTheme.typography.bodyLarge
|
||||
val muted = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
val white = row.white.trim().takeIf { it.isNotEmpty() && it != "?" }
|
||||
val black = row.black.trim().takeIf { it.isNotEmpty() && it != "?" }
|
||||
if (white != null && black == null) {
|
||||
val study = white != null && black == null
|
||||
if (study) {
|
||||
// A study or a book position: a title for White and no Black — two lines of it.
|
||||
// From the top, level with the number, not centred in the two lines.
|
||||
// From the top, level with the number, not centred in the two lines; no discs:
|
||||
// these are not players.
|
||||
Box(Modifier.height(nameLine * 2)) {
|
||||
PlayerLine(white, elo(row.whiteElo), null, style, maxLines = 2, abbreviate = false)
|
||||
PlayerName(white, style, maxLines = 2, abbreviate = false, highlight = query)
|
||||
}
|
||||
} else {
|
||||
PlayerLine(white ?: "?", elo(row.whiteElo), sideResult(row.result, true), style, Modifier.height(nameLine), nameColor = if (white == null) muted else androidx.compose.ui.graphics.Color.Unspecified)
|
||||
PlayerLine(black ?: "?", elo(row.blackElo), sideResult(row.result, false), style, Modifier.height(nameLine), nameColor = if (black == null) muted else androidx.compose.ui.graphics.Color.Unspecified)
|
||||
ListPlayer(white, elo(row.whiteElo), sideResult(row.result, true), true, style, nameLine, query)
|
||||
ListPlayer(black, elo(row.blackElo), sideResult(row.result, false), false, style, nameLine, query)
|
||||
}
|
||||
val details = joinKnown(row.event, year(row.date), row.eco)
|
||||
if (details.isNotEmpty()) {
|
||||
Text(
|
||||
details,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = muted,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.height(detailsLine),
|
||||
val details = joinKnown(row.event, year(row.date))
|
||||
val eco = row.eco.trim().takeIf { it.isNotEmpty() && it != "?" }
|
||||
if (details.isNotEmpty() || eco != null) {
|
||||
// Under the names (past the discs); the ECO tag never gives way, the event does.
|
||||
Row(Modifier.height(detailsLine).padding(start = if (study) 0.dp else 16.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
highlighted(details, query),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = muted,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
if (eco != null) {
|
||||
Spacer(Modifier.width(8.dp))
|
||||
EcoTag(eco, marked = query.split(' ').any { it.isNotBlank() && eco.startsWith(it.trim(), ignoreCase = true) })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One player in the list: the disc of the side, the name (the winner's a little
|
||||
/// heavier), the rating, the share of the result on its tile.
|
||||
@Composable
|
||||
private fun ListPlayer(
|
||||
name: String?,
|
||||
rating: String,
|
||||
result: String?,
|
||||
white: Boolean,
|
||||
style: androidx.compose.ui.text.TextStyle,
|
||||
height: androidx.compose.ui.unit.Dp,
|
||||
query: String,
|
||||
) {
|
||||
val won = result == "1"
|
||||
Row(Modifier.height(height), verticalAlignment = Alignment.CenterVertically) {
|
||||
SideDisc(white, 8.dp)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {
|
||||
PlayerName(
|
||||
name ?: "?",
|
||||
if (won) style.copy(fontWeight = androidx.compose.ui.text.font.FontWeight.Medium) else style,
|
||||
Modifier.weight(1f, fill = false),
|
||||
if (name == null) MaterialTheme.colorScheme.onSurfaceVariant else Color.Unspecified,
|
||||
highlight = query,
|
||||
)
|
||||
if (rating.isNotEmpty()) {
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(rating, style = MaterialTheme.typography.bodyMedium.merge(Tabular), color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(8.dp))
|
||||
ResultTile(result)
|
||||
}
|
||||
}
|
||||
|
||||
/// The opening's code on a small outlined tag at the right of the details line; filled
|
||||
/// like the other matches when it is what was searched for.
|
||||
@Composable
|
||||
private fun EcoTag(eco: String, marked: Boolean) {
|
||||
val shape = RoundedCornerShape(4.dp)
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Box(
|
||||
Modifier.heightIn(min = 16.dp).widthIn(min = 32.dp)
|
||||
.background(if (marked) colors.primaryContainer else Color.Transparent, shape)
|
||||
.border(1.dp, if (marked) colors.primaryContainer else colors.outline, shape)
|
||||
.padding(horizontal = 4.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(
|
||||
eco,
|
||||
style = MaterialTheme.typography.labelSmall.merge(Tabular),
|
||||
color = if (marked) colors.onPrimaryContainer else colors.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -252,6 +252,7 @@ fun MiniBoard(fen: String, flipped: Boolean, size: androidx.compose.ui.unit.Dp)
|
|||
description = "",
|
||||
animated = false,
|
||||
modifier = Modifier.width(size),
|
||||
coordinates = false,
|
||||
)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,26 @@
|
|||
package io.github.vrubelroman.chesspenguin.ui
|
||||
|
||||
import androidx.compose.material.icons.rounded.Info
|
||||
import androidx.compose.material.icons.rounded.SdCard
|
||||
import androidx.compose.material.icons.rounded.DeveloperBoard
|
||||
import androidx.compose.material.icons.rounded.Timer
|
||||
import androidx.compose.material.icons.rounded.Delete
|
||||
import androidx.compose.material.icons.rounded.Memory
|
||||
import androidx.compose.material.icons.rounded.Translate
|
||||
import androidx.compose.material.icons.rounded.Palette
|
||||
import androidx.compose.material.icons.rounded.GridOn
|
||||
import androidx.compose.material.icons.rounded.Save
|
||||
import androidx.compose.material.icons.rounded.Vibration
|
||||
import androidx.compose.material.icons.automirrored.rounded.FormatListBulleted
|
||||
import androidx.compose.material.icons.automirrored.rounded.Notes
|
||||
import androidx.compose.material.icons.automirrored.rounded.VolumeUp
|
||||
import androidx.compose.material.icons.automirrored.rounded.ArrowRightAlt
|
||||
import androidx.compose.material.icons.rounded.Animation
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.background
|
||||
import android.app.Activity
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Column
|
||||
|
|
@ -104,8 +125,9 @@ fun SettingsScreen(onBack: () -> Unit, onAbout: () -> Unit, onBoardStyle: () ->
|
|||
) { padding ->
|
||||
Column(Modifier.fillMaxSize().padding(padding).verticalScroll(rememberScrollState()).padding(bottom = 24.dp)) {
|
||||
Group(stringResource(R.string.group_game))
|
||||
Cards {
|
||||
val notationNow = notationNames.firstOrNull { it.first == prefs.notation } ?: notationNames.first()
|
||||
Item(stringResource(R.string.notation), notationNow.second) {
|
||||
Item(stringResource(R.string.notation), notationNow.second, icon = Icons.AutoMirrored.Rounded.Notes) {
|
||||
choice = Choice(
|
||||
R.string.notation,
|
||||
notationNames.map { it.second },
|
||||
|
|
@ -114,15 +136,17 @@ fun SettingsScreen(onBack: () -> Unit, onAbout: () -> Unit, onBoardStyle: () ->
|
|||
) { i -> set { it.copy(notation = notationNames[i].first) } }
|
||||
}
|
||||
|
||||
Toggle(stringResource(R.string.animation), prefs.animation) { v -> set { it.copy(animation = v) } }
|
||||
Toggle(stringResource(R.string.best_arrow), prefs.bestArrow) { v -> set { it.copy(bestArrow = v) } }
|
||||
Toggle(stringResource(R.string.sound), prefs.sound) { v -> set { it.copy(sound = v) } }
|
||||
Toggle(stringResource(R.string.vibration), prefs.vibration) { v -> set { it.copy(vibration = v) } }
|
||||
Toggle(stringResource(R.string.record_games), prefs.recordGames) { v -> set { it.copy(recordGames = v) } }
|
||||
Toggle(stringResource(R.string.animation), prefs.animation, Icons.Rounded.Animation) { v -> set { it.copy(animation = v) } }
|
||||
Toggle(stringResource(R.string.best_arrow), prefs.bestArrow, Icons.AutoMirrored.Rounded.ArrowRightAlt) { v -> set { it.copy(bestArrow = v) } }
|
||||
Toggle(stringResource(R.string.sound), prefs.sound, Icons.AutoMirrored.Rounded.VolumeUp) { v -> set { it.copy(sound = v) } }
|
||||
Toggle(stringResource(R.string.vibration), prefs.vibration, Icons.Rounded.Vibration) { v -> set { it.copy(vibration = v) } }
|
||||
Toggle(stringResource(R.string.record_games), prefs.recordGames, Icons.Rounded.Save) { v -> set { it.copy(recordGames = v) } }
|
||||
}
|
||||
|
||||
Group(stringResource(R.string.group_look))
|
||||
Item(stringResource(R.string.board_and_pieces), boardLabel(prefs.board) + " · " + prefs.pieces.dir, onClick = onBoardStyle)
|
||||
Item(stringResource(R.string.theme), themeNames.first { it.first == prefs.theme }.second) {
|
||||
Cards {
|
||||
Item(stringResource(R.string.board_and_pieces), boardLabel(prefs.board) + " · " + prefs.pieces.dir, icon = Icons.Rounded.GridOn, onClick = onBoardStyle)
|
||||
Item(stringResource(R.string.theme), themeNames.first { it.first == prefs.theme }.second, icon = Icons.Rounded.Palette) {
|
||||
choice = Choice(R.string.theme, themeNames.map { it.second }, themeNames.indexOfFirst { it.first == prefs.theme }) { i ->
|
||||
set { it.copy(theme = themeNames[i].first) }
|
||||
}
|
||||
|
|
@ -132,42 +156,45 @@ fun SettingsScreen(onBack: () -> Unit, onAbout: () -> Unit, onBoardStyle: () ->
|
|||
if (it.isEmpty()) stringResource(R.string.theme_system) else Locale.forLanguageTag(it).let { l -> l.getDisplayLanguage(l).replaceFirstChar(Char::uppercase) }
|
||||
}
|
||||
val language = remember { Language.get(context) }
|
||||
Item(stringResource(R.string.language), languageNames[LANGUAGES.indexOf(language).coerceAtLeast(0)]) {
|
||||
Item(stringResource(R.string.language), languageNames[LANGUAGES.indexOf(language).coerceAtLeast(0)], icon = Icons.Rounded.Translate) {
|
||||
choice = Choice(R.string.language, languageNames, LANGUAGES.indexOf(language).coerceAtLeast(0)) { i ->
|
||||
if (Language.set(context, LANGUAGES[i])) (context as? Activity)?.recreate()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Group(stringResource(R.string.group_engine))
|
||||
Cards {
|
||||
when {
|
||||
files.builtIn -> Status(stringResource(R.string.engine_built_in))
|
||||
files.builtIn -> Status(stringResource(R.string.engine_built_in), Icons.Rounded.Memory)
|
||||
net == NetState.Ready -> {
|
||||
Status(stringResource(R.string.engine_downloaded))
|
||||
Item(stringResource(R.string.engine_delete, size), null) { deleting = true }
|
||||
Status(stringResource(R.string.engine_downloaded), Icons.Rounded.Memory)
|
||||
Item(stringResource(R.string.engine_delete, size), null, icon = Icons.Rounded.Delete) { deleting = true }
|
||||
}
|
||||
net is NetState.Loading -> {
|
||||
val l = net as NetState.Loading
|
||||
Item(stringResource(R.string.engine_downloading, (l.done / 1_000_000).toInt(), (l.total / 1_000_000).toInt()), null) { sheet = true }
|
||||
Item(stringResource(R.string.engine_downloading, (l.done / 1_000_000).toInt(), (l.total / 1_000_000).toInt()), null, icon = Icons.Rounded.Memory) { sheet = true }
|
||||
}
|
||||
// The same sheet as in a game: the size, mobile data, cancel (§9).
|
||||
else -> Item(stringResource(R.string.engine_missing, size), null) { sheet = true }
|
||||
else -> Item(stringResource(R.string.engine_missing, size), null, icon = Icons.Rounded.Memory) { sheet = true }
|
||||
}
|
||||
Item(stringResource(R.string.lines), "${prefs.engineLines}") {
|
||||
Item(stringResource(R.string.lines), "${prefs.engineLines}", icon = Icons.AutoMirrored.Rounded.FormatListBulleted) {
|
||||
choice = Choice(R.string.lines, listOf("1", "2", "3"), prefs.engineLines - 1) { i -> set { it.copy(engineLines = i + 1) } }
|
||||
}
|
||||
Item(stringResource(R.string.time_per_position), secondsNames.firstOrNull { it.first == prefs.engineSeconds }?.second ?: "") {
|
||||
Item(stringResource(R.string.time_per_position), secondsNames.firstOrNull { it.first == prefs.engineSeconds }?.second ?: "", icon = Icons.Rounded.Timer) {
|
||||
choice = Choice(R.string.time_per_position, secondsNames.map { it.second }, secondsNames.indexOfFirst { it.first == prefs.engineSeconds }) { i ->
|
||||
set { it.copy(engineSeconds = secondsNames[i].first) }
|
||||
}
|
||||
}
|
||||
Item(stringResource(R.string.threads), "${prefs.engineThreads}") {
|
||||
Item(stringResource(R.string.threads), "${prefs.engineThreads}", icon = Icons.Rounded.DeveloperBoard) {
|
||||
choice = Choice(R.string.threads, (1..cores).map { "$it" }, prefs.engineThreads - 1) { i -> set { it.copy(engineThreads = i + 1) } }
|
||||
}
|
||||
val hashes = listOf(16, 32, 64, 128, 256)
|
||||
val hashNames = hashes.map { stringResource(R.string.megabytes, it) }
|
||||
Item(stringResource(R.string.memory), stringResource(R.string.megabytes, prefs.engineHashMb)) {
|
||||
Item(stringResource(R.string.memory), stringResource(R.string.megabytes, prefs.engineHashMb), icon = Icons.Rounded.SdCard) {
|
||||
choice = Choice(R.string.memory, hashNames, hashes.indexOf(prefs.engineHashMb)) { i -> set { it.copy(engineHashMb = hashes[i]) } }
|
||||
}
|
||||
}
|
||||
Text(
|
||||
stringResource(R.string.engine_battery),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
|
|
@ -176,7 +203,9 @@ fun SettingsScreen(onBack: () -> Unit, onAbout: () -> Unit, onBoardStyle: () ->
|
|||
)
|
||||
Spacer(Modifier.height(16.dp))
|
||||
// A newer version of the app, even with its card hidden (android-ui.md §25.5).
|
||||
Item(stringResource(R.string.about), aboutUpdateLine(), valueColor = MaterialTheme.colorScheme.primary, onClick = onAbout)
|
||||
Cards {
|
||||
Item(stringResource(R.string.about), aboutUpdateLine(), valueColor = MaterialTheme.colorScheme.primary, icon = Icons.Rounded.Info, onClick = onAbout)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -250,44 +279,75 @@ private fun Group(title: String) {
|
|||
)
|
||||
}
|
||||
|
||||
/// A group's items as cards (android-lists.md §6): 16 dp corners outside, 4 dp between
|
||||
/// them, 2 dp of the background between cards.
|
||||
@Composable
|
||||
private fun Item(title: String, value: String?, valueColor: androidx.compose.ui.graphics.Color = androidx.compose.ui.graphics.Color.Unspecified, onClick: (() -> Unit)?) {
|
||||
private fun Cards(content: @Composable androidx.compose.foundation.layout.ColumnScope.() -> Unit) {
|
||||
Column(
|
||||
Modifier.padding(horizontal = 12.dp).clip(RoundedCornerShape(16.dp)),
|
||||
verticalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(2.dp),
|
||||
content = content,
|
||||
)
|
||||
}
|
||||
|
||||
/// One card of a group.
|
||||
@Composable
|
||||
private fun Modifier.card(): Modifier = fillMaxWidth().clip(RoundedCornerShape(4.dp)).background(MaterialTheme.colorScheme.surfaceContainerLow)
|
||||
|
||||
/// An item's icon: 24 dp, then 16 dp to its text.
|
||||
@Composable
|
||||
private fun ItemIcon(icon: androidx.compose.ui.graphics.vector.ImageVector?) {
|
||||
if (icon == null) return
|
||||
Icon(icon, null, tint = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.size(24.dp))
|
||||
Spacer(Modifier.width(16.dp))
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Item(
|
||||
title: String,
|
||||
value: String?,
|
||||
valueColor: androidx.compose.ui.graphics.Color = androidx.compose.ui.graphics.Color.Unspecified,
|
||||
icon: androidx.compose.ui.graphics.vector.ImageVector? = null,
|
||||
onClick: (() -> Unit)?,
|
||||
) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.card()
|
||||
.heightIn(min = 56.dp)
|
||||
.then(if (onClick != null) Modifier.clickable(onClick = onClick) else Modifier)
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
verticalArrangement = androidx.compose.foundation.layout.Arrangement.Center,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(title, style = MaterialTheme.typography.bodyLarge)
|
||||
if (value != null) {
|
||||
Text(value, style = MaterialTheme.typography.bodyMedium, color = valueColor.takeOrElse { MaterialTheme.colorScheme.onSurfaceVariant })
|
||||
ItemIcon(icon)
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, style = MaterialTheme.typography.bodyLarge)
|
||||
if (value != null) {
|
||||
Text(value, style = MaterialTheme.typography.bodyMedium, color = valueColor.takeOrElse { MaterialTheme.colorScheme.onSurfaceVariant })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A line that tells, not a button.
|
||||
@Composable
|
||||
private fun Status(text: String) {
|
||||
Text(
|
||||
text,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
)
|
||||
private fun Status(text: String, icon: androidx.compose.ui.graphics.vector.ImageVector? = null) {
|
||||
Row(Modifier.card().heightIn(min = 56.dp).padding(horizontal = 16.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
ItemIcon(icon)
|
||||
Text(text, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Toggle(title: String, value: Boolean, onChange: (Boolean) -> Unit) {
|
||||
private fun Toggle(title: String, value: Boolean, icon: androidx.compose.ui.graphics.vector.ImageVector? = null, onChange: (Boolean) -> Unit) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.card()
|
||||
.heightIn(min = 56.dp)
|
||||
.selectable(selected = value, role = Role.Switch) { onChange(!value) }
|
||||
.padding(horizontal = 16.dp),
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
ItemIcon(icon)
|
||||
Text(title, style = MaterialTheme.typography.bodyLarge, modifier = Modifier.weight(1f))
|
||||
Switch(checked = value, onCheckedChange = null)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -545,4 +545,7 @@
|
|||
<string name="player_written_new">✓ Neue Datenbank „%1$s“, Nr. %2$s ›</string>
|
||||
<string name="player_write_failed">Konnte nicht in „%1$s“ schreiben: %2$s</string>
|
||||
<string name="play_adjourned_replaced">Eine neue Partie ersetzt sie.</string>
|
||||
<string name="last_opened">Zuletzt geöffnet</string>
|
||||
<string name="play_adjourned_title">Partie gegen Maia %1$s</string>
|
||||
<string name="play_move_n">Zug %1$d</string>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -553,4 +553,7 @@
|
|||
<string name="player_written_new">✓ Base nueva «%1$s», n.º %2$s ›</string>
|
||||
<string name="player_write_failed">No se pudo escribir en «%1$s»: %2$s</string>
|
||||
<string name="play_adjourned_replaced">Una partida nueva la sustituye.</string>
|
||||
<string name="last_opened">Abierta por última vez</string>
|
||||
<string name="play_adjourned_title">Partida contra Maia %1$s</string>
|
||||
<string name="play_move_n">jugada %1$d</string>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -553,4 +553,7 @@
|
|||
<string name="player_written_new">✓ Nouvelle base « %1$s », n° %2$s ›</string>
|
||||
<string name="player_write_failed">Impossible d’écrire dans « %1$s » : %2$s</string>
|
||||
<string name="play_adjourned_replaced">Une nouvelle partie la remplace.</string>
|
||||
<string name="last_opened">Ouverte en dernier</string>
|
||||
<string name="play_adjourned_title">Partie contre Maia %1$s</string>
|
||||
<string name="play_move_n">coup %1$d</string>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -553,4 +553,7 @@
|
|||
<string name="player_written_new">✓ Nuovo database «%1$s», n. %2$s ›</string>
|
||||
<string name="player_write_failed">Impossibile scrivere in «%1$s»: %2$s</string>
|
||||
<string name="play_adjourned_replaced">Una nuova partita la sostituisce.</string>
|
||||
<string name="last_opened">Aperta per ultima</string>
|
||||
<string name="play_adjourned_title">Partita contro Maia %1$s</string>
|
||||
<string name="play_move_n">mossa %1$d</string>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -546,4 +546,7 @@
|
|||
<string name="player_written_new">✓ Жаңа база «%1$s», № %2$s ›</string>
|
||||
<string name="player_write_failed">«%1$s» базасына жазу мүмкін болмады: %2$s</string>
|
||||
<string name="play_adjourned_replaced">Жаңа ойын оның орнын басады.</string>
|
||||
<string name="last_opened">Соңғы ашылған</string>
|
||||
<string name="play_adjourned_title">Maia %1$s-мен ойын</string>
|
||||
<string name="play_move_n">%1$d-жүріс</string>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -554,4 +554,7 @@
|
|||
<string name="player_written_new">✓ Nova base «%1$s», n.º %2$s ›</string>
|
||||
<string name="player_write_failed">Não foi possível gravar em «%1$s»: %2$s</string>
|
||||
<string name="play_adjourned_replaced">Uma nova partida a substitui.</string>
|
||||
<string name="last_opened">Aberta por último</string>
|
||||
<string name="play_adjourned_title">Partida contra a Maia %1$s</string>
|
||||
<string name="play_move_n">lance %1$d</string>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -561,4 +561,7 @@
|
|||
<string name="player_written_new">✓ Создана база «%1$s», № %2$s ›</string>
|
||||
<string name="player_write_failed">Не удалось записать в «%1$s»: %2$s</string>
|
||||
<string name="play_adjourned_replaced">Новая партия заменит её.</string>
|
||||
<string name="last_opened">Открыта последней</string>
|
||||
<string name="play_adjourned_title">Партия с Maia %1$s</string>
|
||||
<string name="play_move_n">%1$d-й ход</string>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -544,4 +544,7 @@
|
|||
<string name="player_written_new">✓ Yangi baza «%1$s», № %2$s ›</string>
|
||||
<string name="player_write_failed">«%1$s» ga yozib bo‘lmadi: %2$s</string>
|
||||
<string name="play_adjourned_replaced">Yangi o‘yin uning o‘rnini oladi.</string>
|
||||
<string name="last_opened">Oxirgi ochilgan</string>
|
||||
<string name="play_adjourned_title">Maia %1$s bilan o‘yin</string>
|
||||
<string name="play_move_n">%1$d-yurish</string>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -549,4 +549,7 @@
|
|||
<string name="player_written_new">✓ New database “%1$s”, No. %2$s ›</string>
|
||||
<string name="player_write_failed">Could not write to “%1$s”: %2$s</string>
|
||||
<string name="play_adjourned_replaced">A new game replaces it.</string>
|
||||
<string name="last_opened">Last opened</string>
|
||||
<string name="play_adjourned_title">Game against Maia %1$s</string>
|
||||
<string name="play_move_n">move %1$d</string>
|
||||
</resources>
|
||||
|
|
|
|||
|
|
@ -317,8 +317,8 @@ impl Database {
|
|||
.collect()
|
||||
}
|
||||
|
||||
/// The numbers of the games whose players, event, site or date contain every word
|
||||
/// of `text` (case does not matter); all games for an empty text.
|
||||
/// The numbers of the games whose players, event, site, date or opening code (ECO)
|
||||
/// contain every word of `text` (case does not matter); all games for an empty text.
|
||||
pub fn find(&self, text: String) -> Vec<u32> {
|
||||
let Some(pgn) = self.db.as_pgn() else {
|
||||
return Vec::new();
|
||||
|
|
@ -328,7 +328,7 @@ impl Database {
|
|||
.iter()
|
||||
.filter(|e| {
|
||||
words.is_empty() || {
|
||||
let hay = ["White", "Black", "Event", "Site", "Date"]
|
||||
let hay = ["White", "Black", "Event", "Site", "Date", "ECO"]
|
||||
.iter()
|
||||
.filter_map(|t| e.tag(t))
|
||||
.collect::<Vec<_>>()
|
||||
|
|
@ -626,6 +626,10 @@ mod tests {
|
|||
.all(|r| r.white.contains("Morphy") || r.black.contains("Morphy"))
|
||||
);
|
||||
assert!(db.find("no such player anywhere".into()).is_empty());
|
||||
// By the opening code too: the Opera game is a Philidor (C41).
|
||||
let c41 = db.find("c41".into());
|
||||
assert!(!c41.is_empty());
|
||||
assert!(db.rows_of(c41).iter().all(|r| r.eco == "C41"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
|||
260
docs/design/android-lists.md
Normal file
260
docs/design/android-lists.md
Normal file
|
|
@ -0,0 +1,260 @@
|
|||
# ChessPenguin для Android: списки нарядней
|
||||
|
||||
Статус: утверждено владельцем 2026-10-26 (список партий — направление А, «Базы» — Б, настройки и лист «Добавить базу» в том же стиле), реализовано в тот же день; что сделано и что отложено — §10. Дополняет `android-ui.md` (§3.2 список баз, §6.2 строка партии, §9 настройки, §10 внешний вид) и `android-play.md` (§30.2 «Базы», §31.7 отложенная партия). После утверждения разделы `android-ui.md` правятся ссылкой сюда.
|
||||
|
||||
Макет для владельца: `index.html` (кадры 360×800, «сейчас» и направления, тёмная и светлая темы). Генератор макета хранится в рабочей папке сессии, в репозиторий не входит.
|
||||
|
||||
Запрос владельца: «экран партии можно не трогать… а вот где списки как-то уныло. Список партий бы разделителями разделить… с одной стороны очень хорошо что просто, но визуально чуть бы разнообразнее. По пользовательским путям в целом ок. Оформление скудное».
|
||||
|
||||
Значит: пути, кнопки, порядок экранов и тексты не меняем. Меняем только то, как нарисованы строки и группы. Экран «Партия» не трогаем.
|
||||
|
||||
## 1. Что сейчас не так
|
||||
|
||||
Снимки 1080×2400, тёмная тема: «Базы» и «Партии» (база «Классические партии»).
|
||||
|
||||
**Список партий.**
|
||||
|
||||
1. Строки ничем не отделены друг от друга. Между партиями только чуть больший интервал. Три строки текста одного цвета, и глаз не видит, где кончается партия.
|
||||
2. Результат — голые цифры `1` и `0` у правого края, полужирность почти не заметна. Кто выиграл, приходится вычитывать.
|
||||
3. Белые и чёрные различаются только порядком строк. Плашки у доски (§7.11) различают их явно, а список нет.
|
||||
4. «Турнир · год · ECO» — одна серая строка. ECO теряется в конце, хотя это самая короткая и самая «шахматная» метка.
|
||||
5. Нет никакого акцента. Нет следа партии, из которой человек только что вернулся.
|
||||
|
||||
**Экран «Базы».**
|
||||
|
||||
1. Все плашки одного цвета (`primaryContainer`). PGN, ChessBase, архив, скачанная с Lichess база и своя база выглядят одинаково; разница только в двух-трёх буквах.
|
||||
2. Число партий набрано так же, как формат («267 партий · PGN»). Большую базу не отличить от маленькой с первого взгляда.
|
||||
3. Группы «Мои базы» и «Файлы» — только синий заголовок над плоским списком.
|
||||
4. Карточка отложенной партии — строка текста на синем фоне. О самой партии в ней ничего не видно.
|
||||
5. Кнопки «Играть с Maia» и «Новая партия» шириной по тексту. Справа остаётся пустое место, ряд выглядит недоделанным.
|
||||
|
||||
**Другие списки.** В настройках, на экране «Партии с Lichess и Chess.com» и в листе «Добавить базу» те же плоские строки без значков, без групп и без цвета.
|
||||
|
||||
**Правило, которое мешает.** `android-ui.md` §10.4: «Разделителей нет нигде». Это правило писалось ради чистоты, но на трёхстрочных строках оно и даёт «колонку текста». Предлагается его заменить (§5).
|
||||
|
||||
## 2. Список партий: три направления
|
||||
|
||||
Во всех трёх тексты, порядок, нажатие, долгое нажатие и TalkBack те же. Отличаются только оформление и плотность.
|
||||
|
||||
| | А. Строки с разделителями (рекомендую) | Б. Карточки | В. Одна строка «белые – чёрные» |
|
||||
|---|---|---|---|
|
||||
| Что это | Текущая трёхстрочная строка. Добавлены тонкий разделитель, кружки цвета сторон, плашка у результата победителя и ECO в рамке | Каждая партия — карточка `surfaceContainerLow` со скруглением 12 dp. Номер и турнир наверху, имена под ними | Белые и чёрные на одной строке, между ними плашка «1–0». Под ними турнир |
|
||||
| Высота | 80 dp, как сейчас | ≈ 94 dp вместе с промежутком 8 | 64 dp |
|
||||
| Строк на 360×800 | 8,5 (как сейчас) | 7,3 | 10,7 |
|
||||
| Плюсы | Плотность прежняя. Победителя видно с первого взгляда. Тот же язык, что у плашек у доски | Нарядней всех. Каждая партия — отдельный предмет | Плотнее всех, похоже на таблицу на компьютере |
|
||||
| Минусы | Строки всё ещё текстовые. Это и хорошо: не шумно | В базе на 5 000 и 870 тыс. партий — стена плиток. Теряется 15 % плотности, при прокрутке рябит | Имена приходится сокращать («Zukertort J. H.»), чёрные обрезаются. От этого ушли 2026-10-24 (§6.2) |
|
||||
|
||||
Миниатюра позиции в строке (последняя позиция или позиция после дебюта) рассматривалась и отложена. В `GameRow` нет ни FEN, ни ходов, поэтому для каждой строки пришлось бы разбирать партию. В базе на миллион записей это противоречит «тяжёлое не блокирует». К тому же 48 dp доски на строку съедают имена. Вернуться к ней можно для экрана «Партии игрока» или для своих баз, где партий десятки.
|
||||
|
||||
**Рекомендация — А.** Владелец просит «разделителями разделить» и «чуть разнообразнее», но «хорошо что просто». А делает ровно это: строки разделены, у каждой партии появляются три цветовых акцента (кружки сторон, плашка победителя, метка ECO), а плотность и все пути остаются прежними.
|
||||
|
||||
## 3. Спецификация А: строка партии
|
||||
|
||||
Схема на 360 dp (числа — dp):
|
||||
|
||||
```
|
||||
16 │ № │12│●│8│ имя белых ……………………………… Эло │8│[1]│16 24 bodyLarge
|
||||
│ │ │○│ │ имя чёрных ………………………………… Эло │ │ 0 │ 24 bodyLarge
|
||||
│ │ │ Paris Opera · 1858 ………………… ✓ │8│C41│ 20 bodyMedium
|
||||
└──────── разделитель 1 dp от кружков до 16 dp от правого края ───┘
|
||||
отступы сверху и снизу по 6 → 80
|
||||
```
|
||||
|
||||
### 3.1. Геометрия
|
||||
|
||||
- Высота и сетка — как в §6.2: 6 + 24 + 24 + 20 + 6 = 80 dp, при крупном шрифте строки растут так же, как сейчас (`lineHeight`). Колонка номера — прежняя (ширина по самому большому номеру, `bodySmall`, `tnum`, `onSurfaceVariant`, по линии белых), после неё 12 dp.
|
||||
- **Кружок стороны** — новый столбец перед именем: круг 8 dp, после него 8 dp до имени. Стоит по центру своей строки 24 dp. Имя становится на 16 dp уже. Правило сокращения `PlayerName` (полное → «Фамилия И. О.» → многоточие) не меняется. На 360 dp у имени около 230 dp, «Zukertort, Johannes Hermann» помещается целиком.
|
||||
- Строка подробностей начинается под именем, а не под кружком: отступ 16 dp слева.
|
||||
- **Колонка результата** — 24 dp, перед ней 8 dp, как сейчас.
|
||||
|
||||
### 3.2. Кружки сторон
|
||||
|
||||
| | Светлая | Тёмная |
|
||||
|---|---|---|
|
||||
| белые: заливка | `#FFFFFF` | `#FFFFFF` |
|
||||
| чёрные: заливка | `#1C1D1F` | `#0E0F10` |
|
||||
| кольцо 1 dp у обоих | `onSurfaceVariant` `#5D636B` | `onSurfaceVariant` `#A3A7AD` |
|
||||
|
||||
Цвета добавить в `ChessColors` (`sideWhite`, `sideBlack`), кольцо — роль темы. Сделано пока прежним `SideDisc` (`#F5F5F0` / `#26282B`, кольцо `outline`), см. §10. Кружки декоративные, TalkBack их не читает: стороны и так названы словами («Белые: …»). Когда у этюда нет чёрных (две строки названия, §6.2), кружков нет вовсе: это не игроки.
|
||||
|
||||
### 3.3. Результат
|
||||
|
||||
Плашка 24×20 dp, скругление 6 dp, текст 14sp `tnum` по центру. Стоит на линии своей строки.
|
||||
|
||||
| Результат в PGN | Строка белых | Строка чёрных | Имя победителя |
|
||||
|---|---|---|---|
|
||||
| `1-0` | плашка `1`: фон `primaryContainer`, текст `onPrimaryContainer`, 700 | `0` без плашки, `onSurfaceVariant`, 400 | у белых 500 |
|
||||
| `0-1` | `0` без плашки | плашка `1` | у чёрных 500 |
|
||||
| `1/2-1/2` | плашка `½`: фон `surfaceContainerHigh`, текст `onSurface`, 400 | такая же плашка `½` | оба 400 |
|
||||
| `*` и прочее | пусто, колонка 24 dp остаётся | пусто | оба 400 |
|
||||
|
||||
- Выигрыш намеренно не зелёный, а проигрыш не красный. Выигрыш белых — это проигрыш чёрных, у списка нет «своей» стороны. Акцент — цвет приложения.
|
||||
- Смысл не передаётся одним цветом: цифра остаётся (§12.3).
|
||||
- Контраст: `onPrimaryContainer` на `primaryContainer` — 5,4:1 в светлой и 8,0:1 в тёмной; `onSurface` на `surfaceContainerHigh` — выше 10:1.
|
||||
- Имя победителя 500 и имя проигравшего 400 — в одной строке разница заметна, но не кричит. Если при 500 имя перестаёт помещаться, работает то же правило сокращения: ширину меряем уже с насыщенностью.
|
||||
|
||||
### 3.4. Строка подробностей
|
||||
|
||||
- «Турнир · год» — как сейчас (`bodyMedium`, `onSurfaceVariant`, многоточие).
|
||||
- **ECO — отдельная метка справа** (решение владельца: метка нужна, и поиск находит партию по ECO; найденная метка заливается `primaryContainer` / `onPrimaryContainer`, как совпадение в тексте), выровненная по правому краю колонки результата. Текст `labelSmall` (12sp/16, 500, `tnum`) цветом `onSurfaceVariant`. Рамка 1 dp `outline`, скругление 4 dp, поля 4 dp, ширина не меньше 32 dp, высота 16 dp. Метка не обрезается: обрезается турнир. Нет ECO — нет метки.
|
||||
- **«✓ просмотрена»** (§6.2, когда будет сделано) — значок `check` 16 dp цветом `primary` между турниром и меткой ECO, с отступом 8 dp.
|
||||
|
||||
### 3.5. Разделитель
|
||||
|
||||
- 1 dp цветом `outlineVariant` (`#E1E3E6` / `#2E3033`) по низу строки, внутри её 80 dp: высота строки не меняется, бегунок и прыжки не дёргаются (§6.6).
|
||||
- Слева начинается от столбца кружков (16 + ширина номера + 12), справа кончается за 16 dp до края. Номер остаётся на «поле», как номера страниц.
|
||||
- У последней строки списка разделителя нет. У строки-заглушки (§6.6) он есть: заглушки той же формы.
|
||||
- Реализация: `drawBehind` в строке или `HorizontalDivider` внутри `Box` с `align(BottomStart)`. Не отдельный элемент `LazyColumn`, иначе ломается счёт мест.
|
||||
|
||||
### 3.6. Партия, открытая последней
|
||||
|
||||
После возврата с экрана «Партия» строка этой партии отмечена, пока человек не откроет другую или не уйдёт с экрана:
|
||||
|
||||
- фон строки `surfaceContainer` (`#EEF0F2` / `#232427`);
|
||||
- у левого края полоса 3 dp цветом `primary` со скруглёнными правыми углами (2 dp);
|
||||
- список прокручен так, чтобы строка была видна. Если она уже на экране, прокрутки нет.
|
||||
|
||||
Это то же место в текущем порядке, что «12 из 340» (§7.6): если в партии листали ‹ ›, отмечена та, на которой остановились. TalkBack добавляет в конец описания: «Открыта последней» / “Last opened”.
|
||||
|
||||
### 3.7. Подсветка поиска
|
||||
|
||||
- Совпадение запроса в имени белых, имени чёрных и турнире: фон `primaryContainer`, текст `onPrimaryContainer` (`SpanStyle(background = …, color = …)`; в Compose фон без скругления, это допустимо). Без учёта регистра, первое вхождение в каждом поле.
|
||||
- Если показано сокращённое имя, подсвечивается совпадение в нём. Если совпадение попало в сокращённую часть («Johannes» → «J.»), подсветки нет; строка всё равно найдена.
|
||||
- Заголовок — как сейчас: «Найдено 2 из 38».
|
||||
|
||||
### 3.8. Состояния
|
||||
|
||||
- Нажатие — стандартная рябь M3 поверх фона, включая отмеченную строку.
|
||||
- Заглушка, пока строка читается: серые полосы `surfaceContainerHigh` на месте имён и турнира, кружки и плашки той же формы и того же цвета, разделитель есть.
|
||||
- Большая база (от 20 000): строка та же. Чипы фильтров над списком (§6.5) — без изменений.
|
||||
|
||||
### 3.9. TalkBack
|
||||
|
||||
Текст строки тот же, что в §12.3: «№ 12. Белые: Карлсен, Магнус, Эло 2830. Чёрные: Каруана, Фабиано, Эло 2795. 1-0, победили белые. Норвегия, 2025, C42. Просмотрена». Добавляется только «Открыта последней» (§3.6). Кружки, плашки и рамка ECO смысла не добавляют и не озвучиваются.
|
||||
|
||||
## 4. Экран «Базы»: три направления
|
||||
|
||||
| | А. Цветные плашки, плоский список | Б. Группы-карточки (рекомендую) | В. Плитки в две колонки |
|
||||
|---|---|---|---|
|
||||
| Что это | Строки как сейчас, у плашек цвет по виду базы, тонкие разделители, число партий выделено | То же, плюс каждая группа — набор карточек с зазором 2 dp, как в настройках Android 16 (M3 Expressive). Карточка отложенной партии с маленькой доской. Кнопки поровну | Квадратные плитки 2×N: плашка, имя в две строки, число партий |
|
||||
| Строк на экран | 8–9 | 8 (72 + 2 dp) | 4 ряда по 2 |
|
||||
| Плюсы | Минимум работы | Группы читаются как предметы, экран «собран». Тот же язык, что в настройках системы | Выглядит как «полка» |
|
||||
| Минусы | Остаётся плоским | Имя базы уже на 12 dp | Меню ⋮ не помещается, только долгое нажатие. При 20 базах — длинная лента. Имена режутся по-другому, чем везде |
|
||||
|
||||
**Рекомендация — Б.** Цвет говорит о виде базы, группы становятся видимыми, а отложенная партия показывает себя, а не только подпись. Путей и кнопок не прибавилось.
|
||||
|
||||
## 5. Спецификация Б: экран «Базы»
|
||||
|
||||
### 5.1. Плашки видов
|
||||
|
||||
Плашка — 40×40 dp, скругление 10 dp (было 8). Текст `labelSmall` (12sp, 500) или значок 22 dp. Цвет выбирается по виду, а не по расширению.
|
||||
|
||||
**Решение владельца (2026-10-26): цвета видов — из палитры Catppuccin**: в тёмной теме Mocha, в светлой Latte. Текст или значок — цвет палитры, фон — подкраска того же оттенка, подобранная так, чтобы контраст был не ниже 5:1. Код: `theme/Color.kt`, `kindColor(kind, dark)`, виды — `DbKind`.
|
||||
|
||||
| Вид | Содержимое | Оттенок Catppuccin | Светлая (Latte): фон / текст | Тёмная (Mocha): фон / текст |
|
||||
|---|---|---|---|---|
|
||||
| PGN: файл, папка, копия, пример | `PGN` | blue | `#DFEAFE` / `#1957D0` | `#343E4D` / `#89B4FA` |
|
||||
| ChessBase | `CB` | peach | `#FFE9DD` / `#A54107` | `#4B3D36` / `#FAB387` |
|
||||
| архив 7z, ZIP | `7Z`, `ZIP` | mauve | `#EEE3FD` / `#7A33D7` | `#413B4D` / `#CBA6F7` |
|
||||
| скачанная с Lichess или Chess.com | значок `cloud_download` | teal | `#DFF0F1` / `#116D73` | `#364746` / `#94E2D5` |
|
||||
| своя база | значок `edit_note` | green | `#E4F2E1` / `#2D701E` | `#3A473B` / `#A6E3A1` |
|
||||
| база игрока (партии с Maia) | `♞` | green, как своя | как своя | как своя |
|
||||
| ошибка | `!` | — | `errorContainer` / `error` | так же |
|
||||
|
||||
- Тона ровно пять. Если видов станет больше, новые получают blue (PGN), а не шестой цвет.
|
||||
- Тексты Latte в светлой теме затемнены относительно исходной палитры: чистые Latte-тона на светлой подкраске дают меньше 4,5:1.
|
||||
- Те же цвета у круглых плашек листа «Добавить базу» и у плашек выбора файла.
|
||||
- Смысл не только в цвете: на плашке есть текст или значок, во второй строке формат словами.
|
||||
- Если появятся «Цвета обоев» (`android-ui.md` §10.3; в коде пока нет), цвета видов не меняются, включая PGN: это метки, как NAG.
|
||||
- Онлайн-база больше не показывает `PGN`: её отличие — откуда она, а не формат.
|
||||
|
||||
### 5.2. Строка базы
|
||||
|
||||
- 72 dp, как сейчас. Плашка, 12 dp, имя `bodyLarge` в одну строку с многоточием, ⋮ 48 dp.
|
||||
- **Вторая строка:** число партий — `onSurface`, 500, `tnum`; остальное — `onSurfaceVariant`, 400: «**267** партий · PGN», «**5 340** партий · PGN», «**1 204** партии · обновлено 2 ч назад». Текст тот же, что сейчас, выделено только число. Состояния «ещё не открывалась», «читаю…», ошибки, полоса скачивания 2 dp по низу — без изменений.
|
||||
|
||||
### 5.3. Группы
|
||||
|
||||
- Заголовок группы — как сейчас: 48 dp, `titleSmall` (14sp, 500), `primary`, слева 16 dp; у «Мои базы» справа «+ Новая база».
|
||||
- **Строки группы — отдельные карточки** `surfaceContainerLow` (`#F5F6F7` / `#1F2022`):
|
||||
- поля экрана 12 dp слева и справа, внутри карточки 12 dp до плашки;
|
||||
- между карточками зазор 2 dp цветом фона: он и есть разделитель;
|
||||
- скругления: у первой карточки верхние углы 16 dp и нижние 4 dp, у последней наоборот, у средних все 4 dp, у единственной все 16 dp;
|
||||
- рябь нажатия обрезается по форме карточки.
|
||||
- Имя базы при этом на 12 dp уже, чем сейчас (≈ 224 dp вместо 236 на 360 dp). Это цена карточек.
|
||||
- Пустая группа «Мои базы» — строка-подсказка (§30.2) без карточки, как сейчас.
|
||||
- Порядок групп и строк, правило «группа „Файлы“ без заголовка, если своих баз не было» — без изменений.
|
||||
- Анимации появления и удаления строк (`animateItem`) остаются. При удалении средней строки соседи меняют форму углов (первая или последняя). Форму считать по месту в группе при рисовании, а не хранить.
|
||||
|
||||
### 5.4. Отложенная партия
|
||||
|
||||
```
|
||||
┌────────────────────────────────────────┐ 16 dp скругление, primaryContainer
|
||||
│ ┌──────┐ Партия с Maia 1550 ✕ │ bodyLarge 500, onPrimaryContainer
|
||||
│ │доска │ вы белыми · 6-й ход │ bodyMedium
|
||||
│ │72 dp │ [ Продолжить ] │ Button 32 dp, primary / onPrimary
|
||||
│ └──────┘ │
|
||||
└────────────────────────────────────────┘ поля 12, высота ≈ 96
|
||||
```
|
||||
|
||||
- **Доска 72 dp** — текущая позиция отложенной партии. Те же доска и фигуры, что выбраны в настройках, сторона игрока внизу, без координат, стрелок и последнего хода, скругление 6 dp. Рисуется уже существующим `Board` в режиме «только показать», без нажатий, один раз при появлении карточки. PGN уже лежит в `filesDir/play/current.pgn`.
|
||||
- Текст: первая строка «Партия с Maia {сила}», вторая «вы белыми · {n}-й ход». Ход — тот, что сейчас на доске. Если ход неизвестен, только «вы белыми». Строки — существующие `play_adjourned` / `play_adjourned_sub`, текст разбит на две.
|
||||
- «Продолжить» — заполненная кнопка (`primary`), а не текстовая: это главное действие на экране, пока партия отложена. × — `IconButton` 48 dp в правом верхнем углу, поведение прежнее («Партия удалена · Вернуть»).
|
||||
- Вся карточка нажимается как «Продолжить». TalkBack: «Отложенная партия с Maia 1550, вы белыми, 6-й ход. Продолжить, кнопка».
|
||||
|
||||
### 5.5. Ряд действий
|
||||
|
||||
- Две кнопки поровну, на всю ширину: `Modifier.weight(1f)`, между ними 12 dp, поля 16 dp.
|
||||
- `FilledTonalButton` высотой 56 dp, скругление 16 dp (как у FAB и карточек, а не таблетка). Значки и тексты прежние. На 360 dp у кнопки 158 dp, «Играть с Maia» со значком помещается (сейчас кнопка 148 dp).
|
||||
|
||||
### 5.6. Что остаётся
|
||||
|
||||
Верхняя панель «ChessPenguin ⚙», FAB «Добавить базу» (сжимается при прокрутке), меню ⋮ и долгое нажатие, снекбары «Вернуть», карточка обновления (§25.8) первой в списке, нижний отступ списка 88 dp.
|
||||
|
||||
## 6. Другие списки — тот же язык
|
||||
|
||||
- **Настройки (§9).** Группы — те же карточки, что в §5.3: поля 12, зазор 2, углы 16/4. Заголовки групп прежние (`labelLarge`, `primary`). У каждого пункта слева значок Material Symbols 24 dp цветом `onSurfaceVariant`, после него 16 dp. Пункт по-прежнему не ниже 56 dp, длинные названия переносятся. Значки: «Запись ходов» `notes`, «Анимация фигур» `animation`, «Стрелка лучшего хода» `arrow_right_alt`, «Звук» `volume_up`, «Вибрация» `vibration`, «Записывать партии…» `save`, «Доска и фигуры» `grid_on`, «Тема» `palette`, «Язык» `translate`, движок `memory`, линии `format_list_numbered`, время `timer`, потоки `developer_board`, память `sd_card`, «О программе» `info`. Переключатели и строки состояния не меняются.
|
||||
- **Лист «Добавить базу» (§4.1).** Значок пункта — в круглой плашке 40 dp цвета той базы, которая получится: «Вставить PGN», «Файл», «Папка» — синяя PGN, «Партии с Lichess и Chess.com» — бирюзовая онлайн-база. Тексты и порядок прежние.
|
||||
- **«Партии с Lichess и Chess.com» (§23).** Найденные аккаунты и карточки скачивания — карточками §5.3 (одна группа на экран), плашка у строки аккаунта — бирюзовая с `cloud_download`. Поля ника и переключатель «вместе» не меняются. При реализации свериться с `OnlineScreen.kt` (`FoundRow`, `DownloadCard`).
|
||||
- **Сортировка, фильтры, меню, диалоги** — без изменений.
|
||||
|
||||
## 7. Что меняется в правилах `android-ui.md`
|
||||
|
||||
- §10.4 «Разделителей нет нигде…» заменить на: «Разделители — только в длинных списках: 1 dp `outlineVariant` между строками партий (§6.2, `android-lists.md` §3.5) и линия между нотацией и нижней панелью. Короткие списки (базы, настройки) группируются карточками с зазором 2 dp».
|
||||
- §10.4 скругления: добавить «карточки групп — 16 dp снаружи и 4 dp внутри; плашки видов баз — 10 dp; плашка результата — 6 dp; метка ECO — 4 dp».
|
||||
- §10.3: добавить таблицу цветов видов баз (§5.1) и цвета кружков сторон (§3.2).
|
||||
- §10.6 «Плашка формата базы»: цвет по виду (§5.1).
|
||||
- §3.2, §6.2, §30.2, §31.7 — ссылки на разделы этого документа.
|
||||
|
||||
## 8. Что не меняется
|
||||
|
||||
Экран «Партия» и всё, что на нём. Цепочка Базы → Партии → Партия. Набор кнопок и пунктов меню. Все тексты, кроме разбивки карточки отложенной партии на две строки и «Открыта последней» в TalkBack. Шрифт, сетка 4 dp, поля 16 dp у списка партий. Высота строки партии 80 dp и плотность 8,5 строки на экран.
|
||||
|
||||
## 9. Проверить при реализации
|
||||
|
||||
- Обе темы, шрифт 100 % и 200 %. При 200 % строка партии растёт, плашка результата остаётся на линии своей строки, метка ECO не налезает на турнир.
|
||||
- Контраст по таблицам §3.3 и §5.1 — на устройстве, а не только расчётом.
|
||||
- Большая база (870 тыс.): прокрутка бегунком без рывков. Разделитель не добавляет высоты, у заглушек он тоже есть.
|
||||
- Возврат из «Партии» после ‹ › отмечает ту партию, на которой остановились.
|
||||
- Удаление средней, первой и единственной базы в группе: углы соседей пересчитываются, анимация не дёргается.
|
||||
- TalkBack: строка партии читается как раньше плюс «Открыта последней»; карточка отложенной партии — одним узлом.
|
||||
- «Цвета обоев» (когда появятся): цвета видов баз остаются своими.
|
||||
|
||||
## 10. Что сделано и что отложено (2026-10-26)
|
||||
|
||||
Сделано (`ui/GamesScreen.kt` — `GameRowView`, `ListPlayer`, `EcoTag`; `ui/Common.kt` — `KindBadge`, `groupCard`, `ResultTile`, `highlighted`; `ui/DatabasesScreen.kt`; `ui/SettingsScreen.kt`; `ui/AddDatabase.kt`; `theme/Color.kt`):
|
||||
|
||||
- Строка партии А: кружки сторон 8 dp, плашка результата 24×20, имя победителя 500, метка ECO 16 dp с рамкой `outline`, разделитель 1 dp от кружков, у последней строки нет.
|
||||
- Отметка партии, открытой последней (фон `surfaceContainer`, полоса 3 dp `primary`, TalkBack «Открыта последней»); при возврате список прокручивается к ней.
|
||||
- Подсветка поиска в именах и турнире; поиск по ECO, найденная метка ECO залита.
|
||||
- «Базы» Б: плашки по видам в цветах Catppuccin (§5.1), карточки групп 12/2/16/4, число партий 500 `onSurface`, отложенная партия с доской 72 dp и кнопкой «Продолжить», две кнопки поровну 56 dp.
|
||||
- Настройки — карточки групп и значки 24 dp; лист «Добавить базу» — круглые плашки 40 dp цвета будущей базы.
|
||||
|
||||
Отложено или сделано иначе:
|
||||
|
||||
- «✓ просмотрена» (§3.4) — не сделано, как и раньше.
|
||||
- Заглушка строки (§3.8) — пустая строка с разделителем, без серых полос.
|
||||
- Экран «Партии с Lichess и Chess.com» (§6) — в старом виде.
|
||||
- Кружки сторон — прежние цвета `SideDisc`, а не `sideWhite`/`sideBlack` из §3.2.
|
||||
- Прокрутка к отмеченной партии происходит всегда (строка ставится третьей сверху), а не только когда её не видно.
|
||||
- Светлая тема и шрифт 200 % на устройстве ещё не проверены (§9).
|
||||
|
|
@ -125,6 +125,8 @@
|
|||
|
||||
### 3.2. Список баз
|
||||
|
||||
Оформление строк, групп, плашек видов и карточки отложенной партии — `android-lists.md` §5 (утверждено 2026-10-26); пути и тексты ниже не меняются.
|
||||
|
||||
```
|
||||
┌────────────────────────────────────┐
|
||||
│ ChessPenguin ⚙ │
|
||||
|
|
@ -149,7 +151,7 @@
|
|||
- Имя базы 16sp. Под ним 14sp цветом `onSurfaceVariant`: «N партий · формат».
|
||||
- Числа сокращаются как на компьютере (`short_count`): «870 тыс. партий», «1,6 млн партий»; меньше 100 000 — полностью, с пробелом между разрядами.
|
||||
- Пока базу ни разу не открывали, вторая строка — «ещё не открывалась · PGN». Формат словом, как после открытия: `PGN`, `ChessBase`, `архив 7z`, `архив ZIP`; не код плашки `CB`. Размера нет: у баз из папки его нет без лишнего запроса.
|
||||
- Разделителей между строками нет.
|
||||
- Разделителей между строками нет: строки группы — карточки с зазором 2 dp (`android-lists.md` §5.3).
|
||||
- Базы идут в порядке добавления, новые внизу.
|
||||
- Нажатие открывает «Партии». Долгое нажатие и ⋮ открывают одно и то же меню: «Переименовать», «Сведения», «Убрать из списка».
|
||||
- При прокрутке вниз FAB сжимается до «+», при прокрутке вверх снова показывает текст. Снизу у списка отступ 88 dp, чтобы последняя строка не пряталась под FAB.
|
||||
|
|
@ -364,6 +366,8 @@ FAB открывает лист, а не сразу системный выбо
|
|||
|
||||
### 6.2. Строка партии (80 dp, три строки)
|
||||
|
||||
Оформление с 2026-10-26 — `android-lists.md` §3: кружки сторон, плашка результата, метка ECO, разделитель, отметка партии, открытой последней, подсветка поиска. Сетка и высота ниже не меняются.
|
||||
|
||||
Обновлено 2026-10-24. Раньше «Белые – Чёрные» стояли в одной строке, и на 360 dp фамилия чёрных часто обрезалась. Теперь у каждого игрока своя строка: белые сверху, чёрные под ними, как плашки на доске (§7.11), только в обратном порядке — сверху вниз читается «кто играл белыми, кто чёрными».
|
||||
|
||||
```
|
||||
|
|
@ -975,6 +979,8 @@ FAB открывает лист, а не сразу системный выбо
|
|||
|
||||
Контраст текста и фона не ниже 4,5:1, включая `onSurfaceVariant` и цвет комментария. Разработчик проверяет это на обеих темах.
|
||||
|
||||
**Цвета видов баз** (плашки на «Базах», в листе «Добавить базу» и при выборе файла) — из Catppuccin: Mocha в тёмной теме, Latte в светлой (решение владельца 2026-10-26). PGN — blue, ChessBase — peach, архивы — mauve, скачанные с Lichess и Chess.com — teal, свои базы и база игрока — green; фон — подкраска того же оттенка, контраст не ниже 5:1. Таблица — `android-lists.md` §5.1, код — `kindColor` в `theme/Color.kt`. Это метки, как NAG: «Цвета обоев» их не меняют. Цвета кружков сторон в списке партий — `android-lists.md` §3.2.
|
||||
|
||||
### 10.4. Поверхности, высоты, скругления
|
||||
|
||||
- **Теней нет**, кроме FAB (уровень 3) и листов с затемнением фона. Вместо теней — тональные поверхности. Верхняя панель при прокрутке меняет `surface` на `surfaceContainer` (M3 `pinnedScrollBehavior`).
|
||||
|
|
@ -985,9 +991,11 @@ FAB открывает лист, а не сразу системный выбо
|
|||
- кнопки — полностью скруглённые (M3 по умолчанию);
|
||||
- диалоги и верх листов — 28 dp;
|
||||
- FAB — 16 dp;
|
||||
- карточки групп (базы, настройки) — 16 dp снаружи и 4 dp там, где карточки соседствуют; кнопки «Играть с Maia» и «Новая партия» — 16 dp;
|
||||
- плашки видов баз — 10 dp; плашка результата в списке партий — 6 dp; метка ECO — 4 dp;
|
||||
- доска на телефоне — 0 (во всю ширину), на планшете — 8 dp.
|
||||
- **Блок комментария** — фон `surfaceContainerLow`, без рамки. **Блок варианта** — без фона, только линия слева.
|
||||
- Разделителей нет нигде, кроме линии 1 dp `outlineVariant` между нотацией и нижней панелью.
|
||||
- Разделители — только в длинных списках: 1 dp `outlineVariant` между строками партий (§6.2, `android-lists.md` §3.5) и линия между нотацией и нижней панелью. Короткие списки (базы, настройки) группируются карточками `surfaceContainerLow` с зазором 2 dp (`android-lists.md` §5.3). Правило изменено 2026-10-26: раньше разделителей не было нигде.
|
||||
|
||||
### 10.5. Доски и фигуры
|
||||
|
||||
|
|
@ -1019,7 +1027,7 @@ FAB открывает лист, а не сразу системный выбо
|
|||
| ошибка | `error` |
|
||||
|
||||
- Ход и партия различаются формой значков: у хода — залитые треугольники крупно внизу, у партии — тонкие уголки мелко вверху.
|
||||
- Плашка формата базы — не значок, а текст `PGN`, `CB`, `ZIP` или `7Z` (`labelSmall`, 500) в скруглённом квадрате 40 dp с фоном `primaryContainer`. Это понятнее любого рисунка файла.
|
||||
- Плашка формата базы — не значок, а текст `PGN`, `CB`, `ZIP` или `7Z` (`labelSmall`, 500) в скруглённом квадрате 40 dp (10 dp) цвета вида базы (§10.3, `android-lists.md` §5.1). Это понятнее любого рисунка файла. У скачанной базы вместо текста значок `cloud_download`, у своей — `edit_note`, у базы игрока — `♞`.
|
||||
|
||||
### 10.7. Значок приложения и заставка
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue