Location>code7788 >text

Hongmeng NEXT Development Case: Simplified Chinese Traditional Chinese Converter

Popularity:350 ℃/2024-11-21 09:59:10

[Introduction]

Simplified Traditional Chinese Converter is a useful little tool that helps users easily convert between Simplified Chinese and Traditional Chinese. For users who need to frequently deal with documents from both sides of the * Strait, such a tool is undoubtedly a good helper to improve work efficiency. This case will show how to utilize the components and services provided by Hongmeng NEXT, combined with the third-party library @nutpi/chinese_transverter, to realize this function.

[Environmental Preparation]

- Operating system: Windows 10
- Development Tools: DevEco Studio NEXT Beta1 Build Version: 5.0.3.806
- Target device: Huawei Mate60 Pro
- Development language: ArkTS
- Framework: ArkUI
- API version: API 12
- Tripartite library: chinese_transverter

[Realization steps]

1. Project initialization

First, make sure that your development environment has the relevant toolchain for Hongmeng NEXT installed. Then, create a new Hongmeng NEXT project.

2. Introduction of third-party libraries

Install the @nutpi/chinese_transverter library using the ohpm command:

ohpm install @nutpi/chinese_transverter

3. Development of core logic

Next, introduce the required modules in the main component of the project and define the state variables and methods. The key here is to set up listeners to respond to changes in the input text and call the conversion function to get the result of the conversion.

import { transverter, TransverterType, TransverterLanguage } from "@nutpi/chinese_transverter";

@Entry
@Component
struct SimplifiedTraditionalConverter {
  @State @Watch('onInputTextChanged') inputText: string = '';
  @State simplifiedResult: string = '';
  @State traditionalResult: string = '';
  @State isInputFocused: boolean = false;

  onInputTextChanged() {
     = transverter({
      type: ,
      str: ,
      language: TransverterLanguage.ZH_CN
    });
     = transverter({
      type: ,
      str: ,
      language: TransverterLanguage.ZH_CN
    });
  }

  private copyToClipboard(text: string): void {
    const clipboardData = (pasteboard.MIMETYPE_TEXT_PLAIN, text);
    const systemClipboard = ();
    (clipboardData);
    ({ message: 'Copied to clipboard' });
  }

  build() {
    // UI build code...
  }
}

4. Building the user interface

In the build method, we build the user interface of the application. The main components here are a scrollable container, input area, result display area, and action buttons.

Scroll() {
  Column() {
    Text("Simplified Chinese to Traditional Chinese converter")
      .width('100%')
      .height(54)
      .fontSize(18)
      .fontWeight(600)
      .backgroundColor()
      .textAlign()
      .fontColor();

    // Input field with clear button
    Column() {
      // ... Omit part of the code...

      Text('Empty')
        .borderWidth(1)
        .borderColor()
        .fontColor()
        .height(50)
        .textAlign()
        .borderRadius(10)
        .fontSize(18)
        .width(`${650 -  * 2}lpx`)
        .margin({ top: `${}lpx` })
        .onClick(() =>  = "");
    }
    .width('650lpx')
    .padding(`${}lpx`)
    .margin({ top: 20 })
    .backgroundColor()
    .borderRadius(10)
    .alignItems();

    // Results area
    // ... Omit part of the code...
  }
  .width('100%')
  .height('100%')
  .backgroundColor("#f2f3f5")
  .align()
  .padding({ bottom: `${}lpx` });
}

[complete code]

// Import the necessary conversion libraries to provide conversion between Simplified Chinese and Traditional Chinese.
import { transverter, TransverterType, TransverterLanguage } from "@nutpi/chinese_transverter";
// Import Clipboard service for copying text to the system clipboard
import { pasteboard } from '@';
// Import the alert service for displaying messages to the user
import { promptAction } from '@';

// Use the @Entry decorator to mark this component as the entry point to the application.
@Entry
  // Use the @Component decorator to define a component named SimplifiedTraditionalConverter
@Component
struct SimplifiedTraditionalConverter {
  // Define the state variable inputText, which stores the original text entered by the user and triggers the onInputTextChanged method when its value changes.
  @State @Watch('onInputTextChanged') inputText: string = '';
  // Define the state variable simplifiedResult, which stores the result of the converted simplification.
  @State simplifiedResult: string = '';
  // Define the state variable traditionalResult to store the traditional result of the conversion.
  @State traditionalResult: string = '';
  // Define the state variable isInputFocused, which indicates whether the input box has gained focus.
  @State isInputFocused: boolean = false;
  // Define theme colors
  @State private themeColor: string = '#439fff';
  // Define the text color
  @State private textColor: string = "#2e2e2e";
  // Define the base inner margin size
  @State private basePadding: number = 30;
  // Define the minimum text area height
  @State private minTextAreaHeight: number = 50;
  // Define the maximum text area height
  @State private maxTextAreaHeight: number = 300;

