Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Test
https://github.com/wuyw/test
Admin
No project description could be extracted as the provided content is empty.
Tokens:
6,813
Snippets:
26
Trust Score:
5.9
Update:
9 months ago
Context
Chat
Benchmark
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### ArkTS ForEach Loop Rendering with Key Generation Source: https://context7.com/wuyw/test/llms.txt Illustrates the correct usage of the ForEach loop in ArkTS for rendering lists from arrays. It emphasizes the requirement for a key generator function that returns a string and shows how to handle optional index parameters. This example renders a list of fruits with numbered entries. ```arkts @Entry @Component struct Index { private fruits: string[] = ['Apple', 'Banana', 'Orange', 'Grape', 'Mango'] build() { Column() { Text('Fruit List') .fontSize(24) .fontWeight(FontWeight.Bold) .margin({ bottom: 20 }) // Correct ForEach usage with optional index ForEach( this.fruits, (item: string, index?: number) => { // Key generator must return string return `key_${index}` }, (item: string, index?: number) => { Text(`${index! + 1}. ${item}`) .fontSize(18) .padding(15) .backgroundColor(Color.White) .borderRadius(10) .width('90%') .margin({ bottom: 10 }) } ) } .width('100%') .height('100%') .padding(20) .backgroundColor('#F5F5F5') .justifyContent(FlexAlign.Start) } } ``` -------------------------------- ### Create Reusable UI Components with @Builder in ArkTS Source: https://context7.com/wuyw/test/llms.txt Illustrates how to use the @Builder decorator in ArkTS to create reusable UI fragments. Builder methods should only contain UI component syntax and cannot define internal variables. This example shows a settings dialog that can be conditionally displayed. ```arkts @Entry @Component struct Index { @State showSettings: boolean = false; @State apiKeyInput: string = ''; @Builder SettingsDialog() { Column() { Column() { Row() { Text('AI Settings') .fontSize(20) .fontWeight(FontWeight.Bold) .fontColor('#FFFFFF') .layoutWeight(1) Button() { Text('X') .fontSize(18) .fontColor('#FFFFFF') } .type(ButtonType.Normal) .backgroundColor(Color.Transparent) .width(32) .height(32) .onClick(() => { this.showSettings = false; }) } .width('100%') .margin({ bottom: 24 }) TextInput({ placeholder: 'Enter API Key', text: this.apiKeyInput }) .width('100%') .height(48) .onChange((value: string) => { this.apiKeyInput = value; }) } .width('90%') .padding(24) .backgroundColor('#2A2B32') .borderRadius(16) } .width('100%') .height('100%') .backgroundColor('rgba(0,0,0,0.5)') .justifyContent(FlexAlign.Center) } build() { Stack() { Column() { Text('Main Content') } .width('100%') .height('100%') if (this.showSettings) { this.SettingsDialog() } } .width('100%') .height('100%') } } ``` -------------------------------- ### Implement UIAbility Lifecycle Callbacks in ArkTS Source: https://context7.com/wuyw/test/llms.txt Demonstrates the structure of a UIAbility entry point for Stage model applications in ArkTS. It includes essential lifecycle callbacks such as onCreate, onDestroy, onWindowStageCreate, onForeground, and onBackground, using hilog for logging. ```arkts import { AbilityConstant, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { window } from '@kit.ArkUI'; const DOMAIN = 0x0000; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onCreate'); } onDestroy(): void { hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onDestroy'); } onWindowStageCreate(windowStage: window.WindowStage): void { hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); windowStage.loadContent('pages/Index', (err) => { if (err.code) { hilog.error(DOMAIN, 'testTag', 'Failed to load content: %{public}s', JSON.stringify(err)); return; } hilog.info(DOMAIN, 'testTag', 'Content loaded successfully.'); }); } onForeground(): void { hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onForeground'); } onBackground(): void { hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onBackground'); } } ``` -------------------------------- ### ArkTS @State Decorator for Reactive Variables Source: https://context7.com/wuyw/test/llms.txt Demonstrates the use of the @State decorator in ArkTS to create reactive variables. Changes to these variables automatically trigger UI updates. This example shows a counter component with buttons to modify the state and conditional text rendering based on the counter's value. ```arkts @Entry @Component struct EnhancedCounterExample { @State counter: number = 10 build() { Column({ space: 25 }) { Text('Counter Value') .fontSize(20) .fontColor(Color.Gray) Text(this.counter.toString()) .fontSize(48) .fontWeight(FontWeight.Bold) .fontColor(this.getCounterColor()) // Conditional rendering based on state if (this.counter > 20) { Text('High value') .fontSize(16) .fontColor(Color.Red) } else if (this.counter < 0) { Text('Negative value') .fontSize(16) .fontColor(Color.Orange) } Row({ space: 15 }) { Button('-5') .width(80) .height(50) .onClick(() => { this.counter -= 5 }) Button('+1') .width(80) .height(50) .backgroundColor('#007DFF') .onClick(() => { this.counter += 1 }) Button('+5') .width(80) .height(50) .onClick(() => { this.counter += 5 }) } } .width('100%') .height('100%') .justifyContent(FlexAlign.Center) } getCounterColor(): Color { if (this.counter > 20) return Color.Red; if (this.counter < 0) return Color.Orange; return Color.Blue; } } ``` -------------------------------- ### Proper Error Throwing in ArkTS Source: https://context7.com/wuyw/test/llms.txt Illustrates correct error handling in ArkTS, emphasizing that only `Error` types can be thrown. It demonstrates checking if an exception is an `Error` instance before re-throwing and converting non-Error exceptions to the `Error` type. ```arkts static async callAI(messages: Message[]): Promise<string> { const config: APIConfigItem = AIConfig.getCurrentConfig(); if (config.apiKey.length === 0) { throw new Error('Please configure API Key first'); } try { const response: string = await AIService.callCustomAPI(messages, config); return response; } catch (error) { console.error('AI API call failed:', JSON.stringify(error)); // Must check type before throwing if (error instanceof Error) { throw error; } // Convert to Error type for non-Error exceptions throw new Error(String(error)); } } ``` -------------------------------- ### Conditional Rendering with if Statements in ArkTS Source: https://context7.com/wuyw/test/llms.txt Demonstrates how to use 'if' statements for dynamic UI rendering within the 'build()' method. State changes automatically trigger UI updates. This pattern is useful for showing or hiding UI elements based on application state. ```arkts @Entry @Component struct Index { @State num: number = 15 build() { Column({ space: 20 }) { // Conditional rendering if (this.num > 10) { Text('Number is greater than 10') .fontSize(30) .fontColor(Color.Blue) } Text(`Current number: ${this.num}`) .fontSize(20) Button('Increase') .onClick(() => { this.num += 5 }) .margin(10) Button('Decrease') .onClick(() => { this.num -= 5 }) .margin(10) Button('Reset to 5') .onClick(() => { this.num = 5 }) .margin(10) } .width('100%') .height('100%') .justifyContent(FlexAlign.Center) } } ``` -------------------------------- ### Configure AI API Settings with ArkTS Source: https://context7.com/wuyw/test/llms.txt Defines constants and an interface for API configuration, along with a class to manage API types and settings. It enforces explicit type annotations as required by ArkTS, prohibiting 'any', 'unknown', and 'keyof typeof'. ```arkts export const API_TYPE_OPENAI: string = 'openai'; export const API_TYPE_TONGYI: string = 'tongyi'; export const API_TYPE_CUSTOM: string = 'custom'; export interface APIConfigItem { baseUrl: string; model: string; apiKey: string; } export class AIConfig { private static currentApiType: string = API_TYPE_CUSTOM; private static thinkingEnabled: boolean = false; private static customConfig: APIConfigItem = { baseUrl: 'https://api.example.com/v1/chat/completions', model: 'gpt-3.5-turbo', apiKey: '' }; static getApiType(): string { return AIConfig.currentApiType; } static setApiType(apiType: string): void { if (apiType === API_TYPE_OPENAI || apiType === API_TYPE_TONGYI || apiType === API_TYPE_CUSTOM) { AIConfig.currentApiType = apiType; } } static getCurrentConfig(): APIConfigItem { return AIConfig.customConfig; } static setApiKey(apiType: string, apiKey: string): void { if (apiType === API_TYPE_CUSTOM) { AIConfig.customConfig.apiKey = apiKey; } } } ``` -------------------------------- ### Create Tab Navigation with Custom Tab Builder in ArkTS Source: https://context7.com/wuyw/test/llms.txt Demonstrates how to create a tab-based navigation component using Tabs and TabContent in ArkTS. It shows how to use a custom @Builder method for tab bars, accessing @State variables directly for reactivity, and managing the current tab index. ```arkts import { MyPage } from './MyPage'; @Entry @Component struct Index { @State currentIndex: number = 0; build() { Tabs({ barPosition: BarPosition.End, index: this.currentIndex }) { TabContent() { ChatPage() } .tabBar(this.TabBuilder('Chat', 0)) TabContent() { MyPage() } .tabBar(this.TabBuilder('Profile', 1)) } .width('100%') .height('100%') .barMode(BarMode.Fixed) .onChange((index: number) => { this.currentIndex = index; }) } // Access this.currentIndex directly for reactive updates @Builder TabBuilder(title: string, targetIndex: number) { Column() { Text(title) .fontSize(14) .fontColor(this.currentIndex === targetIndex ? '#007AFF' : '#999999') .fontWeight(this.currentIndex === targetIndex ? FontWeight.Medium : FontWeight.Normal) } .width('100%') .height(56) .justifyContent(FlexAlign.Center) } } ``` -------------------------------- ### Create Standard Page Component with @Entry and @Component in ArkTS Source: https://context7.com/wuyw/test/llms.txt Demonstrates the fundamental structure of a HarmonyOS page using @Entry and @Component decorators. It requires a struct with a build() method and a single root node, typically a Column. State variables are reactive and update the UI automatically. Note that 'space' is a valid parameter for Column, but 'alignItems' is not. ```arkts @Entry @Component struct StandardHomePage { // Reactive state variables - automatically update UI when modified @State message: string = 'HarmonyOS Standard Page'; @State pageCount: number = 0; // Required: UI rendering entry point build() { // Only use 'space' parameter - 'alignItems' is not valid for Column constructor Column({ space: 20 }) { Text(this.message) .fontSize(30) .fontWeight(FontWeight.Bold) .fontColor('#007DFF') Text(`Click count: ${this.pageCount}`) .fontSize(24) .fontColor('#333333') Button('Increment', { type: ButtonType.Capsule }) .width('80%') .height(50) .fontSize(22) .onClick(() => { this.pageCount++; }) Button('Navigate', { type: ButtonType.Capsule }) .width('80%') .height(50) .fontSize(22) .backgroundColor('#00C689') .onClick(() => { router.pushUrl({ url: 'pages/SecondPage' }); }) } .width('100%') .height('100%') .justifyContent(FlexAlign.Center) .backgroundColor('#F5F7FA') } } ``` -------------------------------- ### Long Press Gesture on List Items in ArkTS Source: https://context7.com/wuyw/test/llms.txt Demonstrates how to implement a long press gesture on list items in ArkTS, as ListItems do not have a direct `onLongPress` property. It uses the `.gesture()` modifier with `LongPressGesture` to handle the interaction. ```arkts List({ scroller: this.scroller }) { ForEach(this.messages, (message: ChatMessage, index: number) => { ListItem() { Text(message.content) .fontSize(16) .fontColor('#FFFFFF') } .onClick(() => { if (this.selectedMessageId === message.id) { this.selectedMessageId = ''; } }) .gesture( LongPressGesture({ duration: 500, repeat: false }) .onAction(() => { this.selectedMessageId = message.id; }) ) }, (message: ChatMessage) => message.id) } ``` -------------------------------- ### Login Page Layout with TextInput in ArkTS Source: https://context7.com/wuyw/test/llms.txt Creates a centered login form using 'TextInput' components for username and password. It ensures default values for properties to prevent initialization errors and uses 'InputType.Password' for secure input. The 'onChange' callback updates the component's state. ```arkts @Entry @Component struct Index { @State username: string = '' @State password: string = '' build() { Column() { Column() { Text('User Login') .fontSize(30) .fontWeight(FontWeight.Bold) .margin({ bottom: 40 }) TextInput({ placeholder: 'Enter username', text: this.username }) .width('80%') .height(50) .backgroundColor(Color.White) .borderRadius(8) .padding(10) .margin({ bottom: 20 }) .onChange((value: string) => { this.username = value }) TextInput({ placeholder: 'Enter password', text: this.password }) .width('80%') .height(50) .backgroundColor(Color.White) .borderRadius(8) .padding(10) .margin({ bottom: 30 }) .type(InputType.Password) .onChange((value: string) => { this.password = value }) Button('Login', { type: ButtonType.Capsule }) .width('80%') .height(50) .fontSize(18) .fontWeight(FontWeight.Medium) .backgroundColor('#007DFF') .onClick(() => { console.info(`Username: ${this.username}, Password: ${this.password}`) }) } .width('90%') .padding(30) .backgroundColor('#F5F5F5') .borderRadius(15) .shadow({ radius: 10, color: '#00000020', offsetX: 0, offsetY: 5 }) } .width('100%') .height('100%') .justifyContent(FlexAlign.Center) .alignItems(HorizontalAlign.Center) .backgroundColor('#FFFFFF') } } ``` -------------------------------- ### Chat Message List with State Management in ArkTS Source: https://context7.com/wuyw/test/llms.txt Implements a chat message list using ArkTS class definitions and state management. It utilizes Scroller for list scrolling and defines enums for message roles and statuses. The component initializes with a welcome message. ```arkts enum MessageRole { USER = 'user', ASSISTANT = 'assistant' } enum MessageStatus { SENDING = 'sending', SENT = 'sent', FAILED = 'failed' } class ChatMessage { id: string = ''; role: MessageRole = MessageRole.USER; content: string = ''; timestamp: number = Date.now(); status: MessageStatus = MessageStatus.SENT; constructor(role: MessageRole, content: string) { this.id = `${Date.now()}_${Math.random()}`; this.role = role; this.content = content; this.timestamp = Date.now(); this.status = MessageStatus.SENT; } } @Entry @Component struct Index { @State messages: ChatMessage[] = []; @State inputText: string = ''; @State isSending: boolean = false; scroller: Scroller = new Scroller(); aboutToAppear() { const welcomeMessage = new ChatMessage( MessageRole.ASSISTANT, 'Hello! I am your AI assistant.' ); this.messages.push(welcomeMessage); } build() { Column() { List({ scroller: this.scroller }) { ForEach(this.messages, (message: ChatMessage) => { ListItem() { Text(message.content) .fontSize(16) .fontColor('#FFFFFF') } }, (message: ChatMessage) => message.id) } .layoutWeight(1) .width('100%') } .width('100%') .height('100%') } } ``` -------------------------------- ### ArkTS Image Swiper with Fullscreen Preview Source: https://context7.com/wuyw/test/llms.txt Implements an image carousel using the Swiper component in ArkTS, featuring click-to-fullscreen functionality. It utilizes a Stack as the root node to overlay the fullscreen viewer. The component manages the current index, fullscreen state, and the image to display. ```arkts @Component export struct ImageSwiper { @State currentIndex: number = 0 @State isFullScreen: boolean = false @State fullScreenImage: string = '' @State imageList: string[] = [ 'common/images/img1.jpg', 'common/images/img2.jpg', 'common/images/img3.jpg', 'common/images/img4.jpg' ] build() { // Use Stack as single root to allow overlay Stack() { Column() { Swiper() { ForEach(this.imageList, (item: string, index: number) => { Image(item) .width('100%') .height(200) .objectFit(ImageFit.Cover) .borderRadius(10) .onClick(() => { this.fullScreenImage = item this.isFullScreen = true }) }, (item: string) => item) } .width('100%') .height(200) .indicator(true) .loop(true) .autoPlay(true) .interval(3000) .vertical(false) .onChange((index: number) => { this.currentIndex = index }) Row({ space: 5 }) { ForEach(this.imageList, (item: string, index: number) => { Circle({ width: 8, height: 8 }) .fill(this.currentIndex === index ? Color.Blue : Color.Gray) .opacity(0.8) }) } .margin({ top: 10 }) .justifyContent(FlexAlign.Center) } .width('100%') .padding(16) // Conditional fullscreen overlay if (this.isFullScreen) { FullScreenImageViewer({ imageUrl: this.fullScreenImage, onClose: () => { this.isFullScreen = false } }) } } } } ``` -------------------------------- ### Personal Card Component with Row and Column Layouts in ArkTS Source: https://context7.com/wuyw/test/llms.txt Builds a reusable 'PersonalCard' component using nested 'Row' and 'Column' layouts for structuring profile information. It requires all properties to have default initializers to prevent runtime errors. The component displays an avatar, username, and description. ```arkts @Entry @Component struct Index { build() { Column() { PersonalCard({ avatar: 'https://via.placeholder.com/80', username: 'John Doe', description: 'Full-stack Developer | HarmonyOS Expert', avatarSize: 80 }) } .width('100%') .height('100%') .justifyContent(FlexAlign.Center) .alignItems(HorizontalAlign.Center) } } @Component struct PersonalCard { // All properties must have default values avatar: string = 'https://via.placeholder.com/60' username: string = 'Username' description: string = 'Description' avatarSize: number = 60 build() { Row() { Column() { Image(this.avatar) .width(this.avatarSize) .height(this.avatarSize) .borderRadius(this.avatarSize / 2) .backgroundColor('#f0f0f0') } .margin({ right: 16 }) Column() { Text(this.username) .fontSize(20) .fontWeight(FontWeight.Bold) .fontColor('#333333') .margin({ bottom: 8 }) Text(this.description) .fontSize(14) .fontColor('#666666') .maxLines(2) .textOverflow({ overflow: TextOverflow.Ellipsis }) .width('80%') } .alignItems(HorizontalAlign.Start) .justifyContent(FlexAlign.Center) .height('100%') } .padding(20) .backgroundColor('#ffffff') .borderRadius(12) .shadow({ radius: 8, color: '#1a000000', offsetX: 0, offsetY: 2 }) .width('90%') .constraintSize({ maxWidth: 400 }) } } ``` -------------------------------- ### Make HTTP Requests to AI API using @ohos.net.http in ArkTS Source: https://context7.com/wuyw/test/llms.txt Implements a service class to call AI APIs using the @ohos.net.http module, as HarmonyOS does not support the Web Fetch API. It handles request construction, sending, response parsing, and ensures the HTTP request object is destroyed in a finally block. ```arkts import http from '@ohos.net.http'; export interface Message { role: string; content: string; } interface APIConfig { baseUrl: string; model: string; apiKey: string; } export class AIService { static async callAI(messages: Message[], config: APIConfig): Promise<string> { const httpRequest = http.createHttp(); try { const requestBody: string = JSON.stringify({ model: config.model, messages: messages, temperature: 0.7, max_tokens: 2000, stream: false }); const headers: Record<string, string> = { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + config.apiKey }; const response = await httpRequest.request(config.baseUrl, { method: http.RequestMethod.POST, header: headers, extraData: requestBody, connectTimeout: 60000, readTimeout: 60000 }); if (response.responseCode === 200) { const responseText: string = response.result ? response.result.toString() : ''; const result: Record<string, Object> = JSON.parse(responseText) as Record<string, Object>; const choices = result['choices'] as Array<Record<string, Object>>; if (choices !== undefined && choices.length > 0) { const message = choices[0]['message'] as Record<string, string>; return message['content'] || ''; } return ''; } else { throw new Error('API request failed: ' + response.responseCode.toString()); } } finally { httpRequest.destroy(); } } } ``` -------------------------------- ### Input Box with Send Button in ArkTS Source: https://context7.com/wuyw/test/llms.txt Provides an input box with a send button for messaging interfaces in ArkTS. It includes input validation for character count (up to 500 characters) and conditionally enables/disables the send button based on input presence and sending status. A loading indicator is shown when sending. ```arkts Column() { if (this.inputText.length > 0) { Row() { Text(`${this.inputText.length}/500`) .fontSize(12) .fontColor(this.inputText.length > 500 ? '#FF6B6B' : '#8E8EA0') } .width('100%') .justifyContent(FlexAlign.End) .padding({ right: 8, bottom: 4 }) } Row() { TextInput({ placeholder: 'Enter message...', text: this.inputText }) .layoutWeight(1) .maxLength(500) .height(48) .backgroundColor('#40414F') .borderRadius(24) .padding({ left: 20, right: 20 }) .fontSize(16) .fontColor('#FFFFFF') .placeholderColor('#8E8EA0') .caretColor('#19C37D') .onChange((value: string) => { this.inputText = value; }) .onSubmit(() => { if (this.inputText.length <= 500) { this.sendMessage(); } }) Button() { if (this.isSending) { LoadingProgress() .width(20) .height(20) .color('#FFFFFF') } else { Text('Send') .fontSize(14) .fontColor('#FFFFFF') } } .width(48) .height(48) .borderRadius(24) .backgroundColor(this.inputText.trim() !== '' && !this.isSending ? '#19C37D' : '#565869') .enabled(this.inputText.trim() !== '' && !this.isSending) .margin({ left: 8 }) .onClick(() => { this.sendMessage(); }) } .width('100%') } ```