Skip to content

About

A collection of Detekt rules for Jetpack Compose

Topics

Resources

Stars

147 stars

Watchers

8 watching

Forks

Repository files navigation

Detekt rules for Jetpack Compose

MavenCentral

A set of Detekt rules to help prevent common errors in projects using Jetpack Compose.

Rules

Here are some highlights of rules in this rule set:

  • ReusedModifierInstance finds usages of modifier parameter on non-top-level children of a composable function. This tends to happen during refactorings and often leads to incorrect rendering of a composable

  • UnnecessaryEventHandlerParameter suggests hoisting event argument passing (state parameter access and constants) to the upper level which often simplifies individual composable components (reportConstantArguments: false skips constants)

  • ModifierHeightWithText suggests using Modifier.heightIn() instead of Modifier.height() on a layouts which have Text children, so that if the text turns out to be long and would wrap, layout will not cut it off

  • ComposableEventParameterNaming ensures that all event handler parameters of composable functions are named in the same Compose-like style, i.e. they have on prefix and do not use past tense

  • ComposableParametersOrdering suggests the correct grouping and order of composable functions' parameters, ensures the correct position of the Modifier parameter and keeps slots named in trailingSlotNames (default content) last. Overriding and actual functions are not checked. allowTrailingEventHandlers: false also reports a required event handler placed after optional parameters, allowTrailingLambdas: false any required non-composable lambda there

  • ModifierDefaultValue ensures that modifier parameter has a correct default value

  • MissingModifierDefaultValue checks if modifier default value is specified. Overriding and actual functions are skipped. Abstract and open functions and functions of interfaces are skipped too, unless checkAbstractFunctions: true is set: the Compose compiler accepts default values in abstract composables only from Kotlin language version 2.1 and in open ones from 2.2 (K2 compiler)

  • PublicComposablePreview finds and reports composable previews which are not marked as private

  • TopLevelComposableFunctions ensures that all composable functions are top-level functions (disabled by default; allowInObjects: true also allows them inside objects, allowInInterfaces: true inside interfaces)

  • ComposableFunctionName ensures that Composable functions which return Unit should start with upper-case while the ones that return a value should start with lower case

  • UnnecessaryLayoutWrapper finds a Box, Column or Row without parameters which only wraps a single Box, Column or Row, so the child can usually be used directly (disabled by default)

  • StateReadCouldBeLowered finds a val holding a state read (.value of a State or .current of a CompositionLocal) which is only used minDepth (default 2) or more composable lambdas deeper, so the state can be read closer to its use. Every composable lambda parameter counts (content, topBar, ...), except the ones of inline composables like Box, Column and Row: an inlined lambda is no recomposition scope of its own. A crossinline lambda, like the itemContent of the lazy list items, does count (disabled by default, requires type resolution)

  • NonImmutableDataClassParameter finds a composable parameter whose type, or one of its type arguments (List<Profile>), is a data class not marked with @Immutable or @Stable. With strong skipping (the default since Kotlin 2.0.20) such a composable is still skippable, but the parameter is compared by instance (===) instead of equals(), so an equal copy of the data class recomposes it. Not reported: data classes of the kotlin package, data classes of libraries which the Compose compiler knows to be stable at compile time (@StabilityInferred), ignoredPackageSegments and stableTypePatterns. stableTypePatterns takes the lines of the Compose stability configuration file, comment lines included; a line which the Compose compiler would reject fails the run. Limits: a library data class which holds a class of another file or module is still reported, the Compose compiler decides on its stability only at runtime, list it in stableTypePatterns; a pattern is not matched against the supertypes of a class; only data classes are judged, so an unstable List, Java collection or extension receiver is not reported, and a List<Profile> parameter stays unstable for the Compose compiler even when Profile is annotated (disabled by default, requires type resolution)

  • PartiallyUsedViewState finds a composable which takes a whole view state (a class matching stateClassPattern) but reads fewer than usedFieldsThreshold (default 3) of its properties, such a composable should take the properties instead. Only public and internal properties are counted. Reads inside with(state) {}, state.run {} and state.apply {}, through a destructuring declaration and of inherited properties are counted; state.let {} and state.also {} pass the state on, a composable which reads the state only through them is not reported (disabled by default, requires type resolution)

  • UnwrappedValueClassImageModel finds a value class passed as is to the model of a Coil image function or to the data of an ImageRequest builder: it compiles because the parameter is Any?, but Coil can't load an image from a boxed value class, pass its .value instead. Value classes of the kotlin package (UInt, Result) are not reported (disabled by default, requires type resolution)

  • UnnecessaryModifierArgument finds a Modifier passed to a parameter which already has Modifier as its default value (Text("Hello", modifier = Modifier)), the argument can be removed. Only functions declared in the analyzed sources are checked, the default value of a library function is not available. A positional argument followed by another positional one can't be removed alone, pass the following arguments by name then: Card("Title", Modifier, false) becomes Card("Title", enabled = false). The rule does not check whether the call without the argument resolves to another overload, suppress the finding there with @Suppress("UnnecessaryModifierArgument") (disabled by default, requires type resolution)

  • and others...

