### Create Hello World Page in Kotlin Source: https://kuikly.tds.qq.com/ComposeDSL/quickStart This Kotlin code demonstrates how to create a basic Compose page in Kuikly by defining a class that inherits from ComposeContainer and annotates it with @Page for routing. It requires the Kuikly Compose library setup and uses setContent to define UI. The output is a rendered page in a multi-platform app; limitations include dependency on proper Gradle sync and environment configuration. ```kotlin @Page("helloWorld") internal class HelloWorldPage : ComposeContainer() { override fun willInit() { super.willInit() setContent { // 编写Compose代码 } } } ``` -------------------------------- ### Bash: Build and Serve Kuikly Project Source: https://kuikly.tds.qq.com/QuickStart/Miniapp These bash commands outline the process for starting the development server and building both debug and release versions of the Kuikly project. It includes steps for the shared project and the miniApp, covering dependency installation, local bundling, and webpack compilation. ```bash # 运行 shared 项目 dev server 服务器,没有安装 npm 包则先 npm install 安装一下依赖 npm run serve # 构建 shared 项目 Debug 版 ./gradlew :shared:packLocalJsBundleDebug ``` ```bash # 运行 miniApp 服务器 Debug 版 ./gradlew :miniApp:jsMiniAppDevelopmentWebpack # 复制业务的assets文件到小程序目录 ./gradlew :miniApp:copyAssets ``` ```bash # 首先构建业务 Bundle ./gradlew :demo:packLocalJSBundleRelease # 然后构建 miniApp ./gradlew :miniApp:jsMiniAppProductionWebpack ``` -------------------------------- ### Kuiklyx Coroutines: Coroutine API Usage Source: https://kuikly.tds.qq.com/DevGuide/thread-and-coroutines Provides examples of using the coroutine-based APIs from the `kuiklyx.coroutines` library. This includes launching coroutines with `Dispatchers.Kuikly` and switching contexts within a coroutine. ```kotlin // case 0: js模式使用前需要触发KuiklyContextScheduler初始化,其它模式可忽略 KuiklyContextScheduler // case 1: 启动协程 GlobalScope.launch(Dispatchers.Kuikly[ctx]) { ... } // case 2: 在协程中切换上下文 withContext(Dispatchers.Kuikly[ctx]) { ... } ``` -------------------------------- ### Using Kotlinx Coroutines with Kuiklyx Coroutines (Kotlin) Source: https://kuikly.tds.qq.com/DevGuide/thread-and-coroutines This example shows how to leverage Kotlinx coroutines for launching asynchronous tasks and Kuiklyx coroutines to safely update the UI. It includes dependency setup, launching a coroutine, performing IO operations using `Dispatchers.IO`, and updating reactive fields on the Kuikly thread. ```Kotlin override fun created() { super.created() val ctx = this // 使用kotlinx协程库启动协程,通过kuiklyx协程库切换到Kuikly线程 GlobalScope.launch(Dispatchers.Kuikly[ctx]) { ctx.loadingObservable = true // 更新loading状态 val data = withContext(Dispatchers.IO) { // 在IO线程调用KMP的方法 kmpFetchData() } // 回到Kuikly线程,更新响应式字段 ctx.dataObservable = data ctx.loadingObservable = false } } ``` -------------------------------- ### Start KuiklyRenderActivity in Kotlin Source: https://kuikly.tds.qq.com/QuickStart/android This Kotlin code snippet demonstrates starting KuiklyRenderActivity with a page name and JSONObject data. It takes a context to launch the activity. Essential for navigating to Kuikly pages from the Android code. ```kotlin KuiklyRenderActivity.start(context, "test", JSONObject()) ``` -------------------------------- ### Kotlinx Coroutines Dispatcher Usage Source: https://kuikly.tds.qq.com/DevGuide/thread-and-coroutines Illustrates using the `kotlinx.coroutines` library to specify the dispatcher for coroutine execution. This example shows launching a coroutine in the default dispatcher and then switching to the Main dispatcher using `withContext`. ```kotlin GlobalScope.launch { println("running in default dispatcher") withContext(Dispatchers.Main) { println("running in Main dispatcher") } } ``` -------------------------------- ### CocoaPods集成Kuikly iOS渲染器 Source: https://kuikly.tds.qq.com/QuickStart/iOS 通过CocoaPods将'OpenKuiklyIOSRender'添加到iOS工程的Podfile中。请将'KUIKLY_RENDER_VERSION'替换为实际的Kuikly版本号,并确保与KMP跨端工程版本一致。集成后执行'pod install --repo-update'。 ```ruby source 'https://cdn.cocoapods.org/' platform :ios, '14.1' target 'KuiklyTest' do inhibit_all_warnings! pod 'OpenKuiklyIOSRender', 'KUIKLY_RENDER_VERSION' end ``` -------------------------------- ### Send HTTP GET request and bind data to UI using Kotlin Source: https://kuikly.tds.qq.com/DevGuide/network This Kotlin example shows how to acquire the NetworkModule, send an HTTP GET request to a mock endpoint, and process the JSON response to populate an observable list of ProfileItem objects. The is built with a List view that iterates over the data, displaying each avatar and name. It requires the Kuikly framework and the org.json library. ```Kotlin @Page("3") internal class NetworkPage : Pager() { var profileItemList by observableList() override fun created() { super.created() acquireModule(NetworkModule.MODULE_NAME).httpRequest("https://11006487-ff05-41ed-98bd-200377b92859.mock.pstmn.io/NetworkModule", false, param = JSONObject().apply { put("id", 1) }, responseCallback = {data, success, errorMsg -> val dataList = data.optJSONArray("dataList") ?: JSONArray() val size = dataList.length() for (i in 0 until size) { profileItemList.add(ProfileItem().decode(dataList.optJSONObject(i) ?: JSONObject())) } }) } override fun body(): ViewBuilder { val ctx = this return { List { attr { marginTop(30f) flex(1f) } vforIndex({ ctx.profileItemList }) { item, index, count -> View { attr { height(70f) flexDirectionRow() alignItemsCenter() marginLeft(8f) if (index % 2 == 0) { backgroundColor(Color.GRAY) } } Image { attr { size(30f, 30f) src(item.avatar) } } Text { attr { marginLeft(8f) fontSize(16f) color(Color.BLACK) text(item.name) } } } } } } } } internal class ProfileItem { var name = "" var avatar = "" fun decode(itemJSONObject: JSONObject): ProfileItem { name = itemJSONObject.optString("name") avatar = itemJSONObject.optString("avatar") return this } } ``` -------------------------------- ### Set Kuikly Business Directory Source: https://kuikly.tds.qq.com/DevGuide/android-dev Example configuration for local.properties to specify the path to the local Kuikly business project. ```properties kuikly.biz.dir=xxxx // xxxx替换成本地Kuikly业务工程的路径 ``` -------------------------------- ### Kotlin Example of Blur Component Usage Source: https://kuikly.tds.qq.com/API/components/blur Demonstrates creating a page that displays an image with a blurred overlay using the Blur component. The example defines a TestPage class extending BasePager, sets up an Image, and applies two Blur overlays with different blurRadius values, showcasing attributes like size, blurRadius, marginTop, and absolutePosition. ```Kotlin @Page("demo_page") internal class TestPage : BasePager() { override fun body(): ViewBuilder { return { attr { allCenter() } Image { attr { absolutePosition(0f,0f,0f,0f) size(pagerData.pageViewWidth, pagerData.pageViewHeight) src("https://picsum.photos/id/221/1500/2500") } } Blur { attr { size(pagerData.pageViewWidth, 100f) blurRadius(10f) } } Blur { attr { marginTop(100f) size(pagerData.pageViewWidth, 100f) blurRadius(1f) } } } } } ``` -------------------------------- ### PAG Component Usage Example (Kotlin) Source: https://kuikly.tds.qq.com/API/components/pag Demonstrates how to use the PAG component in a Kotlin-based project. It shows setting the source, repeat count, and replacing layer contents for text and images. ```kotlin @Page("demo_page") internal class TestPage : BasePager() { override fun body(): ViewBuilder { return { attr { allCenter() } PAG { attr { size(pagerData.pageViewWidth, 200f) src(ImageUri.pageAssets("user_avatar.pag")) repeatCount(0) } } PAG { attr { size(pagerData.pageViewWidth, 200f) src(ImageUri.pageAssets("user_avatar.pag")) repeatCount(0) replaceLayerContents( PAGReplaceItem( PAGReplaceItem.TYPE_TEXT, layerName = "text_user_note", text = "Kuikly!" ), PAGReplaceItem( PAGReplaceItem.TYPE_IMAGE, layerName = "img_user_avatar", imageFileAsset = ImageUri.pageAssets("user_portrait.png").toUrl(getPager().pageName) ), ) } } } } } ``` -------------------------------- ### Comment Out iOS Configuration in build.gradle.kts Source: https://kuikly.tds.qq.com/QuickStart/env-setup This code snippet demonstrates how to comment out iOS-specific configurations in the `shared/build.gradle.kts` file. This is useful for developers on Windows or those who do not have an iOS development environment set up, preventing potential compilation failures. ```kotlin plugins { kotlin("native.cocoapods") } ... kotlin { ... iosX64() iosArm64() iosSimulatorArm64() cocoapods { summary = "Some description for the Shared Module" homepage = "Link to the Shared Module homepage" version = "1.0" ios.deploymentTarget = "14.1" podfile = project.file("../iosApp/Podfile") framework { baseName = "shared" isStatic = true license = "MIT" } } ... val iosX64Main by getting val iosArm64Main by getting val iosSimulatorArm64Main by getting val iosMain by creating { dependsOn(commonMain) iosX64Main.dependsOn(this) iosArm64Main.dependsOn(this) iosSimulatorArm64Main.dependsOn(this) } val iosX64Test by getting val iosArm64Test by getting val iosSimulatorArm64Test by getting val iosTest by creating { dependsOn(commonTest) iosX64Test.dependsOn(this) iosArm64Test.dependsOn(this) iosSimulatorArm64Test.dependsOn(this) } } ... dependencies { ... add("kspIosArm64", this) add("kspIosX64", this) add("kspIosSimulatorArm64", this) } ``` -------------------------------- ### Opacity Animation Example Source: https://kuikly.tds.qq.com/DevGuide/animation-declarative This example demonstrates how to animate the opacity of a View component. It uses a state variable `opacityAnmationFlag` to control the opacity change from 1f to 0f over 0.5 seconds with a linear animation curve. The animation is triggered after a 500ms delay. ```Kotlin @Page("1") internal class TestPage : BasePager() { private var opacityAnmationFlag by observable(false) override fun body(): ViewBuilder { val ctx = this return { attr { allCenter() } View { attr { size(150f, 150f) backgroundColor(Color.GREEN) if (ctx.opacityAnmationFlag) { opacity(0f) } else { opacity(1f) } animate(Animation.linear(0.5f), ctx.opacityAnmationFlag) } } } } override fun created() { super.created() setTimeout(500) { opacityAnmationFlag = true } } } ``` -------------------------------- ### JavaScript: Mini Program Page Rendering Example Source: https://kuikly.tds.qq.com/QuickStart/Miniapp This JavaScript code snippet demonstrates how to use the `renderView` function to initialize and render a page within a WeChat Mini Program. It shows how to configure page-specific options like `pageName` and `statusBarHeight`. ```javascript // 例如demo里存在router的Page, 就需要在app.json的pages数组里添加 "pages/router/index", 同时在pages的目录里新建router目录补充和pages/index目录一样的内容 // pages/index/index.js内容 var render = require('../../lib/miniApp.js') render.renderView({ // 这里的pageName是最高优先级,如果没配置,会去拿微信小程序启动参数里的page_name,如果都没有会报错 // 建议微信小程序的第一个页面必须配置pageName // pageName: "router", statusBarHeight: 0 // 如果要全屏,需要把状态栏高度设置为0 }) ``` -------------------------------- ### Kuikly Module: Usage Example (Kotlin) Source: https://kuikly.tds.qq.com/DevGuide/expand-native-api This snippet demonstrates how to use the `MyLogModule` within a `TestPage` class, showcasing the `log`, `logWithCallback`, and `syncLog` methods. ```Kotlin internal class TestPage : Pager() { override fun created() { super.created() val myLogModule = acquireModule("KRMyLogModule") // 调用acquireModule并传入module名字获取module myLogModule.log("test log") // 调用log打印日志 myLogModule.logWithCallback("log with callback") { // 异步调用含有返回值的log方法 val reslt = it // 原生侧返回的JSONObject对象 } val result = myLogModule.syncLog("sync log") // 同步调用含有返回值的log方法 } } ``` -------------------------------- ### Background Color Animation Example Source: https://kuikly.tds.qq.com/DevGuide/animation-declarative This example shows how to animate the background color of a View component. Similar to the opacity animation, it uses a state variable `backgroundColorAnmationFlag` to transition the background color from red to green over 0.5 seconds with a linear animation. The change is initiated after a 500ms delay. ```Kotlin @Page("1") internal class TestPage : BasePager() { private var backgroundColorAnmationFlag by observable(false) override fun body(): ViewBuilder { val ctx = this return { attr { allCenter() } View { attr { size(150f, 150f) if (ctx.backgroundColorAnmationFlag) { backgroundColor(Color.GREEN) } else { backgroundColor(Color.RED) } animate(Animation.linear(0.5f), ctx.backgroundColorAnmationFlag) } } } } override fun created() { super.created() setTimeout(500) { backgroundColorAnmationFlag = true } } } ``` -------------------------------- ### Input Component Example (Kotlin) Source: https://kuikly.tds.qq.com/API/components/input Demonstrates how to use the Input component in Kotlin, setting attributes like size, placeholder, and color. This component is designed as a single-line input field for user data. ```kotlin @Page("demo_page") internal class TestPage : BasePager() { override fun body(): ViewBuilder { return { attr { allCenter() } Input { attr { size(200f, 40f) placeholder("输入框提示") } } } } } ``` -------------------------------- ### GlassEffectContainer Basic Usage (Kotlin) Source: https://kuikly.tds.qq.com/API/components/glass-effect-container Demonstrates the basic usage of the GlassEffectContainer component to arrange LiquidGlass elements in a row with spacing. This example requires the Kuikly core views library. ```kotlin import com.tencent.kuikly.core.views.GlassEffectContainer import com.tencent.kuikly.core.views.LiquidGlass GlassEffectContainer { attr { spacing(15f) flexDirectionRow() } LiquidGlass { attr { flex(1f) height(60f) borderRadius(30f) } } LiquidGlass { attr { flex(1f) height(60f) borderRadius(30f) } } } ``` -------------------------------- ### Kuiklyx Coroutines: Adding Dependency Source: https://kuikly.tds.qq.com/DevGuide/thread-and-coroutines Shows how to add the `kuiklyx.coroutines` library dependency to your project. This is required to utilize the library's features for switching to the Kuikly thread. ```kotlin dependencies { implementation("com.tencent.kuiklyx-open:coroutines:$KUIKLYX_COROUTINES_VERSION") } ``` -------------------------------- ### Create Extension for PagerData Business Parameters (Kotlin) Source: https://kuikly.tds.qq.com/DevGuide/page-data Provides an example of creating an extension property for PagerData to encapsulate business parameters, making them more accessible and maintainable in Kuikly. This approach improves code readability and reduces repetitive parsing logic. ```kotlin // PagerDataExt.kt internal val PageData.test: Int get() = params.optInt("test") ``` -------------------------------- ### Add Kotlinx and Kuiklyx Coroutines Dependencies (Kotlin) Source: https://kuikly.tds.qq.com/DevGuide/thread-and-coroutines This snippet demonstrates how to add the Kotlinx coroutines core and Kuiklyx coroutines library as dependencies in your `build.gradle.kts` file. Ensure you replace `KOTLINX_COROUTINES_VERSION` and `KUIKLYX_COROUTINES_VERSION` with the appropriate versions for your Kotlin version. ```Kotlin val commonMain by getting { dependencies { // kotlinx协程库 implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$KOTLINX_COROUTINES_VERSION") // kuiklyx协程库 implementation("com.tencent.kuiklyx-open:coroutines:$KUIKLYX_COROUTINES_VERSION") } } ``` -------------------------------- ### Kotlin: Integrate Mini Program Page Source: https://kuikly.tds.qq.com/QuickStart/Miniapp This Kotlin code defines the entry point for a Mini Program page, handling initialization and rendering. It uses Kuikly's core render components and interacts with native APIs to get system information. The `renderView` function is the main entry point for rendering the page, and `initApp` initializes the application. ```kotlin import com.tencent.kuikly.core.render.web.collection.FastMutableMap import com.tencent.kuikly.core.render.web.ktx.SizeI import com.tencent.kuikly.core.render.web.runtime.miniapp.MiniDocument import com.tencent.kuikly.core.render.web.runtime.miniapp.core.App import com.tencent.kuikly.core.render.web.runtime.miniapp.core.NativeApi const val TAG = "Main" fun main() { App.onShow { console.log(TAG, "app show") } App.onLaunch { console.log(TAG, "app launch") } App.onHide { console.log(TAG, "app hide") } } /** * Mini program page entry, use renderView delegate method to initialize and create renderView */ @JsName(name = "renderView") @JsExport @ExperimentalJsExport fun renderView(json: dynamic) { // Write to global render function val renderParams = FastMutableMap(json) // View size var size: SizeI? = null if (json.width != null && json.height != null) { size = SizeI(json.width.unsafeCast(), json.height.unsafeCast()) } MiniDocument.initPage(renderParams) { pageId: Int, pageName: String, paramsMap: FastMutableMap -> val systemInfo = NativeApi.plat.getSystemInfoSync() val isAndroid = systemInfo.platform == "android" val params = paramsMap["param"].unsafeCast>() params["is_wx_mp"] = "true" paramsMap["platform"] = if (isAndroid) "android" else "iOS" paramsMap["isIOS"] = !isAndroid paramsMap["isIphoneX"] = !isAndroid && systemInfo.safeArea.top > 30 KuiklyWebRenderViewDelegator().delegate.onAttach( pageId, pageName, paramsMap, size, ) } } /** * Register callback methods on the mini program App object, needs to be called in the app.js of the mini program */ @JsName(name = "initApp") @JsExport @ExperimentalJsExport fun initApp(options: dynamic = js("{}")) { App.initApp(options) } ``` -------------------------------- ### 生成so产物和头文件 - 方式1配置 Source: https://kuikly.tds.qq.com/DevGuide/harmony-dev 使用方式1配置时,通过命令行执行Gradle任务来编译so产物和头文件。 ```bash ./gradlew -c settings.ohos.gradle.kts :shared:linkOhosArm64 ``` -------------------------------- ### 复制本地静态资源 (Gradle) Source: https://kuikly.tds.qq.com/DevGuide/miniapp-dev 使用 Gradle 命令将 `demo` 项目中的 `src/commonMain/assets` 目录下的文件复制到微信小程序的 `dist/assets` 目录。 ```bash // 复制业务的assets文件到微信小程序目录 ./gradlew :miniApp:copyAssets ``` -------------------------------- ### Initialize Kuikly Adapters in HarmonyOS UIAbility Source: https://kuikly.tds.qq.com/QuickStart/harmony This snippet demonstrates initializing Kuikly's adapter manager in the EntryAbility's onWindowStageCreate lifecycle. It sets up logging and routing adapters required for Kuikly functionality. The initialization occurs when the main window is created, establishing necessary dependencies for cross-platform rendering. ```typescript // entry/src/main/ets/entryability/EntryAbility.ets import { KuiklyRenderAdapterManager } from '@kuikly-open/render'; export default class EntryAbility extends UIAbility { ... onWindowStageCreate(windowStage: window.WindowStage): void { // Main window is created, set main page for this ability // 日志适配器 KuiklyRenderAdapterManager.krLogAdapter = new AppKRLogAdapter(); // 路由适配器 KuiklyRenderAdapterManager.krRouterAdapter = new AppKRRouterAdapter(); ... } } ``` -------------------------------- ### Kotlin Coroutine Suspend Function Example Source: https://kuikly.tds.qq.com/DevGuide/thread-and-coroutines Demonstrates a suspend function in Kotlin, which can pause and resume execution without blocking a thread. Suspend functions are fundamental to coroutines and can only be called within other suspend functions or coroutines. ```kotlin suspend fun fetchData(): String { delay(1000) return "data" } ``` -------------------------------- ### 运行H5应用 Source: https://kuikly.tds.qq.com/QuickStart/hello-world 通过Gradle启动dev-server来运行H5应用,包括编译JS代码和启动调试服务。此过程涉及npm包的安装和Gradle任务的执行。 ```shell # 运行 demo 项目 dev server 服务器,没有安装 npm 包则先 npm install 安装一下依赖 npm run serve # 构建 shared 项目 Debug 版 ./gradlew :shared:packLocalJsBundleDebug ``` ```shell # 运行 h5App 服务器 Debug 版 ./gradlew :h5App:jsBrowserRun -t # kotlin 2.0 以上运行: ./gradlew :h5App:jsBrowserDevelopmentRun -t # 如果window平台因为编译iOS模块失败,可以参考"快速开始-环境搭建"指引配置 # 拷贝 assets 资源到 dev server ./gradlew :h5App:copyAssetsToWebpackDevServer ``` -------------------------------- ### Sample JSON response structure Source: https://kuikly.tds.qq.com/DevGuide/network The following JSON illustrates the data format returned by the mock endpoint used in the GET request example. It contains a "dataList" array where each item provides an "avatar" URL and a "name" string. ```JSON { "dataList": [ { "avatar": "https://vfiles.gtimg.cn/wuji_dashboard/xy/componenthub/SmA5owm4.jpeg", "name": "小红" }, { "avatar": "https://vfiles.gtimg.cn/wuji_dashboard/xy/componenthub/nm6gqV8J.jpeg", "name": "小鸡" }, { "avatar": "https://vfiles.gtimg.cn/wuji_dashboard/xy/componenthub/SmA5owm4.jpeg", "name": "小红" }, { "avatar": "https://vfiles.gtimg.cn/wuji_dashboard/xy/componenthub/nm6gqV8J.jpeg", "name": "小鸡" }, { "avatar": "https://vfiles.gtimg.cn/wuji_dashboard/xy/componenthub/SmA5owm4.jpeg", "name": "小红" }, { "avatar": "https://vfiles.gtimg.cn/wuji_dashboard/xy/componenthub/nm6gqV8J.jpeg", "name": "小红" }, { "avatar": "https://vfiles.gtimg.cn/wuji_dashboard/xy/componenthub/SmA5owm4.jpeg", "name": "小鸡" }, { "avatar": "https://vfiles.gtimg.cn/wuji_dashboard/xy/componenthub/nm6gqV8J.jpeg", "name": "小红" }, { "avatar": "https://vfiles.gtimg.cn/wuji_dashboard/xy/componenthub/SmA5owm4.jpeg", "name": "小鸡" }, { "avatar": "https://vfiles.gtimg.cn/wuji_dashboard/xy/componenthub/nm6gqV8J.jpeg", "name": "小红" } ] } ``` -------------------------------- ### Main Entry Point: Initialize Kuikly Web Render App in Kotlin Source: https://kuikly.tds.qq.com/QuickStart/Web The main entry point for the Kuikly Web Render application. It initializes the render view by parsing URL parameters, determining the page name, setting container dimensions, and passing business parameters. It also registers a visibility change listener to pause and resume the render view. ```kotlin import com.tencent.kuikly.core.render.web.ktx.SizeI import kotlinx.browser.document import kotlinx.browser.window import utils.URL /** * WebApp entry, use renderView delegate method to initialize and create renderView */ fun main() { console.log("##### Kuikly Web Render") // Root container id, note that this needs to match the container id in the actual index.html file val containerId = "root" val H5Sign = "is_H5" // Process URL parameters val urlParams = URL.parseParams(window.location.href) // Page name, default is router val pageName = urlParams["page_name"] ?: "router" // Container size val containerWidth = window.innerWidth val containerHeight = window.innerHeight // Business parameters val params: MutableMap = mutableMapOf() // Add business parameters if (urlParams.isNotEmpty()) { // Append all URL parameters to business parameters urlParams.forEach { (key, value) -> params[key] = value } } // Add web-specific parameters params[H5Sign] = "1" // Page parameter Map val paramMap = mapOf( "statusBarHeight" to 0f, "activityWidth" to containerWidth, "activityHeight" to containerHeight, "param" to params, ) // Initialize delegator val delegator = KuiklyWebRenderViewDelegator() // Create render view delegator.init( containerId, pageName, paramMap, SizeI( containerWidth, containerHeight, ) ) // Trigger resume delegator.resume() // Register visibility event document.addEventListener("visibilitychange", { val hidden = document.asDynamic().hidden as Boolean if (hidden) { // Page hidden delegator.pause() } else { // Page restored delegator.resume() } }) } } ``` -------------------------------- ### 运行微信小程序 Source: https://kuikly.tds.qq.com/QuickStart/hello-world 本节介绍了如何通过Gradle编译JS代码,并使用微信开发者工具运行微信小程序。这包括构建开发和发布版本的JS Bundle。 ```shell # 运行 demo 项目 dev server 服务器,没有安装 npm 包则先 npm install 安装一下依赖 npm run serve # 构建 demo 项目 Debug 版 ./gradlew :shared:packLocalJsBundleDebug ``` ```shell # 运行 miniApp 服务器 Debug 版 ./gradlew :miniApp:jsMiniAppDevelopmentWebpack ``` ```shell # 首先构建业务 Bundle ./gradlew :demo:packLocalJSBundleRelease # 然后构建 miniApp ./gradlew :miniApp:jsMiniAppProductionWebpack ``` -------------------------------- ### Using KMP Multithreading with Kuiklyx Coroutines (Kotlin) Source: https://kuikly.tds.qq.com/DevGuide/thread-and-coroutines This example shows how to use KMP multithreading to perform long-running tasks and update the UI through Kuiklyx coroutines. It involves adding the necessary dependencies and using `asyncKmpFetchData` to retrieve data, then switching back to the Kuikly thread to update reactive fields. ```Kotlin override fun created() { super.created() val ctx = this ctx.loadingObservable = true // 更新loading状态 // 调用KMP方法 asyncKmpFetchData { data -> KuiklyContextScheduler.runOnKuiklyThread(ctx.pagerId) { cancel -> if (cancel) { return } // 回到Kuikly线程,更新响应式字段 ctx.dataObservable = data ctx.loadingObservable = false } } } ``` -------------------------------- ### 引入Kuikly子模块到工程根目录 Source: https://kuikly.tds.qq.com/DevGuide/multi_module 在工程根目录的`settings.gradle.kts`文件中,使用`include`命令引入Kuikly工程的子模块。这使得后续可以在主模块中引用这些子模块。 ```kotlin include(":子模块1") include(":子模块2") ``` -------------------------------- ### GET /requestGet Source: https://kuikly.tds.qq.com/API/modules/network Sends an HTTP GET request with specified URL, parameters, and a callback for the response. ```APIDOC ## GET /requestGet ### Description Sends an HTTP GET request. ### Method GET ### Endpoint /requestGet ### Parameters #### Query Parameters - **url** (String) - Required - The request URL. - **param** (JSONObject) - Required - The request parameters. - **responseCallback** (NMAllResponse) - Required - The callback function for the response. ### Request Example ```json { "url": "", "param": {}, "responseCallback": "(data: JSONObject, success: Boolean, errorMsg: String, response: NetworkResponse) -> Unit" } ``` ### Response #### Success Response (200) - **data** (JSONObject) - The data returned from the request. - **success** (Boolean) - Indicates if the request was successful. - **errorMsg** (String) - The error message if the request failed. - **response** (NetworkResponse) - The network response object. #### Response Example ```json { "data": {}, "success": true, "errorMsg": "", "response": { "headerFields": {}, "statusCode": 200 } } ``` ``` -------------------------------- ### Windows平台编译配置 - 模板工程Kotlin版本修改 Source: https://kuikly.tds.qq.com/DevGuide/harmony-dev 在Windows平台编译模板工程时,需要修改build.ohos.gradle.kts以使用支持Windows编译的Kotlin版本。 ```gradle plugins { .... kotlin("android").version("2.0.21-KBA-010").apply(false) kotlin("multiplatform").version("2.0.21-KBA-010").apply(false) .... } ``` -------------------------------- ### GET /requestGetBinary Source: https://kuikly.tds.qq.com/API/modules/network Sends an HTTP GET request for binary data, returning a callback with the raw byte array. ```APIDOC ## GET /requestGetBinary ### Description Sends an HTTP GET request for binary data. ### Method GET ### Endpoint /requestGetBinary ### Parameters #### Query Parameters - **url** (String) - Required - The request URL. - **param** (JSONObject) - Required - The request parameters. - **responseCallback** (NMDataResponse) - Required - The callback function for the binary response. ### Request Example ```json { "url": "", "param": {}, "responseCallback": "(data: ByteArray, success: Boolean, errorMsg: String, response: NetworkResponse) -> Unit" } ``` ### Response #### Success Response (200) - **data** (ByteArray) - The binary data returned from the request. - **success** (Boolean) - Indicates if the request was successful. - **errorMsg** (String) - The error message if the request failed. - **response** (NetworkResponse) - The network response object. #### Response Example ```json { "data": "", "success": true, "errorMsg": "", "response": { "headerFields": {}, "statusCode": 200 } } ``` ``` -------------------------------- ### Kuikly HelloWorld Page 基础结构 Source: https://kuikly.tds.qq.com/QuickStart/hello-world 展示了Kuikly中创建HelloWorld页面的基本Kotlin代码结构。它定义了一个继承自Pager的类,并重写了body方法来构建UI。 ```kotlin internal class HelloWorldPage : Pager() { override fun body(): ViewBuilder { } } ``` ```kotlin internal class HelloWorldPage : Pager() { override fun body(): ViewBuilder { return { attr { allCenter() } Text { attr { text("Hello Kuikly") fontSize(14f) } } } } } ``` ```kotlin @Page("HelloWorld") internal class HelloWorldPage : Pager() { ... } ``` ```kotlin @Page("HelloWorld") internal class HelloWorldPage : Pager() { override fun body(): ViewBuilder { return { attr { allCenter() } Text { attr { text("Hello Kuikly") fontSize(14f) } } } } } ``` -------------------------------- ### DatePicker Component Example in Kotlin Source: https://kuikly.tds.qq.com/API/components/date-picker This example demonstrates how to use the DatePicker component in a Kotlin application. It shows how to set attributes, handle the chooseEvent, and display the selected date and timestamp. The DatePicker is initialized with basic attributes like width, background color, and border radius. ```kotlin @Page("demo_page") internal class TestPage : BasePager() { private var date: Date by observable(Date(0,0,0)) private var dateTimestamp : Long by observable(0L) override fun body(): ViewBuilder { val ctx = this return { attr { allCenter() flexDirectionColumn() } Text { attr { text("现在是${ctx.date}, ${ctx.dateTimestamp}") } } DatePicker { attr { width(300f) backgroundColor(Color.WHITE) borderRadius(8f) } event { chooseEvent { it.date?.let { ctx.date = it } ctx.dateTimestamp = it.timeInMillis } } } } } } ``` -------------------------------- ### 构建 Kuikly 小程序 Release 版本 (Gradle) Source: https://kuikly.tds.qq.com/DevGuide/miniapp-dev 使用 Gradle 命令来构建业务 Bundle 的 Release 版本,然后构建小程序的 Production Release 版本。 ```bash # 首先构建业务 Bundle ./gradlew :demo:packLocalJSBundleRelease # 然后构建 miniApp ./gradlew :miniApp:jsMiniAppProductionWebpack ``` -------------------------------- ### Windows平台编译配置 - 源码工程编译跨端产物 Source: https://kuikly.tds.qq.com/DevGuide/harmony-dev 在Windows平台使用KuiklyUI源码工程时,通过命令行编译跨端产物。 ```bash ./gradlew -c .\settings.2.0.ohos.gradle.kts :demo:linkSharedOhosArm64 仅编译Debug产物: ./gradlew -c settings.2.0.ohos.gradle.kts :demo:linkSharedDebugSharedOhosArm64 仅编译Release产物: ./gradlew -c settings.2.0.ohos.gradle.kts :demo:linkSharedReleaseSharedOhosArm64 ``` -------------------------------- ### Refresh Component Methods Source: https://kuikly.tds.qq.com/API/components/refresh Information about the methods available to control the Refresh component, such as manually starting or ending a refresh. ```APIDOC ## Refresh Component Methods ### beginRefresh * **Description**: Manually initiates the pull-to-refresh action. * **Parameters**: * `animated` (Boolean) - Optional: Specifies whether the animation should be used when starting the refresh. Defaults to `true`. ### endRefresh * **Description**: Ends the current pull-to-refresh operation. * **Parameters**: * `animated` (Boolean) - Optional: Specifies whether the animation should be used when ending the refresh. ### contentInsetWhenEndDrag * **Description**: Adjusts the content inset of the list when the pull-to-refresh action returns to its initial position after the user releases their finger. * **Properties**: * `contentInsetTopWhenEndDrag` (Float) - The top inset value to apply. ### refreshState * **Description**: Sets or gets the current refresh state of the component. * **Type**: `RefreshViewState` * **Possible Values**: * `IDLE`: Normal idle state. * `PULLING`: State where releasing the touch will trigger a refresh. * `REFRESHING`: State indicating that a refresh operation is in progress. ``` -------------------------------- ### Windows平台编译配置 - 编译鸿蒙跨端产物 (模板工程) Source: https://kuikly.tds.qq.com/DevGuide/harmony-dev 在Windows平台通过命令行编译模板工程的鸿蒙跨端产物。 ```bash ./gradlew -c settings.ohos.gradle.kts :shared:linkOhosArm64 仅编译Debug产物: ./gradlew -c settings.ohos.gradle.kts :shared:linkDebugSharedOhosArm64 仅编译Release产物: ./gradlew -c settings.ohos.gradle.kts :shared:linkReleaseSharedOhosArm64 ``` -------------------------------- ### Conditional CocoaPods Configuration Source: https://kuikly.tds.qq.com/DevGuide/android-dev Example of conditionally applying CocoaPods configuration in build.gradle.kts based on the kuiklyEmbed flag. ```kotlin val kuiklyEmbed = rootProject.extra.has("kuiklyEmbed") if (!kuiklyEmbed) { cocoapods { ... } } ``` -------------------------------- ### 添加Kuikly渲染器依赖 Source: https://kuikly.tds.qq.com/QuickStart/android 在宿主模块的gradle文件中添加Kuikly相关依赖。注意core-render-android和core的版本需要与KMM跨端工程使用的版本保持一致,否则可能出现兼容性问题。2.5.0版本后需要额外添加腾讯maven源。 ```gradle dependencies { implementation("com.tencent.kuikly-open:core-render-android:KUIKLY_RENDER_VERSION") implementation("com.tencent.kuikly-open:core:KUIKLY_CORE_VERSION") implementation 'androidx.core:core-ktx:1.7.0' implementation 'androidx.appcompat:appcompat:1.6.1' implementation 'com.google.android.material:material:1.8.0' implementation 'androidx.constraintlayout:constraintlayout:2.1.3' ... } ``` -------------------------------- ### 构建 Kuikly 共享项目和小程序 (npm, Gradle) Source: https://kuikly.tds.qq.com/DevGuide/miniapp-dev 使用 npm 和 Gradle 命令来运行共享项目的开发服务器,构建共享项目的 Debug 版本,以及运行小程序服务器的 Debug 版本。需要先安装 npm 包依赖。 ```bash # 运行 shared 项目 dev server 服务器,没有安装 npm 包则先 npm install 安装一下依赖 npm run serve # 构建 shared 项目 Debug 版 ./gradlew :shared:packLocalJsBundleDebug # 运行 miniApp 服务器 Debug 版 ./gradlew :miniApp:jsMiniAppDevelopmentWebpack ``` -------------------------------- ### 生成so产物和头文件 - 方式2配置 Source: https://kuikly.tds.qq.com/DevGuide/harmony-dev 使用方式2配置时,执行shared module的linkOhosArm64任务来编译so产物和头文件。 ```bash ./gradlew :shared:linkOhosArm64 ``` -------------------------------- ### Input Component with Cursor Color (Kotlin) Source: https://kuikly.tds.qq.com/API/components/input Details how to change the cursor color of the Input component using the tintColor attribute. This example sets it to red. ```kotlin @Page("demo_page") internal class TestPage : BasePager() { override fun body(): ViewBuilder { return { attr { allCenter() } Input { attr { size(200f, 40f) placeholder("输入框提示") tintColor(Color.RED) } } } } } ``` -------------------------------- ### Create Kuikly Test Page in Kotlin Multiplatform Source: https://kuikly.tds.qq.com/QuickStart/harmony This Kotlin code defines a test page for Kuikly framework verification. It creates a centered Text component displaying "Hello Kuikly" in green using Kuikly's DSL syntax. The page serves as a validation mechanism to confirm successful framework integration and rendering pipeline functionality. ```kotlin @Page("test") class TestPage : Pager(){ override fun body(): ViewBuilder { return { attr { allCenter() } Text { attr { fontSize(18f) text("Hello Kuikly") color(Color.GREEN) } } } } } ``` -------------------------------- ### ActivityIndicator Component Usage Example Source: https://kuikly.tds.qq.com/API/components/activity-indicator Demonstrates how to use the ActivityIndicator component in a Kotlin-based UI framework. It shows the default usage and how to apply a grayscale style with scaling and margin adjustments. ```kotlin @Page("demo_page") internal class TestPage : BasePager() { override fun body(): ViewBuilder { return { attr { allCenter() } View { attr { backgroundColor(Color.BLACK) size(pagerData.pageViewWidth, 50f) allCenter() } // 默认尺寸20*20 ActivityIndicator {} } ActivityIndicator { attr { isGrayStyle(true) // 灰色菊花 transform(Scale(1.5f, 1.5f)) marginTop(50f) } } } } } ``` -------------------------------- ### Implement NAPI Init Function for Kuikly Integration Source: https://kuikly.tds.qq.com/QuickStart/harmony This C++ code implements the InitKuikly NAPI function that initializes the Kuikly framework through the compiled Kotlin native library. It retrieves API symbols, calls the Kotlin init function, and returns a handler. The code exposes the function to JavaScript/TypeScript through NAPI property descriptors. ```cpp // entry/src/main/cpp/napi_init.cpp #include "libshared_api.h" #include "napi/native_api.h" static napi_value InitKuikly(napi_env env, napi_callback_info info) { // symbols入口名和kuikly工程的配置有关,具体查看产物的头文件 auto api = libshared_symbols(); int handler = api->kotlin.root.initKuikly(); napi_value result; napi_create_int32(env, handler, &result); return result; } EXTERN_C_START static napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor desc[] = { {"initKuikly", nullptr, InitKuikly, nullptr, nullptr, nullptr, napi_default, nullptr}, }; napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); return exports; } EXTERN_C_END ``` -------------------------------- ### Enable Kuikly Compile Plugin in Hvigor Source: https://kuikly.tds.qq.com/DevGuide/harmony-dev This snippet shows how to import and enable the Kuikly compile plugin within the Hvigor build configuration file (hvigorfile.ts). It assumes the 'kuikly-ohos-compile-plugin' is installed. ```typescript import { kuiklyCompilePlugin } from 'kuikly-ohos-compile-plugin'; export default { // ... other configurations plugins: [kuiklyCompilePlugin()] /* Custom plugin to extend the functionality of Hvigor. */ // ... other configurations } ```