Kotlin PreviewGenerator is a lightweight compiler plugin writ ten with Kotlin Symbol Processing (KSP). Preview Generator creates preview instances for data classes, which can be used in Jetpack Compose view previews.
-
Add the KSP plugin in the main
build.gradle
:plugins { // ... id("com.google.devtools.ksp") version "1.9.21-1.0.15" }
-
Add the Sonatype Maven URL:
repositories { // ... mavenCentral() }
-
Add KSP and the module into Gradle dependencies:
dependencies { implementation("io.github.vram-voskanyan.kmp:PreviewGenerator:1.0.0") // take latest from Maven central ksp("io.github.vram-voskanyan.kmp:PreviewGenerator:1.0.0") }
-
Sync the project, and you are good to go.
- Add a
@DataPreview
annotation to the class that needs to have a generated preview. - Rebuild the project. It will generate a Preview class inside
build\ksp\[BUILD_VARIANT]\ClassName.kt
.
@DataPreview
data class DummyClass(val name: String, val age: Int, val loginDate: Long)
val previewValue = dummyClassPreview
// dummyClassPreview is a generated class which is: DummyClass(name = "Ryan", age = 85, loginDate = 1705600601029)
// Note: `loginDate` is a Timestamp ;)
These are examples that will not work:
class A(items: List<A>)
In this case, it will attempt to create an endless items.
data class B(enumItem: EnumValue)
Currently, enums and sealed classes are not supported. Make the type nullable in this case:
data class B(enumItem: EnumValue?)
For more configurations and setups, please refer here: Configurations.md
Since this project was developed only during non-office hours, not everything is covered. For example, the following types are not currently supported: Non-Data classes, Enum, Map, List (in progress).
We also have some exciting features in mind for implementation, depending on community interest:
-
Customized Data Size: Introduce an option to edit the generated data size for checking how the view behaves with large or small datasets. This may involve adding a parameter option to annotations.
-
Flexible Data Generation: Currently, the generator relies on an argument name-checker to pick values close to the parameter type. For the next step, we aim to provide an option to pass values from outside, allowing customization such as non-English values.
-
Adding caching functionality: Actually, the script is already fast, but there are plans to implement caching for pregenerated data. ;)
- Email: vram.arm@gmail.com
- LinkedIn: Vram Voskanyan
If you would like to contribute code you can do so through GitHub by forking the repository and sending a pull request. When submitting code, please make every effort to follow existing conventions and style in order to keep the code as readable as possible.