Rules can be individually turned on or off in the configuration file.
More detailed rule descriptions with code snippets can be found in the Wiki.

Running checks

Some rules will only work if detekt is running in a type resolution mode, so make sure it is configured for your build if you want to make full use of them.

Installation and configuration

Add detekt rules plugin in your build.gradle (or use any other supported method). Pick the artifact that matches your detekt version:

dependencies {
  // detekt 1.22.0 - 1.23.8
  detektPlugins("ru.kode:detekt-rules-compose:2.0.0")

  // detekt 2.0.0-alpha.6
  detektPlugins("ru.kode:detekt-rules-compose-detekt2:2.0.0")
}

Both artifacts contain the same rules with the same ids and configuration keys, so detekt-config.yml does not change when you switch engines. On detekt 2 the type-resolution rules only run with --analysis-mode full.

Then add this configuration section to your detekt-config.yml to activate the rules:

compose:
  ReusedModifierInstance:
    active: true
  UnnecessaryEventHandlerParameter:
    active: true
    reportConstantArguments: true
  ComposableEventParameterNaming:
    active: true
  ComposableParametersOrdering:
    active: true
    trailingSlotNames: [ 'content' ]
    allowTrailingEventHandlers: true
    allowTrailingLambdas: true
  ModifierHeightWithText:
    active: true
  MissingModifierDefaultValue:
    active: true
    checkAbstractFunctions: false
  PublicComposablePreview:
    active: true
  TopLevelComposableFunctions:
    active: true
    allowInObjects: false
    allowInInterfaces: false
  ComposableFunctionName:
    active: true
  ConditionCouldBeLifted:
    active: true
    ignoreCallsWithArgumentNames: [ 'modifier', 'contentAlignment' ]
  UnnecessaryLayoutWrapper:
    active: true
  StateReadCouldBeLowered:
    active: true
    minDepth: 2
  NonImmutableDataClassParameter:
    active: true
    # data classes of packages with these segments are not reported, for example [ 'schema' ]
    ignoredPackageSegments: [ ]
    # data classes which are stable without an annotation, in the syntax of the Compose stability configuration file
    # (copy its lines here, the rule can't locate the file), for example [ 'com.example.model.**', 'java.time.*' ]
    stableTypePatterns: [ ]
  PartiallyUsedViewState:
    active: true
    # regex for the name of a view state class
    stateClassPattern: '.*ViewState'
    # a state with fewer read properties is reported, classes with fewer properties are not checked
    usedFieldsThreshold: 3
  UnwrappedValueClassImageModel:
    active: true
    # functions whose "model" argument is checked
    imageFunctions: [ 'AsyncImage', 'SubcomposeAsyncImage', 'rememberAsyncImagePainter' ]
  UnnecessaryModifierArgument:
    active: true

Detekt configuration for Compose

Detekt manual contains few useful tips on how to configure Detekt in Compose-based projects, check them out!

Contributors

Maintained by KODE and Contributors ❤️

License

MIT License

Copyright (c) 2024 KODE LLC

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

About

A collection of Detekt rules for Jetpack Compose

Topics

Resources

Stars

147 stars

Watchers

8 watching

Forks

Releases

Packages

Contributors

Languages