Basic knowledge of ArkTS developed by Hongmeng

1. Introduction to ArkTS

ArkTS is the preferred main application development language for HarmonyOS. Based on TypeScript (TS for short), it matches Harmony's ArkUI framework, and expands corresponding capabilities such as declarative UI and state management, allowing developers to develop cross-terminal applications in a more concise and natural way. Before understanding ArkTS, we need to understand the relationship between ArkTS, TypeScript and JavaScript.

  • JavaScript is a high-level scripting language belonging to the network. It has been widely used in the development of web applications. It is often used to add various dynamic functions to web pages to provide users with smoother and more beautiful browsing effects.
  • TypeScript is a superset of JavaScript. It extends the syntax of JavaScript. It is built by adding static type definitions on the basis of JavaScript. It is an open source programming language.
  • ArkTS is compatible with the TypeScript language, and has expanded capabilities such as declarative UI, state management, and concurrent tasks. It can be considered a superset of TypeScript.

It can be seen that TypeScript is a superset of JavaScript, and ArkTS is a superset of TypeScript. Their relationship is shown in the figure below.

insert image description here

Before learning the declarative syntax of ArkTS, you need to have a basic understanding of TypeScript syntax. There is not much introduction here. For details, please refer to: Introduction to ArkTS Development Language

2. The birth background of ArkTS

In terms of language runtime, although TS has type support, it is only used for compile-time checking, and then converted to JS through TS Compiler, and the runtime engine still cannot take advantage of type system-based optimization.

In terms of rendering, due to its own complexity and historical reasons, mainstream web engines have a certain gap with common OS native frameworks in terms of performance and resource occupation, especially on mobile platforms. React Native has improved the performance experience to a certain extent through the improvement of the rendering architecture, but there are still some deficiencies in the consistency of platform rendering effects and capabilities, as well as JS language performance.

Then, Flutter launched by Google at the end of 2018 took another path, combined with the new language Dart, introduced a new declarative development paradigm, and built a cross-platform independent rendering capability based on Skia's self-drawing engine. This is a relatively innovative solution, but there are still some shortcomings, such as the increased learning cost of the Dart language. Interestingly, Google launched a new development framework Jetpack Compose in 2021, combining Kotlin's language ecology to design a new declarative UI development paradigm.

When we were thinking about how to build a new application development framework, we focused on the following dimensions:

  • language ecology
  • development efficiency
  • performance experience
  • Cross-device/cross-platform capability

Since JS/TS has a relatively complete developer ecology, the language is relatively friendly, and there are corresponding standard organizations that can gradually evolve, the JS/TS language has become a relatively natural choice. Based on JS/TS, in the dimension of the development framework, we have made the following architecture evolution design:

  • Through the web-like development paradigm based on JS extensions, it supports mainstream front-end development methods. At the same time, in terms of runtime, through the enhancement of the rendering engine (platform-independent self-drawing mechanism, declarative UI back-end design, dynamic layout/polymorphic UI components, etc.), language compiler and runtime optimization enhancements (code pre-compilation, efficient FFI-Foreign Function Interface, engine miniaturization, etc.), the relevant performance experience is further improved, and it can be deployed on different devices (including lightweight devices with 100 KB-level memory). In addition, through the design of the platform adaptation layer, a cross-OS platform infrastructure is constructed.
  • Through the declarative UI development paradigm based on TS extensions, a simpler and more natural development experience is provided. In terms of runtime, on the basis of the above, combined with the type optimization of the language runtime and the flattened pipeline technology of the rendering runtime, the performance experience is further improved.

The following figure describes the overall architecture of the ArkUI development framework:
insert image description here

It can be seen that the language used in the declarative UI paradigm based on TS extensions is ArkTS. The following uses a specific example to briefly introduce the new declarative development paradigm based on ArkTS from the perspective of application development. For example, the following code is the ArkTS declarative development paradigm (somewhat similar to Flutter):

@Entry
@Component
struct Index {
  @State message: string = 'Hello World'
  build() {
    Column() {
      Text('Hello').fontSize(30)
      Text(this.message).fontSize(30)
      Button(){
        Text('Click Me').fontSize(30)
      }.onClick(()=>{
        this.message='ArkUI'
      })
      .width(200)
      .height(50)
    }
  }
}

The basic components of the ArkTS declarative development paradigm contained in this example are described as follows:

  • decorator

Used to decorate classes, structures, methods, and variables to give them special meanings, such as @Entry, @Component, and @State in the above example are all decorators. Specifically, @Component indicates that this is a custom component; @Entry indicates that this is an entry component; @State indicates the state variable in the component, and this state change will cause UI changes.

  • custom components

A reusable UI unit that can be combined with other components, such as the above struct Hello decorated with @Component.

  • UI description

A declarative way to describe the structure of the UI, such as the code block inside the above build() method.

  • built-in components

The default built-in basic and layout components in the framework can be directly called by developers, such as Column, Text, Divider, and Button in the example.

  • event method

It is used to add the response logic of the component to the event, which is uniformly set through the event method, such as onClick() following the Button.

  • attribute method

It is used to configure component properties, which are set uniformly through property methods, such as fontSize(), width(), height(), color(), etc. Multiple properties can be set through chain calls.

In general, the ArkUI development framework designs a unified UI development paradigm by extending mature languages, combining grammatical sugar or native language meta-programming capabilities, UI components, state management, etc., and combining native language capabilities to complete application development.

