Yokan / rebuild
Course 1 8624561

CODE_STYLE.md

CODE_STYLE.md

documentation / design asset333 lines
1# Code style23This guide describes conventions observed in Yokan's first-party source and the4requirements in [AGENTS.md](AGENTS.md) and the5[Android/Kotlin skill](.codex/skills/compose-kotlin-agent-skills/SKILL.md).6It applies primarily to `composeApp`, with brief notes for the iOS wrapper and7build scripts. Vendored projects and generated files have their own conventions.89The codebase is not uniform. Sections marked **Required direction** describe10project instructions for new or refactored code; they do not claim that every11existing file already complies. Keep unrelated formatting and architecture12changes out of functional patches.1314## Formatting and imports1516- Use four spaces for indentation and opening braces on the declaration line.17- Use a space after commas and around assignments, operators, and control-flow18  conditions: `if (items.isEmpty())`.19- Separate the package, imports, and declarations with blank lines. Separate20  methods and logical steps with blank lines without spacing out every statement.21- Put long parameter lists and constructor calls on multiple lines, one argument22  per line, with the closing parenthesis aligned with the declaration or call.23- Use trailing commas in multiline parameter lists, calls, collections, and enum24  entries. This is common in production code, although some tests omit them.25- Prefer named arguments when constructing models or passing several booleans,26  nullable values, or callbacks. Short, unambiguous calls can remain positional.27- Use expression bodies for simple mappings, getters, and forwarding functions;28  use block bodies for operations with several steps or side effects.29- Break long collection and modifier chains before the dot. Short chains can30  remain on one line. There is no repository-configured maximum line length.31- Prefer explicit imports. Aliases are used to disambiguate APIs, such as lazy32  list `items` versus grid `items`. Import order is not completely consistent,33  and some existing tests use wildcard imports; avoid unrelated import churn.34- Normally omit semicolons. Some compact existing DSL blocks contain them; new35  blocks are clearer with separate statements on separate lines.3637[gradle.properties](gradle.properties) sets `kotlin.code.style=official`; no38formatter (EditorConfig, ktlint, Detekt, Spotless) is configured. What is enforced:3940- The Kotlin compiler runs with `allWarningsAsErrors` on every target, so a41  warning (deprecation, dead branch, unnecessary `!!`) fails the build. Fix it;42  add a narrow `@OptIn` only for an intentional experimental API.43- `LayeringRulesTest` (desktopTest) fails when `data`, `database`, `domain` or44  `services` reference `ui` or `app`, or `domain` references the other layers.45- `HardcodedUiStringsTest` keeps per-file counts of hardcoded user-visible text46  under `ui/` in `src/desktopTest/resources/hardcoded-ui-strings.txt`. Counts47  may only go down; lower the number when you move text to resources.48- `SettingsSearchAnchorsTest` checks every anchored settings-search id against a49  settings item key.50- Forgejo CI runs desktop and Android unit tests and compiles Android and51  Kotlin/Wasm on every push to `main` and pull request. Run Wasm browser and iOS52  simulator tests locally for platform changes (see the README for their state).5354## Naming and file organization5556| Element | Convention and examples |57| --- | --- |58| Packages | Lowercase under `eu.friedcutlet.yokan`, matching directories |59| Types and composables | PascalCase: `HttpRequest`, `LibraryViewModel`, `LibraryScreen` |60| Functions and properties | lowerCamelCase: `updateSettings`, `refreshing`, `lastRefreshSummary` |61| Boolean properties | Descriptive predicates: `isRead`, `hasUpdate`, `shouldUpdate`; follow nearby model vocabulary |62| Enum entries | PascalCase in domain models: `Manga`, `Ongoing`, `ComfortableGrid` |63| Constants | `UPPER_SNAKE_CASE` occurs in service limits, such as `DOWNLOAD_CONNECTION_TIMEOUT_MS`; existing UI constants also use PascalCase |64| Mutable flow backing fields | Leading underscore: `_state`; expose a read-only `state` |65| Implementations | Meaningful prefixes: `DefaultYokanRepository`, `PersistentDownloadService`, `HttpMetadataService` |66| Database models and adapters | `Db` model prefix and conversions such as `toDb`, `toDomain`, `toDomainChapter` |67| Tests and fakes | `SubjectTest`, descriptive lowerCamelCase test functions, `RecordingHttpService` or `TestFileService` |6869Name files after their main type or responsibility. Related small declarations70may share a file: `HttpService.kt` contains its interface and request/response71types, and `LibraryContract.kt` contains state and events. Feature UI commonly72uses `FeatureRoute.kt`, `FeatureScreen.kt`, `FeatureViewModel.kt`, and73`FeatureContract.kt`. Larger features also split helpers into focused files.7475Use `private` for implementation helpers and `internal` for module-scoped APIs.76Constructor dependencies are commonly `private val`. Put small mappings and77parsing helpers near the implementation that uses them, often as private78top-level extension functions.7980## Kotlin idioms and models8182- Prefer `val` and value-oriented `data class` models. Use `copy(...)` to derive83  updated values. Mutable collections are appropriate for internal accumulation84  and test recording, but should not expose writable screen state.85- Give optional model fields explicit defaults such as `null`, `false`, `""`,86  `emptyList()`, and `emptyMap()` when those values express the contract.87- Declare types on interface boundaries and exposed state. Infer obvious local88  types. Existing implementations sometimes infer override/property types.89- Use sealed interfaces with `data class` payloads and `data object` cases for90  event or state alternatives. Handle them with `when`.91- Prefer safe calls, `as?`, `firstOrNull`, and Elvis returns over nested checks.92  Short guards such as `if (state.value.refreshing) return` are idiomatic here.93- Use `map`, `mapNotNull`, `filter`, `buildList`, and `buildString` when they make94  transformations clear. Use named lambda parameters when `it` becomes ambiguous.95- Use method references for simple forwarding and lambdas when arguments need96  adapting: `map(::toDomainChapter)` or `onClick = { onOpen(item.id) }`.9798**Required direction:** avoid production `!!`; use early returns or99`requireNotNull` according to whether absence is expected or violates a contract.100Keep mutable state encapsulated rather than mutating fields inside a UI model.101102For representative models and transformations, see103[Models.kt](composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/domain/Models.kt),104[HttpService.kt](composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/http/HttpService.kt),105and [DefaultYokanRepository.kt](composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/data/DefaultYokanRepository.kt).106107## Multiplatform boundaries and dependencies108109The main application is one Kotlin Multiplatform module, organized by packages110and source sets rather than a separate Gradle module for every feature.111112| Location under `composeApp/src` | Responsibility |113| --- | --- |114| `commonMain` | Shared domain, data, database contracts, services, and Compose UI |115| `nonWebMain` | Shared non-browser implementations, including Room, QuickJS, and mpv |116| `jvmCommonMain` | Code shared by Android and desktop |117| `platformWebViewMain` | Shared WebView integration used by Android and iOS |118| `skikoMain` | Skia-backed code shared by desktop, iOS, and the browser (`coil3.Bitmap` is `org.jetbrains.skia.Bitmap`) |119| `androidMain`, `desktopMain`, `iosMain`, `wasmJsMain` | Platform integrations and entry points |120121Keep platform SDK types in the appropriate platform source set. Common contracts122use interfaces and `expect` declarations; platform implementations use `actual`123and suffixes such as `.android.kt`, `.desktop.kt`, `.ios.kt`, and `.wasm.kt`.124Shared implementation suffixes include `.nonWeb.kt`, `.jvm.kt`, and `.skiko.kt`.125Factory functions commonly use `createPlatform...` names.126127Services take their dependencies through constructors. The application wires128them manually in129[ServiceRegistry.kt](composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/ServiceRegistry.kt)130and exposes them, plus the app-scoped state holders, through `YokanRuntime`.131Hilt is a skill default, not the observed application wiring; do not describe it132as already installed. Preserve existing service interfaces so tests can supply133lightweight fakes. Services that need only HTTP, files or the database belong in134`YokanServices` (`defaultServices`); profile-scoped holders and services that need135the repository or settings are `owned` resources of `ProfileSession`.136137Keep domain models separate from database and transport representations, with138explicit mapping at boundaries. Packages under `eu.friedcutlet.yokan`:139140| Package | Responsibility |141| --- | --- |142| `app` | Composition root: `YokanRuntime`, `ServiceRegistry`, bootstrap and startup |143| `data` | `YokanRepository` and its default implementation, `SettingsStore`, `LibraryIndexStore`, DB↔domain mappers |144| `database`, `database.sync`, `database.room` | Persistence contracts, snapshot models, sync identities, the Room implementation |145| `domain` | Pure domain models and rules |146| `services.<domain>` | One package per capability (`download`, `library`, `migration`, `extensions`, `sync`, …) |147| `ui.navigation`, `ui.components`, `ui.theme`, `ui.image`, `ui.status`, `ui.screens.<feature>` | Compose UI |148149**Required direction:** `data`, `database`, `domain` and `services` never import150`ui` or `app`. Models shared by a service and its screens live in the service151package (for example `services.library.LocalLibraryOverview`,152`services.migration.MassMigrationProgress`). Platform entry points that need the153whole app (WorkManager workers, iOS BGTasks) receive it through an interface or154lambda installed by the entry point (`BackgroundTaskHost`,155`IosBackgroundTaskRegistration`), not by importing `YokanRuntime`.156157## Compose and screen state158159Navigation is typed. `Route` (`ui/navigation/Route.kt`) is a sealed interface of160destinations with their arguments; `Navigator` owns the back stack, the root161section/item type and the minimized-player flag as `StateFlow`s and is created162once in `App.kt`. Every stack entry is a `NavEntry` with its own163`ViewModelStore`: `NavHost` provides it as `LocalViewModelStoreOwner`, so a plain164`viewModel { }` inside a route is scoped to that entry and cleared once the entry165leaves the stack. Root sections (library, updates, history, browse, more) use166`nav.rootViewModelStoreOwner` with explicit keys such as `library-$itemType`.167Only `CoverInspection` keeps a hand-rolled owner because its ViewModel is scoped168to the dialog. `ApplyReaderSystemUi` is the one screen-level composable that reads169`YokanRuntime` (the platform system-UI controller shared by all readers).170171Each destination has a route adapter, `XRoute(route: Route.X, nav: Navigator)`172(settings pages: an `XSettingsRoute(title, settings, onUpdate, onBack)` adapter in173the page's package, dispatched with one line per page from `SettingsRoute`). The174adapter is the only place that reads `YokanRuntime`: it builds the ViewModel from175runtime holders (`settings`, `libraryIndex`, `libraryUpdates`, `localLibrary`,176`migration`, `chapterDownloads`, `sourceInstall`, `repository`, `services`),177collects its state and passes values and `on…` lambdas to a stateless screen.178Screens never take a ViewModel, `Navigator`, holder or service parameter. A179ViewModel takes required dependencies; do not default them to `YokanRuntime` or180make them nullable for tests, because that creates a code path production never181runs.182183One-shot outcomes (navigation, snackbars, notices) are a sealed `XEffect` sent184through a `Channel` and collected by the route while STARTED; see185[ReaderRoute.kt](composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderRoute.kt).186Events never carry UI lambdas.187188The library feature demonstrates the route/contract/ViewModel split:189190- [LibraryContract.kt](composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryContract.kt)191  defines `LibraryState` and `LibraryEvent`.192- [LibraryViewModel.kt](composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryViewModel.kt)193  exposes `StateFlow` and handles events with atomic updates.194- [LibraryRoute.kt](composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryRoute.kt)195  resolves the ViewModel, collects state, and passes values and callbacks onward.196197The characteristic state pattern is:198199```kotlin200private val _state = MutableStateFlow(LibraryState(itemType, query, display))201val state: StateFlow<LibraryState> = _state.asStateFlow()202203fun onEvent(event: LibraryEvent) {204    when (event) {205        LibraryEvent.Refresh -> refresh()206        is LibraryEvent.SelectCategory -> _state.update {207            it.copy(selectedCategoryId = event.categoryId)208        }209        // …210    }211}212```213214**Required direction:** ViewModels own screen state through `MutableStateFlow`,215expose read-only `StateFlow`, and mutate it with `_state.update { ... }`.216Use `viewModelScope` for ViewModel work (never `rememberCoroutineScope` for data217or service calls; it is for scroll/pager animation and platform pickers) and218`collectAsStateWithLifecycle()`, never `collectAsState()`. ViewModels observe the219database through `repository.observe({ it.part }) { read() }` or the holders'220flows, not through a refresh counter. A ViewModel that moves work off the main221thread takes `workDispatcher: CoroutineDispatcher = Dispatchers.Default` and222uses it for every `withContext`/`flowOn`/`observe` hop.223224For new reusable composables, accept `modifier: Modifier = Modifier` as the first225optional parameter and apply it to the root element. Give callbacks descriptive226`on...` names. Supply stable keys in lazy lists, rows, and grids; use appropriate227`contentType` values for distinct item types. Follow the project modifier order228`padding → clip → background → clickable` when those operations occur together.229Use `MaterialTheme` colors and typography and Compose resource accessors such as230`stringResource(Res.string.empty_library)` for user-visible text, including231ViewModel messages (`getString(Res.string.…)`). Plain actions reuse `action_*`232and `ok`. Existing hardcoded labels are debt tracked by `HardcodedUiStringsTest`.233234## Coroutines, errors, and comments235236Service interfaces mark asynchronous operations `suspend`. Existing code uses237guard clauses and nullable/empty results for unavailable optional data, and238`runCatching` around parsing and platform failures. Follow the particular239interface's failure contract; an empty result and a failed operation are not240automatically equivalent.241242**Required direction:** preserve coroutine cancellation when handling failures.243Broad `catch` or `runCatching` around suspending work must not convert cancellation244into ordinary success or an empty result. Keep cleanup tied to the operation or245owner's lifetime.246247Use `catchingNonCancellation` (`services/Concurrency.kt`) whenever suspending248work becomes a `Result` or a fallback. In a `try`/`catch` with a broad catch, make249`catch (e: CancellationException) { throw e }` the first clause. `runCatching` is250only for non-suspending parsing. Never throw `CancellationException` as a domain251signal; use a dedicated exception type. Work that must not outlive a profile or252session owner runs through `CoroutineScope.runJoined`, which joins the work253before returning.254255Use KDoc to explain public contracts, ownership, field semantics, and platform256limitations. Link symbols with `[Symbol]`. Use `//` comments for the reason behind257a workaround or non-obvious ordering constraint. For example, `HttpResponse`258explains why raw `Set-Cookie` headers remain separate from the header map.259Avoid comments that only restate the next line of code.260261## Tests262263Tests generally mirror production packages in `commonTest`; platform-dependent264tests live in `desktopTest`, `androidHostTest`, `iosTest`, or `wasmJsTest`.265Tests for intermediate source sets live in the matching `nonWebTest`,266`jvmCommonTest`, `platformWebViewTest`, or `skikoTest`; every platform test267compilation of that group runs them, including Android host-JVM unit tests.268Tests that need a native library absent from the Android host JVM (QuickJS) are269excluded from Android unit tests in `android.testOptions`. Tests whose code path270resolves Compose resources (`getString(Res.string.…)`) live in `desktopTest`,271because Android host unit tests cannot load them.272273Use `kotlin.test.Test` and assertions such as `assertEquals(expected, actual)`.274Name tests for observable behavior, for example275`sameLanguageRequestReturnsOriginalTextWithoutNetworkCall`. Use `runTest` for276suspending tests. Keep setup, action, and assertions visually distinct with277blank lines. Prefer deterministic fixtures, in-memory databases, and small278recording service implementations over real network calls.279280ViewModel tests use281[ViewModelTestHost](composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/ViewModelTestHost.kt):282it installs one `UnconfinedTestDispatcher` as Main, creates ViewModels through a283`ViewModelStore`, and `close()` (in `@AfterTest`) clears the store before284`Dispatchers.resetMain()`. Pass `host.dispatcher` as the ViewModel's285`workDispatcher` and give holders (`SettingsStore`, `LibraryIndexStore`) and286owned services `runTest`'s `backgroundScope`. All work then stays on the test287scheduler: nothing resumes on a real `Default` thread after Main was reset, which288otherwise surfaces as "uncaught exceptions before the test started" in a later289test. Never end a test with `viewModelScope.cancel()`; it skips `onCleared`.290291Shared fakes live in the test package of the interface they fake, so they can be292found instead of copied: `services/files/TestFiles.kt` (`NoFiles`, `MemoryFiles`,293`NoArchives`), `services/http/RecordingHttpService.kt`,294`services/notifications/TestNotifications.kt`, `domain/TestModels.kt`295(`testManga`). `HttpService` is a `fun interface`, so a one-off fake is a lambda.296Stub an `ExtensionRuntimeService` by delegating to297`DatabaseFallbackRuntimeService` and overriding only what the test needs.298299[TranslatorServiceTest.kt](composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/translation/TranslatorServiceTest.kt)300demonstrates constructor-injected fakes, request recording, and response parsing301assertions. The shared test dependencies are `kotlin("test")` and302`kotlinx.coroutines.test`; Turbine is recommended by the skill but is not an303existing shared test dependency.304305The README documents `./gradlew :composeApp:desktopTest` for tests. In the306repository's RTK agent workflow, invoke it as `rtk ./gradlew :composeApp:desktopTest`.307Run the relevant target's checks for platform changes. Documentation-only style308edits do not require an application build.309310## Build files and native wrapper311312Gradle scripts use Kotlin DSL, four-space indentation, plugin aliases, and313dependency aliases from [gradle/libs.versions.toml](gradle/libs.versions.toml);314every version, including desktop-only artifacts, lives in the catalog.315Place dependencies in the narrowest applicable source set. Intermediate source316sets are groups in the `applyDefaultHierarchyTemplate { }` block of317[composeApp/build.gradle.kts](composeApp/build.gradle.kts); add a group there318instead of wiring `dependsOn` by hand.319320Release builds read `-Pyokan.version=<x.y.z>` (Android `versionName`, desktop321`packageVersion`) and `-Pyokan.versionCode=<n>` (Android `versionCode`). Android322R8 and desktop ProGuard share `composeApp/release-rules.pro`, which only lets the323shrinker drop unused Material icons.324325The Swift wrapper in [YokanApp.swift](iosApp/YokanApp.swift) uses four-space326indentation, PascalCase types, lowerCamelCase members, private stored properties,327and small lifecycle/bridge methods. Follow its ownership conventions, including328weak callback captures and unregistering callbacks during teardown.329330Shell helpers document usage and environment inputs near the top, quote path331expansions, use uppercase configuration variables, and split long commands with332continuations. Respect each script's declared shell and match its existing333indentation and error-handling options.334

Search chapters, reference and source filenames.