JetBrains / compose-multiplatform

Compose Multiplatform, a modern UI framework for Kotlin that makes building performant and beautiful user interfaces easy and enjoyable.
https://jetbrains.com/lp/compose-multiplatform
Apache License 2.0
15.39k stars 1.12k forks source link

User Android Preview in compose multiplatform project #4568

Closed mahramane closed 3 months ago

mahramane commented 3 months ago

Hi I moved all jetpack-compose codes to a directory with layout name in commonMain directory and there isn't any jetbrains-compose codes in that So that when i copy layout directory in another android studio jetpack compose project, It works well. Now i want to user Android preview tools because it's very easy to use and develop compose code.

Is there a way to use the android preview tools feature without copying the layout directory inside an android jetpack compose project?

m-sasha commented 3 months ago

I'm sorry, I'm having trouble understanding the question/issue.

Can you share a project that has the problem, and say the problem is / what you would like to happen?

mahramane commented 3 months ago

I found a way for it. i write this code to gradle :

task("copy") {

    val sourceDir = file("/.../app/src/main/java/ui")
    val destinationDir = file("${project.projectDir.absolutePath}/composeApp/src/commonMain/kotlin/ui")

    destinationDir.deleteRecursively()
    sourceDir.copyRecursively(destinationDir)

    FileUtils.listFiles(destinationDir, arrayOf("kt"), true)
        .filter { it.isFile }
        .forEach { file ->
            var content = file.readText()
            if (content.contains("@Preview")) {

               //remove preview function
                content = content.replace("import androidx.compose.ui.tooling.preview.PreviewScreenSizes", "")
                content = content.replace("import androidx.compose.ui.tooling.preview.Preview", "")

                val pattern = """@PreviewScreenSizes\n@Preview\n@Composable\nprivate fun (.+?)\(\) \{.+?\n}""".toRegex(RegexOption.DOT_MATCHES_ALL)
                content = pattern.replace(content, "")
                file.writeText(content)
            }
        }

    println("copy kt files is done!")
}

I can't explain more than that, but I hope you understand what I mean.