# Code style

This guide describes conventions observed in Yokan's first-party source and the
requirements in [AGENTS.md](AGENTS.md) and the
[Android/Kotlin skill](.codex/skills/compose-kotlin-agent-skills/SKILL.md).
It applies primarily to `composeApp`, with brief notes for the iOS wrapper and
build scripts. Vendored projects and generated files have their own conventions.

The codebase is not uniform. Sections marked **Required direction** describe
project instructions for new or refactored code; they do not claim that every
existing file already complies. Keep unrelated formatting and architecture
changes out of functional patches.

## Formatting and imports

- Use four spaces for indentation and opening braces on the declaration line.
- Use a space after commas and around assignments, operators, and control-flow
  conditions: `if (items.isEmpty())`.
- Separate the package, imports, and declarations with blank lines. Separate
  methods and logical steps with blank lines without spacing out every statement.
- Put long parameter lists and constructor calls on multiple lines, one argument
  per line, with the closing parenthesis aligned with the declaration or call.
- Use trailing commas in multiline parameter lists, calls, collections, and enum
  entries. This is common in production code, although some tests omit them.
- Prefer named arguments when constructing models or passing several booleans,
  nullable values, or callbacks. Short, unambiguous calls can remain positional.
- Use expression bodies for simple mappings, getters, and forwarding functions;
  use block bodies for operations with several steps or side effects.
- Break long collection and modifier chains before the dot. Short chains can
  remain on one line. There is no repository-configured maximum line length.
- Prefer explicit imports. Aliases are used to disambiguate APIs, such as lazy
  list `items` versus grid `items`. Import order is not completely consistent,
  and some existing tests use wildcard imports; avoid unrelated import churn.
- Normally omit semicolons. Some compact existing DSL blocks contain them; new
  blocks are clearer with separate statements on separate lines.

[gradle.properties](gradle.properties) sets `kotlin.code.style=official`; no
formatter (EditorConfig, ktlint, Detekt, Spotless) is configured. What is enforced:

- The Kotlin compiler runs with `allWarningsAsErrors` on every target, so a
  warning (deprecation, dead branch, unnecessary `!!`) fails the build. Fix it;
  add a narrow `@OptIn` only for an intentional experimental API.
- `LayeringRulesTest` (desktopTest) fails when `data`, `database`, `domain` or
  `services` reference `ui` or `app`, or `domain` references the other layers.
- `HardcodedUiStringsTest` keeps per-file counts of hardcoded user-visible text
  under `ui/` in `src/desktopTest/resources/hardcoded-ui-strings.txt`. Counts
  may only go down; lower the number when you move text to resources.
- `SettingsSearchAnchorsTest` checks every anchored settings-search id against a
  settings item key.
- Forgejo CI runs desktop and Android unit tests and compiles Android and
  Kotlin/Wasm on every push to `main` and pull request. Run Wasm browser and iOS
  simulator tests locally for platform changes (see the README for their state).

## Naming and file organization

| Element | Convention and examples |
| --- | --- |
| Packages | Lowercase under `eu.friedcutlet.yokan`, matching directories |
| Types and composables | PascalCase: `HttpRequest`, `LibraryViewModel`, `LibraryScreen` |
| Functions and properties | lowerCamelCase: `updateSettings`, `refreshing`, `lastRefreshSummary` |
| Boolean properties | Descriptive predicates: `isRead`, `hasUpdate`, `shouldUpdate`; follow nearby model vocabulary |
| Enum entries | PascalCase in domain models: `Manga`, `Ongoing`, `ComfortableGrid` |
| Constants | `UPPER_SNAKE_CASE` occurs in service limits, such as `DOWNLOAD_CONNECTION_TIMEOUT_MS`; existing UI constants also use PascalCase |
| Mutable flow backing fields | Leading underscore: `_state`; expose a read-only `state` |
| Implementations | Meaningful prefixes: `DefaultYokanRepository`, `PersistentDownloadService`, `HttpMetadataService` |
| Database models and adapters | `Db` model prefix and conversions such as `toDb`, `toDomain`, `toDomainChapter` |
| Tests and fakes | `SubjectTest`, descriptive lowerCamelCase test functions, `RecordingHttpService` or `TestFileService` |

Name files after their main type or responsibility. Related small declarations
may share a file: `HttpService.kt` contains its interface and request/response
types, and `LibraryContract.kt` contains state and events. Feature UI commonly
uses `FeatureRoute.kt`, `FeatureScreen.kt`, `FeatureViewModel.kt`, and
`FeatureContract.kt`. Larger features also split helpers into focused files.

Use `private` for implementation helpers and `internal` for module-scoped APIs.
Constructor dependencies are commonly `private val`. Put small mappings and
parsing helpers near the implementation that uses them, often as private
top-level extension functions.

