### Install and Run Documentation Website (Vue 3) Source: https://github.com/piagari/dev/blob/main/HarmonyOS-Examples-main/HarmonyOS-Examples-main/Silkui/CLAUDE.md Commands to install dependencies, start a development server, build for production, and preview the production build of the documentation website using npm. ```bash cd docs-vue npm install npm run dev npm run build npm run preview ``` -------------------------------- ### List MySQL Databases using MysqlListApi Source: https://github.com/piagari/dev/blob/main/HarmonyOS-Examples-main/HarmonyOS-Examples-main/News/NewsServer/mysqlclient-ffi/doc/feature_api.md This snippet demonstrates how to list databases in MySQL using the MysqlListApi. It initializes the MySQL driver, opens a data source, establishes a connection, and then uses MysqlListApi to fetch and verify database information. It also utilizes MysqlRecordApi to get the number of fields and rows, and to fetch each row. ```cangjie import mysqlclient_ffi.* import std.unittest.* import std.unittest.testmacro.* main():Int64{ // 初始化数据库驱动 let mysqlDriver: MysqlDriver = MysqlDriver("mysql") // 通过connectionString和选项打开数据源 let mysqlDatasource: MysqlDatasource = mysqlDriver.open( "HOST=127.0.0.1;USER=root;PASSWD=123;DB=mysql;PORT=3306;UNIX_SOCKET=;CLIENT_FLAG=0", Array<(String, String)>() ) // 返回一个可用的链接 let mysqlConnection: MysqlConnection = mysqlDatasource.connect() let mysqlListApi: MysqlListApi = MysqlListApi(mysqlConnection) let mysqlRecordApi: MysqlRecordApi = MysqlRecordApi(mysqlConnection) let cp1: CPointer = mysqlListApi.mysqlListDbs("information_schema") let retFields: UInt32 = mysqlRecordApi.mysqlNumFields(cp1) @Assert(1, retFields) let retEof: Bool = mysqlRecordApi.mysqlEof(cp1) @Assert(true, retEof) let retRows: UInt64 = mysqlRecordApi.mysqlNumRows(cp1) @Assert(1, retRows) unsafe { for (i in 0..retRows) { var cpCString: CPointer = mysqlRecordApi.mysqlFetchRow(cp1) for (j in 0..retFields) { var cString: CString = cpCString.read(Int64(j)) if (i == 0) { @Assert("information_schema", cString.toString()) } } } } mysqlRecordApi.mysqlFreeResult(cp1) mysqlConnection.close() } ``` -------------------------------- ### Configure MySQL SSL using MysqlSslApi Source: https://github.com/piagari/dev/blob/main/HarmonyOS-Examples-main/HarmonyOS-Examples-main/News/NewsServer/mysqlclient-ffi/doc/feature_api.md This snippet demonstrates how to configure and retrieve SSL information for a MySQL connection using MysqlSslApi. It includes setting SSL parameters, getting the SSL cipher, checking if the SSL session was reused, and managing SSL session data. Assertions are used to verify the results. ```cangjie import mysqlclient_ffi.* import std.unittest.* import std.unittest.testmacro.* main():Int64{ // 初始化数据库驱动 let mysqlDriver: MysqlDriver = MysqlDriver("mysql") // 通过connectionString和选项打开数据源 let mysqlDatasource: MysqlDatasource = mysqlDriver.open( "HOST=127.0.0.1;USER=root;PASSWD=123;DB=mysql;PORT=3306;UNIX_SOCKET=;CLIENT_FLAG=0", Array<(String, String)>() ) // 返回一个可用的链接 let mysqlConnection: MysqlConnection = mysqlDatasource.connect() let mysqlSslApi: MysqlSslApi = MysqlSslApi(mysqlConnection) var isBool: Bool = mysqlSslApi.mysqlSslSet("", "", "", "", "") @Assert(false, isBool) var strCipher: String = mysqlSslApi.mysqlGetSslCipher() @Assert("", strCipher) isBool = mysqlSslApi.mysqlGetSslSessionReused() @Assert(false, isBool) mysqlSslApi.mysqlGetSslSessionData(0, CPointer()) isBool = mysqlSslApi.mysqlFreeSslSessionData(CPointer()) @Assert(true, isBool) mysqlConnection.close() } ``` -------------------------------- ### Manage MySQL Server using MysqlServerApi Source: https://github.com/piagari/dev/blob/main/HarmonyOS-Examples-main/HarmonyOS-Examples-main/News/NewsServer/mysqlclient-ffi/doc/feature_api.md This snippet shows how to manage a MySQL server using the MysqlServerApi. It includes initializing the server, ending the server process, refreshing server status, and killing a process. Assertions are used to verify the success of these operations. ```cangjie import mysqlclient_ffi.* import std.unittest.* import std.unittest.testmacro.* main():Int64{ // 初始化数据库驱动 let mysqlDriver: MysqlDriver = MysqlDriver("mysql") // 通过connectionString和选项打开数据源 let mysqlDatasource: MysqlDatasource = mysqlDriver.open( "HOST=127.0.0.1;USER=root;PASSWD=123;DB=mysql;PORT=3306;UNIX_SOCKET=;CLIENT_FLAG=0", Array<(String, String)>() ) // 返回一个可用的链接 let mysqlConnection: MysqlConnection = mysqlDatasource.connect() let mysqlServerApi: MysqlServerApi = MysqlServerApi(mysqlConnection) var cpCtringArgv: CPointer = CPointer() var cpCtringGroups: CPointer = CPointer() var ret: Int32 = mysqlServerApi.mysqlServerInit(10, cpCtringArgv, cpCtringGroups) @Assert(0, ret) mysqlServerApi.mysqlServerEnd() ret = mysqlServerApi.mysqlRefresh(0) @Assert(0, ret) ret = mysqlServerApi.mysqlKill(0) @Assert(1, ret) mysqlConnection.close() } ``` -------------------------------- ### Cangjie Animation and Touch Gesture Handling Source: https://context7.com/piagari/dev/llms.txt Illustrates how to implement animations and handle touch gestures in Cangjie. It uses the 'animateTo' function for state transitions and defines touch event handlers to track user input, such as swipes. This example requires the '@Entry' and '@Component' decorators. ```cangjie @Entry @Component class AnimatedGameView { @State var score: Int64 = 0 @State var gameBegin: Bool = false // Touch tracking var down: (Float64, Float64) = (0.0, 0.0) var up: (Float64, Float64) = (0.0, 0.0) // Animate game state change func changeGame(): Unit { animateTo(AnimateParam(duration: 1000), { => this.gameBegin = !this.gameBegin }) } // Calculate swipe direction func currentDirect(): String { let x = up[0] - down[0] let y = up[1] - down[1] if (abs(x) > abs(y)) { if (x > 0.0) { "right" } else { "left" } } else { if (y > 0.0) { "down" } else { "up" } } } // Move animation with callback func moveAnimate(animateCallBack: () -> Unit, onFinish: () -> Unit): Unit { animateTo( AnimateParam( duration: 200, curve: Curve.FastOutLinearIn, delay: 0, iterations: 1, playMode: PlayMode.Normal, onFinish: onFinish, expectedFrameRateRange: ExpectedFrameRateRange( min: 10, max: 60, expected: 30 ) ), animateCallBack ) } func build() { Column { Grid { // Grid items... } .onTouch { event => if (!gameBegin) { return } if ("Down" == event.eventType.toString()) { down = (event.touches[0].x, event.touches[0].y) } if ("Up" == event.eventType.toString()) { up = (event.touches[0].x, event.touches[0].y) // Process move with animation moveAnimate( { => processMove(currentDirect()) }, { => afterMove() } ) } } if (!gameBegin) { Button("New Game") .onClick { _ => PromptAction.showToast(message: "Game Started") resetGame() changeGame() } } } } } ``` -------------------------------- ### State Management with @State Decorator in Cangjie Source: https://context7.com/piagari/dev/llms.txt Demonstrates reactive state management using the @State decorator in Cangjie. When state variables like 'score' or 'items' change, the UI automatically updates. This example initializes data in 'aboutToAppear' and updates the score on button click. ```cangjie package ohos_app_cangjie_entry import ohos.base.* import ohos.component.* import ohos.state_manage.* import ohos.state_macro_manage.* import std.collection.* @Entry @Component class EntryView { @State var items: ArrayList = ArrayList() @State var score: Int64 = 0 @State var gameBegin: Bool = false let animateTextSize = AnimateParam( duration: 100, curve: Curve.Linear ) public func aboutToAppear(): Unit { // Initialize data when component appears prepareData() } private func prepareData() { items = ArrayList( Keyboards.One, Keyboards.Two, Keyboards.Three, Keyboards.Four, Keyboards.Five, Keyboards.Six ) } func build() { Column { Text("Score: ${score}") .fontWeight(FontWeight.Bold) .animationStart(animateTextSize) .fontSize(24) .animationEnd() Button("Increment").onClick { _ => score = score + 1 } } } } ``` -------------------------------- ### Cangjie Package Manager Configuration (cjpm.toml) Source: https://context7.com/piagari/dev/llms.txt Defines the package name, version, Cangjie compiler version, source directory, and dependencies for a HarmonyOS application using Cangjie. It also includes build profiles for incremental and customized build options. ```toml # cjpm.toml - Cangjie Package Manager Configuration [package] name = "ohos_app_cangjie_entry" version = "1.0.0" cjc-version = "0.48.2" output-type = "dynamic" src-dir = "src" description = "CangjieUI Application" [dependencies] [dependencies.cj_res_entry] path = "./cj_res" version = "1.0.0" [profile] [profile.build] incremental = true [profile.customized-option] debug = "-g -Woff all" release = "--fast-math -O2 -s -Woff all" ``` -------------------------------- ### Execute MySQL Query using MysqlRecordApi Source: https://github.com/piagari/dev/blob/main/HarmonyOS-Examples-main/HarmonyOS-Examples-main/News/NewsServer/mysqlclient-ffi/doc/feature_api.md This snippet demonstrates executing a MySQL query using the MysqlRecordApi. It initializes the MySQL driver, opens a data source, establishes a connection, and then uses MysqlRecordApi to execute an empty query. The result of the query is asserted to be 1, indicating success. ```cangjie import mysqlclient_ffi.* import std.unittest.* import std.unittest.testmacro.* main():Int64{ // 初始化数据库驱动 let mysqlDriver: MysqlDriver = MysqlDriver("mysql") // 通过connectionString和选项打开数据源 let mysqlDatasource: MysqlDatasource = mysqlDriver.open( "HOST=127.0.0.1;USER=root;PASSWD=123;DB=mysql;PORT=3306;UNIX_SOCKET=;CLIENT_FLAG=0", Array<(String, String)>() ) // 返回一个可用的链接 let mysqlConnection: MysqlConnection = mysqlDatasource.connect() let mysqlRecordApi: MysqlRecordApi = MysqlRecordApi(mysqlConnection) let retInt32: Int32 = mysqlRecordApi.mysqlQuery("") @Assert(1, retInt32) // 关闭链接 mysqlConnection.close() } ``` -------------------------------- ### CMake Project Setup and Library Linking Source: https://github.com/piagari/dev/blob/main/HarmonyOS-Examples-main/HarmonyOS-Examples-main/AIClassify/entry/src/main/cpp/CMakeLists.txt Configures the CMake build system for the native_demo project. It sets the minimum required CMake version, defines the project name, includes necessary directories, and links the 'entry' shared library with 'mindspore_lite_ndk' and 'hilog_ndk.z'. ```cmake cmake_minimum_required(VERSION 3.5.0) project(native_demo) # set(CMAKE_C_STANDARD 11) add_library(entry SHARED ms_lite.c) target_link_libraries(entry PUBLIC mindspore_lite_ndk) target_link_libraries(entry PUBLIC hilog_ndk.z) ``` -------------------------------- ### HarmonyOS Entry Component with @Entry and @Component (Cangjie) Source: https://context7.com/piagari/dev/llms.txt Defines the main entry view for a HarmonyOS application using Cangjie. It utilizes @Entry and @Component decorators and a declarative build() function to create a UI with text, scrolling, and dynamically positioned elements. ```cangjie package ohos_app_cangjie_entry import ohos.base.* import ohos.component.* import ohos.state_manage.* import ohos.state_macro_manage.* import ohos.display.* import std.random.* const N = 1024 let random = Random() @Entry @Component class EntryView { let words = Array(N) { _ => Rune(0x4E00 + random.nextUInt32(0x9FFF - 0x4E00)) } let width = Int64(getDefaultDisplaySync().width) let fontSize = width / 8 let height = N * fontSize func build() { Stack { Text("Cangjie").fontSize((width / 4).px).fontColor(0xCCCCCC) Scroll { Stack { ForEach(words, itemGeneratorFunc: { word: Rune, _: Int64 => Text(String(word)) .fontSize(fontSize.px) .borderWidth(1) .position(x: random.nextInt64(100).percent, y: random.nextInt64(height).px) }) } .width(100.percent) .height(height.px) } } } } ``` -------------------------------- ### HarmonyOS Ability Lifecycle Management (Cangjie) Source: https://context7.com/piagari/dev/llms.txt Manages the lifecycle of the main ability in a HarmonyOS application using Cangjie. It handles ability creation, logging the launch reason, and setting up the window stage by loading the 'EntryView' component. ```cangjie package ohos_app_cangjie_entry internal import ohos.base.AppLog internal import ohos.ability.AbilityStage internal import ohos.ability.LaunchReason internal import cj_res_entry.app class MainAbility <: Ability { public init() { super() registerSelf() } public override func onCreate(want: Want, launchParam: LaunchParam): Unit { AppLog.info("MainAbility OnCreated.${want.abilityName}") match (launchParam.launchReason) { case LaunchReason.START_ABILITY => AppLog.info("START_ABILITY") case _ => () } } public override func onWindowStageCreate(windowStage: WindowStage): Unit { AppLog.info("MainAbility onWindowStageCreate.") windowStage.loadContent("EntryView") } } ``` -------------------------------- ### SilkUI Button Component Usage Source: https://context7.com/piagari/dev/llms.txt Demonstrates the basic and advanced usage of the SilkUI Button component in Cangjie. This includes different button types, plain styles, sizes, custom colors, loading states, and disabled states. It requires importing necessary SilkUI modules. ```cangjie package silkui.components.button internal import ohos.base.* internal import ohos.component.* internal import ohos.state_manage.* import ohos.state_macro_manage.* // Basic button usage SilkButton(props: SilkButtonOptions(text: "Button")) // Button types SilkButton(props: SilkButtonOptions(text: "Primary", buttonType: SilkButtonType.PRIMARY)) SilkButton(props: SilkButtonOptions(text: "Success", buttonType: SilkButtonType.SUCCESS)) SilkButton(props: SilkButtonOptions(text: "Warning", buttonType: SilkButtonType.WARNING)) SilkButton(props: SilkButtonOptions(text: "Danger", buttonType: SilkButtonType.DANGER)) // Plain button style SilkButton(props: SilkButtonOptions(text: "Plain", plain: true)) SilkButton(props: SilkButtonOptions(text: "Primary Plain", buttonType: SilkButtonType.PRIMARY, plain: true)) // Button sizes SilkButton(props: SilkButtonOptions(text: "Large", size: SilkButtonSize.LARGE)) SilkButton(props: SilkButtonOptions(text: "Normal", size: SilkButtonSize.NORMAL)) SilkButton(props: SilkButtonOptions(text: "Small", size: SilkButtonSize.SMALL)) SilkButton(props: SilkButtonOptions(text: "Mini", size: SilkButtonSize.MINI)) // Custom color SilkButton(props: SilkButtonOptions(text: "Custom", color: Color(255, 0, 0, alpha: 1.0))) // Loading state button @Component class LoadingButtonExample { @State var loading: Bool = false func build() { SilkButtonLoading( props: SilkButtonOptions(text: "Submit", buttonType: SilkButtonType.PRIMARY), loading: loading, click: { e => loading = true // Perform async operation spawn { // ... async work launch { loading = false } } } ) } } // Disabled button SilkButtonDisabled( props: SilkButtonOptions(text: "Disabled"), disabled: true ) ``` -------------------------------- ### TCP Client Implementation in Cangjie Source: https://context7.com/piagari/dev/llms.txt The Socket4CJ class in Cangjie implements a TCP client for connecting to a server, sending messages, and receiving responses. It handles connection establishment, data transmission, and connection closure, with basic error logging. ```cangjie package ohos_app_cangjie_entry.utils import std.socket.* import encoding.url.* import std.collection.* public class Socket4CJ { let SERVER_ADDR: String = "192.168.3.66" let SERVER_PORT: UInt16 = 8080 var tcpSocket: TcpSocket public init() { this.tcpSocket = TcpSocket(SERVER_ADDR, SERVER_PORT) } public func connectServer(): Unit { try { this.tcpSocket.connect() HiLog.info("Socket", "Connect to server successfully") } catch (e: Exception) { HiLog.error("Socket", "Connect to server failed, reason is ${e.message}") } } public func sendMsg(msg: String): Unit { try { this.tcpSocket.write(msg.toArray()) HiLog.info("Socket", "Send message successfully") } catch (e: Exception) { HiLog.error("Socket", "Send message failed, reason is ${e.message}") } } public func receiveMsg(): (String, Int64) { let buffer: Array = Array(1024, item: 0) let bufferLen: Int64 = this.tcpSocket.read(buffer) HiLog.info("Socket", "Buffer length is ${bufferLen}") let msg: String = String.fromUtf8(buffer) return (msg, bufferLen) } public func closeClient(): Unit { this.tcpSocket.close() } } ``` -------------------------------- ### HarmonyOS Router Navigation with Cangjie Source: https://context7.com/piagari/dev/llms.txt This Cangjie code defines the main entry view for a HarmonyOS application, listing navigation options. It utilizes the Router API to navigate to different views when an item is clicked. Dependencies include HarmonyOS base, component, and router modules. ```cangjie package ohos_app_cangjie_entry import ohos.base.* import ohos.component.* import ohos.router.* import ohos.resource_manager. * @Entry @Component class EntryView { let padX: Int64 = 40 let padTop: Int64 = 100 let itemGap: Int64 = 40 func build() { Column(itemGap.lpx) { EntryItem( iconSrc: @r(app.media.scroll_icon), title: "Scroll View", components: "Scroll", url: "ScrollView" ) EntryItem( iconSrc: @r(app.media.list_icon), title: "List View", components: "List ListItem ListItemGroup", url: "ListView" ) EntryItem( iconSrc: @r(app.media.badge_icon), title: "Badge Component", components: "Badge", url: "BadgeView" ) EntryItem( iconSrc: @r(app.media.block_icon), title: "Layout Components", components: "Row Column RowSplit ColumnSplit", url: "SimpleLayoutView" ) } .padding(left: padX, right: padX, top: padTop) .width(100.percent) } } // Navigation item component @Component class EntryItem { var iconSrc: Resource var title: String var components: String var url: String func build() { Row { Image(iconSrc).width(40).height(40) Column { Text(title).fontSize(16).fontWeight(FontWeight.Bold) Text(components).fontSize(12).fontColor(0x666666) } .alignItems(HorizontalAlign.Start) .margin(left: 12) } .width(100.percent) .padding(16) .backgroundColor(0xFFFFFF) .borderRadius(8) .onClick { _ => Router.push(url: url) } } } ``` -------------------------------- ### 2048 Game Logic Implementation in Cangjie Source: https://context7.com/piagari/dev/llms.txt Implements the core logic for the 2048 game using Cangjie. It includes functions to reset the board, place new tiles, check for game over conditions, reverse arrays, merge tiles, and move tiles in specified directions. The implementation relies on standard library collections, random number generation, and math functions. ```cangjie package ohos_app_cangjie_entry.core import std.collection.* import std.random.* import std.math.* public class Puzzle { public static const size: Int64 = 16 public var board = Array(size, {i => 0}) public var score: Int64 = 0 private static let random = Random() // Reset board with random initial tiles public func reset(pick!: Int64 = 2): Unit { board = Array(size, {i => 0}) score = 0 for (_ in 0..pick) { pickOne() } } // Place random 2 or 4 in empty cell public func pickOne(): Unit { let r = random.nextInt64(size) for (i in 0..size) { let idx = (r + i) % board.size if (board[idx] == 0) { board[idx] = if (r > size / 2) { 4 } else { 2 } return } } } // Check if game over public func check(): Bool { for (tile in board) { if (tile == 0) { return false } } let rowSize = Int64(sqrt(Float64(board.size))) for (i in 0..rowSize) { for (j in 0..rowSize) { if (i + 1 < rowSize && board[i + j * rowSize] == board[i + j * rowSize + 1]) { return false } if (j + 1 < rowSize && board[i + j * rowSize] == board[i + (j + 1) * rowSize]) { return false } } } return true } // Reverse array func reverse(row: Array): Array { for (i in 0..(row.size / 2)) { let temp = row[i] row[i] = row[row.size - i - 1] row[row.size - i - 1] = temp } return row } // Merge tiles func merge(row: Array): Array { var newRow = Array(row.size, {i => 0}) var newIndex = 0 for (i in 0..row.size) { if (row[i] == 0) { continue } if (newIndex > 0 && newRow[newIndex - 1] == row[i]) { newRow[newIndex - 1] *= 2 score += newRow[newIndex - 1] } else { newRow[newIndex] = row[i] newIndex++ } } return newRow } // Move tiles in direction public func move(direction: String): Array { let boradSize: Int64 = board.size var newBorad = Array(boradSize, {i => 0}) let rowSize = Int64(sqrt(Float64(boradSize))) for (i in 0..rowSize) { var row = Array(rowSize, {i => 0}) for (j in 0..rowSize) { if ("left" == direction || "right" == direction) { row[j] = board[i * rowSize + j] } else { row[j] = board[j * rowSize + i] } } if ("right" == direction || "down" == direction) { row = reverse(row) } row = merge(row) if ("right" == direction || "down" == direction) { row = reverse(row) } for (j in 0..rowSize) { if ("left" == direction || "right" == direction) { newBorad[i * rowSize + j] = row[j] } else { newBorad[j * rowSize + i] = row[j] } } } board = newBorad return newBorad } } ``` -------------------------------- ### UI Layout Components in Cangjie (Row, Column, Grid) Source: https://context7.com/piagari/dev/llms.txt Showcases Cangjie's flexible UI layout components: Row for horizontal arrangement, Column for vertical arrangement, and Grid for complex grid structures. These components help in building responsive and structured user interfaces. ```cangjie @Entry @Component class IndexView { func build() { Scroll() { Column() { // Title Text("UIPlayground").fontSize(40).margin(top: 50, bottom: 75) Column(20) { Row(20) { // Horizontal layout with spacing IndexText() IndexButton() } // Image component IndexImage() // TextInput component IndexTextInput() Row(20) { IndexCheckBox() IndexBadge() } // Slider component IndexMusicPlayer() // Swiper component IndexSwiper() // Tabs component IndexTab() }.width(100.percent) }.padding(20) } } } // Grid layout example @Entry @Component class GridExample { @State var numbers: ObservedArray = ObservedArray([2, 4, 8, 16, 32, 64, 128, 256]) func build() { Grid { ForEach( this.numbers, itemGeneratorFunc: { num: Int64, idx: Int64 => GridItem { Text(num.toString()) .fontSize(32) .width(100.percent) .height(100.percent) .textAlign(TextAlign.Center) } } ) } .columnsGap(10) .rowsGap(10) .columnsTemplate("1fr 1fr 1fr 1fr") .rowsTemplate("1fr 1fr") .width(90.percent) .height(200) } } ``` -------------------------------- ### HarmonyOS WebView Browser Implementation Source: https://context7.com/piagari/dev/llms.txt This code implements a WebView component in a HarmonyOS application. It includes a search bar for URL input, navigation controls (back, forward, refresh, home), and supports JavaScript injection for features like dark mode. The component handles URL validation and page loading events. ```cangjie package ohos_app_cangjie_entry internal import ohos.{base.*, component.*, resource_manager.*, router.*, state_manage.*, webview.*} import ohos.state_macro_manage.* import std.{convert.*, regex.*} @Entry @Component class MainView { // Dark mode injection script var darkmodeScript = "/* dark mode CSS injection */" let _colorMode = Environment.envProp("colorMode", ColorMode.Light) @StorageProp["colorMode"] let color: ColorMode = ColorMode.Light @State var url: String = "https://m.baidu.com/" var webviewController: WebviewController = WebviewController() func isUrl(text: String): Bool { let regex = Regex("^[a-zA-Z0-9-.]+.[a-zA-Z]{2,}$") match (regex.matches(text)) { case Some(r) => true case None => false } } func build() { Column { // Search bar Row { Search(placeholder: "Search or enter URL", value: this.url) .onSubmit { content => if (isUrl(content)) { this.url = content } else { this.url = "https://baidu.com/s?wd=" + content } this.webviewController.loadUrl(this.url) } .width(80.percent) Image("/resources/base/media/arrow_clockwise.svg") .fillColor(@r(app.color.foreground)) .width(5.percent) .onClick { _ => this.webviewController.refresh() } } .width(100.percent) .height(8.percent) .justifyContent(FlexAlign.Center) // WebView content Row { Web(src: this.url, controller: webviewController) .onPageBegin { _ => this.webviewController.setCustomUserAgent( "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15" ) } .onPageEnd { event => this.url = event.url match(this.color) { case ColorMode.Dark => this.webviewController.runJavaScript(darkmodeScript, {_, _ => ()}) case _ => { => ()}() } } } .width(100.percent) .height(84.percent) // Navigation bar Row { Row { Image(@r(app.media.chevron_left)).fillColor(@r(app.color.foreground)).height(40.percent) } .width(20.percent) .onClick { _ => if (this.webviewController.accessBackward()) { this.webviewController.backward() } } Row { Image(@r(app.media.chevron_right)).fillColor(@r(app.color.foreground)).height(40.percent) } .width(20.percent) .onClick { _ => this.webviewController.forward() } Row { Image(@r(app.media.house)).fillColor(@r(app.color.foreground)).height(40.percent) } .width(20.percent) .onClick { _ => this.webviewController.loadUrl("https://m.baidu.com/") } } .width(100.percent) .height(8.percent) } .width(100.percent) .height(100.percent) .expandSafeArea() } } ``` -------------------------------- ### Cangjie LLM Class for AI Chat Integration Source: https://context7.com/piagari/dev/llms.txt Implements an LLM class in Cangjie for AI chat applications. It handles HTTP requests to LLM APIs, supports streaming and non-streaming responses, and manages conversation memory. Dependencies include standard libraries for IO, time, JSON encoding, HTTP, and TLS. ```cangjie package ohos_app_cangjie_entry.utils import std.io.StringReader import std.time.Duration import encoding.json.* import net.http.* import net.tls.* public enum Role <: ToString { I | AI | System public func toString() { match (this) { case I => 'user' case AI => 'assistant' case System => 'system' } } } public class LLM { let client: Client let history = StringBuilder() public LLM(let url!: String, let key!: String, let model!: String, let memory!: Bool = false) { var config = TlsClientConfig() config.verifyMode = TrustAll client = ClientBuilder() .tlsConfig(config) .readTimeout(Duration.Max) .build() } func encode(role: Role, content: String) { '{"role":"${role}","content":${JsonString(content)}}"' } func send(input: String, stream!: Bool = false) { let message = encode(I, input) let content = '{"model":"${model}","messages":[${history}${message}],"stream":${stream}}' if (memory) { history.append(message) } let request = HttpRequestBuilder() .url(url) .header('Authorization', 'Bearer ${key}') .header('Content-Type', 'application/json') .header('Accept', if (stream) { 'text/event-stream' } else { 'application/json' }) .body(content) .post() .build() client.send(request) } // Streaming chat with callback public func chats(input: String, task: (String) -> Unit) { const INDEX = 6 let response = send(input, stream: true) let output = StringBuilder() let buffer = Array(1024 * 8, item: 0) var length = response.body.read(buffer) while (length != 0) { let text = String.fromUtf8(buffer[..length]) for (line in text.split('\n', removeEmpty: true)) { if (line.size > INDEX && line[INDEX] == b'{') { let json = line[INDEX..line.size] let slice = parse(json, stream: true) if (memory) { output.append(slice) } task(slice) } } length = response.body.read(buffer) } if (memory) { history.append(',${encode(AI, output.toString())},') } } // Non-streaming chat public func chat(input: String) { let response = send(input) let output = StringReader(response.body).readToEnd() |> parse if (memory) { history.append(',${encode(AI, output)},') } return output } public func preset(memory: Array<(Role, String)>) { history.reset() for ((role, message) in memory) { history.append(encode(role, message) + ',') } } public func reset() { history.reset() } } // Usage example in UI component @Entry @Component class AIChatView { @State var input: String = '' @State var talking: Message = Message('', You, now()) let llm = LLM( url: 'https://api.siliconflow.cn/v1/chat/completions', key: 'your-api-key', model: 'deepseek-ai/DeepSeek-V3', memory: true ) func build() { Column { // Chat messages display Scroll { LazyForEach(messages, itemGeneratorFunc: { value: Message, _: Int64 => ChatBlock(message: value) }) } // Input area Row { TextInput(text: input) .onChange { value => input = value } Button("Send").onClick { spawn { llm.chats(input) { slice: String => launch { talking = Message(talking.content + slice, You, talking.time) } } } input = '' } } } } } ``` -------------------------------- ### HarmonyOS Application Build Commands Source: https://github.com/piagari/dev/blob/main/HarmonyOS-Examples-main/HarmonyOS-Examples-main/Silkui/CLAUDE.md Instructions for building HarmonyOS applications using the DevEco Studio build system with hvigor. Build commands are typically executed via DevEco Studio or hvigor CLI. ```bash # Build commands should be run through DevEco Studio or using hvigor CLI tools. ``` -------------------------------- ### Documentation Site Integration Script (JavaScript) Source: https://github.com/piagari/dev/blob/main/HarmonyOS-Examples-main/HarmonyOS-Examples-main/Silkui/CLAUDE.md A JavaScript snippet illustrating how to add a component name to a script responsible for copying markdown documentation for the Vue-based documentation site. ```javascript // Example: Add component name to docs-vue/scripts/copy-markdown.js // ... const componentName = "MyNewComponent"; // ... add componentName to the list or logic for copying markdown files ``` -------------------------------- ### CangjieScript Component Structure Source: https://github.com/piagari/dev/blob/main/HarmonyOS-Examples-main/HarmonyOS-Examples-main/Silkui/CLAUDE.md Defines the typical file structure for a single UI component developed in CangjieScript, including the main implementation, model/types, package exports, and documentation. ```plaintext component_name/ ├── component_name.cj # Main component implementation ├── model.cj # Types and interfaces ├── pkg.cj # Package exports └── README.md # Component documentation ``` -------------------------------- ### CoverCard Component Definition (ArkTS) Source: https://github.com/piagari/dev/blob/main/HarmonyOS-Examples-main/HarmonyOS-Examples-main/WaterFall/entry/src/main/cangjie/src/component/card/CoverCard.txt Defines the CoverCard component, which can display either an image or a video. It handles touch events to play/stop videos and manages the playback state. Dependencies include various ArkTS framework modules and custom entity/mock types. ```ArkTS /** * Created on 2024/8/26 */ package ohos_app_cangjie_entry.component.card import ohos.base.* import ohos.component.* import ohos.state_manage.* import ohos.state_macro_manage.* import std.sync.{Timer, sleep} import std.time.{Duration} import ohos_app_cangjie_entry.entity.* import ohos_app_cangjie_entry.mock.VideoData let TOP_BORDER_RADIUS = 6.fp @Component public class CoverCard { // 资源类型 @Prop var mediaType: MediaType // 标题 @Prop var title: String // 文本描述 @Prop var desc: String @State var onPlaying: Bool = false let videoController = func cardOnTouch(e: TouchEvent) { if (let MediaType.VIDEO(_) <- this.mediaType) { if (let TouchType.Up <- e.eventType) { this.stopVideo() } else if(let TouchType.Down <- e.eventType) { this.playVideo() } } } func playVideo() { this.onPlaying = true this.videoController.start() } func stopVideo() { this.onPlaying = false this.videoController.stop() } func build() { Column(10) { if(let IMAGE(src) <- mediaType) { Image(src).width(100.percent) .borderRadius(topLeft: TOP_BORDER_RADIUS, topRight: TOP_BORDER_RADIUS) .objectFit(ImageFit.Cover) } else if (let VIDEO(src) <- mediaType) { if (this.onPlaying) { Video(src: src[1], controller: videoController) .objectFit(ImageFit.Fill).height(150) .loop(true) .controls(false) } else { Image(src[0]).width(100.percent) .borderRadius(topLeft: TOP_BORDER_RADIUS, topRight: TOP_BORDER_RADIUS) .objectFit(ImageFit.Fill).height(150) } } Column(10) { Text(title).fontSize(14).width(100.percent) Text(desc).fontSize(12).width(100.percent) }.padding(left: 10, right: 10, bottom: 10) }.width(100.percent) .alignItems(HorizontalAlign.Start) .borderRadius(TOP_BORDER_RADIUS) .backgroundColor(0xffffff) .onTouch(cardOnTouch) } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.