  // Method triggered when the state of the inputText changes, used to update the result of the conversion.
  onInputTextChanged() {
    // Convert inputText to simplified and update simplifiedResult
     = transverter({
      type: ,
      str: ,
      language: TransverterLanguage.ZH_CN
    });
    // Convert the inputText to traditional and update the traditionalResult.
     = transverter({
      type: ,
      str: ,
      language: TransverterLanguage.ZH_CN
    });
  }

  // Copies the given text to the clipboard and displays a prompt message
  private copyToClipboard(text: string): void {
    const clipboardData = (pasteboard.MIMETYPE_TEXT_PLAIN, text); // Create clipboard data
    const systemClipboard = (); // Get the system clipboard
    (clipboardData); // Setting Clipboard Data
    ({ message: 'Copied to clipboard' }); // Display a prompt that the copy was successful
  }

  // Build the component's UI
  build() {
    Scroll() { // Create scrollable containers
      Column() { // Create a vertical layout in a scrolling container
        // Create header text
        Text("Simplified Chinese to Traditional Chinese converter")
          .width('100%')
          .height(54)
          .fontSize(18)
          .fontWeight(600)
          .backgroundColor()
          .textAlign()
          .fontColor();

        // Create user input fields
        Column() {
          // Create multi-line text input boxes
          TextArea({ text: $$, placeholder: 'Please input Simplified/Traditional characters (support mixed input)' })
            .fontSize(18)
            .placeholderColor( ?  : )
            .fontColor( ?  : )
            .borderColor( ?  : )
            .caretColor()
            .onBlur(() =>  = false) // update the isInputFocused state when the input box loses focus
            .onFocus(() =>  = true) // Update the isInputFocused state when the input box gets focus.
            .borderWidth(1)
            .borderRadius(10)
            .backgroundColor()
            .constraintSize({ minHeight: , maxHeight:  });

          // Create the Clear button
          Text('Empty')
            .borderWidth(1)
            .borderColor()
            .fontColor()
            .height(50)
            .textAlign()
            .borderRadius(10)
            .fontSize(18)
            .width(`${650 -  * 2}lpx`)
            .margin({ top: `${}lpx` })
            .clickEffect({ level: , scale: 0.8 }) // Add a click effect
            .onClick(() =>  = ""); // Clear the input box
        }
        .width('650lpx')
        .padding(`${}lpx`)
        .margin({ top: 20 })
        .backgroundColor()
        .borderRadius(10)
        .alignItems();

        // Create a Traditional Results Display and Replication Area
        Column() {
          // Create Traditional Chinese result titles
          Text(`Traditional results:`)
            .fontWeight(600)
            .fontSize(18)
            .fontColor();

          // Create Traditional Results Display Text
          Text(`${}`)
            .constraintSize({ minHeight: , maxHeight:  })
            .fontColor()
            .fontSize(18)
            .textAlign()
            .copyOption()
            .margin({ top: `${ / 3}lpx` });

          // Create the Copy Traditional Results button
          Text('Copy')
            .enabled( ? true : false) // Buttons are only available if there is a Traditional Chinese result
            .fontColor()
            .backgroundColor()
            .height(50)
            .textAlign()
            .borderRadius(10)
            .fontSize(18)
            .width(`${650 -  * 2}lpx`)
            .margin({ top: `${}lpx` })
            .clickEffect({ level: , scale: 0.8 })
            .onClick(() => ()); // Copy the traditional results to the clipboard
        }
        .width('650lpx')
        .padding(`${}lpx`)
        .backgroundColor()
        .borderRadius(10)
        .margin({ top: `${}lpx` })
        .alignItems();

        // Create an area for displaying and copying simplified results
        Column() {
          // Create Simplified Result Titles
          Text(`Simplified results:`)
            .fontWeight(600)
            .fontSize(18)
            .fontColor();

          // Create Simplified Results Display Text
          Text(`${}`)
            .constraintSize({ minHeight: , maxHeight:  })
            .fontColor()
            .fontSize(18)
            .textAlign()
            .copyOption()
            .margin({ top: `${ / 3}lpx` });

          // Create a Copy Simplified Results button
          Text('Copy')
            .enabled( ? true : false) // Buttons are only available if there is an abbreviated result.
            .fontColor()
            .backgroundColor()
            .height(50)
            .textAlign()
            .borderRadius(10)
            .fontSize(18)
            .width(`${650 -  * 2}lpx`)
            .margin({ top: `${}lpx` })
            .clickEffect({ level: , scale: 0.8 })
            .onClick(() => ()); // Copy the simplified result to the clipboard
        }
        .width('650lpx')
        .padding(`${}lpx`)
        .backgroundColor()
        .borderRadius(10)
        .margin({ top: `${}lpx` })
        .alignItems();
      }
    }
    .width('100%')
    .height('100%')
    .backgroundColor("#f2f3f5")
    .align()
    .padding({ bottom: `${}lpx` });
  }
}