## Kotlin idioms and models

- Prefer `val` and value-oriented `data class` models. Use `copy(...)` to derive
  updated values. Mutable collections are appropriate for internal accumulation
  and test recording, but should not expose writable screen state.
- Give optional model fields explicit defaults such as `null`, `false`, `""`,
  `emptyList()`, and `emptyMap()` when those values express the contract.
- Declare types on interface boundaries and exposed state. Infer obvious local
  types. Existing implementations sometimes infer override/property types.
- Use sealed interfaces with `data class` payloads and `data object` cases for
  event or state alternatives. Handle them with `when`.
- Prefer safe calls, `as?`, `firstOrNull`, and Elvis returns over nested checks.
  Short guards such as `if (state.value.refreshing) return` are idiomatic here.
- Use `map`, `mapNotNull`, `filter`, `buildList`, and `buildString` when they make
  transformations clear. Use named lambda parameters when `it` becomes ambiguous.
- Use method references for simple forwarding and lambdas when arguments need
  adapting: `map(::toDomainChapter)` or `onClick = { onOpen(item.id) }`.

**Required direction:** avoid production `!!`; use early returns or
`requireNotNull` according to whether absence is expected or violates a contract.
Keep mutable state encapsulated rather than mutating fields inside a UI model.

For representative models and transformations, see
[Models.kt](composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/domain/Models.kt),
[HttpService.kt](composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/http/HttpService.kt),
and [DefaultYokanRepository.kt](composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/data/DefaultYokanRepository.kt).

## Multiplatform boundaries and dependencies

The main application is one Kotlin Multiplatform module, organized by packages
and source sets rather than a separate Gradle module for every feature.

| Location under `composeApp/src` | Responsibility |
| --- | --- |
| `commonMain` | Shared domain, data, database contracts, services, and Compose UI |
| `nonWebMain` | Shared non-browser implementations, including Room, QuickJS, and mpv |
| `jvmCommonMain` | Code shared by Android and desktop |
| `platformWebViewMain` | Shared WebView integration used by Android and iOS |
| `skikoMain` | Skia-backed code shared by desktop, iOS, and the browser (`coil3.Bitmap` is `org.jetbrains.skia.Bitmap`) |
| `androidMain`, `desktopMain`, `iosMain`, `wasmJsMain` | Platform integrations and entry points |

Keep platform SDK types in the appropriate platform source set. Common contracts
use interfaces and `expect` declarations; platform implementations use `actual`
and suffixes such as `.android.kt`, `.desktop.kt`, `.ios.kt`, and `.wasm.kt`.
Shared implementation suffixes include `.nonWeb.kt`, `.jvm.kt`, and `.skiko.kt`.
Factory functions commonly use `createPlatform...` names.

Services take their dependencies through constructors. The application wires
them manually in
[ServiceRegistry.kt](composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/ServiceRegistry.kt)
and exposes them, plus the app-scoped state holders, through `YokanRuntime`.
Hilt is a skill default, not the observed application wiring; do not describe it
as already installed. Preserve existing service interfaces so tests can supply
lightweight fakes. Services that need only HTTP, files or the database belong in
`YokanServices` (`defaultServices`); profile-scoped holders and services that need
the repository or settings are `owned` resources of `ProfileSession`.

Keep domain models separate from database and transport representations, with
explicit mapping at boundaries. Packages under `eu.friedcutlet.yokan`:

| Package | Responsibility |
| --- | --- |
| `app` | Composition root: `YokanRuntime`, `ServiceRegistry`, bootstrap and startup |
| `data` | `YokanRepository` and its default implementation, `SettingsStore`, `LibraryIndexStore`, DB↔domain mappers |
| `database`, `database.sync`, `database.room` | Persistence contracts, snapshot models, sync identities, the Room implementation |
| `domain` | Pure domain models and rules |
| `services.<domain>` | One package per capability (`download`, `library`, `migration`, `extensions`, `sync`, …) |
| `ui.navigation`, `ui.components`, `ui.theme`, `ui.image`, `ui.status`, `ui.screens.<feature>` | Compose UI |

**Required direction:** `data`, `database`, `domain` and `services` never import
`ui` or `app`. Models shared by a service and its screens live in the service
package (for example `services.library.LocalLibraryOverview`,
`services.migration.MassMigrationProgress`). Platform entry points that need the
whole app (WorkManager workers, iOS BGTasks) receive it through an interface or
lambda installed by the entry point (`BackgroundTaskHost`,
`IosBackgroundTaskRegistration`), not by importing `YokanRuntime`.

## Compose and screen state