3. ArkUI planning and evolution

Next, ArkUI will make some improvements in the following two aspects:

3.1 A more complete type system

A special runtime has been designed and implemented, using the type input of ArkTS to obtain high running performance at the beginning of program execution (unlike other traditional JS engines that need to be warmed up to obtain high performance). However, the current type system still considers the compatibility mode in the runtime design, that is, at runtime, when the object type changes, it will go through the Bailout mechanism, so that the program can still run normally when the type does not match. A more extreme way is to introduce a specific mode to support the expression of a certain type, and when the developer can specify the type, provide the corresponding information, so that the runtime can further improve the performance experience through targeted design. In addition, ArkTS will also expand some new types in the type system in the future, which will provide a better performance experience in the optimization combined with the runtime.

3.2 More flexible parallel processing

Current mobile devices are basically multi-core devices (including multi-core with the same configuration and different configurations of large and small cores), and some devices also carry multiple computing chips (CPU/GPU/NPU/…). How to make full use of multi-core devices and even heterogeneous chips in terms of language concurrency features is an important topic. At present, we are still using the industry-common Actor-like concurrency interface—Worker, which makes up for some disadvantages of the Actor model, that is, allowing users to transfer and share a large number of Buffers to avoid copying overhead during communication.

However, developers still need to manage the life cycle of Worker by themselves, and it is not very convenient to use Worker to trigger an asynchronous parallel task. We are already trying to encapsulate a task interface on the Actor model to make it easier for users to use multi-core to trigger asynchronous parallel tasks. We have also been paying attention to the development and runtime implementation of the concurrency features of Swift, Dart, Kotlin, and Go. The introduction of the static type model in the specific mode of ArkTS will also bring more possibilities for high-performance implementation of the concurrency mechanism, such as object freezing, ownership transfer, value semantics, etc. We will continue to work on providing concise and efficient concurrency APIs to help application developers develop high-performance applications more easily.

Of course, the ArkTS and ArkUI development frameworks are still very young, and there are many other aspects that will continue to evolve, such as the further improvement of UI customization capabilities, the further optimization of language runtime and cross-language interaction, the expansion of cross-OS platform capabilities, and the distributed development paradigm.

4. ArkTS development practice

4.1 Basic concepts of declarative UI

The application interface is composed of pages. ArkTS is provided by the ArkUI framework and is used to develop the interface in a declarative development paradigm. The process of building a page with a declarative UI is actually a process of combining components. The idea of ​​a declarative UI is mainly reflected in two aspects:

  • Describe the rendering results of the UI, no need to care about the process;
  • State-driven view updates;

Similar to Apple's SwiftUI by combining Views and Android Jetpack Compose by combining @Composable functions, ArkUI, as a UI development framework for HarmonyOS application development, uses the ArkTS language to build custom components, and completes page construction by combining custom components.

4.2 Custom components

ArkTS declares the component name through struct, and uses @Component and @Entry decorators to form a custom component. Moreover, the custom component decorated with @Entry and @Component is used as the entry of the page, and it will be rendered first when the page is loaded. for example:

@Entry
@Component
struct Index {
  ...
}

The build method needs to be used in the custom component to describe the UI.

@Entry
@Component
 struct Index
   ...
   build() {
   ...
  } 
}

At the same time, the build method can accommodate built-in components and other custom components, and the content rendered in it is the content displayed on the final page.

4.3 Configuration properties and layout

Custom components usually use a combination of base components and built-in components such as container components. But sometimes the style of the built-in components can't meet our needs, ArkTS provides property methods to describe the style of the interface. Property methods support the following usages:

  • Constant passing: use fontSize(50) to configure font size
Text('Hello World').fontSize(50)
  • Variable transfer: After the corresponding variable is defined in the component, the variable can be used in the form of this.variable
Text('Hello World').fontSize(this.size)
  • Chain call: When configuring multiple properties, ArkTS provides a chain call method, which is configured continuously through the '.' method
Text('Hello World').fontSize(this.size).width(100).height(100)
  • Built-in enumeration types: ArkTS has many built-in enumeration types, such as Color, FontWeight, etc.
Text('Hello World').fontColor(Color.Red).fontWeight(FontWeight.Bold)

4.4 State change

In actual development, the content of the page is not constant, and the content of the page may need to change. At this time, state management is needed, similar to the setState of the front end. However, ArkTS will automatically refresh after changes.

The characteristic of the declarative UI is that the UI is automatically refreshed as the data changes. Here we define a variable isComplete of type boolean. After it is decorated with @State, the binding between the data and the view is established in the framework, and the change of its value affects the display of the UI.

@State isComplete : boolean = false;

The role of the @State decorator is as shown in the figure below.

insert image description here

4.5 Loop rendering list

When we have multiple pieces of to-do data that need to be displayed on the page, we can use the ForEach loop rendering syntax. For example, there is the following set of data:

total_Tasks:Array<string> = [
  '早起晨练',
  '准备早餐',
  '阅读名著',
  '学习ArkTS',
  '看剧放松'
]

Here is a complete piece of code:

@Entry
@Component
struct ToDoList {
   ...
   build() {
     Row() {
       Column() {
         Text(...)
           ...
         ForEach(this.totalTasks,(item) => {
           TodoItem({content:item})
         },...)
       }
       .width('100%')
     }
     .height('100%')
   }
 }

Reference Code

Guess you like

Origin blog.csdn.net/xiangzhihong8/article/details/131845607