Use KSP to add extra properties to Compose components

148 Views Asked by At

I'm learning Navigating with Compose.

I found that @Composable components should be coupled with routing, but unfortunately, The way navigation-compose solves hardcoding is not so perfect. like this:

const val forYouNavigationRoute = "for_you_route"

A @Composable component is separate from its routing path, and I think it's better for them to be bound together.

I want to implement the following functionality, adding additional properties to @Composable components, using it like this:

@Composable
fun HomeScreen(navController: NavHostController) {...}

fun main(){
  println(HomeScreen.label)
  println(HomeScreen.route)
}

what should I do?

1

There are 1 best solutions below

0
Nikola Despotoski On

You need to declare your own annotation so you can easily locate target composable

const val USE_COMPOSABLE_FUNCTION_NAME = "use_function_name
@Target(FUNCTION)
annotation class Route(val route : String = USE_COMPOSABLE_FUNCTION_NAME, val label = USE_COMPOSABLE_FUNCTION_NAME)

Then use KSP do find this symbol then use a visitor to visit function declaration in the current file to get the name of the composable function.

Once you have got the function name (or annotation's values route and label) that is annotated with @Route, use code generator to generate object that has the properties you want as stated in

fun main(){
  println(HomeScreen.label)
  println(HomeScreen.route)
}