Navigation is typed. `Route` (`ui/navigation/Route.kt`) is a sealed interface of
destinations with their arguments; `Navigator` owns the back stack, the root
section/item type and the minimized-player flag as `StateFlow`s and is created
once in `App.kt`. Every stack entry is a `NavEntry` with its own
`ViewModelStore`: `NavHost` provides it as `LocalViewModelStoreOwner`, so a plain
`viewModel { }` inside a route is scoped to that entry and cleared once the entry
leaves the stack. Root sections (library, updates, history, browse, more) use
`nav.rootViewModelStoreOwner` with explicit keys such as `library-$itemType`.
Only `CoverInspection` keeps a hand-rolled owner because its ViewModel is scoped
to the dialog. `ApplyReaderSystemUi` is the one screen-level composable that reads
`YokanRuntime` (the platform system-UI controller shared by all readers).

Each destination has a route adapter, `XRoute(route: Route.X, nav: Navigator)`
(settings pages: an `XSettingsRoute(title, settings, onUpdate, onBack)` adapter in
the page's package, dispatched with one line per page from `SettingsRoute`). The
adapter is the only place that reads `YokanRuntime`: it builds the ViewModel from
runtime holders (`settings`, `libraryIndex`, `libraryUpdates`, `localLibrary`,
`migration`, `chapterDownloads`, `sourceInstall`, `repository`, `services`),
collects its state and passes values and `on…` lambdas to a stateless screen.
Screens never take a ViewModel, `Navigator`, holder or service parameter. A
ViewModel takes required dependencies; do not default them to `YokanRuntime` or
make them nullable for tests, because that creates a code path production never
runs.

One-shot outcomes (navigation, snackbars, notices) are a sealed `XEffect` sent
through a `Channel` and collected by the route while STARTED; see
[ReaderRoute.kt](composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderRoute.kt).
Events never carry UI lambdas.

The library feature demonstrates the route/contract/ViewModel split:

- [LibraryContract.kt](composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryContract.kt)
  defines `LibraryState` and `LibraryEvent`.
- [LibraryViewModel.kt](composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryViewModel.kt)
  exposes `StateFlow` and handles events with atomic updates.
- [LibraryRoute.kt](composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryRoute.kt)
  resolves the ViewModel, collects state, and passes values and callbacks onward.

The characteristic state pattern is:

```kotlin
private val _state = MutableStateFlow(LibraryState(itemType, query, display))
val state: StateFlow<LibraryState> = _state.asStateFlow()

fun onEvent(event: LibraryEvent) {
    when (event) {
        LibraryEvent.Refresh -> refresh()
        is LibraryEvent.SelectCategory -> _state.update {
            it.copy(selectedCategoryId = event.categoryId)
        }
        // …
    }
}
```

**Required direction:** ViewModels own screen state through `MutableStateFlow`,
expose read-only `StateFlow`, and mutate it with `_state.update { ... }`.
Use `viewModelScope` for ViewModel work (never `rememberCoroutineScope` for data
or service calls; it is for scroll/pager animation and platform pickers) and
`collectAsStateWithLifecycle()`, never `collectAsState()`. ViewModels observe the
database through `repository.observe({ it.part }) { read() }` or the holders'
flows, not through a refresh counter. A ViewModel that moves work off the main
thread takes `workDispatcher: CoroutineDispatcher = Dispatchers.Default` and
uses it for every `withContext`/`flowOn`/`observe` hop.

For new reusable composables, accept `modifier: Modifier = Modifier` as the first
optional parameter and apply it to the root element. Give callbacks descriptive
`on...` names. Supply stable keys in lazy lists, rows, and grids; use appropriate
`contentType` values for distinct item types. Follow the project modifier order
`padding → clip → background → clickable` when those operations occur together.
Use `MaterialTheme` colors and typography and Compose resource accessors such as
`stringResource(Res.string.empty_library)` for user-visible text, including
ViewModel messages (`getString(Res.string.…)`). Plain actions reuse `action_*`
and `ok`. Existing hardcoded labels are debt tracked by `HardcodedUiStringsTest`.

## Coroutines, errors, and comments

Service interfaces mark asynchronous operations `suspend`. Existing code uses
guard clauses and nullable/empty results for unavailable optional data, and
`runCatching` around parsing and platform failures. Follow the particular
interface's failure contract; an empty result and a failed operation are not
automatically equivalent.

**Required direction:** preserve coroutine cancellation when handling failures.
Broad `catch` or `runCatching` around suspending work must not convert cancellation
into ordinary success or an empty result. Keep cleanup tied to the operation or
owner's lifetime.

Use `catchingNonCancellation` (`services/Concurrency.kt`) whenever suspending
work becomes a `Result` or a fallback. In a `try`/`catch` with a broad catch, make
`catch (e: CancellationException) { throw e }` the first clause. `runCatching` is
only for non-suspending parsing. Never throw `CancellationException` as a domain
signal; use a dedicated exception type. Work that must not outlive a profile or
session owner runs through `CoroutineScope.runJoined`, which joins the work
before returning.

Use KDoc to explain public contracts, ownership, field semantics, and platform
limitations. Link symbols with `[Symbol]`. Use `//` comments for the reason behind
a workaround or non-obvious ordering constraint. For example, `HttpResponse`
explains why raw `Set-Cookie` headers remain separate from the header map.
Avoid comments that only restate the next line of code.

## Tests

Tests generally mirror production packages in `commonTest`; platform-dependent
tests live in `desktopTest`, `androidHostTest`, `iosTest`, or `wasmJsTest`.
Tests for intermediate source sets live in the matching `nonWebTest`,
`jvmCommonTest`, `platformWebViewTest`, or `skikoTest`; every platform test
compilation of that group runs them, including Android host-JVM unit tests.
Tests that need a native library absent from the Android host JVM (QuickJS) are
excluded from Android unit tests in `android.testOptions`. Tests whose code path
resolves Compose resources (`getString(Res.string.…)`) live in `desktopTest`,
because Android host unit tests cannot load them.

Use `kotlin.test.Test` and assertions such as `assertEquals(expected, actual)`.
Name tests for observable behavior, for example
`sameLanguageRequestReturnsOriginalTextWithoutNetworkCall`. Use `runTest` for
suspending tests. Keep setup, action, and assertions visually distinct with
blank lines. Prefer deterministic fixtures, in-memory databases, and small
recording service implementations over real network calls.

ViewModel tests use
[ViewModelTestHost](composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/ViewModelTestHost.kt):
it installs one `UnconfinedTestDispatcher` as Main, creates ViewModels through a
`ViewModelStore`, and `close()` (in `@AfterTest`) clears the store before
`Dispatchers.resetMain()`. Pass `host.dispatcher` as the ViewModel's
`workDispatcher` and give holders (`SettingsStore`, `LibraryIndexStore`) and
owned services `runTest`'s `backgroundScope`. All work then stays on the test
scheduler: nothing resumes on a real `Default` thread after Main was reset, which
otherwise surfaces as "uncaught exceptions before the test started" in a later
test. Never end a test with `viewModelScope.cancel()`; it skips `onCleared`.

Shared fakes live in the test package of the interface they fake, so they can be
found instead of copied: `services/files/TestFiles.kt` (`NoFiles`, `MemoryFiles`,
`NoArchives`), `services/http/RecordingHttpService.kt`,
`services/notifications/TestNotifications.kt`, `domain/TestModels.kt`
(`testManga`). `HttpService` is a `fun interface`, so a one-off fake is a lambda.
Stub an `ExtensionRuntimeService` by delegating to
`DatabaseFallbackRuntimeService` and overriding only what the test needs.

[TranslatorServiceTest.kt](composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/translation/TranslatorServiceTest.kt)
demonstrates constructor-injected fakes, request recording, and response parsing
assertions. The shared test dependencies are `kotlin("test")` and
`kotlinx.coroutines.test`; Turbine is recommended by the skill but is not an
existing shared test dependency.

The README documents `./gradlew :composeApp:desktopTest` for tests. In the
repository's RTK agent workflow, invoke it as `rtk ./gradlew :composeApp:desktopTest`.
Run the relevant target's checks for platform changes. Documentation-only style
edits do not require an application build.

## Build files and native wrapper

Gradle scripts use Kotlin DSL, four-space indentation, plugin aliases, and
dependency aliases from [gradle/libs.versions.toml](gradle/libs.versions.toml);
every version, including desktop-only artifacts, lives in the catalog.
Place dependencies in the narrowest applicable source set. Intermediate source
sets are groups in the `applyDefaultHierarchyTemplate { }` block of
[composeApp/build.gradle.kts](composeApp/build.gradle.kts); add a group there
instead of wiring `dependsOn` by hand.

Release builds read `-Pyokan.version=<x.y.z>` (Android `versionName`, desktop
`packageVersion`) and `-Pyokan.versionCode=<n>` (Android `versionCode`). Android
R8 and desktop ProGuard share `composeApp/release-rules.pro`, which only lets the
shrinker drop unused Material icons.

The Swift wrapper in [YokanApp.swift](iosApp/YokanApp.swift) uses four-space
indentation, PascalCase types, lowerCamelCase members, private stored properties,
and small lifecycle/bridge methods. Follow its ownership conventions, including
weak callback captures and unregistering callbacks during teardown.

Shell helpers document usage and environment inputs near the top, quote path
expansions, use uppercase configuration variables, and split long commands with
continuations. Respect each script's declared shell and match its existing
indentation and error-handling options.
