提交 1679c579 编写于 作者: E ester.zhou

Update docs (21636)

Signed-off-by: Nester.zhou <ester.zhou@huawei.com>
上级 47cb75c3
......@@ -7,16 +7,16 @@ ArkTS is the preferred main programming language for application development in
The following syntaxes in TS are restricted in ArkTS:
- Static typing is enforced. Static typing is one of the most important features of ArkTS. If the program is statically typed, i.e. all types are known at the compile time, it’s much easier to understand which data structures are used in the code. At the same time, since all types are known before the program actually runs, code correctness can be verified by the compiler, which eliminates many runtime type checks and improves the performance.
- Static typing is enforced. Static typing is one of the most important features of ArkTS. If the program is statically typed, that is, all types are known at the compile time, it's much easier to understand which data structures are used in the code. At the same time, since all types are known before the program actually runs, code correctness can be verified by the compiler, which eliminates many runtime type checks and improves the performance.
- Changing object layout in runtime is prohibited. To achieve maximum performance benefits, ArkTS requires that layout of objects does not change during program execution.
- Semantics of operators is restricted. To achieve better performance and encourage developers to write cleaner code, ArkTS restricts the semantics of operators. Such as, the binary `+` operator supports only for strings and numbers but not for objects.
- Semantics of operators is restricted. To achieve better performance and encourage developers to write cleaner code, ArkTS restricts the semantics of operators. For example, the binary `+` operator is supported for strings and numbers, but not for objects.
- structural typing is not supported. Support for structural typing is a major feature which needs lots of consideration and careful implementation in language specification, compiler and runtime. Currently, ArkTS does not supports structural typing. The team will be ready to reconsider based on real-world scenarios and feedback.
- Structural typing is not supported. Support for structural typing is a major feature that needs lots of consideration and careful implementation in language specification, compiler and runtime. Currently, ArkTS does not supports structural typing. The team will be ready to reconsider this feature based on real-world scenarios and feedback.
The added features offered by ArkTS for ArkUI framework include the following:
The added features offered by ArkTS for the ArkUI framework include the following:
- [Basic syntax](arkts-basic-syntax-overview.md): ArkTS defines declarative UI description, custom components, and dynamic extension of UI elements. All these, together with built-in components, event methods, and attribute methods in ArkUI, jointly underpin UI development.
......
......@@ -36,7 +36,7 @@ LocalStorage provides two decorators based on the synchronization type of the co
## Restrictions
- Once created, the type of a named attribute cannot be changed. Subsequent calls to **Set** must set a value of same type.
- LocalStorage provides page-level storage. The [GetShared](../reference/arkui-ts/ts-state-management.md#getshared9) API can only obtain the LocalStorage instance transferred through [windowStage.loadContent](../reference/apis/js-apis-window.md#loadcontent9) in the current stage. Otherwise, **undefined** is returned. Example: [Sharing a LocalStorage Instance from UIAbility to One or More Pages](#sharing-a-localstorage-instance-from-uiability-to-one-or-more-pages).
- LocalStorage provides page-level storage. The [GetShared](../reference/arkui-ts/ts-state-management.md#getshared10) API can only obtain the LocalStorage instance passed through [windowStage.loadContent](../reference/apis/js-apis-window.md#loadcontent9) in the current stage. If the instance is not available, **undefined** is returned. For the example, see [Example of Sharing a LocalStorage Instance from UIAbility to One or More Pages](#example-of-sharing-a-localstorage-instance-from-uiability-to-one-or-more-pages).
## \@LocalStorageProp
......@@ -300,9 +300,9 @@ struct CompA {
```
### State Variable Synchronization Between Sibling Nodes
### Example of Syncing State Variable Between Sibling Components
This example shows how to use \@LocalStorageLink to create a two-way synchronization for the state between sibling nodes.
This example shows how to use \@LocalStorageLink to create a two-way synchronization for the state between sibling components.
Check the changes in the **Parent** custom component.
......@@ -377,7 +377,7 @@ Changes in the **Child** custom component:
```
### Sharing a LocalStorage Instance from UIAbility to One or More Pages
### Example of Sharing a LocalStorage Instance from UIAbility to One or More Pages
In the preceding examples, the LocalStorage instance is shared only in an \@Entry decorated component and its owning child component (a page). To enable a LocalStorage instance to be shared across pages, you can create a LocalStorage instance in the owning UIAbility and call windowStage.[loadContent](../reference/apis/js-apis-window.md#loadcontent9).
......
# Introduction
Welcome to the tutorial for ArkTS, a TypeScript-based programming language
designed specifically to build high-performance mobile applications!
Welcome to the tutorial for ArkTS, a TypeScript-based programming language designed specifically to build high-performance mobile applications!
ArkTS is optimized to provide better performance and efficiency, while still
maintaining the familiar syntax of TypeScript.
ArkTS is optimized to provide better performance and efficiency, while still maintaining the familiar syntax of TypeScript.
As mobile devices continue to become more prevalent in our daily lives,
there is a growing need for programming languages optimized for the
mobile environment. Many current programming languages were not designed with
mobile devices in mind, resulting in slow and inefficient applications that
drain battery life. ArkTS has been specifically designed to address such concerns
by prioritizing higher execution efficiency.
As mobile devices continue to become more prevalent in our daily lives, there is a growing need for programming languages optimized for the mobile environment. Many current programming languages were not designed with mobile devices in mind, resulting in slow and inefficient applications that drain battery life. ArkTS has been specifically designed to address such concerns by prioritizing higher execution efficiency.
ArkTS is based on the popular programming language TypeScript that extends
JavaScript by adding type definitions. TypeScript is well-loved by many developers as it
provides a more structured approach to coding in JavaScript. ArkTS aims to
keep the look and feel of TypeScript to enable a seamless transition for the existing
TypeScript developers, and to let mobile developers learn ArkTS quickly.
ArkTS is based on the popular programming language TypeScript that extends JavaScript by adding type definitions. TypeScript is well-loved by many developers as it provides a more structured approach to coding in JavaScript. ArkTS aims to keep the look and feel of TypeScript to enable a seamless transition for the existing TypeScript developers, and to let mobile developers learn ArkTS quickly.
One of the key features of ArkTS is its focus on low runtime overhead.
ArkTS imposes stricter limitations on the TypeScript’s dynamically typed features,
reducing runtime overhead and allowing faster execution. By eliminating
the dynamically typed features from the language, ArkTS code can be compiled
ahead-of-time more efficiently, resulting in faster application startup and
lower power consumption.
Interoperability with JavaScript was a critical consideration in the ArkTS language
design. Many mobile app developers already have TypeScript and JavaScript code and libraries
they would want to reuse. ArkTS has been designed for seamless JavaScript
interoperability, making it easy for the developers to integrate the JavaScript code
into their applications and vice versa. This will allow the developers to
use their existing codebases and libraries to leverage the power of our
new language.
To ensure best experience for UI app development for OpenHarmony ecosystem,
ArkTS provides support for ArkUI, including its declarative syntax and other
features. Since this feature is outside the scope of the “stock” TypeScript, a verbose
ArkUI example is provided in a separate chapter.
This tutorial will guide the developers through the core features, syntax,
and best practices of ArkTS. After reading this tutorial through the end,
the developers will be able to build performant and efficient mobile
applications in ArkTS.
ArkTS imposes stricter limitations on the TypeScript's dynamically typed features, reducing runtime overhead and allowing faster execution. By eliminating the dynamically typed features from the language, ArkTS code can be compiled ahead-of-time more efficiently, resulting in faster application startup and lower power consumption.
Interoperability with JavaScript was a critical consideration in the ArkTS language design. Many mobile app developers already have TypeScript and JavaScript code and libraries they would want to reuse. ArkTS has been designed for seamless JavaScript interoperability, making it easy for the developers to integrate the JavaScript code into their applications and vice versa. This will allow the developers to use their existing codebases and libraries to leverage the power of our new language.
To ensure best experience for UI app development for OpenHarmony ecosystem, ArkTS provides support for ArkUI, including its declarative syntax and other features. Since this feature is outside the scope of the "stock" TypeScript, a verbose ArkUI example is provided in a separate chapter.
This tutorial will guide you through the core features, syntax, and best practices of ArkTS. After reading this tutorial through the end, you will be able to build performant and efficient mobile applications in ArkTS.
# The Basics
......@@ -50,15 +23,14 @@ applications in ArkTS.
Declarations in ArkTS introduce:
- variables,
- constants,
- functions, and
- types.
- Variables
- Constants
- Functions
- Types
### Variable Declaration
A declaration starting with the keyword `let` introduces a variable which
can have different values during program execution.
A declaration starting with the keyword `let` introduces a variable which can have different values during program execution.
```typescript
let hi: string = "hello"
......@@ -67,8 +39,7 @@ hi = "hello, world"
### Constant Declaration
A declaration starting with the keyword `const` introduces a read-only
constant that can be assigned only once.
A declaration starting with the keyword `const` introduces a read-only constant that can be assigned only once.
```typescript
const hello: string = "hello"
......@@ -78,16 +49,13 @@ A compile-time error occurs if a new value is assigned to a constant.
### Automatic Type Inference
As ArkTS is a statically typed language, the types of all entities, like
variables and constants, have to be known at compile time.
As ArkTS is a statically typed language, the types of all entities, like variables and constants, have to be known at compile time.
However, developers do not need to explicitly specify the type of a declared
entity if a variable or a constant declaration contains an initial value.
All cases that allow the type to be inferred automatically are specified in
the ArkTS Specification.
However, developers do not need to explicitly specify the type of a declared entity if a variable or a constant declaration contains an initial value.
Both variable declarations are valid, and both variables are of the `string`
type:
All cases that allow the type to be inferred automatically are specified in the ArkTS Specification.
Both variable declarations are valid, and both variables are of the `string` type:
```typescript
let hi1: string = "hello"
......@@ -96,32 +64,30 @@ let hi2 = "hello, world"
## Types
`Class`, `interface`, `function`, `enum`, `union` types, and type
`aliases` are described in the corresponding sections.
`Class`, `interface`, `function`, `enum`, `union` types, and type `aliases` are described in the corresponding sections.
### Numeric Types
ArkTS has `number` and `Number` numeric types. Any integer and
floating-point values can be assigned to a variable of these types.
ArkTS has `number` and `Number` numeric types. Any integer and floating-point values can be assigned to a variable of these types.
Numeric literals include integer literals and floating-point literals
with the decimal base.
Integer literals include the following:
* decimal integers that consist of a sequence of digits. For example: `0`, `117`, `-345`;
* hexadecimal integers that start with 0x (or 0X), and can contain digits (0-9) and letters a-f or A-F. For example: `0x1123`, `0x00111`, `-0xF1A7`;
* octal integers that start with 0o (or 0O) and can only contain digits (0-7). For example: `0o777`;
* binary integers that start with 0b (or 0B), and can only contain the digits 0 and 1. For example: `0b11`, `0b0011`, `-0b11`.
* Decimal integers that consist of a sequence of digits. For example: `0`, `117`, `-345`.
* Hexadecimal integers that start with 0x (or 0X), and can contain digits (0-9) and letters a-f or A-F. For example: `0x1123`, `0x00111`, `-0xF1A7`.
* Octal integers that start with 0o (or 0O) and can only contain digits (0-7). For example: `0o777`.
* Binary integers that start with 0b (or 0B), and can only contain the digits 0 and 1. For example: `0b11`, `0b0011`, `-0b11`.
A floating-point literal includes the following:
* decimal integer, optionally signed (i.e., prefixed with “+” or “-“);
* decimal point (“.”);
* fractional part (represented by a string of decimal digits);
* exponent part that starts with “e” or “E”, followed by an optionally signed (i.e., prefixed with “+” or “-”) integer.
* Decimal integer, optionally signed (i.e., prefixed with "+" or "-");
* Decimal point (".").
* Fractional part (represented by a string of decimal digits).
* Exponent part that starts with "e" or "E", followed by an optionally signed (i.e., prefixed with "+" or "-") integer.
For example:
Example:
```typescript
let n1 = 3.14
......@@ -139,8 +105,7 @@ function factorial(n: number) : number {
### `Boolean`
The `boolean` type represents logical values that are either `true`
or `false`.
The `boolean` type represents logical values that are either `true` or `false`.
Usually variables of this type are used in conditional statements:
......@@ -156,12 +121,9 @@ if (isDone) {
### `String`
A `string` is a sequence of characters; some characters can be set by using
escape sequences.
A `string` is a sequence of characters; some characters can be set by using escape sequences.
A `string` literal consists of zero or more characters enclosed in single
(’) or double quotes (“). The special form of string literals are template
literals enclosed in backtick quotes (\`).
A `string` literal consists of zero or more characters enclosed in single (') or double quotes ("). The special form of string literals are template literals enclosed in backtick quotes (\`).
```typescript
let s1 = "Hello, world!\n"
......@@ -185,18 +147,12 @@ let instance: Class <void>
### `Object` Type
An `Object` class type is a base type for all reference types. Any value,
including values of primitive types (they will be automatically boxed), can
be directly assigned to variables of the type `Object`.
An `Object` class type is a base type for all reference types. Any value, including values of primitive types (they will be automatically boxed), can be directly assigned to variables of the type `Object`.
### `Array` Type
An `array` is an object comprised of elements of data types assignable to
the element type specified in the array declaration.
A value of an `array` is set by using *array composite literal*, that is a
list of zero or more expressions enclosed in square brackets ([]). Each
expression represents an element of the `array`. The length of the `array`
is set by the number of expressions. Index of the first array element is 0.
An `array` is an object comprised of elements of data types assignable to the element type specified in the array declaration.
A value of an `array` is set by using *array composite literal*, that is a list of zero or more expressions enclosed in square brackets ([]). Each expression represents an element of the `array`. The length of the `array` is set by the number of expressions. Index of the first array element is 0.
The following example creates the `array` with three elements:
......@@ -206,18 +162,15 @@ let names: string[] = ["Alice", "Bob", "Carol"]
### `Enum` Type
An `enum` type is a value type with a defined set of named values called
enum constants.
In order to be used, an `enum` constant must be prefixed with an enum
`type` name.
An `enum` type is a value type with a defined set of named values called enum constants.
In order to be used, an `enum` constant must be prefixed with an enum `type` name.
```typescript
enum Color { Red, Green, Blue }
let c: Color = Color.Red
```
A constant expression can be used to explicitly set the value of an `enum`
constant.
A constant expression can be used to explicitly set the value of an `enum` constant.
```typescript
enum Color { White = 0xFF, Grey = 0x7F, Black = 0x00 }
......@@ -226,9 +179,7 @@ let c: Color = Color.Black
### `Union` Type
A `union` type is a reference type which is created as a combination
of other types. Values of union types can be valid values of all types
a union was created from.
A `union` type is a reference type which is created as a combination of other types. Values of union types can be valid values of all types a union was created from.
```typescript
class Cat {
......@@ -251,7 +202,7 @@ animal = 42
There are different mechanisms to get a value of a particular type from a union.
For example
Example:
```typescript
class Cat { sleep () {}; meow () {} }
......@@ -273,8 +224,7 @@ animal.sleep () // Any animal can sleep
### Type `Aliases`
Type `aliases` provide names for anonymous types (array, function, object
literal or union types) or alternative names for existing types.
Type `aliases` provides names for anonymous types (array, function, object literal or union types) or alternative names for existing types.
```typescript
type Matrix = number[][]
......@@ -287,24 +237,22 @@ type NullableObject = Object | null
### Assignment Operators
Simple assignment operator ‘=’ is used as in “x = y”.
Simple assignment operator '=' is used as in "x = y".
Compound assignment operators combine an assignment with an operator, where
`x op = y` equals `x = x op y`.
Compound assignment operators combine an assignment with an operator, where `x op = y` equals `x = x op y`.
Compound assignment operators are as follows: `+=`, `-=`, `*=`, `/=`,
`%=`, `<<=`, `>>=`, `>>>=`, `&=`, `|=`, `^=`.
Compound assignment operators are as follows: `+=`, `-=`, `*=`, `/=`, `%=`, `<<=`, `>>=`, `>>>=`, `&=`, `|=`, `^=`.
### Comparison Operators
| Operator | Description |
|------------|------------------------------------------------------------------------|
| `==` | returns true if both operands are equal |
| `!=` | returns true if both operands are not equal |
| `>` | returns true if the left operand is greater than the right |
| `>=` | returns true if the left operand is greater than or equal to the right |
| `<` | returns true if the left operand is less then the right |
| `<=` | returns true if the left operand is less than or equal to the right |
| Operator | Description |
| -------- | ------------------------------------------------------------ |
| `==` | Returns true if both operands are equal. |
| `!=` | Returns true if both operands are not equal. |
| `>` | Returns true if the left operand is greater than the right. |
| `>=` | Returns true if the left operand is greater than or equal to the right. |
| `<` | Returns true if the left operand is less than the right. |
| `<=` | Returns true if the left operand is less than or equal to the right. |
### Arithmetic Operators
Unary operators are `-`, `+`, `--` and `++`.
......@@ -333,15 +281,15 @@ Binary operators are as follows:
| Operator | Description |
|------------|---------------|
| `a && b` | logical AND |
| `a \|\| b` | logical OR |
| `! a` | logical NOT |
| `a && b` | Logical AND |
| `a \|\| b` | Logical OR |
| `! a` | Logical NOT |
## Control Flow
### `If` Statements
An `if` statement is used to execute a sequence of statements when a logical
condition is `true`, or another set of statements (if provided) otherwise.
An `if` statement is used to execute a sequence of statements when a logical condition is `true`, or another set of statements (if provided) otherwise.
The `else` part can also contain more `if` statements.
An `if` statement looks as follows:
......@@ -356,9 +304,7 @@ if (condition1) {
}
```
All conditional expressions must be of the type `boolean` or other types
(`string`, `number`, etc.). For types other than `boolean`, implicit
conversion rules apply:
All conditional expressions must be of the type `boolean` or other types (`string`, `number`, etc.). For types other than `boolean`, implicit conversion rules apply:
```typescript
let s1 = "Hello"
......@@ -374,8 +320,7 @@ if (s2.length != 0) {
### `Switch` Statements
A `switch` statement is used to execute a sequence of statements that match
the value of a switch expression.
A `switch` statement is used to execute a sequence of statements that match the value of a switch expression.
A `switch` statement looks as follows:
......@@ -397,27 +342,21 @@ default:
}
```
The `switch` expression type must be of `number`, `enum` or `string`
types.
The `switch` expression type must be of `number`, `enum` or `string` types.
Each label must be either a constant expression or the name of an enum constant.
If the value of a `switch` expression equals the value of some label, then
the corresponding statements are executed.
If the value of a `switch` expression equals the value of some label, then the corresponding statements are executed.
If there is no match, and the `switch` has the default clause, then the
default statements are executed.
If there is no match, and the `switch` has the default clause, then the default statements are executed.
An optional `break` statement allows to break out of the `switch` and
continue executing the statement that follows the `switch`.
An optional `break` statement allows you to break out of the `switch` and continue executing the statement that follows the `switch`.
If there is no `break`, then the next statements in the `switch` is
executed.
If there is no `break`, then the next statements in the `switch` are executed.
### Conditional Expressions
The conditional expression `? :` uses the `boolean` value of the first
expression to decide which of two other expressions to evaluate.
The conditional expression `? :` uses the `boolean` value of the first expression to decide which of two other expressions to evaluate.
A conditional expression looks as follows:
......@@ -425,9 +364,7 @@ A conditional expression looks as follows:
condition ? expression1 : expression2
```
The condition must be a logical expression. If that logical expression is
`true`, then the first expression is used as the result of the ternary
expression; otherwise, the second expression is used.
The condition must be a logical expression. If that logical expression is `true`, then the first expression is used as the result of the ternary expression; otherwise, the second expression is used.
Example:
......@@ -438,8 +375,7 @@ let message = isValid ? 'Valid' : 'Failed'
### `For` Statements
A `for` statement is executed repeatedly until the specified loop exit
condition is `false`.
A `for` statement is executed repeatedly until the specified loop exit condition is `false`.
A `for` statement looks as follows:
......@@ -451,15 +387,10 @@ for ([init]; [condition]; [update]) {
When a `for` statement is executed, the following process takes place:
1. An `init` expression is executed, if any. This expression usually
initializes one or more loop counters.
2. The condition is evaluated. If the value of condition is `true`, or
if the conditional expression is omitted, then the statements in the
`for` body are to be executed. If the value of condition is `false`,
then the `for` loop terminates.
1. An `init` expression is executed, if any. This expression usually initializes one or more loop counters.
2. The condition is evaluated. If the value of condition is `true`, or if the conditional expression is omitted, then the statements in the `for` body are to be executed. If the value of condition is `false`, then the `for` loop terminates.
3. The statements of the `for` body are executed.
4. If there is an `update` expression, then the `update` expression
is executed.
4. If there is an `update` expression, then the `update` expression is executed.
5. Go back to step 2.
Example:
......@@ -491,8 +422,7 @@ for (let ch of "a string object") { /* process ch */ }
### `While` Statements
A `while` statement has its body statements executed as long as the
specified condition evaluates to `true`.
A `while` statement has its body statements executed as long as the specified condition evaluates to `true`.
A `while` statement looks as follows:
......@@ -517,8 +447,7 @@ while (n < 3) {
### `Do-while` Statements
`do-while` statements are executed repetitively until a specified
condition evaluates to false.
`do-while` statements are executed repetitively until a specified condition evaluates to false.
A `do-while` statement looks as follows:
......@@ -555,8 +484,7 @@ while (true) {
}
```
A `break` statement with a label identifier transfers control out of the
enclosing statement to the one which has the same label identifier.
A `break` statement with a label identifier transfers control out of the enclosing statement to the one which has the same label identifier.
Example:
......@@ -573,8 +501,7 @@ label: while (true) {
### `Continue` Statements
A `continue` statement stops the execution of the current loop iteration
and passes control to the next iteration.
A `continue` statement stops the execution of the current loop iteration and passes control to the next iteration.
Example:
......@@ -606,8 +533,7 @@ try {
}
```
The example below shows the `throw` and `try` statements used to handle
the zero division case:
The example below shows the `throw` and `try` statements used to handle the zero division case:
```typescript
class ZeroDivisor extends Error {}
......@@ -655,8 +581,7 @@ function processData(s: string) {
## Function Declarations
A function declaration introduces a named function, specifying its name,
parameters, return type and body.
A function declaration introduces a named function, specifying its name, parameters, return type and body.
Below is a simple function with two string parameters and string return type:
......@@ -668,8 +593,7 @@ function add(x: string, y: string): string {
```
For every parameter its type annotation must be specified.
An optional parameter allows to omit the corresponding argument when
calling a function. The last parameter of a function can be a rest parameter.
An optional parameter allows you to omit the corresponding argument when calling a function. The last parameter of a function can be a rest parameter.
## Optional Parameters
......@@ -686,8 +610,7 @@ function hello(name?: string) {
```
Another form contains an expression that specifies a default value.
If the corresponding argument to such parameter is omitted in a function call,
then this parameter’s value is default.
If the corresponding argument to such parameter is omitted in a function call, then this parameter's value is default.
```typescript
function multiply(n: number, coeff: number = 2): number {
......@@ -699,8 +622,7 @@ multiply(2, 3) // returns 2*3
## The Rest Parameter
The last parameter of a function can be a rest parameter.
It allows functions or methods to take unlimited number of arguments.
The last parameter of a function can be a rest parameter. It allows functions or methods to take unlimited number of arguments.
```typescript
function sum(...numbers: number[]): number {
......@@ -716,8 +638,7 @@ sum(1, 2, 3) // returns 6
## Return Types
If function return type can be inferred from its body content, then it can
be omitted from the function declaration.
If function return type can be inferred from its body content, then it can be omitted from the function declaration.
```typescript
// Explicit return type
......@@ -727,9 +648,7 @@ function foo(): string { return "foo" }
function goo() { return "goo" }
```
The return type of a function that does not need to return a value can be
explicitly specified as `void` or omitted altogether. No return statement
is needed for such functions.
The return type of a function that does not need to return a value can be explicitly specified as `void` or omitted altogether. No return statement is needed for such functions.
Both notations below are valid:
......@@ -740,16 +659,13 @@ function hi2(): void { console.log("hi") }
## Function Scope
Variables and other entities defined in a function are local to the function
and cannot be accessed from the outside.
Variables and other entities defined in a function are local to the function and cannot be accessed from the outside.
If the name of a variable defined in the function is equal to the name of an
entity in the outer scope, then the local definition shadows the outer entity.
If the name of a variable defined in the function is equal to the name of an entity in the outer scope, then the local definition shadows the outer entity.
## Function Calls
Calling a function actually leads to the execution of its body, while
the arguments of the call are assigned to the function parameters.
Calling a function actually leads to the execution of its body, while the arguments of the call are assigned to the function parameters.
If the function is defined as follows:
......@@ -791,11 +707,9 @@ let sum = (x: number, y: number): number => {
}
```
An arrow function return type can be omitted; in such case, it is inferred
from the function body.
An arrow function return type can be omitted; in such case, it is inferred from the function body.
An expression can be specified as an arrow function to make the notation
shorter, i.e., the following two notations are equivalent:
An expression can be specified as an arrow function to make the notation shorter, i.e., the following two notations are equivalent:
```typescript
let sum1 = (x: number, y: number) => { return x + y }
......@@ -804,9 +718,7 @@ let sum2 = (x: number, y: number) => x + y
## Closure
An arrow function is usually defined inside another function. As an inner
function, it can access all variables and functions defined in the outer
functions.
An arrow function is usually defined inside another function. As an inner function, it can access all variables and functions defined in the outer functions.
To capture the context, an inner function forms a closure of its environment.
The closure allows accessing such an inner function outside its own environment.
......@@ -826,15 +738,12 @@ In the sample above, the arrow function closure captures the `count` variable.
## Function Overload Signatures
A function can be specified to be called in different ways by writing
overload signatures. To do so, several functions’ headers that have the
same name but different signatures are written and immediately followed
by the single implementation function.
A function can be specified to be called in different ways by writing overload signatures. To do so, several functions' headers that have the same name but different signatures are written and immediately followed by the single implementation function.
```typescript
function foo(): void; /* 1st signature */
function foo(x: string): void; /* 2nd signature */
function foo(x?: string): void { /* implementation signature */
function foo(x?: string): void { /* Implementation signature */
console.log(x)
}
......@@ -846,11 +755,9 @@ An error occurs if two overload signatures have identical parameter lists.
# Classes
A class declaration introduces a new type and defines its fields, methods
and constructors.
A class declaration introduces a new type and defines its fields, methods and constructors.
In the following example, class `Person` is defined, which has fields
‘name’ and ‘surname’, constructor, and a method `fullName`:
In the following example, class `Person` is defined, which has fields **name** and **surname**, constructor, and a method `fullName`:
```typescript
class Person {
......@@ -866,8 +773,7 @@ class Person {
}
```
After the class is defined, its instances can be created by using
the keyword `new`:
After the class is defined, its instances can be created by using the keyword `new`:
```typescript
let p = new Person("John", "Smith")
......@@ -887,12 +793,12 @@ let p: Point = {x: 42, y: 42}
## Fields
A field is a variable of some type that is declared directly in a class.
Classes may have instance fields, static fields or both.
### Instance Fields
Instance fields exist on every instance of a class. Each instance has its own
set of instance fields.
Instance fields exist on every instance of a class. Each instance has its own set of instance fields.
```typescript
class Person {
......@@ -917,9 +823,7 @@ this.name
### Static Fields
The keyword `static` is used to declare a field as static. Static fields
belong to the class itself, and all instances of the class share one static
field.
The keyword `static` is used to declare a field as static. Static fields belong to the class itself, and all instances of the class share one static field.
The class name is used to access a static field:
......@@ -938,11 +842,9 @@ console.log(Person.numberOfPersons)
### Getters and Setters
Setters and getters can be used to provide controlled access to object
properties.
Setters and getters can be used to provide controlled access to object properties.
In the following example, a setter is used to forbid setting invalid
values of the ‘age’ property:
In the following example, a setter is used to forbid setting invalid values of the 'age' property:
```typescript
class Person {
......@@ -968,16 +870,13 @@ A class can define a getter, a setter or both.
A method is a function that belongs to a class.
A class can define instance methods, static methods or both.
A static method belongs to the class itself, and can have access to static
fields only.
A `while` instance method has access to both static (class) fields and
instance fields including private ones of its class.
A static method belongs to the class itself, and can have access to static fields only.
A `while` instance method has access to both static (class) fields and instance fields including private ones of its class.
### Instance Methods
The example below illustrates how instanced methods work.
The `calculateArea` method calculates the area of a rectangle by
multiplying the height by the width:
The `calculateArea` method calculates the area of a rectangle by multiplying the height by the width:
```typescript
class Rectangle {
......@@ -1001,8 +900,7 @@ console.log(square.calculateArea()) // output: 100
### Static Methods
The keyword `static` is used to declare a method as static. Static methods
belong to the class itself and have access to static fields only.
The keyword `static` is used to declare a method as static. Static methods belong to the class itself and have access to static fields only.
A static method defines a common behavior of the class as a whole.
All instances have access to static methods.
......@@ -1019,8 +917,7 @@ console.log(Cl.staticMethod())
### Inheritance
A class can extend another class (called base class) and implement several
interfaces by using the following syntax:
A class can extend another class (called base class) and implement several interfaces by using the following syntax:
```typescript
class [extends BaseClassName] [implements listOfInterfaces] {
......@@ -1028,12 +925,9 @@ class [extends BaseClassName] [implements listOfInterfaces] {
}
```
The extended class inherits fields and methods from the base class, but
not constructors, and can add its own fields and methods as well as override
methods defined by the base class.
The extended class inherits fields and methods from the base class, but not constructors, and can add its own fields and methods as well as override methods defined by the base class.
The base class is also called ‘parent class’ or ‘superclass’.
The extended class also called ‘derived class’ or ‘subclass’.
The base class is also called 'parent class' or 'superclass'. The extended class also called 'derived class' or 'subclass'.
Example:
......@@ -1053,9 +947,7 @@ class Employee extends Person {
}
```
A class containing the `implements` clause must implement all methods
defined in all listed interfaces, except the methods defined with default
implementation.
A class containing the `implements` clause must implement all methods defined in all listed interfaces, except the methods defined with default implementation.
```typescript
interface DateInterface {
......@@ -1071,11 +963,9 @@ class MyDate implements DateInterface {
### Access to Super
The keyword `super` can be used to access instance fields, instance methods
and constructors from the super class.
The keyword `super` can be used to access instance fields, instance methods and constructors from the super class.
It is often used to extend basic functionality of subclass with the required
behavior taken from the super class:
It is often used to extend basic functionality of subclass with the required behavior taken from the super class:
```typescript
class Rectangle {
......@@ -1109,10 +999,8 @@ class FilledRectangle extends Rectangle {
### Override Methods
A subclass can override implementation of a method defined in its superclass.
An overridden method can be marked with the keyword `override` to improve
readability.
An overridden method must have the same types of parameters, and same or
derived return type as the original method.
An overridden method can be marked with the keyword `override` to improve readability.
An overridden method must have the same types of parameters, and same or derived return type as the original method.
```typescript
class Rectangle {
......@@ -1132,10 +1020,7 @@ class Square extends Rectangle {
### Method Overload Signatures
A method can be specified to be called in different ways by writing overload
signatures. To do so, several method headers that have the same name but
different signatures are written and immediately followed by the single
implementation method.
A method can be specified to be called in different ways by writing overload signatures. To do so, several method headers that have the same name but different signatures are written and immediately followed by the single implementation method.
```typescript
class C {
......@@ -1150,13 +1035,11 @@ c.foo() // ok, 1st signature is used
c.foo("aa") // ok, 2nd signature is used
```
An error occurs if two overload signatures have the same name and identical
parameter lists.
An error occurs if two overload signatures have the same name and identical parameter lists.
## Constructors
A class declaration may contain a constructor that is used to initialize
object state.
A class declaration may contain a constructor that is used to initialize object state.
A constructor is defined as follows:
......@@ -1166,8 +1049,7 @@ constructor ([parameters]) {
}
```
If no constructor is defined, then a default constructor with an empty
parameter list is created automatically, for example:
If no constructor is defined, then a default constructor with an empty parameter list is created automatically, for example:
```typescript
class Point {
......@@ -1177,13 +1059,11 @@ class Point {
let p = new Point()
```
In this case the default constructor fills the instance fields with
default values for the field types.
In this case the default constructor fills the instance fields with default values for the field types.
### Constructors in Derived Class
The first statement of a constructor body can use the keyword `super`
to explicitly call a constructor of the direct superclass.
The first statement of a constructor body can use the keyword `super` to explicitly call a constructor of the direct superclass.
```typescript
class Rectangle {
......@@ -1198,22 +1078,17 @@ class Square extends Rectangle {
}
```
If a constructor body does not begin with such an explicit call of a
superclass constructor, then the constructor body implicitly begins
with a superclass constructor call `super()`.
If a constructor body does not begin with such an explicit call of a superclass constructor, then the constructor body implicitly begins with a superclass constructor call `super()`.
### Constructor Overload Signatures
A constructor can be specified to be called in different ways by writing
overload signatures. To do so, several constructor headers that have the
same name but different signatures are written and immediately followed
by the single implementation constructor.
A constructor can be specified to be called in different ways by writing overload signatures. To do so, several constructor headers that have the same name but different signatures are written and immediately followed by the single implementation constructor.
```typescript
class C {
constructor() /* 1st signature */
constructor(x: string) /* 2nd signature */
constructor(x?: string) { /* implementation signtaure */
constructor(x?: string) { /* Implementation signature */
console.log(x)
}
}
......@@ -1221,8 +1096,7 @@ let c1 = new C() // ok, 1st signature is used
let c2 = new C("abc") // ok, 2nd signature is used
```
An error occurs if two overload signatures have the same name and
identical parameter lists.
An error occurs if two overload signatures have the same name and identical parameter lists.
## Visibility Modifiers
......@@ -1236,18 +1110,16 @@ There are several visibility modifiers:
- `internal`.
The default visibility is `public`.
The modifier `internal` allows to limit visibility within
the current package.
The modifier `internal` allows you to limit visibility within the current package.
### Public Visibility
The `public` members (fields, methods, constructors) of a class are
visible in any part of the program, where their class is visible.
The `public` members (fields, methods, constructors) of a class are visible in any part of the program, where their class is visible.
### Private Visibility
A `private` member cannot be accessed outside the class it is declared in,
for example:
A `private` member cannot be accessed outside the class it is declared in.
Example:
```typescript
class C {
......@@ -1264,8 +1136,8 @@ c.y = "b" // compile-time error: 'y' is not visible
### Protected Visibility
The modifier `protected` acts much like the modifier `private`, but
the `protected` members are also accessible in derived classes, for example:
The modifier `protected` acts much like the modifier `private`, but the `protected` members are also accessible in derived classes.
Example:
```typescript
class Base {
......@@ -1282,12 +1154,9 @@ class Derived extends Base {
## Object Literals
An object literal is an expression that can be used to create a class instance
and provide some initial values. It can be used instead of the expression
`new` as it is more convenient in some cases.
An object literal is an expression that can be used to create a class instance and provide some initial values. It can be used instead of the expression `new` as it is more convenient in some cases.
A class composite is written as a comma-separated list of name-value pairs
enclosed in ‘{’ and ‘}’.
A class composite is written as a comma-separated list of name-value pairs enclosed in '{' and '}'.
```typescript
class C {
......@@ -1298,9 +1167,7 @@ class C {
let c: C = {n: 42, s: "foo"}
```
Due to the static typing of the ArkTS, object literals can be used in a
context where the class or interface type of the object literal can be
inferred as in the example above. Other valid cases are illustrated below:
Due to the static typing of the ArkTS, object literals can be used in a context where the class or interface type of the object literal can be inferred as in the example above. Other valid cases are illustrated below:
```typescript
class C {
......@@ -1332,8 +1199,7 @@ let cc: C[] = [{n: 1, s: "a"}, {n: 2, s: "b"}]
### Object Literals of Record Type
The generic Record<K, V> type is used to map the properties of a type
(Key type) to another type (Value type).
The generic Record<K, V> type is used to map the properties of a type (Key type) to another type (Value type).
A special form of object literal is used to initialize the value of such type:
......@@ -1361,11 +1227,9 @@ let map: Record<string, PersonInfo> = {
# Interfaces
An interface declaration introduces a new type. Interfaces are a common way
of defining contracts between various part of codes.
An interface declaration introduces a new type. Interfaces are a common way of defining contracts between various part of codes.
Interfaces are used to write polymorphic code, which can be applied to any
class instances that implement a particular interface.
Interfaces are used to write polymorphic code, which can be applied to any class instances that implement a particular interface.
An interface usually contains properties and method headers.
......@@ -1406,11 +1270,9 @@ class Rectangle implements Area {
## Interface Properties
An interface property can be in a form of field, getter, setter, or both
getter and setter.
An interface property can be in a form of field, getter, setter, or both getter and setter.
A property field is just a shortcut notation of a getter/setter pair, and
the following notations are equal:
A property field is just a shortcut notation of a getter/setter pair, and the following notations are equal:
```typescript
interface Style {
......@@ -1463,8 +1325,7 @@ interface ExtendedStyle extends Style {
}
```
An extended interface contains all properties and methods of the
interface it extends, and can also add its own properties and methods.
An extended interface contains all properties and methods of the interface it extends, and can also add its own properties and methods.
## Interface Visibility Modifiers
......@@ -1474,13 +1335,11 @@ Only methods with default implementation can be defined as `private`.
# Generic Types and Functions
Generic types and functions allow creating the code capable to work over a
variety of types rather than a single type.
Generic types and functions allow creating the code capable to work over a variety of types rather than a single type.
## Generic Classes and Interfaces
A class and an interface can be defined as generics, adding parameters to the
type definition, like the type parameter `Element` in the following example:
A class and an interface can be defined as generics, adding parameters to the type definition, like the type parameter `Element` in the following example:
```typescript
class Stack<Element> {
......@@ -1510,9 +1369,7 @@ s.push(55) // That will be a compile-time error
## Generic Constraints
Type parameters of generic types can be bounded. For example, the `Key`
type parameter in the `HashMap<Key, Value>` container must have a hash
method, i.e., it must be hashable.
Type parameters of generic types can be bounded. For example, the `Key` type parameter in the `HashMap<Key, Value>` container must have a hash method, that is, it must be hashable.
```typescript
interface Hashable {
......@@ -1526,13 +1383,11 @@ class HasMap<Key extends Hashable, Value> {
}
```
In the above example, the `Key` type extends `Hashable`, and all methods
of `Hashable` interface can be called for keys.
In the above example, the `Key` type extends `Hashable`, and all methods of `Hashable` interface can be called for keys.
## Generic Functions
Use a generic function to create a more universal code. Consider a function
that returns the last element of the array:
Use a generic function to create a more universal code. Consider a function that returns the last element of the array:
```typescript
function last(x: number[]): number {
......@@ -1541,8 +1396,7 @@ function last(x: number[]): number {
console.log(last([1, 2, 3])) // output: 3
```
If the same function needs to be defined for any array, then define it as
a generic with a type parameter:
If the same function needs to be defined for any array, then define it as a generic with a type parameter:
```typescript
function last<T>(x: T[]): T {
......@@ -1566,10 +1420,8 @@ console.log(last([1, 2, 3]))
## Generic Defaults
Type parameters of generic types can have defaults.
It allows using just the generic type name instead of specifying the actual
type arguments.
Example below illustrates this for both classes and functions.
Type parameters of generic types can have defaults. It allows using just the generic type name instead of specifying the actual type arguments.
The example below illustrates this for both classes and functions.
```typescript
class SomeType {}
......@@ -1589,10 +1441,8 @@ foo<number>()
# Null Safety
All types in ArkTS by default are non-nullable, so the value of a type
cannot be null.
It is similar to TypeScript behavior in strict null checking mode
(`strictNullChecks`), but the rules are stricter.
All types in ArkTS by default are non-nullable, so the value of a type cannot be null.
It is similar to TypeScript behavior in strict null checking mode (`strictNullChecks`), but the rules are stricter.
In the example below, all lines cause a compile-time error:
......@@ -1615,8 +1465,7 @@ if (x != null) { /* do something */ }
A postfix operator `!` can be used to assert that its operand is non-null.
If applied to a null value, the operator throws an error. Otherwise, the
type of the value is changed from `T | null` to `T`:
If applied to a null value, the operator throws an error. Otherwise, the type of the value is changed from `T | null` to `T`:
```typescript
let x: number | null = 1
......@@ -1627,15 +1476,12 @@ y = x! + 1 // ok
## Null-Coalescing Operator
The null-coalescing binary operator `??` checks whether the evaluation
of the left-hand-side expression is equal to null.
If it is, then the result of the expression is the right-hand-side expression;
otherwise, it is the left-hand-side expression.
The null-coalescing binary operator `??` checks whether the evaluation of the left-hand-side expression is equal to null.
If it is, then the result of the expression is the right-hand-side expression; otherwise, it is the left-hand-side expression.
In other words, `a ?? b` equals the ternary operator `a != null ? a : b`.
In the following example, the method `getNick` returns a nickname if it is
set; otherwise, an empty string is returned:
In the following example, the method `getNick` returns a nickname if it is set; otherwise, an empty string is returned:
```typescript
class Person {
......@@ -1649,8 +1495,7 @@ class Person {
## Optional Chaining
Optional chaining operator `?.` allows writing code where the evaluation
stops at an expression that is partially evaluated to `null` or `undefined`.
Optional chaining operator `?.` allows writing code where the evaluation stops at an expression that is partially evaluated to `null` or `undefined`.
```typescript
class Person {
......@@ -1672,14 +1517,11 @@ class Person {
}
```
**Note**: the return type of `getSpouseNick` must be `string | null | undefined`, as
the method can return null or undefined.
**Note**: The return type of `getSpouseNick` must be `string | null | undefined`, as the method can return null or undefined.
An optional chain can be of any length and contain any number of `?.`
operators.
An optional chain can be of any length and contain any number of `?.` operators.
In the following sample, the output is a person’s spouse nickname if that
person has a spouse, and the spouse has a nickname.
In the following sample, the output is a person's spouse nickname if that person has a spouse, and the spouse has a nickname.
Otherwise, the output is `undefined`:
......@@ -1702,19 +1544,15 @@ console.log(p.spouse?.nick) // print: undefined
Programs are organized as sets of compilation units or modules.
Each module creates its own scope, i.e., any declarations (variables,
functions, classes, etc.) declared in the module are not visible outside
that module unless they are explicitly exported.
Each module creates its own scope, i.e., any declarations (variables, functions, classes, etc.) declared in the module are not visible outside that module unless they are explicitly exported.
Conversely, a variable, function, class, interface, etc. exported from
another module must first be imported to a module.
Conversely, a variable, function, class, interface, etc. exported from another module must first be imported to a module.
## Export
A top-level declaration can be exported by using the keyword `export`.
A declared name that is not exported is considered private and can be used
only in the module where it is declared.
A declared name that is not exported is considered private and can be used only in the module where it is declared.
```typescript
export class Point {
......@@ -1733,20 +1571,17 @@ export function Distance(p1: Point, p2: Point): number {
## Import
Import declarations are used to import entities exported from other modules
and provide their bindings in the current module. An import declaration
consists of two parts:
Import declarations are used to import entities exported from other modules and provide their bindings in the current module.
An import declaration consists of two parts:
* Import path that determines the module to import from;
* Import bindings that define the set of usable entities in the imported
module, and the form of use (i.e., qualified or unqualified use).
* Import path that determines the module to import from.
* Import bindings that define the set of usable entities in the imported module, and the form of use (i.e., qualified or unqualified use).
Import bindings may have several forms.
Let’s assume a module has the path ‘./utils’ and export entities ‘X’ and ‘Y’.
Let's assume a module has the path './utils' and export entities 'X' and 'Y'.
An import binding of the form `* as A` binds the name ‘A’, and all entities
exported from the module defined by the import path can be accessed by using
An import binding of the form `* as A` binds the name 'A', and all entities exported from the module defined by the import path can be accessed by using
the qualified name `A.name`:
```typescript
......@@ -1755,8 +1590,7 @@ Utils.X // denotes X from Utils
Utils.Y // denotes Y from Utils
```
An import binding of the form `{ ident1, ..., identN }` binds an exported
entity with a specified name, which can be used as a simple name:
An import binding of the form `{ ident1, ..., identN }` binds an exported entity with a specified name, which can be used as a simple name:
```typescript
import { X, Y } from "./utils"
......@@ -1764,8 +1598,7 @@ X // denotes X from Utils
Y // denotes Y from Utils
```
If a list of identifiers contains aliasing of the form `ident as alias`,
then entity `ident` is bound under the name `alias`:
If a list of identifiers contains aliasing of the form `ident as alias`, then entity `ident` is bound under the name `alias`:
```typescript
import { X as Z, Y } from "./utils"
......@@ -1778,17 +1611,13 @@ X // Compile-time error: 'X' is not visible
A module can contain any statements at the module level, except `return` ones.
If a module contains a `main` function (program entry point), then
top-level statements of the module are executed immediately before
the body of this function.
Otherwise, they are executed before execution of any other function
of the module.
If a module contains a `main` function (program entry point), then top-level statements of the module are executed immediately before the body of this function.
Otherwise, they are executed before execution of any other function of the module.
## Program Entry Point
An entry point of a program (application) is the top-level `main` function.
The `main` function must have either an empty parameter list or a single
parameter of `string[]` type.
The `main` function must have either an empty parameter list or a single parameter of `string[]` type.
```typescript
function main() {
......@@ -1798,18 +1627,11 @@ function main() {
# Support for ArkUI
This section demonstrates mechanisms that ArkTS provides for
creating graphical user interface (GUI) programs. The section is based on
the ArkUI declarative framework. ArkUI provides a set of extensions of
the standard TypeScript to declaratively describe the GUI of the applications
and the interaction between the GUI components.
This section demonstrates mechanisms that ArkTS provides for creating graphical user interface (GUI) programs. The section is based on the ArkUI declarative framework. ArkUI provides a set of extensions of the standard TypeScript to declaratively describe the GUI of the applications and the interaction between the GUI components.
## ArkUI Example
The following example provides a complete ArkUI-based application as an
illustration of GUI programming capabilities. For more details of the
ArkUI features, refer to the ArkUI
[tutorial](arkts-get-started.md).
The following example provides a complete ArkUI-based application as an illustration of GUI programming capabilities. For more details of the ArkUI features, refer to the ArkUI [tutorial](arkts-get-started.md).
```typescript
// ViewModel classes ---------------------------
......@@ -1990,7 +1812,7 @@ struct PersonEditView {
// delete found contact
this.addrBook.contacts.splice(index, 1)
// determin new selectedPerson
// determine new selectedPerson
index = (index < this.addrBook.contacts.length)
? index
: index - 1
......
......@@ -254,20 +254,20 @@ struct WebComponent {
.onClick(() => {
// Use the local port to send messages to HTML5.
try {
console.log("In eTS side send true start");
console.log("In ArkTS side send true start");
if (this.nativePort) {
this.message.setString("helloFromEts");
this.nativePort.postMessageEventExt(this.message);
}
}
catch (error) {
console.log("In eTS side send message catch error:" + error.code + ", msg:" + error.message);
console.log("In ArkTS side send message catch error:" + error.code + ", msg:" + error.message);
}
})
Web({ src: $rawfile('index.html'), controller: this.controller })
.onPageEnd((e)=>{
console.log("In eTS side message onPageEnd init mesaage channel");
console.log("In ArkTS side message onPageEnd init mesaage channel");
// 1. Create a message port.
this.ports = this.controller.createWebMessagePorts(true);
// 2. Send port 1 to HTML5.
......@@ -276,10 +276,10 @@ struct WebComponent {
this.nativePort = this.ports[0];
// 4. Set the callback.
this.nativePort.onMessageEventExt((result) => {
console.log("In eTS side got message");
console.log("In ArkTS side got message");
try {
var type = result.getType();
console.log("In eTS side getType:" + type);
console.log("In ArkTS side getType:" + type);
switch (type) {
case web_webview.WebMessageType.STRING: {
this.msg1 = "result type:" + typeof (result.getString());
......@@ -592,8 +592,8 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
| 17100002 | Invalid url. |
| 17100003 | Invalid resource path or file type. |
| 17100002 | Invalid url. |
| 17100003 | Invalid resource path or file type. |
**Example**
......@@ -652,71 +652,71 @@ struct WebComponent {
There are three methods for loading local resource files:
1. Using $rawfile
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('loadUrl')
.onClick(() => {
try {
// Load a local resource file through $rawfile.
this.controller.loadUrl($rawfile('index.html'));
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('loadUrl')
.onClick(() => {
try {
// Load a local resource file through $rawfile.
this.controller.loadUrl($rawfile('index.html'));
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
2. Using the resources protocol
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('loadUrl')
.onClick(() => {
try {
// Load a local resource file through the resource protocol.
this.controller.loadUrl("resource://rawfile/index.html");
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('loadUrl')
.onClick(() => {
try {
// Load local resource files through the resource protocol.
this.controller.loadUrl("resource://rawfile/index.html");
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
3. Using a sandbox path. For details, see the example of loading local resource files in the sandbox in [Web](../arkui-ts/ts-basic-components-web.md#web).
HTML file to be loaded:
```html
<!-- index.html -->
<!DOCTYPE html>
<html>
<body>
<p>Hello World</p>
</body>
</html>
```
HTML file to be loaded:
```html
<!-- index.html -->
<!DOCTYPE html>
<html>
<body>
<p>Hello World</p>
</body>
</html>
```
### loadData
......@@ -748,7 +748,7 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
| 17100002 | Invalid url. |
| 17100002 | Invalid url. |
**Example**
......@@ -1773,7 +1773,7 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web compoent. |
| 17100008 | Cannot delete JavaScriptProxy. |
| 17100008 | Cannot delete JavaScriptProxy. |
**Example**
......@@ -1824,7 +1824,7 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web compoent. |
| 17100004 | Function not enable. |
| 17100004 | Function not enable. |
**Example**
......@@ -2361,7 +2361,7 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
| 17100004 | Function not enable. |
| 17100004 | Function not enable. |
**Example**
......@@ -2405,7 +2405,7 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
| 17100004 | Function not enable. |
| 17100004 | Function not enable. |
**Example**
......@@ -2804,7 +2804,7 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
| 17100003 | Invalid resource path or file type. |
| 17100003 | Invalid resource path or file type. |
**Example**
......
......@@ -165,7 +165,7 @@ Not supported
strokeColor: '#0081ff',
fillColor: '#cce5ff',
data: [763, 550, 551, 554, 731, 654, 525, 696, 595, 628, 791, 505, 613, 575, 475, 553, 491, 680, 657, 716],
gradient: true,
gradient: false,
}
],
lineOps: {
......
......@@ -28,9 +28,9 @@ Not supported
| Name| Parameter| Description|
| -------- | -------- | -------- |
| click | - | Triggered when the component is clicked. |
| longpress | - | Triggered when the component is long pressed. |
| swipe<sup>5+</sup> | [SwipeEvent](js-common-events.md) | Triggered when a user quickly swipes on the component. |
| click | - | Triggered when the component is clicked.|
| longpress | - | Triggered when the component is long pressed.|
| swipe<sup>5+</sup> | [SwipeEvent](js-common-events.md) | Triggered when a user quickly swipes on the component.|
## Styles
......@@ -39,8 +39,8 @@ Not supported
| -------- | -------- | -------- | -------- | -------- |
| color | &lt;color&gt; | \#000000 | No| Color of the QR code.|
| background-color | &lt;color&gt; | \#ffffff | No| Background color of the QR code.|
| width | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | - | No| Component width.<br>If this attribute is not set, the default value **0** is used. |
| height | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | - | No| Component height.<br>If this attribute is not set, the default value **0** is used. |
| width | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | - | No| Component width.<br>If this attribute is not set, the default value **0** is used.|
| height | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | - | No| Component height.<br>If this attribute is not set, the default value **0** is used.|
| padding | &lt;length&gt; | 0 | No| Shorthand attribute to set the padding for all sides.<br>The attribute can have one to four values:<br>- If you set only one value, it specifies the padding for all the four sides.<br>- If you set two values, the first value specifies the top and bottom padding, and the second value specifies the left and right padding.<br>- If you set three values, the first value specifies the top padding, the second value specifies the left and right padding, and the third value specifies the bottom padding.<br>- If you set four values, they respectively specify the padding for top, right, bottom, and left sides (in clockwise order).|
| padding-[left\|top\|right\|bottom] | &lt;length&gt; | 0 | No| Left, top, right, and bottom padding.|
| margin | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | 0 | No| Shorthand attribute to set the margin for all sides. The attribute can have one to four values:<br>- If you set only one value, it specifies the margin for all the four sides.<br>- If you set two values, the first value specifies the top and bottom margins, and the second value specifies the left and right margins.<br>- If you set three values, the first value specifies the top margin, the second value specifies the left and right margins, and the third value specifies the bottom margin.<br>- If you set four values, they respectively specify the margin for top, right, bottom, and left sides (in clockwise order).|
......@@ -49,7 +49,7 @@ Not supported
| border-color | &lt;color&gt; | black | No| Shorthand attribute to set the color for all borders.|
| border-radius | &lt;length&gt; | - | No| Radius of round-corner borders.|
| display | string | flex | No| How and whether to display the box containing an element. Available values are as follows:<br>- **flex**: flexible layout<br>- **none**: not rendered|
| [left\|top] | &lt;length&gt; \| &lt;percentage&gt;<sup>6+</sup> | - | No| Edge of the element.<br>- **left**: left edge position of the element. This attribute defines the offset between the left edge of the margin area of a positioned element and left edge of its containing block.<br>- **top**: top edge position of the element. This attribute defines the offset between the top edge of a positioned element and that of a block included in the element. |
| [left\|top] | &lt;length&gt; \| &lt;percentage&gt;<sup>6+</sup> | - | No| Edge of the element.<br>- **left**: left edge position of the element. This attribute defines the offset between the left edge of the margin area of a positioned element and left edge of its containing block.<br>- **top**: top edge position of the element. This attribute defines the offset between the top edge of a positioned element and that of a block included in the element.|
> **NOTE**
> - If the values of **width** and **height** are different, the smaller value is used as the length of the QR code. The generated QR code is center displayed.
......@@ -63,10 +63,10 @@ Not supported
```html
<!-- xxx.hml -->
<div class="container">
<qrcode value="{{qr_value}}" class="qrCode" style="color: {{qr_color}};background-color: {{qr_bcol}};"></qrcode>
<input type="button" onclick="changeColor" class="button">Color</input>
<input type="button" onclick="changeBackgroundColor" class="button">BackgroundColor</input>
<input type="button" onclick="changeColor" class="button">Value</input>
<qrcode value="{{qr_value}}" class="qrCode" style="color: {{qr_col}};background-color: {{qr_bcol}};"></qrcode>
<input type="button" onclick="changeColor" class="button">Color</input>
<input type="button" onclick="changeBackgroundColor" class="button">BackgroundColor</input>
<input type="button" onclick="changeValue" class="button">Value</input>
</div>
```
......@@ -93,32 +93,32 @@ Not supported
```javascript
// xxx.js
export default {
data: {
qr_col: '#87ceeb',
qr_bcol: '#f0ffff',
qr_value: 'value'
},
changeColor() {
if (this.qr_col == '#87ceeb') {
this.qr_col = '#fa8072';
} else {
this.qr_col = '#87ceeb';
data: {
qr_col: '#87ceeb',
qr_bcol: '#f0ffff',
qr_value: 'value'
},
changeColor() {
if (this.qr_col == '#87ceeb') {
this.qr_col = '#fa8072';
} else {
this.qr_col = '#87ceeb';
}
},
changeBackgroundColor() {
if (this.qr_bcol == '#f0ffff') {
this.qr_bcol = '#ffffe0';
} else {
this.qr_bcol = '#f0ffff';
}
},
changeValue() {
if (this.qr_value == 'value') {
this.qr_value = 'change';
} else {
this.qr_value = 'value';
}
}
},
changeBackgroundColor() {
if (this.qr_bcol == '#f0ffff') {
this.qr_bcol = '#ffffe0';
} else {
this.qr_bcol = '#f0ffff';
}
},
changeValue() {
if (this.qr_value == 'value') {
this.qr_value = 'change';
} else {
this.qr_value = 'value';
}
}
}
```
......
......@@ -13,44 +13,54 @@ Supported
Since API version 9, it is recommended that this component be used together with the **[\<NavRouter>](ts-basic-components-navrouter.md)** component.
## APIs
**API 1**: Navigation()
### Navigation
Navigation()
### Navigation<sup>10+</sup>
**API 2**: Navigation(pathInfos: NavPathStack)<sup>10+</sup>
Navigation(pathInfos: NavPathStack)
Binds a navigation stack to the **\<Navigation>** component.
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ----------------------------------- | ---- | ------------- |
| pathInfos | [NavPathStack](#navpathstack10) | No | Information about the navigation stack.|
| Name | Type | Mandatory | Description |
| --------- | ------------------------------- | ---- | ------ |
| pathInfos | [NavPathStack](#navpathstack10) | No | Information about the navigation stack.|
## Attributes
In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| Name | Type | Description |
| ----------------------------- | ---------------------------------------- | ---------------------------------------- |
| title | [ResourceStr](ts-types.md#resourcestr)<sup>10+</sup> \| [CustomBuilder](ts-types.md#custombuilder8)<sup>8+</sup> \| [NavigationCommonTitle](#navigationcommontitle)<sup>9+</sup> \| [NavigationCustomTitle](#navigationcustomtitle)<sup>9+</sup> | Page title.<br>**NOTE**<br>When the NavigationCustomTitle type is used to set the height, the **titleMode** attribute does not take effect.<br>When the title string is too long: (1) If no subtitle is set, the string is scaled down, wrapped in two lines, and then clipped with an ellipsis (...); (2) If a subtitle is set, the subtitle is scaled down and then clipped with an ellipsis (...).|
| subTitle<sup>(deprecated)</sup> | string | Subtitle of the page. If this attribute is not set, no subtitle is displayed. This attribute is deprecated since API version 9. You are advised to use **title** instead.|
| menus | Array<[NavigationMenuItem](#navigationmenuitem)&gt; \| [CustomBuilder](ts-types.md#custombuilder8)<sup>8+</sup> | Menu items in the upper right corner of the page. If this attribute is not set, no menu item is displayed. When the value type is Array\<[NavigationMenuItem](#navigationmenuitem)>, the menu shows a maximum of three icons in portrait mode and a maximum of five icons in landscape mode, with excess icons (if any) placed under the automatically generated **More** icon.|
| titleMode | [NavigationTitleMode](#navigationtitlemode) | Display mode of the page title bar.<br>Default value: **NavigationTitleMode.Free**|
| toolBar<sup>(deprecated)</sup> | [object](#object) \| [CustomBuilder](ts-types.md#custombuilder8)<sup>8+</sup> | Content of the toolbar. If this attribute is not set, no toolbar is displayed.<br>**items**: items on the toolbar.<br>**NOTE**<br>Items are evenly distributed on the toolbar at the bottom. Text and icons are evenly distributed in each content area. If the text is too long, it is scaled down level by level, wrapped in two lines, and then clipped with an ellipsis (...).<br>This API is deprecated since API version 10. You are advised to use **toolbarConfiguration** instead.|
| Name | Type | Description |
| ---------------------------------- | ---------------------------------------- | ---------------------------------------- |
| title | [ResourceStr](ts-types.md#resourcestr)<sup>10+</sup> \| [CustomBuilder](ts-types.md#custombuilder8)<sup>8+</sup> \| [NavigationCommonTitle](#navigationcommontitle)<sup>9+</sup> \| [NavigationCustomTitle](#navigationcustomtitle)<sup>9+</sup> | Page title.<br>**NOTE**<br>When the NavigationCustomTitle type is used to set the height, the **titleMode** attribute does not take effect.<br>When the title string is too long: (1) If no subtitle is set, the string is scaled down, wrapped in two lines, and then clipped with an ellipsis (...); (2) If a subtitle is set, the subtitle is scaled down and then clipped with an ellipsis (...).|
| subTitle<sup>(deprecated)</sup> | string | Subtitle of the page. If this attribute is not set, no subtitle is displayed. This attribute is deprecated since API version 9. You are advised to use **title** instead.|
| menus | Array<[NavigationMenuItem](#navigationmenuitem)&gt; \| [CustomBuilder](ts-types.md#custombuilder8)<sup>8+</sup> | Menu items in the upper right corner of the page. If this attribute is not set, no menu item is displayed. When the value type is Array<[NavigationMenuItem](#navigationmenuitem)&gt;, the menu shows a maximum of three icons in portrait mode and a maximum of five icons in landscape mode, with excess icons (if any) placed under the automatically generated **More** icon.|
| titleMode | [NavigationTitleMode](#navigationtitlemode) | Display mode of the page title bar.<br>Default value: **NavigationTitleMode.Free**|
| toolBar<sup>(deprecated)</sup> | [object](#object) \| [CustomBuilder](ts-types.md#custombuilder8)<sup>8+</sup> | Content of the toolbar. If this attribute is not set, no toolbar is displayed.<br>**items**: all items on the toolbar.<br>**NOTE**<br>Items are evenly distributed on the toolbar at the bottom. Text and icons are evenly distributed in each content area. If the text is too long, it is scaled down level by level, wrapped in two lines, and then clipped with an ellipsis (...).<br>This API is deprecated since API version 10. You are advised to use **toolbarConfiguration** instead.|
| toolbarConfiguration<sup>10+</sup> | Array<[ToolbarItem](#toolbaritem10)<sup>10+</sup>&gt; \| [CustomBuilder](ts-types.md#custombuilder8)<sup>8+</sup> | Content of the toolbar. If this attribute is not set, no toolbar is displayed.<br>**NOTE**<br>When the value type is Array<[ToolbarItem](#ToolbarItem>, the toolbar exhibits the following features:<br>Items are evenly distributed on the toolbar at the bottom. Text and icons are evenly distributed in each content area.<br>If any item contains overlong text and there are fewer than five items, the following measures are taken: 1. Increase the item's width to accommodate the text until it is as large as the screen width; 2. Scale down the text level by level; 3. Wrap the text in two lines; 4. Clip the text with an ellipsis (...).<br>The toolbar shows a maximum of five icons in portrait mode, with excess icons (if any) placed under the automatically generated **More** icon. In landscape mode, this attribute must be used together with Array<[NavigationMenuItem](#navigationmenuitem)> of the **menus** attribute; the toolbar at the bottom is automatically hidden, and all items on the toolbar are moved to the menu in the upper right corner of the screen.<br>When the value type is [CustomBuilder](ts-types.md#custombuilder8), and the toolbar does not exhibit the preceding features except that items are evenly distributed on the toolbar at the bottom.|
| hideToolBar | boolean | Whether to hide the toolbar.<br>Default value: **false**<br>**true**: Hide the toolbar.<br>**false**: Display the toolbar.|
| hideTitleBar | boolean | Whether to hide the title bar.<br>Default value: **false**<br>**true**: Hide the title bar.<br>**false**: Display the title bar.|
| hideBackButton | boolean | Whether to hide the back button.<br>Default value: **false**<br>**true**: Hide the back button.<br>**false**: Display the back button.<br>The back button in the title bar of the **\<NavDestination>** component cannot be hidden.<br>**NOTE**<br>The back button works only when **titleMode** is set to **NavigationTitleMode.Mini**.|
| navBarWidth<sup>9+</sup> | [Length](ts-types.md#length) | Width of the navigation bar.<br>Default value: **240**<br>Unit: vp<br>**NOTE**<br>This attribute is valid only when the **\<Navigation>** component is split.|
| navBarPosition<sup>9+</sup> | [NavBarPosition](#navbarposition) | Position of the navigation bar.<br>Default value: **NavBarPosition.Start**<br>**NOTE**<br>This attribute is valid only when the **\<Navigation>** component is split.|
| mode<sup>9+</sup> | [NavigationMode](#navigationmode) | Display mode of the navigation bar.<br>Default value: **NavigationMode.Auto**<br>At the default settings, the component adapts to a single column or two columns based on the component width.<br>**NOTE**<br>Available options are **Stack**, **Split**, and **Auto**.|
| backButtonIcon<sup>9+</sup> | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Back button icon on the navigation bar. The back button in the title bar of the **\<NavDestination>** component cannot be hidden.|
| hideNavBar<sup>9+</sup> | boolean | Whether to hide the navigation bar. This attribute is valid only when **mode** is set to **NavigationMode.Split**.|
| navDestination<sup>10+</sup> | builder: (name: string, param: unknown) => void | Creates a **\<NavDestination>** component.<br>**NOTE**<br>The **builder** function is used, with the **name** and **param** parameters passed in. In the builder, a layer of custom components can be included outside the **\<NavDestination>** component. However, no attributes or events can be set for the custom components. Otherwise, only blank components are displayed.|
| navBarWidthRange<sup>10+</sup> | [[Dimension](ts-types.md#dimension10), [Dimension](ts-types.md#dimension10)] | Minimum and maximum widths of the navigation bar (valid in dual-column mode).<br>Default value: **240** for the minimum value; 40% of the component width (not greater than 432) for the maximum value<br>Unit: vp<br>Priority rules:<br>Custom value > Default value<br>Minimum value > Maximum value<br>navBar > content<br>If values conflict, the global value takes precedence, and the local minimum value depends on the container size.|
| minContentWidth<sup>10+</sup> | [Dimension](ts-types.md#dimension10) | Minimum width of the navigation bar content area (valid in dual-column mode).<br>Default value: **360**<br>Unit: vp<br>Priority rules:<br>Custom value > Default value<br>Minimum value > Maximum value<br>navBar > content<br>If values conflict, the global value takes precedence, and the local minimum value depends on the container size.<br>Breakpoint calculation in Auto mode: default 600 vp = minNavBarWidth (240 vp) + minContentWidth (360 vp)|
| hideToolBar | boolean | Whether to hide the toolbar.<br>Default value: **false**<br>**true**: Hide the toolbar.<br>**false**: Display the toolbar.|
| hideTitleBar | boolean | Whether to hide the title bar.<br>Default value: **false**<br>**true**: Hide the title bar.<br>**false**: Display the title bar.|
| hideBackButton | boolean | Whether to hide the back button.<br>Default value: **false**<br>**true**: Hide the back button.<br>**false**: Display the back button.<br>The back button in the title bar of the **\<NavDestination>** component cannot be hidden.<br>**NOTE**<br>The back button works only when **titleMode** is set to **NavigationTitleMode.Mini**.|
| navBarWidth<sup>9+</sup> | [Length](ts-types.md#length) | Width of the navigation bar.<br>Default value: **240**<br>Unit: vp<br>**NOTE**<br>This attribute is valid only when the **\<Navigation>** component is split.|
| navBarPosition<sup>9+</sup> | [NavBarPosition](#navbarposition) | Position of the navigation bar.<br>Default value: **NavBarPosition.Start**<br>**NOTE**<br>This attribute is valid only when the **\<Navigation>** component is split.|
| mode<sup>9+</sup> | [NavigationMode](#navigationmode) | Display mode of the navigation bar.<br>Default value: **NavigationMode.Auto**<br>At the default settings, the component adapts to a single column or two columns based on the component width.<br>**NOTE**<br>Available options are **Stack**, **Split**, and **Auto**.|
| backButtonIcon<sup>9+</sup> | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Back button icon on the navigation bar. The back button in the title bar of the **\<NavDestination>** component cannot be hidden.|
| hideNavBar<sup>9+</sup> | boolean | Whether to hide the navigation bar. This attribute is valid only when **mode** is set to **NavigationMode.Split**.|
| navDestination<sup>10+</sup> | builder: (name: string, param: unknown) => void | Creates a **\<NavDestination>** component.<br>**NOTE**<br>The **builder** function is used, with the **name** and **param** parameters passed in. In the builder, a layer of custom components can be included outside the **\<NavDestination>** component. However, no attributes or events can be set for the custom components. Otherwise, only blank components are displayed.|
| navBarWidthRange<sup>10+</sup> | [[Dimension](ts-types.md#dimension10), [Dimension](ts-types.md#dimension10)] | Minimum and maximum widths of the navigation bar (valid in dual-column mode).<br>Default value: **240** for the minimum value; 40% of the component width (not greater than 432) for the maximum value<br>Unit: vp<br>Priority rules:<br>Custom value > Default value<br>Minimum value > Maximum value<br>navBar > content<br>If values conflict, the global value takes precedence, and the local minimum value depends on the container size.|
| minContentWidth<sup>10+</sup> | [Dimension](ts-types.md#dimension10) | Minimum width of the navigation bar content area (valid in dual-column mode).<br>Default value: **360**<br>Unit: vp<br>Priority rules:<br>Custom value > Default value<br>Minimum value > Maximum value<br>navBar > content<br>If values conflict, the global value takes precedence, and the local minimum value depends on the container size.<br>Breakpoint calculation in Auto mode: default 600 vp = minNavBarWidth (240 vp) + minContentWidth (360 vp)|
## Events
| Name | Description |
| ---------------------------------------- | ---------------------------------------- |
| onTitleModeChange(callback: (titleMode: NavigationTitleMode) =&gt; void) | Called when **titleMode** is set to **NavigationTitleMode.Free** and the title bar mode changes as content scrolls.|
| onNavBarStateChange(callback: (isVisible: boolean) =&gt; void) | Called when the navigation bar visibility status changes. The value **true** means that the navigation bar is displayed, and **false** means the opposite.|
## NavPathStack<sup>10+</sup>
......@@ -64,9 +74,9 @@ Pushes the NavDestination page information specified by **info** to the stack.
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ----------------------- | ---- | --------------- |
| info | [NavPathInfo](#navpathinfo10) | Yes | Information about the navigation destination page. |
| Name | Type | Mandatory | Description |
| ---- | ----------------------------- | ---- | -------------------- |
| info | [NavPathInfo](#navpathinfo10) | Yes | Information about the navigation destination page.|
### pushName<sup>10+</sup>
......@@ -76,10 +86,10 @@ Pushes the navigation destination page specified by **name** to the navigation s
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ----------------------- | ---- | --------------- |
| name | string | Yes | Name of the navigation destination page. |
| param | unknown | Yes | Parameter information of the navigation destination page. |
| Name | Type | Mandatory | Description |
| ----- | ------- | ---- | --------------------- |
| name | string | Yes | Name of the navigation destination page. |
| param | unknown | Yes | Parameter information of the navigation destination page.|
### pop<sup>10+</sup>
......@@ -89,10 +99,10 @@ Pops the top element out of the navigation stack.
**Return value**
| Type | Description |
| ------ | -------- |
| Type | Description |
| ----------- | ------------------------ |
| NavPathInfo | Returns the information about the navigation destination page at the top of the stack.|
| undefined | Returns **undefined** if the navigation stack is empty.|
| undefined | Returns **undefined** if the navigation stack is empty. |
### popTo<sup>10+</sup>
......@@ -102,14 +112,14 @@ Returns the navigation stack to the first navigation destination page that match
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ----------------------- | ---- | --------------- |
| name | string | Yes | Name of the navigation destination page. |
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ------------------- |
| name | string | Yes | Name of the navigation destination page.|
**Return value**
| Type | Description |
| ------ | -------- |
| Type | Description |
| ------ | ---------------------------------------- |
| number | Returns the index of the first navigation destination page that matches the value of **name** if it exists in the navigation stack; returns **-1** otherwise.|
### popToIndex<sup>10+</sup>
......@@ -120,9 +130,9 @@ Returns the navigation stack to the navigation destination page that matches the
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ----------------------- | ---- | --------------- |
| index | number | Yes | Index of the navigation destination page. |
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ---------------------- |
| index | number | Yes | Index of the navigation destination page.|
### moveToTop<sup>10+</sup>
......@@ -132,14 +142,14 @@ Moves to the top of the navigation stack the first navigation destination page t
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ----------------------- | ---- | --------------- |
| name | string | Yes | Name of the navigation destination page. |
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ------------------- |
| name | string | Yes | Name of the navigation destination page.|
**Return value**
| Type | Description |
| ------ | -------- |
| Type | Description |
| ------ | ---------------------------------------- |
| number | Returns the index of the first navigation destination page that matches the value of **name** if it exists in the navigation stack; returns **-1** otherwise.|
### moveIndexToTop<sup>10+</sup>
......@@ -150,9 +160,9 @@ Moves to the top of the navigation stack the navigation destination page that ma
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ----------------------- | ---- | --------------- |
| index | number | Yes | Index of the navigation destination page. |
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ---------------------- |
| index | number | Yes | Index of the navigation destination page.|
### clear<sup>10+</sup>
......@@ -168,8 +178,8 @@ Obtains the names of all navigation destination pages in the navigation stack.
**Return value**
| Type | Description |
| ------ | -------- |
| Type | Description |
| -------------- | -------------------------- |
| Array<string\> | Names of all navigation destination pages in the navigation stack.|
### getParamByIndex<sup>10+</sup>
......@@ -180,16 +190,16 @@ Obtains the parameter information of the navigation destination page that matche
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ----------------------- | ---- | --------------- |
| index | number | Yes | Index of the navigation destination page. |
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ---------------------- |
| index | number | Yes | Index of the navigation destination page.|
**Return value**
| Type | Description |
| ------ | -------- |
| unknown | Returns the parameter information of the matching navigation destination page.|
| undefined | Returns **undefined** if the passed index is invalid.|
| Type | Description |
| --------- | -------------------------- |
| unknown | Returns the parameter information of the matching navigation destination page.|
| undefined | Returns **undefined** if the passed index is invalid. |
### getParamByName<sup>10+</sup>
......@@ -199,15 +209,15 @@ Obtains the parameter information of all the navigation destination pages that m
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ----------------------- | ---- | --------------- |
| name | string | Yes | Name of the navigation destination page. |
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ------------------- |
| name | string | Yes | Name of the navigation destination page.|
**Return value**
| Type | Description |
| ------ | -------- |
| Array<unknown\> | Parameter information of all the matching navigation destination pages.|
| Type | Description |
| --------------- | --------------------------------- |
| Array<unknown\> | Parameter information of all the matching navigation destination pages.|
### getIndexByName<sup>10+</sup>
......@@ -217,15 +227,15 @@ Obtains the indexes information of all the navigation destination pages that mat
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ----------------------- | ---- | --------------- |
| name | string | Yes | Name of the navigation destination page. |
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ------------------- |
| name | string | Yes | Name of the navigation destination page.|
**Return value**
| Type | Description |
| ------ | -------- |
| Array<number\> | Indexes of all the matching navigation destination pages.|
| Type | Description |
| -------------- | --------------------------------- |
| Array<number\> | Indexes of all the matching navigation destination pages.|
### size<sup>10+</sup>
......@@ -235,9 +245,9 @@ Obtains the stack size.
**Return value**
| Type | Description |
| ------ | -------- |
| number | Stack size.|
| Type | Description |
| ------ | ------ |
| number | Stack size.|
## NavPathInfo<sup>10+</sup>
......@@ -249,52 +259,52 @@ constructor(name: string, param: unknown)
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ----------------------- | ---- | --------------- |
| name | string | Yes | Name of the navigation destination page. |
| param | unknown | No | Parameter information of the navigation destination page. |
| Name | Type | Mandatory | Description |
| ----- | ------- | ---- | --------------------- |
| name | string | Yes | Name of the navigation destination page. |
| param | unknown | No | Parameter information of the navigation destination page.|
## NavigationMenuItem
| Name | Type | Mandatory | Description |
| ------ | ----------------------- | ---- | --------------- |
| value | string | Yes | Text of a menu item. |
| icon | string | No | Icon path of a menu item.|
| Name | Type | Mandatory | Description |
| ------ | ------------- | ---- | --------------- |
| value | string | Yes | Text of a menu item. |
| icon | string | No | Icon path of a menu item.|
| action | () =&gt; void | No | Callback invoked when a menu item is selected. |
## object
| Name | Type | Mandatory | Description |
| ------ | ----------------------- | ---- | --------------- |
| value | string | Yes | Text of a toolbar item. |
| icon | string | No | Icon path of a toolbar item.|
| Name | Type | Mandatory | Description |
| ------ | ------------- | ---- | --------------- |
| value | string | Yes | Text of a toolbar item. |
| icon | string | No | Icon path of a toolbar item.|
| action | () =&gt; void | No | Callback invoked when a toolbar item is selected. |
## ToolbarItem<sup>10+</sup>
| Name | Type | Mandatory| Description |
| ---------- | ------------------------------------------------- | ---- | ----------------------------------------------------------- |
| value | ResourceStr | Yes | Text of a toolbar item. |
| icon | ResourceStr | No | Icon path of a toolbar item. |
| action | () =&gt; void | No | Callback invoked when a toolbar item is selected. |
| status | [ToolbarItemStatus](#toolbaritemstatus10) | No | Status of a toolbar item.<br>Default value: **ToolbarItemStatus.NORMAL**|
| activeIcon | ResourceStr | No | Icon path of the toolbar item in the active state. |
| Name | Type | Mandatory | Description |
| ---------- | ---------------------------------------- | ---- | ---------------------------------------- |
| value | ResourceStr | Yes | Text of a toolbar item. |
| icon | ResourceStr | No | Icon path of a toolbar item. |
| action | () =&gt; void | No | Callback invoked when a toolbar item is selected. |
| status | [ToolbarItemStatus](#toolbaritemstatus10) | No | Status of a toolbar item.<br>Default value: **ToolbarItemStatus.NORMAL**|
| activeIcon | ResourceStr | No | Icon path of the toolbar item in the active state. |
## ToolbarItemStatus<sup>10+</sup>
| Name | Description |
| -------- | ------------------------------------------------------------ |
| Name | Description |
| -------- | ---------------------------------------- |
| NORMAL | Normal state. In this state, the toolbar item takes on the default style and can switch to another state-specific style by responding to the hover, press, and focus events.|
| DISABLED | Disabled state. In this state, the toolbar item is disabled and does not allow for user interactions.|
| ACTIVE | Active state. In this state, the toolbar item can update its icon to the one specified by **activeIcon** by responding to a click event.|
## NavigationTitleMode
| Name| Description |
| ---- | ------------------------------------------------------------ |
| Free | When the content is a scrollable component, the main title shrinks as the content scrolls down (the subtitle fades out with its size remaining unchanged) and restores when the content scrolls up to the top.<br>**NOTE**<br>The size linkage effect works only when **title** is set to **ResourceStr** or **NavigationCommonTitle**. If **title** is set to any other value type, the main title changes in mere location when pulled down.|
| Mini | The title is fixed at mini mode. |
| Full | The title is fixed at full mode. |
| Name | Description |
| ---- | ---------------------------------------- |
| Free | When the content is a scrollable component, the main title shrinks as the content scrolls down (the subtitle fades out with its size remaining unchanged) and restores as the content scrolls up to the top.<br>**NOTE**<br>The size linkage effect works only when **title** is set to **ResourceStr** or **NavigationCommonTitle**. If **title** is set to any other value type, the main title changes in mere location when pulled down.|
| Mini | The title is fixed at mini mode. |
| Full | The title is fixed at full mode. |
## NavigationCommonTitle
......@@ -322,7 +332,7 @@ constructor(name: string, param: unknown)
| Name | Description |
| ----- | ------------------------------------------------------------ |
| Stack | The navigation bar and content area are displayed independently of each other, which are equivalent to two pages. |
| Split | The navigation bar and content area are displayed in different columns. |
| Split | The navigation bar and content area are displayed in different columns.<br>The values of **navBarWidthRange** are represented by [minNavBarWidth,maxNavBarWidth].<br>1. When the value of **navBarWidth** is beyond the value range specified by **navBarWidthRange**, **navBarWidth** is set according to the following rules:<br>Value of **navBarWidth** < Value of **minNavBarWidth**: The value of **navBarWidth** is changed to that of **minNavBarWidth**.<br>Value of **navBarWidth** > Value of **maxNavBarWidth** and Component width - Value of **minContentWidth** - Divider width (1 vp) > Value of **maxNavBarWidth**: The value of **navBarWidth** is changed to that of **maxNavBarWidth**.<br>Value of **navBarWidth** > Value of **maxNavBarWidth** and Component width - Value of **minContentWidth** - Divider width (1 vp) < Value of **minNavBarWidth**: The value of **navBarWidth** is changed to that of **minNavBarWidth**.<br>Value of **navBarWidth** > Value of **maxNavBarWidth** and Component width - Value of **minContentWidth** - Divider width (1 vp) is within the value range specified by **navBarWidthRange**: The value of **navBarWidth** is changed to Component width - Value of **minContentWidth** - Divider width (1 vp).<br>2. When the value of **navBarWidth** is within the value range specified by **navBarWidthRange**, **navBarWidth** is set according to the following rules:<br>Value of **minNavBarWidth** + Value of **minContentWidth** + Divider width (1 vp) > = Component width: The value of **navBarWidth** is changed to that of **minNavBarWidth**.<br>Value of **minNavBarWidth** + Value of **minContentWidth** + Divider width (1 vp) < Component width and Value of **navBarWidth** + Value of **minContentWidth** + Divider width (1 vp) > = Component width: The value of **navBarWidth** is changed to Component width - Value of **minContentWidth** - Divider width (1 vp).<br>Value of **minNavBarWidth** + Value of **minContentWidth** + Divider width (1 vp) < Component width and Value of **navBarWidth** + Value of **minContentWidth** + Divider width (1 vp) < Component width: The value of **navBarWidth** is the set value. <br>3. When the component size is decreased, the content area is shrunk until its width reaches the value defined by **minContentWidth**, and then the navigation bar is shrunk until its width reaches the value defined by **minNavBarWidth**; if the component size is further decreased, the content area is further shrunk until it disappears, and then navigation bar is shrunk.<br>4. When the navigation bar is set to a fixed size and the component size is continuously decreased, the navigation bar is shrunk.<br>5. If only **navBarWidth** is set, the width of the navigation bar is fixed at the value of **navBarWidth**, and the divider cannot be dragged.|
| Auto | In API version 9 and earlier versions: When the window width is greater than or equal to 520 vp, the Split mode is used. In other cases, the Stack mode is used.<br>In API version 10 and later versions: When the window width is greater than or equal to 600 vp, the Split mode is used. In other cases, the Stack mode is used. 600 vp = minNavBarWidth (240 vp) + minContentWidth (360 vp).|
## TitleHeight
......@@ -334,17 +344,10 @@ constructor(name: string, param: unknown)
> **NOTE**
>
> Among the scrollable components, only **\<List>** is supported.
## Events
| Name | Description |
| ---------------------------------------- | ---------------------------------------- |
| onTitleModeChange(callback: (titleMode: NavigationTitleMode) =&gt; void) | Called when **titleMode** is set to **NavigationTitleMode.Free** and the title bar mode changes as content scrolls.|
| onNavBarStateChange(callback: (isVisible: boolean) =&gt; void) | Called when the navigation bar visibility status changes. The value **true** means that the navigation bar is displayed, and **false** means the opposite.|
## Example
```ts
......
......@@ -70,6 +70,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| strokeWidth | [Length](ts-types.md#length) | No | Stroke width of the progress indicator. It cannot be set in percentage.<br>Default value: **4.0vp** |
| scaleCount | number | No | Number of divisions on the ring-style process indicator.<br>Default value: **120** |
| scaleWidth | [Length](ts-types.md#length) | No | Scale width of the ring-style progress bar. It cannot be set in percentage. If it is greater than the value of **strokeWidth**, the default scale width is used.<br>Default value: **2.0vp**|
| enableSmoothEffect<sup>10+</sup> | boolean | No| Whether to enable the smooth effect. When this effect is enabled, the progress change to the set value takes place gradually. Otherwise, it takes place immediately.<br>Default value: **true**|
## CapsuleStyleOptions<sup>10+</sup>
| Name | Type| Mandatory| Description|
......@@ -81,6 +82,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| fontColor | [ResourceColor](ts-types.md#resourcecolor) | No| Font color.<br>Default value: **'\#ff182431'**|
| enableScanEffect | boolean | No| Whether to enable the scan effect.<br>Default value: **false**|
| showDefaultPercentage | boolean | No| Whether to show the percentage of the current progress. This attribute does not take effect when the **content** attribute is set.<br>Default value: **false**|
| enableSmoothEffect<sup>10+</sup> | boolean | No| Whether to enable the smooth effect. When this effect is enabled, the progress change to the set value takes place gradually. Otherwise, it takes place immediately.<br>Default value: **true**|
## RingStyleOptions<sup>10+</sup>
| Name | Type | Mandatory| Description |
......@@ -89,12 +91,14 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| shadow | boolean | No | Whether to enable the shadow effect.<br>Default value: **false** |
| status | [ProgressStatus<sup>10+</sup>](#progressstatus10) | No| Status of the progress indicator. When this parameter is set to **LOADING**, the check update animation is played, and the **value** settings do not take effect. When the value changes from **LOADING** to **PROGRESSING**, the check update animation stops when it has reached the end state.<br>Default value: **ProgressStatus.PROGRESSING**|
| enableScanEffect | boolean | No| Whether to enable the scan effect.<br>Default value: **false**|
| enableSmoothEffect<sup>10+</sup> | boolean | No| Whether to enable the smooth effect. When this effect is enabled, the progress change to the set value takes place gradually. Otherwise, it takes place immediately.<br>Default value: **true**|
## LinearStyleOptions<sup>10+</sup>
| Name | Type | Mandatory| Description |
| ------------- | ---------------------------- | ---- | ------------------------------------------------------------------------------------------ |
| strokeWidth | [Length](ts-types.md#length) | No | Stroke width of the progress indicator. It cannot be set in percentage.<br>Default value: **4.0vp**|
| enableScanEffect | boolean | No| Whether to enable the scan effect.<br>Default value: **false**|
| enableSmoothEffect<sup>10+</sup> | boolean | No| Whether to enable the smooth effect. When this effect is enabled, the progress change to the set value takes place gradually. Otherwise, it takes place immediately.<br>Default value: **true**|
## ScaleRingStyleOptions<sup>10+</sup>
| Name | Type | Mandatory| Description |
......@@ -102,9 +106,12 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| strokeWidth | [Length](ts-types.md#length) | No | Stroke width of the progress indicator. It cannot be set in percentage.<br>Default value: **4.0vp** |
| scaleCount | number | No | Number of divisions on the ring-style process indicator.<br>Default value: **120** |
| scaleWidth | [Length](ts-types.md#length) | No | Scale width of the ring-style progress bar. It cannot be set in percentage. If it is greater than the value of **strokeWidth**, the default scale width is used.<br>Default value: **2.0vp**|
| enableSmoothEffect<sup>10+</sup> | boolean | No| Whether to enable the smooth effect. When this effect is enabled, the progress change to the set value takes place gradually. Otherwise, it takes place immediately.<br>Default value: **true**|
## EclipseStyleOptions<sup>10+</sup>
No parameter available.
| Name | Type | Mandatory| Description |
| ------------ | ---------------------------- | ---- | ------------------------------------------------------------------------------------------ |
| enableSmoothEffect<sup>10+</sup> | boolean | No| Whether to enable the smooth effect. When this effect is enabled, the progress change to the set value takes place gradually. Otherwise, it takes place immediately.<br>Default value: **true**|
## ProgressStatus<sup>10+</sup>
| Name | Description |
......@@ -249,3 +256,38 @@ struct ProgressExample {
}
```
![capsuleProgressStyleEffect](figures/arkts-capsuleProgressStyleEffect.png)
### Example 5
This example shows the smooth effect.
```ts
@Entry
@Component
struct Index {
@State value: number = 0
build() {
Column({space: 10}) {
Text('enableSmoothEffect: true').fontSize(9).fontColor(0xCCCCCC).width('90%').margin(5)
.margin({top: 20})
Progress({value: this.value, total: 100, type:ProgressType.Linear})
.style({strokeWidth: 10, enableSmoothEffect: true})
Text('enableSmoothEffect: false').fontSize(9).fontColor(0xCCCCCC).width('90%').margin(5)
Progress({value: this.value, total: 100, type:ProgressType.Linear})
.style({strokeWidth: 10, enableSmoothEffect: false})
Button('value +10').onClick(() => {
this.value += 10
})
.width(75)
.height(15)
.fontSize(9)
}
.width('50%')
.height('100%')
.margin({left:20})
}
}
```
![progressSmoothEffect](figures/arkts-progressSmoothEffect.gif)
......@@ -37,7 +37,7 @@ Among the [universal attributes](ts-universal-attributes-size.md) and [universal
| caretColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the caret in the text box.<br>Default value: **'#007DFF'** |
| inputFilter<sup>8+</sup> | {<br>value: [ResourceStr](ts-types.md#resourcestr),<br>error?: (value: string) => void<br>} | Regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are filtered out. The specified regular expression can match single characters, but not strings.<br>- **value**: regular expression to set.<br>- **error**: filtered-out content to return when regular expression matching fails.|
| copyOption<sup>9+</sup> | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.<br>Default value: **CopyOptions.LocalDevice**<br>If this attribute is set to **CopyOptions.None**, the paste operation is allowed, but the copy and cut operations are not.|
| maxLength<sup>10+</sup> | number | Maximum number of characters in the text input.<br>By default, there is no maximum number of characters.|
| maxLength<sup>10+</sup> | number | Maximum number of characters in the text input.<br>By default, there is no maximum number of characters.<br>When the maximum number of characters is reached, no more characters can be entered, and the border turns red.|
| showCounter<sup>10+</sup> | boolean | Whether to show the number of entered characters when **maxLength** is set.<br>Default value: **false** |
| style<sup>10+</sup> | [TextContentStyle](ts-appendix-enums.md#textcontentstyle10) | Style of the component.<br>Default value: **TextContentStyle.DEFAULT** |
| enableKeyboardOnFocus<sup>10+</sup> | boolean | Whether to enable the input method when the component obtains focus.<br>Default value: **true** |
......
......@@ -286,7 +286,7 @@ struct ListLanesExample {
}
```
![list](figures/list1.gif)
![list](figures/list-alignListItem.gif)
### Example 3
......
......@@ -299,7 +299,7 @@ List() {
})
```
This example draws a divider with a stroke thickness of 1 vp from a position 60 vp away from the start edge of the list to a position 10 vp away from the end edge of the list. The effect is shown in Figure 8.
This example draws a divider with a stroke thickness of 1 vp from a position 60 vp away from the start edge of the list to a position 10 vp away from the end edge of the list. The effect is shown in Figure 9.
>**NOTE**
>
......@@ -653,8 +653,6 @@ The following describes the implementation of the pull-and-refresh feature:
3. Listen for the finger lift event. If the movement reaches the maximum value, trigger data loading and display the refresh view. After the loading is complete, hide the view.
You can also use the third-party component [PullToRefresh](https://gitee.com/openharmony-sig/PullToRefresh) to implement this feature.
## Editing a List
......
......@@ -11,23 +11,26 @@ Page redirection is an important part of the development process. When using an
**Figure 1** Page redirection
![router-jump-to-detail](figures/router-jump-to-detail.gif)
The **Router** module provides two redirection modes: [router.pushUrl()](../reference/apis/js-apis-router.md#routerpushurl9) and [router.replaceUrl()](../reference/apis/js-apis-router.md#routerreplaceurl9). The two modes determine whether the target page will replace the current page.
The **Router** module provides two redirection modes: [router.pushUrl()](../reference/apis/js-apis-router.md#routerpushurl9) and [router.replaceUrl()](../reference/apis/js-apis-router.md#routerreplaceurl9). Whether the target page will replace the current page depends on the mode used.
- **router.pushUrl()**: The target page does not replace the current page. Instead, it is pushed into the [page stack](../application-models/page-mission-stack.md). In this way, the state of the current page can be retained, and users can return to the current page by pressing the back button or calling the [router.back()](../reference/apis/js-apis-router.md#routerback) API.
- **router.pushUrl()**: The target page is pushed into the [page stack](../application-models/page-mission-stack.md) and does not replace the current page. In this mode, the state of the current page is retained, and users can return to the current page by pressing the back button or calling the [router.back()](../reference/apis/js-apis-router.md#routerback) API.
- **router.replaceUrl()**: The target page replaces the current page and destroys the current page. In this way, the resources of the current page can be released, and users cannot return to the current page.
- **router.replaceUrl()**: The target page replaces and destroys the current page. In this mode, the resources of the current page can be released, and users cannot return to the current page.
>**NOTE**
>
>The maximum capacity of a page stack is 32 pages. If this limit is exceeded, the [router.clear()](../reference/apis/js-apis-router.md#routerclear) API can be called to clear the historical page stack and free the memory.
>- When creating a page, configure the route to this page by following instructions in [Building the Second Page](../quick-start/start-with-ets-stage.md).
>
>
>- The maximum capacity of a page stack is 32 pages. If this limit is exceeded, the [router.clear()](../reference/apis/js-apis-router.md#routerclear) API can be called to clear the historical page stack and free the memory.
The **Router** module also provides two instance modes: **Standard** and **Single**. The two modes determine whether the target URL corresponds to multiple instances.
The **Router** module also provides two instance modes: **Standard** and **Single**. Depending on the mode, the target URL is mapped to one or more instances.
- **Standard**: standard instance mode, which is the default instance mode. Each time this API is called, a target page is created and pushed to the top of the stack.
- **Standard**: multi-instance mode. It is the default instance mode. In this mode, the target page is added to the top of the page stack, regardless of whether a page with the same URL exists in the stack.
- **Single**: singleton mode. If the URL of the target page already exists in the page stack, the page with the same URL closest to the top of the stack is moved to the top of the stack and reloaded. If the URL of the target page does not exist in the page stack, the page is redirected in standard mode.
- **Single**: singleton mode. In this mode, if the URL of the target page already exists in the page stack, the page closest to the top of the stack with the same URL is moved to the top of the stack and becomes the new page. If the URL of the target page does not exist in the page stack, the page is redirected in standard mode.
Before using the **Router** module, you need to import it to the code.
Before using the **Router** module, import it first.
```ts
......@@ -54,7 +57,7 @@ import router from '@ohos.router';
>**NOTE**
>
>In **Standard** instance mode, the **router.RouterMode.Standard** parameter can be omitted.
>In standard (multi-instance) mode, the **router.RouterMode.Standard** parameter can be omitted.
- Scenario 2: There is a login page (**Login**) and a personal center page (**Profile**). After a user successfully logs in from the **Login** page, the **Profile** page is displayed. At the same time, the **Login** page is destroyed, and the application exits when the back button is pressed. In this scenario, you can use the **replaceUrl()** API and use the Standard instance mode (which can also be omitted).
......@@ -76,7 +79,7 @@ import router from '@ohos.router';
>**NOTE**
>
>In **Standard** instance mode, the **router.RouterMode.Standard** parameter can be omitted.
>In standard (multi-instance) mode, the **router.RouterMode.Standard** parameter can be omitted.
- Scenario 3: There is a setting page (**Setting**) and a theme switching page (**Theme**). You want to click a theme option on the **Setting** page to go to the **Theme** page. In addition, you want to ensure that only one **Theme** page exists in the page stack at a time. When the back button is clicked on the **Theme** page, the **Setting** page is displayed. In this scenario, you can use the **pushUrl()** API and use the **Single** instance mode.
......@@ -115,7 +118,7 @@ import router from '@ohos.router';
The preceding scenarios do not involve parameter transfer.
If you need to transfer some data to the target page during redirection, you can add a **params** attribute and specify an object as a parameter when invoking an API of the **Router** module. Example:
If you need to transfer data to the target page during redirection, you can add a **params** attribute and specify an object as a parameter when invoking an API of the **Router** module. Example:
```ts
......@@ -150,11 +153,11 @@ function onJumpClick(): void {
}
```
On the target page, you can call the [getParams()](../reference/apis/js-apis-router.md#routergetparams) API of the **Router** module to obtain the transferred parameters. Example:
On the target page, you can call the [getParams()](../reference/apis/js-apis-router.md#routergetparams) API of the **Router** module to obtain the passed parameters. Example:
```ts
const params = router.getParams(); // Obtain the transferred parameter object.
const params = router.getParams(); // Obtain the passed parameters.
const id = params['id']; // Obtain the value of the id attribute.
const age = params['info'].age; // Obtain the value of the age attribute.
```
......@@ -162,13 +165,13 @@ const age = params['info'].age; // Obtain the value of the age attribute.
## Page Return
After a user completes an operation on a page, the user usually needs to return to the previous page or a specified page. In this case, the page return function is required. During the return process, the data may need to be transferred to the target page, which requires the data transfer function.
Implement the page return feature so that users can return to the previous page or a specified page. You can pass parameters to the target page during the return process.
**Figure 2** Page return
![router-back-to-home](figures/router-back-to-home.gif)
Before using the **Router** module, you need to import it to the code.
Before using the **Router** module, import it first.
```ts
......@@ -195,7 +198,7 @@ You can use any of the following methods to return to a page:
});
```
This method allows you to return to a specified page. You need to specify the path of the target page. For this method to work, the target page must it exist in the page stack.
This method allows uesrs to return to a page with the specified path. For this method to work, the target page must exist in the page stack.
- Method 3: Return to the specified page and transfer custom parameter information.
......@@ -209,14 +212,14 @@ You can use any of the following methods to return to a page:
});
```
This method not only allows you to return to the specified page, but also transfer custom parameter information when returning. The parameter information can be obtained and parsed by invoking the **router.getParams()** API on the target page.
This method not only allows you to return to the specified page, but also pass in custom parameter information during the return process. The parameter information can be obtained and parsed by invoking the **router.getParams()** API on the target page.
On the target page, call the **router.getParams()** API at the position where parameters need to be obtained, for example, in the **onPageShow()** lifecycle callback:
```ts
onPageShow() {
const params = router.getParams(); // Obtain the transferred parameter object.
const params = router.getParams(); // Obtain the passed parameters.
const info = params['info']; // Obtain the value of the info attribute.
}
```
......@@ -243,7 +246,7 @@ Such a dialog box can be in the [default style](#default-confirmation-dialog-box
To implement this function, you can use the [router.showAlertBeforeBackPage()](../reference/apis/js-apis-router.md#routershowalertbeforebackpage9) and [router.back()](../reference/apis/js-apis-router.md#routerback) APIs provided by the **Router** module.
Before using the **Router** module, you need to import it to the code.
Before using the **Router** module, import it first.
```ts
......@@ -272,17 +275,16 @@ function onBackClick(): void {
The **router.showAlertBeforeBackPage()** API receives an object as a parameter. The object contains the following attributes:
- **message**: content of the dialog box. The value is of the string type.
If the API is successfully called, the confirmation dialog box is displayed on the target page. Otherwise, an exception is thrown and the error code and error information is obtained through **err.code** and **err.message**.
When the user clicks the back button, a confirmation dialog box is displayed, prompting the user to confirm their operation. If the user selects Cancel, the application stays on the current page. If the user selects OK, the **router.back()** API is triggered and the redirection is performed based on the parameters.
**message**: content of the dialog box. The value is of the string type.
If the API is successfully called, the confirmation dialog box is displayed on the target page. Otherwise, an exception is thrown and the error code and error information is obtained through **err.code** and **err.message**.
When the user clicks the back button, a confirmation dialog box is displayed, prompting the user to confirm their operation. If the user selects Cancel, the application stays on the current page. If the user selects OK, the **router.back()** API is triggered and the redirection is performed based on the parameters.
### Custom Confirmation Dialog Box
To implement a custom confirmation dialog box, use APIs in the [PromptAction](../reference/apis/js-apis-promptAction.md#promptactionshowdialog) module or customize a popup window. This topic uses the APIs in the **PromptAction** module an example to describe how to implement a custom confirmation dialog box.
Before using the **Router** module, you need to import it to the code.
Before using the **Router** module, import it first.
```ts
......@@ -324,3 +326,63 @@ function onBackClick() {
```
When the user clicks the back button, the custom confirmation dialog box is displayed, prompting the user to confirm their operation. If the user selects Cancel, the application stays on the current page. If the user selects OK, the **router.back()** API is triggered and the redirection is performed based on the parameters.
## Named Route
To redirect to a [page in a shared package](../quick-start/shared-guide.md), you can use [router.pushNamedRoute()](../reference/apis/js-apis-router.md#routerpushnamedroute10).
Before using the **Router** module, import it first.
```ts
import router from '@ohos.router';
```
In the target page in the [shared package](../quick-start/shared-guide.md), name the [@Entry decorated custom component](../quick-start/arkts-create-custom-components.md#entryoptions10).
```ts
// library/src/main/ets/pages/Index.ets
@Entry({ routeName : 'myPage' })
@Component
struct MyComponent {
}
```
When the configuration is successful, import the named route page to the page from which you want to redirect.
```ts
// entry/src/main/ets/pages/Index.ets
import router from '@ohos.router';
import 'library/src/main/ets/Index.ets' // Import the named route page from the shared package library.
@Entry
@Component
struct Index {
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text('Hello World')
.fontSize(50)
.fontWeight(FontWeight.Bold)
.margin({ top: 20 })
.backgroundColor('#ccc')
.onClick(() => { // Click to go to a page in another shared package.
try {
router.pushNamedRoute({
name: 'myPage',
params: {
data1: 'message',
data2: {
data3: [123, 456, 789]
}
}
})
} catch (err) {
console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`);
}
})
}
.width('100%')
.height('100%')
}
}
```
......@@ -14,51 +14,37 @@ Perform the following steps on Ubuntu.
1. Run the following command to install hb and update it to the latest version:
```
pip3 install --user build/lite
```shell
python3 -m pip install --user build/hb
```
2. Set an environment variable.
```
```shell
vim ~/.bashrc
```
Copy the following command to the last line of the .bashrc file, save the file, and exit.
```
```shell
export PATH=~/.local/bin:$PATH
```
Update the environment variable.
```
```shell
source ~/.bashrc
```
3. Run the **hb -h** command in the source code directory. If the following information is displayed, the installation is successful:
```
usage: hb
OHOS build system
positional arguments:
{build,set,env,clean}
build Build source code
set OHOS build settings
env Show OHOS build env
clean Clean output
optional arguments:
-h, --help show this help message and exit
```
3. Run the **hb help** command in the source code directory. If the following information is displayed, the installation is successful:
![hb_help](figures/hb_help.png)
> ![icon-notice.gif](public_sys-resources/icon-notice.gif) **NOTICE**
> - To uninstall hb, run the following command:
>
> ```
> pip3 uninstall ohos-build
>
> ```shell
> python3 -m pip uninstall ohos-build
> ```
>
> - If any issue occurs during the hb installation, see [FAQs](quickstart-pkg-common-hberr.md).
......@@ -77,26 +63,26 @@ Perform the following steps on Ubuntu.
2. [Download LLVM](https://repo.huaweicloud.com/harmonyos/compiler/clang/9.0.0-36191/linux/llvm-linux-9.0.0-36191.tar).
3. Decompress the LLVM installation package to **~/llvm**.
```
```shell
tar -zxvf llvm.tar -C ~/
```
4. Set an environment variable.
```
```shell
vim ~/.bashrc
```
Copy the following command to the last line of the .bashrc file, save the file, and exit.
```
```shell
export PATH=~/llvm/bin:$PATH
```
5. Validate the environment variable.
```
```shell
source ~/.bashrc
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册