提交 f52412f9 编写于 作者: zyjhandsome's avatar zyjhandsome

Merge branch 'OpenHarmony-3.2-Release' of https://gitee.com/openharmony/docs...

Merge branch 'OpenHarmony-3.2-Release' of https://gitee.com/openharmony/docs into OpenHarmony-3.2-Release
......@@ -64,7 +64,8 @@ API references encompass all components and APIs available in OpenHarmony, helpi
They are organized as follows:
- [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/ts-components-summary.md)
- [Component Reference (JavaScript-compatible Web-like Development Paradigm)](reference/arkui-js/js-components-common-attributes.md)
- [Component Reference (JavaScript-compatible Web-like Development Paradigm- ArkUI.Full)](reference/arkui-js/Readme-EN.md)
- [Component Reference (JavaScript-compatible Web-like Development Paradigm- ArkUI.Lite)](reference/arkui-js-lite/Readme-EN.md)
- [JS Service Widget UI Components](reference/js-service-widget-ui/js-service-widget-file.md)
- [JS and TS APIs](reference/apis/development-intro.md)
- Native APIs
......
# AccessibilityExtensionAbility Development
# AccessibilityExtensionAbility
The **AccessibilityExtensionAbility** module provides accessibility extension capabilities based on the **ExtensionAbility** framework. You can develop your accessibility applications by applying the **AccessibilityExtensionAbility** template to enhance usability.
......
......@@ -3,42 +3,45 @@
## Implementation Principles
**Figure 1** ArkTS widget implementation principles
**Figure 1** ArkTS widget implementation principles
![WidgetPrinciple](figures/WidgetPrinciple.png)
- Widget host: an application that displays the widget content and controls the widget location. Only the system application can function as a widget host.
- Widget provider: an application that provides the widget content to display and controls how widget components are laid out and how they interact with users.
- Widget Manager: a resident agent that manages widgets in the system. It provides the [formProvider](../reference/apis/js-apis-app-form-formProvider.md) and [formHost](../reference/apis/js-apis-app-form-formHost.md) APIs as well as widget management, usage, and periodic updates.
- Widget Manager: a resident agent that manages widgets in the system. It provides the [formProvider](../reference/apis/js-apis-app-form-formProvider.md) and [formHost](../reference/apis/js-apis-app-form-formHost.md) APIs as well as the APIs for widget management, usage, and periodic updates.
- Widget rendering service: a service that manages widget rendering instances. Widget rendering instances are bound to the [widget components](../reference/arkui-ts/ts-basic-components-formcomponent.md) on the widget host on a one-to-one basis. The widget rendering service runs the widget page code **widgets.abc** for rendering, and sends the rendered data to the corresponding widget component on the widget host.
**Figure 2** Working principles of the ArkTS widget rendering service
![WidgetRender](figures/WidgetRender.png)
Unlike JS widgets, ArkTS widgets support logic code running. To avoid potential ArkTS widget issues from affecting the use of applications, the widget page code **widgets.abc** is executed by the widget rendering service, which is managed by the Widget Manager. Each widget component of a widget host corresponds to a rendering instance in the widget rendering service. Rendering instances of an application provider run in the same virtual machine operating environment, and rendering instances of different application providers run in different virtual machine operating environments. In this way, the resources and state data are isolated between widgets of different application providers. During development, pay attention to the use of the [globalThis](uiability-data-sync-with-ui.md#using-globalthis-between-uiability-and-page) object. Use one **globalThis** object for widgets by the same application provider, and different **globalThis** objects for widgets by different application providers.
Unlike JS widgets, ArkTS widgets support logic code running. The widget page code **widgets.abc** is executed by the widget rendering service, which is managed by the Widget Manager. Each widget component of a widget host corresponds to a rendering instance in the widget rendering service. Rendering instances of a widget provider run in the same virtual machine operating environment, and rendering instances of different widget providers run in different virtual machine operating environments. In this way, the resources and state data are isolated between widgets of different widget providers. During development, pay attention to the use of the [globalThis](uiability-data-sync-with-ui.md#using-globalthis-between-uiability-and-page) object. Use one **globalThis** object for widgets from the same widget provider, and different **globalThis** objects for widgets from different widget providers.
## Advantages of ArkTS Widgets
As a quick entry to applications, ArkTS widgets have the following advantages over JS widgets:
As a quick entry to applications, ArkTS widgets outperform JS widgets in the following aspects:
- Improved development experience and efficiency, thanks to the unified development paradigm
ArkTS widgets share the same declarative UI development framework as application pages. This means that the page layouts can be directly reused in widgets, improving development experience and efficiency.
**Figure 3** Comparison of widget project structures
**Figure 3** Comparison of widget project structures
![WidgetProject](figures/WidgetProject.png)
- More widget features
- Animation: The ArkTS widget supports the [attribute animation](../reference/arkui-ts/ts-animatorproperty.md) and [explicit animation](../reference/arkui-ts/ts-explicit-animation.md) capabilities, which can be leveraged to deliver a more engaging experience.
- Custom drawing: The ArkTS widget allows you to draw graphics with the [Canvas](../reference/arkui-ts/ts-components-canvas-canvas.md) component to present information more vividly.
- Logic code execution: The capability to run logic code in widgets means that service logic can be self-closed in widgets, expanding the service application scenarios of widgets.
- Animation: ArkTS widgets support the [attribute animation](../reference/arkui-ts/ts-animatorproperty.md) and [explicit animation](../reference/arkui-ts/ts-explicit-animation.md) capabilities, which can be leveraged to deliver a more engaging experience.
- Custom drawing: ArkTS widgets allow you to draw graphics with the [\<Canvas>](../reference/arkui-ts/ts-components-canvas-canvas.md) component to present information more vividly.
- Logic code execution: The capability to run logic code in widgets means that service logic can be self-closed in widgets, expanding the use cases of widgets.
## Constraints on ArkTS Widgets
Compared with JS widgets, ArkTS widgets provide more capabilities, but they are also more prone to malicious behavior. The ArkTS widget is displayed in the widget host, which is usually the home screen. To ensure user experience and power consumption, the ArkTS widget capability is restricted as follows:
Compared with JS widgets, ArkTS widgets provide more capabilities, but they are also more prone to malicious behavior. To account for the impact on the widget host – typically the home screen, ArkTS widgets are subject to the following restrictions:
- The .so file cannot be loaded.
......@@ -46,12 +49,14 @@ Compared with JS widgets, ArkTS widgets provide more capabilities, but they are
- Only [partial](arkts-ui-widget-page-overview.md) components, events, animations, data management, state management, and API capabilities of the declarative paradigm are supported.
- The event processing of the widget is independent of that of the widget host. It is recommended that you do not use the left and right sliding components when the widget host supports left and right swipes to prevent gesture conflicts.
- The event processing of the widget is independent of that of the widget host. To prevent gesture conflicts, avoid using swipers in the widget when the widget host supports left and right swipes.
The following features are coming to ArkTS widgets in later versions:
In addition, ArkTS widgets do not support the following features:
- Breakpoint debugging
- import statements
- Importing modules
- Instant preview
- Breakpoint debugging.
- Hot reload
......@@ -10,7 +10,7 @@ For details about the APIs, see [ohos.file.statvfs](../reference/apis/js-apis-fi
| Module| API| Description|
| -------- | -------- | -------- |
| \@ohos.file.storageStatistic | getCurrentBundleStats | Obtains the storage space of the current application, in bytes.|
| \@ohos.file.storageStatistics | getCurrentBundleStats | Obtains the storage space of the current application, in bytes.|
| \@ohos.file.statvfs | getFreeSize | Obtains the free space of a file system, in bytes.|
| \@ohos.file.statvfs | getTotalSize | Obtains the total space of a file system, in bytes.|
......
......@@ -7,10 +7,11 @@ The operations for saving images, audio or video clips, and documents are simila
## Saving Images or Video Files
1. Import the **FilePicker** module.
1. Import the **picker** module and **fs** module.
```ts
import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs';
```
2. Create a **photoSaveOptions** instance.
......@@ -20,27 +21,43 @@ The operations for saving images, audio or video clips, and documents are simila
photoSaveOptions.newFileNames = ["PhotoViewPicker01.jpg"]; // (Optional) Set the names of the files to save.
```
3. Create a **photoViewPicker** instance and call [save()](../reference/apis/js-apis-file-picker.md#save) to open the **FilePicker** page to save the files.
After the user selects the target folder, the file saving operation is complete. After the files are saved successfully, the URIs of the files saved are returned.
3. Create a **photoViewPicker** instance and call [save()](../reference/apis/js-apis-file-picker.md#save) to open the **FilePicker** page to save the files. After the user selects the target folder, the file saving operation is complete. After the files are saved successfully, the URIs of the files saved are returned.
<br>The permission on the URIs returned by **save()** is read/write. Further file operations can be performed based on the URIs in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
```ts
let URI = null;
const photoViewPicker = new picker.PhotoViewPicker();
photoViewPicker.save(photoSaveOptions)
.then(async (photoSaveResult) => {
let uri = photoSaveResult[0];
// Perform operations on the files based on the file URIs obtained.
})
.catch((err) => {
console.error(`Invoke documentPicker.select failed, code is ${err.code}, message is ${err.message}`);
})
photoViewPicker.save(photoSaveOptions).then((photoSaveResult) => {
URI = photoSaveResult[0];
console.info('photoViewPicker.save to file succeed and URI is:' + URI);
}).catch((err) => {
console.error(`Invoke photoViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
})
```
4. Use a button to trigger invocation of other functions. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_WRITE**.
```ts
let file = fs.openSync(URI, fs.OpenMode.READ_WRITE);
console.info('file fd: ' + file.fd);
```
5. Use [fs.writeSync()](../reference/apis/js-apis-file-fs.md#writesync) to edit the file based on the FD, and then close the FD.
```ts
let writeLen = fs.writeSync(file.fd, 'hello, world');
console.info('write data to file succeed and size is:' + writeLen);
fs.closeSync(file);
```
## Saving Documents
1. Import the **FilePicker** module.
1. Import the **picker** module and **fs** module.
```ts
import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs';
```
2. Create a **documentSaveOptions** instance.
......@@ -50,31 +67,43 @@ The operations for saving images, audio or video clips, and documents are simila
documentSaveOptions.newFileNames = ["DocumentViewPicker01.txt"]; // (Optional) Set the names of the documents to save.
```
3. Create a **documentViewPicker** instance, and call [save()](../reference/apis/js-apis-file-picker.md#save-3) to open the **FilePicker** page to save the documents.
After the user selects the target folder, the file saving operation is complete. After the files are saved successfully, the URIs of the files saved are returned.
> **NOTE**
>
> Currently, **DocumentSelectOptions** is not configurable. By default, all types of user files are selected.
3. Create a **documentViewPicker** instance, and call [save()](../reference/apis/js-apis-file-picker.md#save-3) to open the **FilePicker** page to save the documents. After the user selects the target folder, the file saving operation is complete. After the files are saved successfully, the URIs of the files saved are returned.
The permission on the URIs returned by **save()** is read/write. Further file operations can be performed based on the URIs in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
```ts
let URI = null;
const documentViewPicker = new picker.DocumentViewPicker(); // Create a documentViewPicker instance.
documentViewPicker.save(documentSaveOptions)
.then(async (documentSaveResult) => {
let uri = documentSaveResult[0];
// For example, write data to the documents based on the obtained URIs.
})
.catch((err) => {
console.error(`Invoke documentPicker.save failed, code is ${err.code}, message is ${err.message}`);
})
documentViewPicker.save(documentSaveOptions).then((documentSaveResult) => {
URI = documentSaveResult[0];
console.info('documentViewPicker.save to file succeed and URI is:' + URI);
}).catch((err) => {
console.error(`Invoke documentViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
})
```
4. Use a button to trigger invocation of other functions. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_WRITE**.
```ts
let file = fs.openSync(URI, fs.OpenMode.READ_WRITE);
console.info('file fd: ' + file.fd);
```
5. Use [fs.writeSync()](../reference/apis/js-apis-file-fs.md#writesync) to edit the file based on the FD, and then close the FD.
```ts
let writeLen = fs.writeSync(file.fd, 'hello, world');
console.info('write data to file succeed and size is:' + writeLen);
fs.closeSync(file);
```
## Saving Audio Files
1. Import the **FilePicker** module.
1. Import the **picker** module and **fs** module.
```ts
import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs';
```
2. Create an **audioSaveOptions** instance.
......@@ -84,20 +113,33 @@ The operations for saving images, audio or video clips, and documents are simila
audioSaveOptions.newFileNames = ['AudioViewPicker01.mp3']; // (Optional) Set the names of the files to save.
```
3. Create an **audioViewPicker** instance, and call [save()](../reference/apis/js-apis-file-picker.md#save-6) to open the **FilePicker** page to save the files.
After the user selects the target folder, the file saving operation is complete. After the files are saved successfully, the URIs of the files saved are returned.
> **NOTE**
>
> Currently, **AudioSelectOptions** is not configurable. By default, all types of user files are selected.
3. Create an **audioViewPicker** instance, and call [save()](../reference/apis/js-apis-file-picker.md#save-6) to open the **FilePicker** page to save the files. After the user selects the target folder, the file saving operation is complete. After the files are saved successfully, the URIs of the files saved are returned.
The permission on the URIs returned by **save()** is read/write. Further file operations can be performed based on the URIs in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
```ts
let URI = null;
const audioViewPicker = new picker.AudioViewPicker();
audioViewPicker.save(audioSaveOptions)
.then((audioSelectResult) => {
let uri = audioSelectResult[0];
// Perform operations on the audio files based on the file URIs.
})
.catch((err) => {
console.error(`Invoke audioPicker.select failed, code is ${err.code}, message is ${err.message}`);
})
audioViewPicker.save(audioSaveOptions).then((audioSelectResult) => {
URI = audioSelectResult[0];
console.info('audioViewPicker.save to file succeed and URI is:' + URI);
}).catch((err) => {
console.error(`Invoke audioViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
})
```
4. Use a button to trigger invocation of other functions. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_WRITE**.
```ts
let file = fs.openSync(URI, fs.OpenMode.READ_WRITE);
console.info('file fd: ' + file.fd);
```
5. Use [fs.writeSync](../reference/apis/js-apis-file-fs.md#writesync) to edit the file based on the FD, and then close the FD.
```ts
let writeLen = fs.writeSync(file.fd, 'hello, world');
console.info('write data to file succeed and size is:' + writeLen);
fs.closeSync(file);
```
# Selecting User Files
If your application needs to support share and saving of user files (such as images and videos) by users, you can use the [FilePicker](../reference/apis/js-apis-file-picker.md) prebuilt in OpenHarmony to implement selecting and saving of user files.
If your application needs to support share and saving of user files (such as images and videos), you can use OpenHarmony [FilePicker](../reference/apis/js-apis-file-picker.md) to implement selection and saving of user files.
The **FilePicker** provides the following interfaces by file type:
......@@ -12,10 +12,11 @@ The **FilePicker** provides the following interfaces by file type:
## Selecting Images or Video Files
1. Import the **FilePicker** module.
1. Import the **picker** module and **fs** module.
```ts
import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs';
```
2. Create a **photoSelectOptions** instance.
......@@ -32,28 +33,44 @@ The **FilePicker** provides the following interfaces by file type:
photoSelectOptions.maxSelectNumber = 5; // Set the maximum number of images to select.
```
4. Create a **photoPicker** instance and call [select()](../reference/apis/js-apis-file-picker.md#select) to open the **FilePicker** page for the user to select files.
4. Create a **photoPicker** instance and call [select()](../reference/apis/js-apis-file-picker.md#select) to open the **FilePicker** page for the user to select files. After the files are selected, [PhotoSelectResult](../reference/apis/js-apis-file-picker.md#photoselectresult) is returned.
<br>The permission on the URIs returned by **select()** is read-only. Further file operations can be performed based on the URIs in the **PhotoSelectResult**. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
Use [PhotoSelectResult](../reference/apis/js-apis-file-picker.md#photoselectresult) to return a result set. Further operations on the selected files can be performed based on the file URIs in the result set.
```ts
let URI = null;
const photoViewPicker = new picker.PhotoViewPicker();
photoViewPicker.select(photoSelectOptions).then((photoSelectResult) => {
URI = photoSelectResult.photoUris[0];
console.info('photoViewPicker.select to file succeed and URI is:' + URI);
}).catch((err) => {
console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
})
```
5. Use a button to trigger invocation of other functions. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_ONLY**.
```ts
let file = fs.openSync(URI, fs.OpenMode.READ_ONLY);
console.info('file fd: ' + file.fd);
```
6. Use [fs.readSync()](../reference/apis/js-apis-file-fs.md#readsync) to read the file data based on the FD. After the data is read, close the FD.
```ts
const photoPicker = new picker.PhotoViewPicker();
photoPicker.select(photoSelectOptions)
.then(async (photoSelectResult) => {
let uri = photoSelectResult.photoUris[0];
// Perform operations on the files based on the file URIs obtained.
})
.catch((err) => {
console.error(`Invoke documentPicker.select failed, code is ${err.code}, message is ${err.message}`);
})
let buffer = new ArrayBuffer(4096);
let readLen = fs.readSync(file.fd, buffer);
console.info('readSync data to file succeed and buffer size is:' + readLen);
fs.closeSync(file);
```
## Selecting Documents
1. Import the **FilePicker** module.
1. Import the **picker** module and **fs** module.
```ts
import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs';
```
2. Create a **documentSelectOptions** instance.
......@@ -62,26 +79,25 @@ The **FilePicker** provides the following interfaces by file type:
const documentSelectOptions = new picker.DocumentSelectOptions();
```
3. Create a **documentViewPicker** instance, and call [**select()**](../reference/apis/js-apis-file-picker.md#select-3) to open the **FilePicker** page for the user to select documents.
After the documents are selected successfully, a result set containing the file URIs is returned. Further operations can be performed on the documents based on the file URIs.
For example, you can use [file management APIs](../reference/apis/js-apis-file-fs.md) to obtain file attribute information, such as the file size, access time, and last modification time, based on the URI. If you need to obtain the file name, use [startAbilityForResult](../../application-dev/application-models/uiability-intra-device-interaction.md).
3. Create a **documentViewPicker** instance, and call [**select()**](../reference/apis/js-apis-file-picker.md#select-3) to open the **FilePicker** page for the user to select documents. After the documents are selected, a result set containing the file URIs is returned.
<br>The permission on the URIs returned by **select()** is read-only. Further file operations can be performed based on the URIs in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
<br>For example, you can use [file management APIs](../reference/apis/js-apis-file-fs.md) to obtain file attribute information, such as the file size, access time, and last modification time, based on the URI. If you need to obtain the file name, use [startAbilityForResult](../../application-dev/application-models/uiability-intra-device-interaction.md).
> **NOTE**
>
> Currently, **DocumentSelectOptions** is not configurable. By default, all types of user files are selected.
```ts
let URI = null;
const documentViewPicker = new picker.DocumentViewPicker(); // Create a documentViewPicker instance.
documentViewPicker.select(documentSelectOptions)
.then((documentSelectResult) => {
let uri = documentSelectResult[0];
// Perform operations on the documents based on the file URIs.
})
.catch((err) => {
console.error(`Invoke documentPicker.select failed, code is ${err.code}, message is ${err.message}`);
})
documentViewPicker.select(documentSelectOptions).then((documentSelectResult) => {
URI = documentSelectResult[0];
console.info('documentViewPicker.select to file succeed and URI is:' + URI);
}).catch((err) => {
console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
})
```
> **NOTE**
......@@ -98,7 +114,7 @@ The **FilePicker** provides the following interfaces by file type:
try {
let result = await context.startAbilityForResult(config, {windowMode: 1});
if (result.resultCode !== 0) {
console.error(`DocumentPicker.select failed, code is ${result.resultCode}, message is ${result.want.parameters.message}`);
console.error(`documentViewPicker.select failed, code is ${result.resultCode}, message is ${result.want.parameters.message}`);
return;
}
// Obtain the URI of the document.
......@@ -106,16 +122,34 @@ The **FilePicker** provides the following interfaces by file type:
// Obtain the name of the document.
let file_name_list = result.want.parameters.file_name_list;
} catch (err) {
console.error(`Invoke documentPicker.select failed, code is ${err.code}, message is ${err.message}`);
console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
}
```
4. Use a button to trigger invocation of other functions. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_ONLY**.
```ts
let file = fs.openSync(URI, fs.OpenMode.READ_ONLY);
console.info('file fd: ' + file.fd);
```
5. Use [fs.readSync()](../reference/apis/js-apis-file-fs.md#readsync) to read the file data based on the FD. After the data is read, close the FD.
```ts
let buffer = new ArrayBuffer(4096);
let readLen = fs.readSync(file.fd, buffer);
console.info('readSync data to file succeed and buffer size is:' + readLen);
fs.closeSync(file);
```
## Selecting an Audio File
1. Import the **FilePicker** module.
1. Import the **picker** module and **fs** module.
```ts
import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs';
```
2. Create an **audioSelectOptions** instance.
......@@ -124,24 +158,39 @@ The **FilePicker** provides the following interfaces by file type:
const audioSelectOptions = new picker.AudioSelectOptions();
```
3. Create an **audioViewPicker** instance, and call [**select()**](../reference/apis/js-apis-file-picker.md#select-6) to open the **FilePicker** page for the user to select audio files.
After the files are selected successfully, a result set containing the URIs of the audio files selected is returned. Further operations can be performed on the documents based on the file URIs.
For example, use the [file management interface](../reference/apis/js-apis-file-fs.md) to obtain the file handle (FD) of the audio clip based on the URI, and then develop the audio playback function based on the media service. For details, see [Audio Playback Development](../media/audio-playback-overview.md).
3. Create an **audioViewPicker** instance, and call [**select()**](../reference/apis/js-apis-file-picker.md#select-6) to open the **FilePicker** page for the user to select audio files. After the files are selected, a result set containing the URIs of the audio files selected is returned.
<br>The permission on the URIs returned by **select()** is read-only. Further file operations can be performed based on the URIs in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
<br>For example, use the [file management interface](../reference/apis/js-apis-file-fs.md) to obtain the file handle (FD) of the audio clip based on the URI, and then develop the audio playback function based on the media service. For details, see [Audio Playback Development](../media/audio-playback-overview.md).
> **NOTE**
>
> Currently, **AudioSelectOptions** is not configurable. By default, all types of user files are selected.
```ts
let URI = null;
const audioViewPicker = new picker.AudioViewPicker();
audioViewPicker.select(audioSelectOptions)
.then(audioSelectResult => {
let uri = audioSelectOptions[0];
// Perform operations on the audio files based on the file URIs.
})
.catch((err) => {
console.error(`Invoke audioPicker.select failed, code is ${err.code}, message is ${err.message}`);
})
audioViewPicker.select(audioSelectOptions).then(audioSelectResult => {
URI = audioSelectOptions[0];
console.info('audioViewPicker.select to file succeed and URI is:' + URI);
}).catch((err) => {
console.error(`Invoke audioViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
})
```
4. Use a button to trigger invocation of other functions. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_ONLY**.
```ts
let file = fs.openSync(URI, fs.OpenMode.READ_ONLY);
console.info('file fd: ' + file.fd);
```
5. Use [fs.readSync()](../reference/apis/js-apis-file-fs.md#readsync) to read the file data based on the FD. After the data is read, close the FD.
```ts
let buffer = new ArrayBuffer(4096);
let readLen = fs.readSync(file.fd, buffer);
console.info('readSync data to file succeed and buffer size is:' + readLen);
fs.closeSync(file);
```
......@@ -9,7 +9,9 @@ Below is the process of developing, debugging, releasing, and deploying multiple
You can use [DevEco Studio](https://developer.harmonyos.com/en/develop/deveco-studio) to create multiple modules as needed and develop services in respective modules.
## Debugging
After building code into one or more HAP files and installing or updating these HAP files, you can debug them by using the methods:
After building code into one or more HAP files and installing or updating these HAP files, you can debug them. You can leverage a single set of code and files to build multiple target editions for different audiences, deployment environments, operating environments, and more. For details, see [Customizing Multi-Target and Multi-Product Builds](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/customized-multi-targets-and-products-0000001430013853-V3?catalogVersion=V3).
You can debug HAP files using the methods:
* Using DevEco Studio for debugging
Follow the instructions in [Debugging Configuration](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-debugging-and-running-0000001263040487#section10491183521520).
......@@ -49,7 +51,7 @@ After building code into one or more HAP files and installing or updating these
// The execution result is as follows:
uninstall bundle successfully.
```
After the HAP files are installed or updated, you can debug them by following the instructions in [Ability Assistant](https://docs.openharmony.cn/pages/v3.2Beta/en/application-dev/tools/aa-tool.md/).
After the HAP files are installed or updated, you can debug them by following the instructions in [Ability Assistant](../tools/aa-tool.md).
## Release
When your application package meets the release requirements, you can package and build it into an App Pack and release it to the application market on the cloud. The application market verifies the signature of the App Pack. If the signature verification is successful, the application market obtains the HAP files from the App Pack, signs them, and distributes the signed HAP files.
......
# Shared Package Overview
OpenHarmony provides two types of shared packages: [Harmony Achive (HAR)](har-package.md) static shared package and Harmony Shared Package (HSP) dynamic shared package.
OpenHarmony provides two types of shared packages: [Harmony Archive (HAR)](har-package.md) static shared package and Harmony Shared Package (HSP) dynamic shared package.
Both the HAR and HSP are used to share code and resources and can contain code, C++ libraries, resources, and configuration files. The biggest differences between them are as follows: The code and resources in the HAR are compiled with the invoking module, and if there are multiple invoking modules, the build product contains multiple copies of the same code and resources; the code and resources in the HSP can be compiled independently, and the build product contains only one copy of the code and resources.
......
......@@ -37,14 +37,14 @@
- **AppScope** > **app.json5**: global configuration of your application.
- **entry**: OpenHarmony project module, which can be built into an OpenHarmony Ability Package ([HAP](../../glossary.md#hap)).
- **oh_modules**: third-party library dependency information. For details about how to adapt a historical npm project to ohpm, see [Manually Migrating Historical Projects](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/project_overview-0000001053822398-V3#section108143331212).
- **src > main > ets**: a collection of ArkTS source code.
- **src > main > ets > entryability**: entry to your application/service.
- **src > main > ets > pages**: pages included in your application/service.
- **src > main > resources**: a collection of resource files used by your application/service, such as graphics, multimedia, character strings, and layout files. For details about resource files, see [Resource Categories and Access](resource-categories-and-access.md#resource-categories).
- **src > main > module.json5**: module configuration file. This file describes the global configuration information of the application/service, the device-specific configuration information, and the configuration information of the HAP file. For details, see [module.json5 Configuration File](module-configuration-file.md).
- **build-profile.json5**: current module information and build configuration options, including **buildOption** and **targets**. Under **targets**, you can set **runtimeOS** to **HarmonyOS** (default) or **OpenHarmony**, depending on the OS of your application.
- **hvigorfile.ts**: module-level build script. You can customize related tasks and code implementation.
- **hvigorfile.ts**: module-level build script. You can customize related tasks and code implementation.
- **oh_modules**: third-party library dependency information. For details about how to adapt a historical npm project to ohpm, see [Manually Migrating Historical Projects](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/project_overview-0000001053822398-V3#section108143331212).
- **build-profile.json5**: application-level configuration information, including the signature and product configuration.
- **hvigorfile.ts**: application-level build script.
......
......@@ -21,11 +21,11 @@ Enumerates the NFC card emulation types.
**System capability**: SystemCapability.Communication.NFC.CardEmulation
| Name| Value| Description|
| -------- | -------- | -------- |
| HCE | 0 | HCE.|
| UICC | 1 | Subscriber identity module (SIM) card emulation.|
| ESE | 2 | embedded Secure Element (eSE) emulation.|
| Name | Value | Description |
| ---- | ---- | -------- |
| HCE | 0 | HCE.|
| UICC | 1 | Subscriber identity module (SIM) card emulation.|
| ESE | 2 | embedded Secure Element (eSE) emulation. |
## CardType<sup>9+</sup>
......@@ -33,10 +33,10 @@ Enumerates the types of services used by the card emulation application.
**System capability**: SystemCapability.Communication.NFC.CardEmulation
| Name| Value| Description|
| -------- | -------- | -------- |
| Name | Value | Description |
| ------- | --------- | ----------------- |
| PAYMENT | "payment" | Payment type.|
| OTHER | "other" | Other types.|
| OTHER | "other" | Other types.|
## isSupported
......@@ -51,14 +51,14 @@ Checks whether a certain type of card emulation is supported.
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | -------- | ---- | ----------------------- |
| feature | number | Yes | Card emulation type. For details, see [FeatureType](#featuretype).|
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ---------------------------------------- |
| feature | number | Yes | Card emulation type. For details, see [FeatureType](#featuretype).|
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| **Type** | **Description** |
| ------- | -------------------------------------- |
| boolean | Returns **true** if the card emulation type is supported; returns **false** otherwise.|
## hasHceCapability<sup>9+</sup>
......@@ -73,8 +73,8 @@ Checks whether HCE is supported.
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| **Type** | **Description** |
| ------- | -------------------------------- |
| boolean | Returns **true** if HCE is supported; returns **false** otherwise.|
## isDefaultService<sup>9+</sup>
......@@ -89,15 +89,15 @@ Checks whether an application is the default application of the specified servic
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | -------- | ---- | ----------------------- |
| elementName | [ElementName](js-apis-bundleManager-elementName.md#elementname) | Yes| Application description, which consists of the bundle name and component name.|
| type | [CardType](#cardtype9) | Yes| Card emulation service type.|
| Name | Type | Mandatory | Description |
| ----------- | ---------------------------------------- | ---- | ----------------------- |
| elementName | [ElementName](js-apis-bundleManager-elementName.md#elementname) | Yes | Application description, which consists of the bundle name and component name.|
| type | [CardType](#cardtype9) | Yes | Card emulation service type. |
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| **Type** | **Description** |
| ------- | ------------------------------------ |
| boolean | Returns **true** if the application is the default payment application; returns **false** otherwise.|
**Example**
......@@ -108,13 +108,11 @@ import cardEmulation from '@ohos.nfc.cardEmulation';
var isHceSupported = cardEmulation.isSupported(cardEmulation.FeatureType.HCE);
if (!isHceSupported) {
console.log('this device is not supported for HCE, ignore it.');
return;
}
var hasHceCap = cardEmulation.hasHceCapability();
if (!hasHceCap) {
console.log('this device hasHceCapability false, ignore it.');
return;
}
var elementName = {
......
......@@ -6,7 +6,7 @@ The **relationalStore** module provides the following functions:
- [RdbPredicates](#rdbpredicates): provides predicates indicating the nature, feature, or relationship of a data entity in an RDB store. It is used to define the operation conditions for an RDB store.
- [RdbStore](#rdbstore): provides APIs for managing data in an RDB store.
- [ResultSet](#resultset): provides APIs for accessing the result set obtained from the RDB store.
- [Resultset](#resultset): provides APIs for accessing the result set obtained from the RDB store.
> **NOTE**
>
......@@ -38,11 +38,11 @@ Obtains an RDB store. This API uses an asynchronous callback to return the resul
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | ------------------------------------------------- |
| **ID**| **Error Message** |
| ------------ | ----------------------------------------------------------- |
| 14800010 | Failed to open or delete database by invalid database path. |
| 14800011 | Failed open database, database corrupted. |
| 14800000 | The inner error is occurred. |
| 14800011 | Failed to open database by database corrupted. |
| 14800000 | Inner error. |
**Example**
......@@ -122,11 +122,11 @@ Obtains an RDB store. This API uses a promise to return the result. You can set
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | ------------------------------------------------- |
| **ID**| **Error Message** |
| ------------ | ----------------------------------------------------------- |
| 14800010 | Failed to open or delete database by invalid database path. |
| 14800011 | Failed open database, database corrupted. |
| 14800000 | The inner error is occurred. |
| 14800011 | Failed to open database by database corrupted. |
| 14800000 | Inner error. |
**Example**
......@@ -198,10 +198,10 @@ Deletes an RDB store. This API uses an asynchronous callback to return the resul
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | ------------------------------------------------- |
| **ID**| **Error Message** |
| ------------ | ----------------------------------------------------------- |
| 14800010 | Failed to open or delete database by invalid database path. |
| 14800000 | The inner error is occurred. |
| 14800000 | Inner error. |
**Example**
......@@ -265,10 +265,10 @@ Deletes an RDB store. This API uses a promise to return the result.
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | ------------------------------------------------- |
| **ID**| **Error Message** |
| ------------ | ----------------------------------------------------------- |
| 14800010 | Failed to open or delete database by invalid database path. |
| 14800000 | The inner error is occurred. |
| 14800000 | Inner error. |
**Example**
......@@ -323,7 +323,7 @@ Enumerates the RDB store security levels.
> **NOTE**
>
> To perform data synchronization operations, the RDB store security level must be lower than or equal to that of the peer device. For details, see the [Access Control Mechanism in Cross-Device Synchronization](../../database/access-control-by-device-and-data-level.md#access-control-mechanism-in-cross-device-synchronization).
> To perform data synchronization operations, the RDB store security level must be lower than or equal to that of the peer device. For details, see the [Cross-Device Data Synchronization Mechanism]( ../../database/sync-app-data-across-devices-overview.md#cross-device-data-synchronization-mechanism).
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
......@@ -378,10 +378,26 @@ Defines the subscription type.
| Name | Value | Description |
| --------------------- | ---- | ------------------ |
| SUBSCRIBE_TYPE_REMOTE | 0 | Subscribe to remote data changes.|
| SUBSCRIBE_TYPE_CLOUD<sup>10+</sup> | 1 | Subscribe to cloud data changes.|
## ConflictResolution<sup>10+</sup>
Defines the resolution to use when **insert()** and **update()** conflict.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
| Name | Value | Description |
| -------------------- | ---- | ------------------------------------------------------------ |
| ON_CONFLICT_NONE | 0 | No operation is performed.|
| ON_CONFLICT_ROLLBACK | 1 | Abort the SQL statement and roll back the current transaction. |
| ON_CONFLICT_ABORT | 2 | Abort the current SQL statement and revert any changes made by the current SQL statement. However, the changes made by the previous SQL statement in the same transaction are retained and the transaction remains active.|
| ON_CONFLICT_FAIL | 3 | Abort the current SQL statement. The **FAIL** resolution does not revert previous changes made by the failed SQL statement or end the transaction.|
| ON_CONFLICT_IGNORE | 4 | Skip the rows that contain constraint violations and continue to process the subsequent rows of the SQL statement.|
| ON_CONFLICT_REPLACE | 5 | Delete pre-existing rows that cause the constraint violation before inserting or updating the current row, and continue to execute the command normally.|
## RdbPredicates
Defines the predicates for an RDB store. This class determines whether the conditional expression for the RDB store is true or false. This type is not multi-thread safe. If a **RdbPredicates** instance is operated by multiple threads at the same time in an application, use a lock for the instance.
Defines the predicates for an RDB store. This class determines whether the conditional expression for the RDB store is true or false. This type is not multi-thread safe. If an **RdbPredicates** instance is operated by multiple threads at the same time in an application, use a lock for the instance.
### constructor
......@@ -1237,10 +1253,27 @@ predicates.notIn("NAME", ["Lisa", "Rose"]);
## RdbStore
Provides methods to manage an RDB store.
Provides APIs to manage an RDB store.
Before using the APIs of this class, use [executeSql](#executesql) to initialize the database table structure and related data.
### Attributes<sup>10+</sup>
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
| Name | Type | Mandatory| Description |
| ------------ | ----------- | ---- | -------------------------------- |
| version<sup>10+</sup> | number | Yes | RDB store version, which is an integer greater than 0. |
**Example**
```js
// Set the RDB store version.
store.version = 3;
// Obtain the RDB store version.
console.info(`RdbStore version is ${store.version}`);
```
### insert
insert(table: string, values: ValuesBucket, callback: AsyncCallback&lt;number&gt;):void
......@@ -1257,6 +1290,15 @@ Inserts a row of data into a table. This API uses an asynchronous callback to re
| values | [ValuesBucket](#valuesbucket) | Yes | Row of data to insert. |
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.|
**Error codes**
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800047 | The WAL file size exceeds the default limit. |
| 14800000 | Inner error. |
**Example**
```js
......@@ -1275,6 +1317,49 @@ store.insert("EMPLOYEE", valueBucket, function (err, rowId) {
})
```
### insert<sup>10+</sup>
insert(table: string, values: ValuesBucket, conflict: ConflictResolution, callback: AsyncCallback&lt;number&gt;):void
Inserts a row of data into a table. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------- | ---- | ---------------------------------------------------------- |
| table | string | Yes | Name of the target table. |
| values | [ValuesBucket](#valuesbucket) | Yes | Row of data to insert. |
| conflict | [ConflictResolution](#conflictresolution10) | Yes | Resolution used to resolve the conflict. |
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.|
**Error codes**
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800047 | The WAL file size exceeds the default limit. |
| 14800000 | Inner error. |
**Example**
```js
const valueBucket = {
"NAME": "Lisa",
"AGE": 18,
"SALARY": 100.5,
"CODES": new Uint8Array([1, 2, 3, 4, 5]),
};
store.insert("EMPLOYEE", valueBucket, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE, function (err, rowId) {
if (err) {
console.error(`Insert is failed, code is ${err.code},message is ${err.message}`);
return;
}
console.info(`Insert is successful, rowId = ${rowId}`);
})
```
### insert
......@@ -1303,7 +1388,8 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800000 | The inner error is occurred. |
| 14800047 | The WAL file size exceeds the default limit. |
| 14800000 | Inner error. |
**Example**
......@@ -1322,6 +1408,53 @@ promise.then((rowId) => {
})
```
### insert<sup>10+</sup>
insert(table: string, values: ValuesBucket, conflict: ConflictResolution):Promise&lt;number&gt;
Inserts a row of data into a table. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------- | ---- | -------------------------- |
| table | string | Yes | Name of the target table. |
| values | [ValuesBucket](#valuesbucket) | Yes | Row of data to insert.|
| conflict | [ConflictResolution](#conflictresolution10) | Yes | Resolution used to resolve the conflict. |
**Return value**
| Type | Description |
| --------------------- | ------------------------------------------------- |
| Promise&lt;number&gt; | Promise used to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.|
**Error codes**
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800047 | The WAL file size exceeds the default limit. |
| 14800000 | Inner error. |
**Example**
```js
const valueBucket = {
"NAME": "Lisa",
"AGE": 18,
"SALARY": 100.5,
"CODES": new Uint8Array([1, 2, 3, 4, 5]),
};
let promise = store.insert("EMPLOYEE", valueBucket, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE);
promise.then((rowId) => {
console.info(`Insert is successful, rowId = ${rowId}`);
}).catch((err) => {
console.error(`Insert is failed, code is ${err.code},message is ${err.message}`);
})
```
### batchInsert
......@@ -1345,7 +1478,8 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800000 | The inner error is occurred. |
| 14800047 | The WAL file size exceeds the default limit. |
| 14800000 | Inner error. |
**Example**
......@@ -1406,7 +1540,8 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800000 | The inner error is occurred. |
| 14800047 | The WAL file size exceeds the default limit. |
| 14800000 | Inner error. |
**Example**
......@@ -1455,14 +1590,14 @@ Updates data in the RDB store based on the specified **RdbPredicates** object. T
| predicates | [RdbPredicates](#rdbpredicates) | Yes | Update conditions specified by the **RdbPredicates** object. |
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the number of rows updated. |
**Error codes**
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800000 | The inner error is occurred. |
| 14800047 | The WAL file size exceeds the default limit. |
| 14800000 | Inner error. |
**Example**
......@@ -1484,6 +1619,51 @@ store.update(valueBucket, predicates, function (err, rows) {
})
```
### update<sup>10+</sup>
update(values: ValuesBucket, predicates: RdbPredicates, conflict: ConflictResolution, callback: AsyncCallback&lt;number&gt;):void
Updates data in the RDB store based on the specified **RdbPredicates** object. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ---------- | ------------------------------------------- | ---- | ------------------------------------------------------------ |
| values | [ValuesBucket](#valuesbucket) | Yes | Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.|
| predicates | [RdbPredicates](#rdbpredicates) | Yes | Update conditions specified by the **RdbPredicates** object. |
| conflict | [ConflictResolution](#conflictresolution10) | Yes | Resolution used to resolve the conflict. |
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the number of rows updated. |
**Error codes**
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800047 | The WAL file size exceeds the default limit. |
| 14800000 | Inner error. |
**Example**
```js
const valueBucket = {
"NAME": "Rose",
"AGE": 22,
"SALARY": 200.5,
"CODES": new Uint8Array([1, 2, 3, 4, 5]),
};
let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
predicates.equalTo("NAME", "Lisa");
store.update(valueBucket, predicates, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE, function (err, rows) {
if (err) {
console.error(`Updated failed, code is ${err.code},message is ${err.message}`);
return;
}
console.info(`Updated row count: ${rows}`);
})
```
### update
......@@ -1512,7 +1692,8 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800000 | The inner error is occurred. |
| 14800047 | The WAL file size exceeds the default limit. |
| 14800000 | Inner error. |
**Example**
......@@ -1533,6 +1714,55 @@ promise.then(async (rows) => {
})
```
### update<sup>10+</sup>
update(values: ValuesBucket, predicates: RdbPredicates, conflict: ConflictResolution):Promise&lt;number&gt;
Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ---------- | ------------------------------------------- | ---- | ------------------------------------------------------------ |
| values | [ValuesBucket](#valuesbucket) | Yes | Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.|
| predicates | [RdbPredicates](#rdbpredicates) | Yes | Update conditions specified by the **RdbPredicates** object. |
| conflict | [ConflictResolution](#conflictresolution10) | Yes | Resolution used to resolve the conflict. |
**Return value**
| Type | Description |
| --------------------- | ----------------------------------------- |
| Promise&lt;number&gt; | Promise used to return the number of rows updated.|
**Error codes**
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800047 | The WAL file size exceeds the default limit. |
| 14800000 | Inner error. |
**Example**
```js
const valueBucket = {
"NAME": "Rose",
"AGE": 22,
"SALARY": 200.5,
"CODES": new Uint8Array([1, 2, 3, 4, 5]),
};
let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
predicates.equalTo("NAME", "Lisa");
let promise = store.update(valueBucket, predicates, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE);
promise.then(async (rows) => {
console.info(`Updated row count: ${rows}`);
}).catch((err) => {
console.error(`Updated failed, code is ${err.code},message is ${err.message}`);
})
```
### update
......@@ -1561,7 +1791,8 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800000 | The inner error is occurred. |
| 14800047 | The WAL file size exceeds the default limit. |
| 14800000 | Inner error. |
**Example**
......@@ -1616,7 +1847,8 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800000 | The inner error is occurred. |
| 14800047 | The WAL file size exceeds the default limit. |
| 14800000 | Inner error. |
**Example**
......@@ -1659,7 +1891,8 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800000 | The inner error is occurred. |
| 14800047 | The WAL file size exceeds the default limit. |
| 14800000 | Inner error. |
**Example**
......@@ -1693,7 +1926,7 @@ Deletes data from the RDB store based on the specified **RdbPredicates** object.
| Type | Description |
| --------------------- | ------------------------------- |
| Promise&lt;number&gt; | Promise used to return the number of rows deleted. |
| Promise&lt;number&gt; | Promise used to return the number of rows deleted.|
**Error codes**
......@@ -1701,7 +1934,8 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800000 | The inner error is occurred. |
| 14800047 | The WAL file size exceeds the default limit. |
| 14800000 | Inner error. |
**Example**
......@@ -1734,7 +1968,7 @@ Deletes data from the RDB store based on the specified **DataSharePredicates** o
| ---------- | ------------------------------------------------------------ | ---- | --------------------------------------------- |
| table | string | Yes | Name of the target table. |
| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Conditions specified by the **DataSharePredicates** object for deleting data.|
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the number of rows deleted. |
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the number of rows deleted. |
**Error codes**
......@@ -1742,7 +1976,8 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800000 | The inner error is occurred. |
| 14800047 | The WAL file size exceeds the default limit. |
| 14800000 | Inner error. |
**Example**
......@@ -1790,7 +2025,8 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800000 | The inner error is occurred. |
| 14800047 | The WAL file size exceeds the default limit. |
| 14800000 | Inner error. |
**Example**
......@@ -1826,9 +2062,9 @@ Queries data from the RDB store based on specified conditions. This API uses an
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800000 | The inner error is occurred. |
| **ID**| **Error Message** |
| ------------ | ---------------------------- |
| 14800000 | Inner error. |
**Example**
......@@ -1840,8 +2076,17 @@ store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err,
console.error(`Query failed, code is ${err.code},message is ${err.message}`);
return;
}
console.info(`ResultSet column names: ${resultSet.columnNames}`);
console.info(`ResultSet column count: ${resultSet.columnCount}`);
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
while(resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY"));
console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`);
}
// Release the dataset memory.
resultSet.close();
})
```
......@@ -1860,20 +2105,20 @@ Queries data from the RDB store based on specified conditions. This API uses a p
| predicates | [RdbPredicates](#rdbpredicates) | Yes | Query conditions specified by the **RdbPredicates** object. |
| columns | Array&lt;string&gt; | No | Columns to query. If this parameter is not specified, the query applies to all columns.|
**Error codes**
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | ---------------------------- |
| 14800000 | Inner error. |
**Return value**
| Type | Description |
| ------------------------------------------------------- | -------------------------------------------------- |
| Promise&lt;[ResultSet](#resultset)&gt; | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.|
**Error codes**
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800000 | The inner error is occurred. |
**Example**
```js
......@@ -1881,8 +2126,17 @@ let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
predicates.equalTo("NAME", "Rose");
let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]);
promise.then((resultSet) => {
console.info(`ResultSet column names: ${resultSet.columnNames}`);
console.info(`ResultSet column count: ${resultSet.columnCount}`);
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
while(resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY"));
console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`);
}
// Release the dataset memory.
resultSet.close();
}).catch((err) => {
console.error(`Query failed, code is ${err.code},message is ${err.message}`);
})
......@@ -1913,9 +2167,9 @@ Queries data from the RDB store based on specified conditions. This API uses an
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800000 | The inner error is occurred. |
| **ID**| **Error Message** |
| ------------ | ---------------------------- |
| 14800000 | Inner error. |
**Example**
......@@ -1928,8 +2182,17 @@ store.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], fu
console.error(`Query failed, code is ${err.code},message is ${err.message}`);
return;
}
console.info(`ResultSet column names: ${resultSet.columnNames}`);
console.info(`ResultSet column count: ${resultSet.columnCount}`);
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
while(resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY"));
console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`);
}
// Release the dataset memory.
resultSet.close();
})
```
......@@ -1963,9 +2226,9 @@ Queries data from the RDB store based on specified conditions. This API uses a p
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800000 | The inner error is occurred. |
| **ID**| **Error Message** |
| ------------ | ---------------------------- |
| 14800000 | Inner error. |
**Example**
......@@ -1975,8 +2238,17 @@ let predicates = new dataSharePredicates.DataSharePredicates();
predicates.equalTo("NAME", "Rose");
let promise = store.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]);
promise.then((resultSet) => {
console.info(`ResultSet column names: ${resultSet.columnNames}`);
console.info(`ResultSet column count: ${resultSet.columnCount}`);
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
while(resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY"));
console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`);
}
// Release the dataset memory.
resultSet.close();
}).catch((err) => {
console.error(`Query failed, code is ${err.code},message is ${err.message}`);
})
......@@ -1988,7 +2260,7 @@ remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: A
Queries data from the RDB store of a remote device based on specified conditions. This API uses an asynchronous callback to return the result.
> **NOTE**
> **NOTE**<br/>
>
> The value of **device** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
......@@ -2008,9 +2280,9 @@ Queries data from the RDB store of a remote device based on specified conditions
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800000 | The inner error is occurred. |
| **ID**| **Error Message** |
| ------------ | ---------------------------- |
| 14800000 | Inner error. |
**Example**
......@@ -2037,8 +2309,17 @@ store.remoteQuery(deviceId, "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALAR
console.error(`Failed to remoteQuery, code is ${err.code},message is ${err.message}`);
return;
}
console.info(`ResultSet column names: ${resultSet.columnNames}`);
console.info(`ResultSet column count: ${resultSet.columnCount}`);
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
while(resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY"));
console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`);
}
// Release the dataset memory.
resultSet.close();
}
)
```
......@@ -2049,7 +2330,7 @@ remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: A
Queries data from the RDB store of a remote device based on specified conditions. This API uses a promise to return the result.
> **NOTE**
> **NOTE**<br/>
>
> The value of **device** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
......@@ -2074,9 +2355,9 @@ Queries data from the RDB store of a remote device based on specified conditions
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800000 | The inner error is occurred. |
| **ID**| **Error Message** |
| ------------ | ---------------------------- |
| 14800000 | Inner error. |
**Example**
......@@ -2099,8 +2380,17 @@ let predicates = new relationalStore.RdbPredicates('EMPLOYEE');
predicates.greaterThan("id", 0);
let promise = store.remoteQuery(deviceId, "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]);
promise.then((resultSet) => {
console.info(`ResultSet column names: ${resultSet.columnNames}`);
console.info(`ResultSet column count: ${resultSet.columnCount}`);
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
while(resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY"));
console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`);
}
// Release the dataset memory.
resultSet.close();
}).catch((err) => {
console.error(`Failed to remoteQuery, code is ${err.code},message is ${err.message}`);
})
......@@ -2126,9 +2416,9 @@ Queries data using the specified SQL statement. This API uses an asynchronous ca
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800000 | The inner error is occurred. |
| **ID**| **Error Message** |
| ------------ | ---------------------------- |
| 14800000 | Inner error. |
**Example**
......@@ -2138,8 +2428,17 @@ store.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['s
console.error(`Query failed, code is ${err.code},message is ${err.message}`);
return;
}
console.info(`ResultSet column names: ${resultSet.columnNames}`);
console.info(`ResultSet column count: ${resultSet.columnCount}`);
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
while(resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY"));
console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`);
}
// Release the dataset memory.
resultSet.close();
})
```
......@@ -2168,17 +2467,26 @@ Queries data using the specified SQL statement. This API uses a promise to retur
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800000 | The inner error is occurred. |
| **ID**| **Error Message** |
| ------------ | ---------------------------- |
| 14800000 | Inner error. |
**Example**
```js
let promise = store.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = 'sanguo'");
promise.then((resultSet) => {
console.info(`ResultSet column names: ${resultSet.columnNames}`);
console.info(`ResultSet column count: ${resultSet.columnCount}`);
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
while(resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY"));
console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`);
}
// Release the dataset memory.
resultSet.close();
}).catch((err) => {
console.error(`Query failed, code is ${err.code},message is ${err.message}`);
})
......@@ -2206,7 +2514,8 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800000 | The inner error is occurred. |
| 14800047 | The WAL file size exceeds the default limit. |
| 14800000 | Inner error. |
**Example**
......@@ -2248,7 +2557,8 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800000 | The inner error is occurred. |
| 14800047 | The WAL file size exceeds the default limit. |
| 14800000 | Inner error. |
**Example**
......@@ -2276,7 +2586,8 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800000 | The inner error is occurred. |
| 14800047 | The WAL file size exceeds the default limit. |
| 14800000 | Inner error. |
**Example**
......@@ -2397,9 +2708,9 @@ Backs up an RDB store. This API uses an asynchronous callback to return the resu
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800000 | The inner error is occurred. |
| **ID**| **Error Message** |
| ------------ | ---------------------------- |
| 14800000 | Inner error. |
**Example**
......@@ -2427,20 +2738,20 @@ Backs up an RDB store. This API uses a promise to return the result.
| -------- | ------ | ---- | ------------------------ |
| destName | string | Yes | Name of the RDB store backup file.|
**Error codes**
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800000 | The inner error is occurred. |
**Return value**
| Type | Description |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|
**Error codes**
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | ---------------------------- |
| 14800000 | Inner error. |
**Example**
```js
......@@ -2471,9 +2782,9 @@ Restores an RDB store from a backup file. This API uses an asynchronous callback
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800000 | The inner error is occurred. |
| **ID**| **Error Message** |
| ------------ | ---------------------------- |
| 14800000 | Inner error. |
**Example**
......@@ -2511,9 +2822,9 @@ Restores an RDB store from a backup file. This API uses a promise to return the
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800000 | The inner error is occurred. |
| **ID**| **Error Message** |
| ------------ | ---------------------------- |
| 14800000 | Inner error. |
**Example**
......@@ -2547,9 +2858,9 @@ Sets distributed tables. This API uses an asynchronous callback to return the re
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800000 | The inner error is occurred. |
| **ID**| **Error Message** |
| ------------ | ---------------------------- |
| 14800000 | Inner error. |
**Example**
......@@ -2589,9 +2900,9 @@ Sets distributed tables. This API uses a promise to return the result.
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800000 | The inner error is occurred. |
| **ID**| **Error Message** |
| ------------ | ---------------------------- |
| 14800000 | Inner error. |
**Example**
......@@ -2630,9 +2941,9 @@ Obtains the distributed table name of a remote device based on the local table n
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800000 | The inner error is occurred. |
| **ID**| **Error Message** |
| ------------ | ---------------------------- |
| 14800000 | Inner error. |
**Example**
......@@ -2691,9 +3002,9 @@ Obtains the distributed table name of a remote device based on the local table n
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800000 | The inner error is occurred. |
| **ID**| **Error Message** |
| ------------ | ---------------------------- |
| 14800000 | Inner error. |
**Example**
......@@ -2742,9 +3053,9 @@ Synchronizes data between devices. This API uses an asynchronous callback to ret
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800000 | The inner error is occurred. |
| **ID**| **Error Message** |
| ------------ | ---------------------------- |
| 14800000 | Inner error. |
**Example**
......@@ -2806,9 +3117,9 @@ Synchronizes data between devices. This API uses a promise to return the result.
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800000 | The inner error is occurred. |
| **ID**| **Error Message** |
| ------------ | ---------------------------- |
| 14800000 | Inner error. |
**Example**
......@@ -2854,9 +3165,9 @@ Registers an observer for this RDB store. When the data in the RDB store changes
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------- | ---- | ------------------------------------------- |
| event | string | Yes | Event to observe. The value is **dataChange**, which indicates a data change event. |
| event | string | Yes | Event to observe. The value is **dataChange**, which indicates a data change event. |
| type | [SubscribeType](#subscribetype) | Yes | Subscription type to register.|
| observer | Callback&lt;Array&lt;string&gt;&gt; | Yes | Callback invoked to return the data change. **Array<string>** indicates the IDs of the peer devices whose data in the database is changed.|
| observer | Callback&lt;Array&lt;string&gt;&gt; | Yes | Callback invoked to return the data change event. **Array<string>** indicates the IDs of the peer devices whose data in the database is changed.|
**Example**
......@@ -2885,9 +3196,9 @@ Unregisters the observer of the specified type from the RDB store. This API uses
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------- | ---- | ------------------------------------------ |
| event | string | Yes | Event to observe. The value is **dataChange**, which indicates a data change event. |
| type | [SubscribeType](#subscribetype) | Yes | Subscription type to unregister. |
| observer | Callback&lt;Array&lt;string&gt;&gt; | Yes | Callback for the data change. **Array<string>** indicates the IDs of the peer devices whose data in the database is changed.|
| event | string | Yes | Event type. The value is **dataChange**, which indicates a data change event. |
| type | [SubscribeType](#subscribetype) | Yes | Subscription type to unregister. |
| observer | Callback&lt;Array&lt;string&gt;&gt; | Yes | Callback for the data change event. **Array<string>** indicates the IDs of the peer devices whose data in the database is changed.|
**Example**
......@@ -3040,7 +3351,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
| **ID**| **Error Message** |
| ------------ | ------------------------------------------------------------ |
| 14800012 | The result set is empty, or the specified location is invalid. |
| 14800012 | The result set is empty or the specified location is invalid. |
**Example**
......@@ -3081,7 +3392,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
| **ID**| **Error Message** |
| ------------ | ------------------------------------------------------------ |
| 14800012 | The result set is empty, or the specified location is invalid. |
| 14800012 | The result set is empty or the specified location is invalid. |
**Example**
......@@ -3117,7 +3428,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
| **ID**| **Error Message** |
| ------------ | ------------------------------------------------------------ |
| 14800012 | The result set is empty, or the specified location is invalid. |
| 14800012 | The result set is empty or the specified location is invalid. |
**Example**
......@@ -3152,7 +3463,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
| **ID**| **Error Message** |
| ------------ | ------------------------------------------------------------ |
| 14800012 | The result set is empty, or the specified location is invalid. |
| 14800012 | The result set is empty or the specified location is invalid. |
**Example**
......@@ -3187,7 +3498,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
| **ID**| **Error Message** |
| ------------ | ------------------------------------------------------------ |
| 14800012 | The result set is empty, or the specified location is invalid. |
| 14800012 | The result set is empty or the specified location is invalid. |
**Example**
......@@ -3222,7 +3533,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
| **ID**| **Error Message** |
| ------------ | ------------------------------------------------------------ |
| 14800012 | The result set is empty, or the specified location is invalid. |
| 14800012 | The result set is empty or the specified location is invalid. |
**Example**
......@@ -3323,7 +3634,7 @@ Obtains the value of the Long type based on the specified column and the current
| Type | Description |
| ------ | ------------------------------------------------------------ |
| number | Value obtained.<br>The value range supported by this API is **Number.MIN_SAFE_INTEGER** to **Number.MAX_SAFE_INTEGER**. If the value is out of this range, use [getDouble](#getdouble).|
| number | Value obtained.<br>The value range supported by API is **Number.MIN_SAFE_INTEGER** to **Number.MAX_SAFE_INTEGER**. If the value is out of this range, use [getDouble](#getdouble).|
**Error codes**
......@@ -3433,4 +3744,4 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
| **ID**| **Error Message** |
| ------------ | ------------------------------------------------------------ |
| 14800012 | The result set is empty, or the specified location is invalid. |
| 14800012 | The result set is empty or the specified location is invalid. |
......@@ -14,7 +14,7 @@ import fileShare from '@ohos.fileshare';
## fileShare.grantUriPermission
grantUriPermission(uri: string, bundleName: string, mode: number, callback: AsyncCallback&lt;void&gt;): void
grantUriPermission(uri: string, bundleName: string, flag: wantConstant.Flags, callback: AsyncCallback&lt;void&gt;): void
Grants permissions on a user file by the URI to an application. This API uses an asynchronous callback to return the result.
......@@ -30,7 +30,7 @@ Grants permissions on a user file by the URI to an application. This API uses an
| ------ | ------ | ---- | -------------------------- |
| uri | string | Yes | URI of a user file.|
| bundleName | string | Yes | Bundle name of the application to be grated with the permissions.|
| mode | number | Yes | Permissions to grant. For details, see [wantConstant.Flags](js-apis-app-ability-wantConstant.md#wantconstantflags).<br>**wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION**: permission to read the file. <br>**wantConstant.Flags.FLAG_AUTH_WRITE_URI_PERMISSION**: permission to write the file.|
| flag | wantConstant.Flags | Yes | Permissions to grant. For details, see [wantConstant.Flags](js-apis-app-ability-wantConstant.md#wantconstantflags).<br>**wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION**: permission to read the file. <br>**wantConstant.Flags.FLAG_AUTH_WRITE_URI_PERMISSION**: permission to write the file.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. |
**Error codes**
......@@ -67,7 +67,7 @@ try {
## fileShare.grantUriPermission
grantUriPermission(uri: string, bundleName: string, mode: number): Promise&lt;void&gt;
grantUriPermission(uri: string, bundleName: string, flag: wantConstant.Flags): Promise&lt;void&gt;
Grants permissions on a user file by the URI to an application. This API uses a promise to return the result.
......@@ -83,7 +83,7 @@ Grants permissions on a user file by the URI to an application. This API uses a
| ------ | ------ | ---- | -------------------------- |
| uri | string | Yes | URI of a user file.|
| bundleName | string | Yes | Bundle name of the application to be grated with the permissions.|
| mode | number | Yes | Permissions to grant. For details, see [wantConstant.Flags](js-apis-app-ability-wantConstant.md#wantconstantflags).<br>**wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION**: permission to read the file. <br>**wantConstant.Flags.FLAG_AUTH_WRITE_URI_PERMISSION**: permission to write the file.|
| flag | wantConstant.Flags | Yes | Permissions to grant. For details, see [wantConstant.Flags](js-apis-app-ability-wantConstant.md#wantconstantflags).<br>**wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION**: permission to read the file. <br>**wantConstant.Flags.FLAG_AUTH_WRITE_URI_PERMISSION**: permission to write the file.|
**Return value**
......
......@@ -21,8 +21,9 @@ Before using the APIs provided by this module to perform operations on files or
**Stage Model**
```js
import Ability from '@ohos.application.Ability';
class MainAbility extends Ability {
import UIAbility from '@ohos.app.ability.UIAbility';
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
let context = this.context;
let pathDir = context.filesDir;
......@@ -30,19 +31,18 @@ class MainAbility extends Ability {
}
```
For details about how to obtain the stage model context, see [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md).
**FA Model**
```js
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
context.getFilesDir().then((data) => {
let pathDir = data;
})
```
For details about how to obtain the FA model context, see [Contex](js-apis-inner-app-context.md#context).
For details about how to obtain the FA model context, see [Contex](js-apis-inner-app-context.md#context).
## fileio.stat
......
# @ohos.font (Custom Font Registration)
The **font** module provides APIs for registering custom fonts.
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```ts
import font from '@ohos.font'
```
## font.registerFont
registerFont(options: FontOptions): void
Registers a custom font with the font manager.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | --------------------------- | ---- | ----------- |
| options | [FontOptions](#fontoptions) | Yes | Information about the custom font to register.|
## FontOptions
| Name | Type | Mandatory | Description |
| ---------- | ------ | ---- | ------------ |
| familyName | string | Yes | Name of the custom font to register. |
| familySrc | string | Yes | Path of the custom font to register.|
## Example
```ts
// xxx.ets
import font from '@ohos.font';
@Entry
@Component
struct FontExample {
@State message: string =' Hello, World'
aboutToAppear() {
font.registerFont({
familyName: 'medium',
familySrc: '/font/medium.ttf'
})
}
build() {
Column() {
Text(this.message)
.align(Alignment.Center)
.fontSize(20)
.fontFamily('medium') // medium: name of the custom font to register.
.height('100%')
}.width('100%')
}
}
```
......@@ -610,7 +610,7 @@ Defines the accessibilityelement. Before calling APIs of **AccessibilityElement*
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
## attributeNames
### attributeNames
attributeNames\<T extends keyof ElementAttributeValues>(): Promise\<Array\<T>>;
......@@ -636,7 +636,7 @@ rootElement.attributeNames().then((data) => {
console.log('failed to get attribute names, because ' + JSON.stringify(err));
});
```
## attributeNames
### attributeNames
attributeNames\<T extends keyof ElementAttributeValues>(callback: AsyncCallback\<Array\<T>>): void;
......@@ -664,7 +664,7 @@ rootElement.attributeNames((err, data) => {
console.info('get attribute names success');
});
```
## AccessibilityElement.attributeValue
### attributeValue
attributeValue\<T extends keyof ElementAttributeValues>(attributeName: T): Promise\<ElementAttributeValues[T]>;
......@@ -709,7 +709,7 @@ try {
console.log('failed to get attribute value, because ' + JSON.stringify(exception));
}
```
## AccessibilityElement.attributeValue
### attributeValue
attributeValue\<T extends keyof ElementAttributeValues>(attributeName: T,
callback: AsyncCallback\<ElementAttributeValues[T]>): void;
......@@ -752,7 +752,7 @@ try {
console.log('failed to get attribute value, because ' + JSON.stringify(exception));
}
```
## actionNames
### actionNames
actionNames(): Promise\<Array\<string>>;
......@@ -778,7 +778,7 @@ rootElement.actionNames().then((data) => {
console.log('failed to get action names because ' + JSON.stringify(err));
});
```
## actionNames
### actionNames
actionNames(callback: AsyncCallback\<Array\<string>>): void;
......@@ -806,7 +806,7 @@ rootElement.actionNames((err, data) => {
console.info('get action names success');
});
```
## performAction
### performAction
performAction(actionName: string, parameters?: object): Promise\<void>;
......@@ -849,7 +849,7 @@ try {
console.log('failed to perform action, because ' + JSON.stringify(exception));
}
```
## performAction
### performAction
performAction(actionName: string, callback: AsyncCallback\<void>): void;
......@@ -888,7 +888,7 @@ try {
console.log('failed to perform action, because ' + JSON.stringify(exception));
}
```
## performAction
### performAction
performAction(actionName: string, parameters: object, callback: AsyncCallback\<void>): void;
......@@ -932,7 +932,7 @@ try {
console.log('failed to perform action, because ' + JSON.stringify(exception));
}
```
## findElement('content')
### findElement('content')
findElement(type: 'content', condition: string): Promise\<Array\<AccessibilityElement>>;
......@@ -971,7 +971,7 @@ try {
console.log('failed to find element, because ' + JSON.stringify(exception));
}
```
## findElement('content')
### findElement('content')
findElement(type: 'content', condition: string, callback: AsyncCallback\<Array\<AccessibilityElement>>): void;
......@@ -1007,7 +1007,7 @@ try {
console.log('failed to find element, because ' + JSON.stringify(exception));
}
```
## findElement('focusType')
### findElement('focusType')
findElement(type: 'focusType', condition: FocusType): Promise\<AccessibilityElement>;
......@@ -1046,7 +1046,7 @@ try {
console.log('failed to find element, because ' + JSON.stringify(exception));
}
```
## findElement('focusType')
### findElement('focusType')
findElement(type: 'focusType', condition: FocusType, callback: AsyncCallback\<AccessibilityElement>): void;
......@@ -1082,7 +1082,7 @@ try {
console.log('failed to find element, because ' + JSON.stringify(exception));
}
```
## findElement('focusDirection')
### findElement('focusDirection')
findElement(type: 'focusDirection', condition: FocusDirection): Promise\<AccessibilityElement>;
......@@ -1121,7 +1121,7 @@ try {
console.log('failed to find element, because ' + JSON.stringify(exception));
}
```
## findElement('focusDirection')
### findElement('focusDirection')
findElement(type: 'focusDirection', condition: FocusDirection, callback: AsyncCallback\<AccessibilityElement>): void;
......
......@@ -48,10 +48,11 @@ Before developing applications related to tag read and write, you must declare N
}
```
> **CAUTION**<br>
1. The **actions** field is mandatory. It must be **ohos.nfc.tag.action.TAG_FOUND** and cannot be changed.
2. The **name** field under **metadata** is mandatory. It must be **tag-tech** and cannot be changed.
3. The **value** field under **metadata** is mandatory. It can be **NfcA**, **NfcB**, **NfcF**, **NfcV**, **IsoDep**, **Ndef**, **MifareClassic**, **MifareUL**, **NdefFormatable** or any of their combinations. Incorrect settings of this field will cause a parsing failure.
4. The **name** field under **requestPermissions** is mandatory. It must be **ohos.permission.NFC_TAG** and cannot be changed.
>
> - The **actions** field is mandatory. It must be **ohos.nfc.tag.action.TAG_FOUND** and cannot be changed.
> - The **name** field under **metadata** is mandatory. It must be **tag-tech** and cannot be changed.
> - The **value** field under **metadata** is mandatory. It can be **NfcA**, **NfcB**, **NfcF**, **NfcV**, **IsoDep**, **Ndef**, **MifareClassic**, **MifareUL**, **NdefFormatable** or any of their combinations. Incorrect settings of this field will cause a parsing failure.
> - The **name** field under **requestPermissions** is mandatory. It must be **ohos.permission.NFC_TAG** and cannot be changed.
## **Modules to Import**
......@@ -98,7 +99,7 @@ onCreate(want, launchParam) {
if (isNfcATag) {
var nfcA;
try {
nfcA = tag.getNfcATag(taginfo);
nfcA = tag.getNfcATag(tagInfo);
} catch (error) {
console.log("tag.getNfcATag caught error: " + error);
}
......@@ -109,7 +110,7 @@ onCreate(want, launchParam) {
if (isIsoDepTag) {
var isoDep;
try {
isoDep = tag.getIsoDep(taginfo);
isoDep = tag.getIsoDep(tagInfo);
} catch (error) {
console.log("tag.getIsoDep caught error: " + error);
}
......@@ -139,8 +140,8 @@ Obtains an **NfcATag** object, which allows access to the tags that use the NFC-
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| **Type** | **Description** |
| ------------------------------------- | ------------- |
| [NfcATag](js-apis-nfctech.md#nfcatag) | **NfcATag** object obtained.|
## tag.getNfcA<sup>9+</sup>
......@@ -159,16 +160,16 @@ Obtains an **NfcATag** object, which allows access to the tags that use the NFC-
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| **Type** | **Description** |
| ------------------------------------- | ------------- |
| [NfcATag](js-apis-nfctech.md#nfcatag) | **NfcATag** object obtained.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| ID | Error Message |
| ------- | ---------------------------------------- |
| 3100201 | Tag running state is abnormal in service. |
## tag.getNfcBTag
......@@ -190,9 +191,9 @@ Obtains an **NfcBTag** object, which allows access to the tags that use the NFC-
**Return value**
| **Type**| **Description** |
| -------- | ---------------- |
| [NfcBTag](js-apis-nfctech.md#nfcbtag) | **NfcBTag** object obtained.|
| **Type** | **Description** |
| ------------------------------------- | ------------- |
| [NfcBTag](js-apis-nfctech.md#nfcbtag) | **NfcBTag** object obtained.|
## tag.getNfcB<sup>9+</sup>
......@@ -210,16 +211,16 @@ Obtains an **NfcBTag** object, which allows access to the tags that use the NFC-
**Return value**
| **Type**| **Description** |
| -------- | ---------------- |
| [NfcBTag](js-apis-nfctech.md#nfcbtag) | **NfcBTag** object obtained.|
| **Type** | **Description** |
| ------------------------------------- | ------------- |
| [NfcBTag](js-apis-nfctech.md#nfcbtag) | **NfcBTag** object obtained.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| ID | Error Message |
| ------- | ---------------------------------------- |
| 3100201 | Tag running state is abnormal in service. |
## tag.getNfcFTag
......@@ -241,9 +242,9 @@ Obtains an **NfcFTag** object, which allows access to the tags that use the NFC-
**Return value**
| **Type**| **Description** |
| -------- | ---------------- |
| [NfcFTag](js-apis-nfctech.md#nfcftag) | **NfcFTag** object obtained.|
| **Type** | **Description** |
| ------------------------------------- | ------------- |
| [NfcFTag](js-apis-nfctech.md#nfcftag) | **NfcFTag** object obtained.|
## tag.getNfcF<sup>9+</sup>
......@@ -261,16 +262,16 @@ Obtains an **NfcFTag** object, which allows access to the tags that use the NFC-
**Return value**
| **Type**| **Description** |
| -------- | ---------------- |
| [NfcFTag](js-apis-nfctech.md#nfcftag) | **NfcFTag** object obtained.|
| **Type** | **Description** |
| ------------------------------------- | ------------- |
| [NfcFTag](js-apis-nfctech.md#nfcftag) | **NfcFTag** object obtained.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| ID | Error Message |
| ------- | ---------------------------------------- |
| 3100201 | Tag running state is abnormal in service. |
## tag.getNfcVTag
......@@ -292,9 +293,9 @@ Obtains an **NfcVTag** object, which allows access to the tags that use the NFC-
**Return value**
| **Type**| **Description** |
| -------- | ---------------- |
| [NfcVTag](js-apis-nfctech.md#nfcvtag) | **NfcVTag** object obtained.|
| **Type** | **Description** |
| ------------------------------------- | ------------- |
| [NfcVTag](js-apis-nfctech.md#nfcvtag) | **NfcVTag** object obtained.|
## tag.getNfcV<sup>9+</sup>
......@@ -312,16 +313,16 @@ Obtains an **NfcVTag** object, which allows access to the tags that use the NFC-
**Return value**
| **Type**| **Description** |
| -------- | ---------------- |
| [NfcVTag](js-apis-nfctech.md#nfcvtag) | **NfcVTag** object obtained.|
| **Type** | **Description** |
| ------------------------------------- | ------------- |
| [NfcVTag](js-apis-nfctech.md#nfcvtag) | **NfcVTag** object obtained.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| ID | Error Message |
| ------- | ---------------------------------------- |
| 3100201 | Tag running state is abnormal in service. |
## tag.getIsoDep<sup>9+</sup>
......@@ -334,22 +335,22 @@ Obtains an **IsoDepTag** object, which allows access to the tags that use the IS
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------------------------- | ---- | ---------------------------------------- |
| taginfo | [TagInfo](#taginfo) | Yes| Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. |
| Name | Type | Mandatory | Description |
| ------- | ------------------- | ---- | ---------------------------------------- |
| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**.|
**Return value**
| **Type**| **Description** |
| ---------- | ------------------|
| [IsoDepTag](js-apis-nfctech.md#isodeptag9) | **IsoDepTag** object obtained.|
| **Type** | **Description** |
| ---------------------------------------- | ----------------------------------- |
| [IsoDepTag](js-apis-nfctech.md#isodeptag9) | **IsoDepTag** object obtained.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| ID | Error Message |
| ------- | ---------------------------------------- |
| 3100201 | Tag running state is abnormal in service. |
## tag.getNdef<sup>9+</sup>
......@@ -362,22 +363,22 @@ Obtains an **NdefTag** object, which allows access to the tags in the NFC Data E
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------------------------- | ---- | ---------------------------------------- |
| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. |
| Name | Type | Mandatory | Description |
| ------- | ------------------- | ---- | ---------------------------------------- |
| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**.|
**Return value**
| **Type**| **Description** |
| ---------| -------------- |
| [NdefTag](js-apis-nfctech.md#ndeftag9) | **NdefTag** object obtained.|
| **Type** | **Description** |
| -------------------------------------- | ------------------------------- |
| [NdefTag](js-apis-nfctech.md#ndeftag9) | **NdefTag** object obtained.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| ID | Error Message |
| ------- | ---------------------------------------- |
| 3100201 | Tag running state is abnormal in service. |
## tag.getMifareClassic<sup>9+</sup>
......@@ -390,22 +391,22 @@ Obtains a **MifareClassicTag** object, which allows access to the tags that use
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------------------------- | ---- | ---------------------------------------- |
| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. |
| Name | Type | Mandatory | Description |
| ------- | ------------------- | ---- | ---------------------------------------- |
| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**.|
**Return value**
| **Type**| **Description** |
| ----------------- | ------------------------|
| [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) | **MifareClassicTag** object obtained.|
| **Type** | **Description** |
| ---------------------------------------- | ---------------------------------------- |
| [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) | **MifareClassicTag** object obtained.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| ID | Error Message |
| ------- | ---------------------------------------- |
| 3100201 | Tag running state is abnormal in service. |
## tag.getMifareUltralight<sup>9+</sup>
......@@ -417,22 +418,22 @@ Obtains a **MifareUltralightTag** object, which allows access to the tags that u
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------------------------- | ---- | ---------------------------------------- |
| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. |
| Name | Type | Mandatory | Description |
| ------- | ------------------- | ---- | ---------------------------------------- |
| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**.|
**Return value**
| **Type**| **Description** |
| -------------------- | ---------------------------|
| [MifareUltralightTag](js-apis-nfctech.md#mifareultralighttag9) | **MifareUltralightTag** object obtained.|
| **Type** | **Description** |
| ---------------------------------------- | ---------------------------------------- |
| [MifareUltralightTag](js-apis-nfctech.md#mifareultralighttag9) | **MifareUltralightTag** object obtained.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| ID | Error Message |
| ------- | ---------------------------------------- |
| 3100201 | Tag running state is abnormal in service. |
## tag.getNdefFormatable<sup>9+</sup>
......@@ -445,16 +446,16 @@ Obtains an **NdefFormatableTag** object, which allows access to the tags that ar
**Return value**
| **Type**| **Description** |
| ------------------ | --------------------------|
| [NdefFormatableTag](js-apis-nfctech.md#ndefformatabletag) | **NdefFormatableTag** object obtained.|
| **Type** | **Description** |
| ---------------------------------------- | ---------------------------------------- |
| [NdefFormatableTag](js-apis-nfctech.md#ndefformatabletag) | **NdefFormatableTag** object obtained.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| ID | Error Message |
| ------- | ---------------------------------------- |
| 3100201 | Tag running state is abnormal in service. |
## tag.getTagInfo<sup>9+</sup>
......@@ -467,14 +468,14 @@ Obtains **TagInfo** from **Want**, which is initialized by the NFC service and c
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------------------------- | ---- | ---------------------------------------- |
| want | [Want](js-apis-app-ability-want.md#Want) | Yes | Data obtained from the parameters of the **onCreate** entry function when an ability is dispatched. |
| Name | Type | Mandatory | Description |
| ---- | ---------------------------------------- | ---- | --------------------------------- |
| want | [Want](js-apis-app-ability-want.md#Want) | Yes | Data obtained from the parameters of the **onCreate** entry function when an ability is dispatched.|
**Return value**
| **Type**| **Description** |
| ------------------ | --------------------------|
| **Type** | **Description** |
| ------------------- | --------------------------- |
| [TagInfo](#taginfo) | **TagInfo** object obtained.|
......@@ -488,14 +489,14 @@ Creates an NDEF record based on the specified URI.
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- |
| uri | string | Yes| Data to write to the NDEF record.|
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ---------------------- |
| uri | string | Yes | Data to write to the NDEF record.|
**Return value**
| **Type**| **Description** |
| ------------------ | --------------------------|
| **Type** | **Description** |
| -------------------------- | ---------------------------------------- |
| [NdefRecord](#ndefrecord9) | NDEF record created. For details, see *NFCForum-TS-NDEF_1.0*.|
**Example**
......@@ -527,15 +528,15 @@ Creates an NDEF record based on the specified text data and encoding type.
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- |
| text | string | Yes | Text to write to the NDEF record.|
| locale | string | Yes | Encoding mode of the text.|
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ------------------------ |
| text | string | Yes | Text to write to the NDEF record.|
| locale | string | Yes | Encoding mode of the text. |
**Return value**
| **Type**| **Description** |
| ------------------ | --------------------------|
| **Type** | **Description** |
| -------------------------- | ---------------------------------------- |
| [NdefRecord](#ndefrecord9) | NDEF record created. For details, see *NFCForum-TS-NDEF_1.0*.|
**Example**
......@@ -569,15 +570,15 @@ Creates an NDEF record based on the specified MIME data and type.
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- |
| mimeType | string | Yes | MIME type that complies with RFC rules, for example, **text/plain** or **image/jpeg**.|
| mimeData | number[] | Yes | MIME data, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
| Name | Type | Mandatory | Description |
| -------- | -------- | ---- | ---------------------------------------- |
| mimeType | string | Yes | MIME type that complies with RFC rules, for example, **text/plain** or **image/jpeg**.|
| mimeData | number[] | Yes | MIME data, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**. |
**Return value**
| **Type**| **Description** |
| ------------------ | --------------------------|
| **Type** | **Description** |
| -------------------------- | ---------------------------------------- |
| [NdefRecord](#ndefrecord9) | NDEF record created. For details, see *NFCForum-TS-NDEF_1.0*.|
**Example**
......@@ -609,16 +610,16 @@ Creates an NDEF record based on application-specific data.
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- |
| domainName | string | Yes | Bundle name of the application or domain name of the organization that releases the applications.|
| type | string | Yes | Type of the application data.|
| externalData | number[] | Yes | Application data, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
| Name | Type | Mandatory | Description |
| ------------ | -------- | ---- | ----------------------------------- |
| domainName | string | Yes | Bundle name of the application or domain name of the organization that releases the applications. |
| type | string | Yes | Type of the application data. |
| externalData | number[] | Yes | Application data, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
**Return value**
| **Type**| **Description** |
| ------------------ | --------------------------|
| **Type** | **Description** |
| -------------------------- | ---------------------------------------- |
| [NdefRecord](#ndefrecord9) | NDEF record created. For details, see *NFCForum-TS-NDEF_1.0*.|
**Example**
......@@ -652,14 +653,14 @@ Converts an NDEF message to bytes.
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- |
| ndefMessage | [NdefMessage](js-apis-nfctech.md#ndefmessage9) | Yes | NDEF message to convert.|
| Name | Type | Mandatory | Description |
| ----------- | ---------------------------------------- | ---- | ----------- |
| ndefMessage | [NdefMessage](js-apis-nfctech.md#ndefmessage9) | Yes | NDEF message to convert.|
**Return value**
| **Type**| **Description** |
| ------------------ | --------------------------|
| **Type** | **Description** |
| -------- | ---------------------------------------- |
| number[] | NDEF message in bytes, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
**Example**
......@@ -693,14 +694,14 @@ Creates an NDEF message from raw byte data. The data must comply with the NDEF r
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| data | number[] | Yes| Raw byte data, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**. The data must comply with the NDEF record format.|
| **Name**| **Type** | **Mandatory**| **Description** |
| ------- | -------- | ------ | ---------------------------------------- |
| data | number[] | Yes | Raw byte data, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**. The data must comply with the NDEF record format.|
**Return value**
| **Type**| **Description** |
| ------------------ | --------------------------|
| **Type** | **Description** |
| ---------------------------------------- | ---------------------------------------- |
| [NdefMessage](js-apis-nfctech.md#ndefmessage9) | NDEF message created. For details, see *NFCForum-TS-NDEF_1.0*.|
**Example**
......@@ -727,14 +728,14 @@ Creates an NDEF message from the NDEF records list.
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| ndefRecords | [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] | Yes| NDEF record list used to create the NDEF message. For details, see *NFCForum-TS-NDEF_1.0*.|
| **Name** | **Type** | **Mandatory**| **Description** |
| ----------- | ---------------------------------------- | ------ | ---------------------------------------- |
| ndefRecords | [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] | Yes | NDEF record list used to create the NDEF message. For details, see *NFCForum-TS-NDEF_1.0*.|
**Return value**
| **Type**| **Description** |
| ------------------ | --------------------------|
| **Type** | **Description** |
| ---------------------------------------- | ---------------------------------------- |
| [NdefMessage](js-apis-nfctech.md#ndefmessage9) | NDEF message created. For details, see *NFCForum-TS-NDEF_1.0*.|
**Example**
......@@ -762,66 +763,66 @@ Defines the **TagInfo** object, which provides information about the tag technol
**Required permissions**: ohos.permission.NFC_TAG
| **Name**| **Type**| **Readable**| **Writable**| **Description**|
| -------- | -------- | -------- | -------- | -------- |
| uid<sup>9+</sup> | number[] | Yes| No| Tag unique identifier (UID), which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
| technology<sup>9+</sup> | number[] | Yes| No| Supported technologies. Each number is a constant indicating the supported technology.|
| supportedProfiles | number[] | Yes| No| Supported profiles. This parameter is not supported since API version 9. Use [tag.TagInfo#technology](#tagtaginfo) instead.|
| extrasData<sup>9+</sup> | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap)[] | Yes| No| Extended attribute value of the tag technology.<br>**System API**: This is a system API.|
| tagRfDiscId<sup>9+</sup> | number | Yes| No| ID allocated when the tag is discovered.<br>**System API**: This is a system API.|
| remoteTagService<sup>9+</sup> | [rpc.RemoteObject](js-apis-rpc.md#remoteobject) | Yes| No| Remote object of the NFC service process used for interface communication between the client and the service.<br>**System API**: This is a system API.|
| **Name** | **Type** | **Readable**| **Writable**| **Description** |
| ----------------------------- | ---------------------------------------- | ------ | ------ | ---------------------------------------- |
| uid<sup>9+</sup> | number[] | Yes | No | Tag unique identifier (UID), which consists of hexadecimal numbers ranging from **0x00** to **0xFF**. |
| technology<sup>9+</sup> | number[] | Yes | No | Supported technologies. Each number is a constant indicating the supported technology. |
| supportedProfiles | number[] | Yes | No | Supported profiles. This parameter is not supported since API version 9. Use [tag.TagInfo#technology](#tagtaginfo) instead.|
| extrasData<sup>9+</sup> | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap)[] | Yes | No | Extended attribute value of the tag technology.<br>**System API**: This is a system API. |
| tagRfDiscId<sup>9+</sup> | number | Yes | No | ID allocated when the tag is discovered.<br>**System API**: This is a system API. |
| remoteTagService<sup>9+</sup> | [rpc.RemoteObject](js-apis-rpc.md#remoteobject) | Yes | No | Remote object of the NFC service process used for interface communication between the client and the service.<br>**System API**: This is a system API.|
## NdefRecord<sup>9+</sup>
Defines an NDEF record. For details, see *NFCForum-TS-NDEF_1.0*.
**System capability**: SystemCapability.Communication.NFC.Tag
| **Name**| **Type**| **Readable**| **Writable**| **Description**|
| -------- | -------- | -------- | -------- | -------- |
| tnf | number | Yes| No| Type name field (TNF) of the NDEF record.|
| rtdType| number[] | Yes| No| Record type definition (RTD) of the NDEF record. It consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
| id | number[] | Yes| No| NDEF record ID, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
| payload | number[] | Yes| No| NDEF payload, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
| **Name** | **Type** | **Readable**| **Writable**| **Description** |
| ------- | -------- | ------ | ------ | ---------------------------------------- |
| tnf | number | Yes | No | Type name field (TNF) of the NDEF record. |
| rtdType | number[] | Yes | No | Record type definition (RTD) of the NDEF record. It consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
| id | number[] | Yes | No | NDEF record ID, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
| payload | number[] | Yes | No | NDEF payload, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
## Technology Type Definition
Enumerates the tag technology types.
**System capability**: SystemCapability.Communication.NFC.Tag
| **Name**| **Value**| **Description**|
| -------- | -------- | -------- |
| NFC_A | 1 | NFC-A (ISO 14443-3A).|
| **Name** | **Value**| **Description** |
| ---------------------------- | ----- | ------------------------ |
| NFC_A | 1 | NFC-A (ISO 14443-3A). |
| NFC_B | 2 | NFC-B (ISO 14443-3B).|
| ISO_DEP | 3 | ISO-DEP (ISO 14443-4).|
| NFC_F | 4 | NFC-F (JIS 6319-4).|
| NFC_V | 5 | NFC-V (ISO 15693).|
| NDEF | 6 | NDEF.|
| NDEF_FORMATABLE<sup>9+</sup> | 7 | NDEF formattable.|
| MIFARE_CLASSIC | 8 | MIFARE Classic.|
| MIFARE_ULTRALIGHT | 9 | MIFARE Ultralight.|
| ISO_DEP | 3 | ISO-DEP (ISO 14443-4).|
| NFC_F | 4 | NFC-F (JIS 6319-4). |
| NFC_V | 5 | NFC-V (ISO 15693). |
| NDEF | 6 | NDEF. |
| NDEF_FORMATABLE<sup>9+</sup> | 7 | NDEF formattable. |
| MIFARE_CLASSIC | 8 | MIFARE Classic. |
| MIFARE_ULTRALIGHT | 9 | MIFARE Ultralight. |
## TnfType<sup>9+</sup>
Enumerates the TNF types. For details, see *NFCForum-TS-NDEF_1.0*.
**System capability**: SystemCapability.Communication.NFC.Tag
| **Name**| **Value**| **Description**|
| -------- | -------- | -------- |
| TNF_EMPTY | 0x0 | Empty.|
| TNF_WELL_KNOWN | 0x1 | NFC Forum Well Known Type [NFC RTD].|
| TNF_MEDIA | 0x2 | Media-type as defined in RFC 2046 [RFC 2046].|
| TNF_ABSOLUTE_URI | 0x3 | Absolute URI as defined in RFC 3986 [RFC 3986].|
| TNF_EXT_APP | 0x4 | NFC Forum external type [NFC RTD].|
| TNF_UNKNOWN | 0x5 | Unknown.|
| TNF_UNCHANGED | 0x6 | Unchanged (see section 2.3.3 in *NFCForum-TS-NDEF_1.0*).|
| **Name** | **Value**| **Description** |
| ---------------- | ----- | ---------------------------------------- |
| TNF_EMPTY | 0x0 | Empty. |
| TNF_WELL_KNOWN | 0x1 | NFC Forum Well Known Type [NFC RTD]. |
| TNF_MEDIA | 0x2 | Media-type as defined in RFC 2046 [RFC 2046].|
| TNF_ABSOLUTE_URI | 0x3 | Absolute URI as defined in RFC 3986 [RFC 3986].|
| TNF_EXT_APP | 0x4 | NFC Forum external type [NFC RTD]. |
| TNF_UNKNOWN | 0x5 | Unknown. |
| TNF_UNCHANGED | 0x6 | Unchanged (see section 2.3.3 in *NFCForum-TS-NDEF_1.0*). |
## NDEF Record RTD
Enumerates the NDEF record types. For details about the RTD, see *NFCForum-TS-NDEF_1.0*.
**System capability**: SystemCapability.Communication.NFC.Tag
| **Name**| **Value**| **Description**|
| -------- | -------- | -------- |
| RTD_TEXT<sup>9+</sup> | [0x54] | NDEF record of the text type.|
| **Name** | **Value** | **Description** |
| --------------------- | ------ | ------------------ |
| RTD_TEXT<sup>9+</sup> | [0x54] | NDEF record of the text type. |
| RTD_URI<sup>9+</sup> | [0x55] | NDEF record of the URI type.|
## NfcForumType<sup>9+</sup>
......@@ -829,46 +830,47 @@ Enumerates the NFC Forum tag types.
**System capability**: SystemCapability.Communication.NFC.Tag
| **Name**| **Value**| **Description**|
| -------- | -------- | -------- |
| NFC_FORUM_TYPE_1 | 1 | NFC Forum tag type 1.|
| NFC_FORUM_TYPE_2 | 2 | NFC Forum tag type 2.|
| NFC_FORUM_TYPE_3 | 3 | NFC Forum tag type 3.|
| NFC_FORUM_TYPE_4 | 4 | NFC Forum tag type 4.|
| MIFARE_CLASSIC | 101 | MIFARE Classic.|
| **Name** | **Value**| **Description** |
| ---------------- | ----- | ----------------- |
| NFC_FORUM_TYPE_1 | 1 | NFC Forum tag type 1. |
| NFC_FORUM_TYPE_2 | 2 | NFC Forum tag type 2. |
| NFC_FORUM_TYPE_3 | 3 | NFC Forum tag type 3. |
| NFC_FORUM_TYPE_4 | 4 | NFC Forum tag type 4. |
| MIFARE_CLASSIC | 101 | MIFARE Classic.|
## MifareClassicType<sup>9+</sup>
Enumerates the MIFARE Classic tag types.
**System capability**: SystemCapability.Communication.NFC.Tag
| **Name**| **Value**| **Description**|
| -------- | -------- | -------- |
| TYPE_UNKNOWN | 0 | Unknown type.|
| TYPE_CLASSIC | 1 | MIFARE Classic.|
| TYPE_PLUS | 2 | MIFARE Plus.|
| TYPE_PRO | 3 | MIFARE Pro.|
| **Name** | **Value**| **Description** |
| ------------ | ----- | ----------------- |
| TYPE_UNKNOWN | 0 | Unknown type. |
| TYPE_CLASSIC | 1 | MIFARE Classic.|
| TYPE_PLUS | 2 | MIFARE Plus. |
| TYPE_PRO | 3 | MIFARE Pro. |
## MifareClassicSize<sup>9+</sup>
Enumerates the sizes of a MIFARE Classic tag.
**System capability**: SystemCapability.Communication.NFC.Tag
| **Name**| **Value**| **Description**|
| -------- | -------- | -------- |
| MC_SIZE_MINI | 320 | Each tag has 5 sectors, and each sector has 4 blocks.|
| MC_SIZE_1K | 1024 | Each tag has 16 sectors, and each sector has 4 blocks.|
| MC_SIZE_2K | 2048 | Each tag has 32 sectors, and each sector has 4 blocks.|
| MC_SIZE_4K | 4096 | Each tag has 40 sectors, and each sector has 4 blocks.|
| **Name** | **Value**| **Description** |
| ------------ | ----- | ------------------ |
| MC_SIZE_MINI | 320 | Each tag has 5 sectors, and each sector has 4 blocks. |
| MC_SIZE_1K | 1024 | Each tag has 16 sectors, and each sector has 4 blocks.|
| MC_SIZE_2K | 2048 | Each tag has 32 sectors, and each sector has 4 blocks.|
| MC_SIZE_4K | 4096 | Each tag has 40 sectors, and each sector has 4 blocks.|
## MifareUltralightType<sup>9+</sup>
Enumerates the MIFARE Ultralight tag types.
**System capability**: SystemCapability.Communication.NFC.Tag
| **Name**| **Value**| **Description**|
| -------- | -------- | -------- |
| TYPE_UNKNOWN | 0 | Unknown type.|
| TYPE_ULTRALIGHT | 1 | MIFARE Ultralight.|
| TYPE_ULTRALIGHT_C | 2 | MIFARE Ultralight C.|
| **Name** | **Value**| **Description** |
| ----------------- | ----- | ---------------------- |
| TYPE_UNKNOWN | 0 | Unknown type. |
| TYPE_ULTRALIGHT | 1 | MIFARE Ultralight. |
| TYPE_ULTRALIGHT_C | 2 | MIFARE Ultralight C.|
<!--no_check-->
\ No newline at end of file
......@@ -2397,7 +2397,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
```ts
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -2415,10 +2415,10 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
......@@ -4860,7 +4860,7 @@ Reads the exception information from this **MessageParcel** object.
```ts
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -4878,10 +4878,10 @@ Reads the exception information from this **MessageParcel** object.
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
......@@ -5452,6 +5452,7 @@ Marshals this **Parcelable** object into a **MessageSequence** object.
| Type | Description |
| ------- | -------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
```ts
......@@ -5557,6 +5558,7 @@ Marshals the sequenceable object into a **MessageParcel** object.
| Type | Description |
| ------- | -------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
```ts
......@@ -5673,7 +5675,7 @@ Obtains a proxy or remote object. This API must be implemented by its derived cl
```ts
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -5691,10 +5693,10 @@ Obtains a proxy or remote object. This API must be implemented by its derived cl
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
......@@ -6117,7 +6119,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
```ts
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6135,10 +6137,10 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
......@@ -6193,7 +6195,7 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn
```ts
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6211,10 +6213,10 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
......@@ -6277,7 +6279,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
```ts
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6295,10 +6297,10 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
......@@ -6354,7 +6356,7 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn
```ts
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6385,10 +6387,10 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn
result.data.reclaim();
result.reply.reclaim();
}
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
......@@ -6435,7 +6437,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
```ts
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6466,10 +6468,10 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
result.data.reclaim();
result.reply.reclaim();
}
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
......@@ -6519,7 +6521,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
```ts
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6537,10 +6539,10 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
......@@ -6585,7 +6587,7 @@ Obtains the **LocalInterface** object of an interface token.
```ts
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6603,10 +6605,10 @@ Obtains the **LocalInterface** object of an interface token.
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
......@@ -6647,7 +6649,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
```ts
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6665,10 +6667,10 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
......@@ -6689,7 +6691,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
}
```
### addDeathRecippient<sup>(deprecated)</sup>
### addDeathRecipient<sup>(deprecated)</sup>
>This API is no longer maintained since API version 9. You are advised to use [registerDeathRecipient](#registerdeathrecipient9).
......@@ -6719,7 +6721,7 @@ Adds a callback for receiving the death notifications of the remote object, incl
```ts
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6737,14 +6739,14 @@ Adds a callback for receiving the death notifications of the remote object, incl
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **addDeathRecippient()** of the proxy object is called to add a callback for receiving the death notification of the remove object.
The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **addDeathRecipient()** of the proxy object is called to add a callback for receiving the death notification of the remove object.
```ts
class MyDeathRecipient {
......@@ -6786,7 +6788,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
```ts
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6804,10 +6806,10 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
......@@ -6859,7 +6861,7 @@ Removes the callback used to receive death notifications of the remote object.
```ts
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6877,10 +6879,10 @@ Removes the callback used to receive death notifications of the remote object.
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
......@@ -6927,7 +6929,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
```ts
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6945,10 +6947,10 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **getDescriptor()** of the proxy object is called to obtain the interface descriptor of the object.
......@@ -6986,7 +6988,7 @@ Obtains the interface descriptor of this proxy object.
```ts
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -7004,10 +7006,10 @@ Obtains the interface descriptor of this proxy object.
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
......@@ -7039,7 +7041,7 @@ Checks whether the **RemoteObject** is dead.
```ts
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -7057,10 +7059,10 @@ Checks whether the **RemoteObject** is dead.
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
......@@ -7095,9 +7097,9 @@ A constructor used to create a **MessageOption** object.
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------ | ---- | -------------------------------------- |
| syncFlags | number | No | Call flag, which can be synchronous or asynchronous. The default value is **synchronous**.|
| Name| Type | Mandatory| Description |
| ------ | ------- | ---- | -------------------------------------- |
| async | boolean | No | Call flag, which can be synchronous or asynchronous. The default value is **synchronous**.|
**Example**
......@@ -7146,7 +7148,7 @@ Checks whether **SendMessageRequest** is called synchronously or asynchronously.
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if **SendMessageRequest** is called synchronously; returns **false** if **SendMessageRequest** is called asynchronously.|
| boolean | Returns **true** if **SendMessageRequest** is called asynchronously; returns **false** if it is called synchronously.|
**Example**
......@@ -7825,7 +7827,7 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn
| Type | Description |
| ---------------------------- | --------------------------------------------- |
| Promise&lt;RequestResult&gt; | Promise used to return the **sendRequestResult** object.|
| Promise&lt;RequestResult&gt; | Promise used to return the **RequestResult** instance. |
**Example**
......@@ -9101,29 +9103,30 @@ Reads data from the shared file associated with this **Ashmem** object.
```ts
import Ability from '@ohos.app.ability.UIAbility';
export default class MainAbility extends Ability {
onCreate(want, launchParam) {
console.log("[Demo] MainAbility onCreate");
globalThis.context = this.context;
}
onDestroy() {
console.log("[Demo] MainAbility onDestroy");
}
onWindowStageCreate(windowStage) {
// Main window is created, set main page for this ability
console.log("[Demo] MainAbility onWindowStageCreate");
}
onWindowStageDestroy() {
// Main window is destroyed, release UI related resources
console.log("[Demo] MainAbility onWindowStageDestroy");
}
onForeground() {
// Ability has brought to foreground
console.log("[Demo] MainAbility onForeground");
}
onBackground() {
// Ability has back to background
console.log("[Demo] MainAbility onBackground");
}
onCreate(want, launchParam) {
console.log("[Demo] MainAbility onCreate");
globalThis.context = this.context;
}
onDestroy() {
console.log("[Demo] MainAbility onDestroy");
}
onWindowStageCreate(windowStage) {
// Main window is created, set main page for this ability
console.log("[Demo] MainAbility onWindowStageCreate");
}
onWindowStageDestroy() {
// Main window is destroyed, release UI related resources
console.log("[Demo] MainAbility onWindowStageDestroy");
}
onForeground() {
// Ability has brought to foreground
console.log("[Demo] MainAbility onForeground");
}
onBackground() {
// Ability has back to background
console.log("[Demo] MainAbility onBackground");
}
};
```
......@@ -97,7 +97,7 @@ Obtains the time elapsed since the Unix epoch. This API uses an asynchronous cal
| Name | Type | Mandatory| Description |
| -------- | -------------- | ---- | ------------------ |
| isNano | boolean | Yes | Whether the time to return is in nanoseconds.<br>- **true**: The time to return is in nanoseconds.<br>- **false**: The time to return is in milliseconds.|
| isNano | boolean | Yes | Whether the time to return is in nanoseconds.<br>- **true**: The time to return is in nanoseconds.<br>- **false**: The time to return is in milliseconds. |
| callback | AsyncCallback&lt;number&gt; | Yes | Callback used to return the time elapsed since the Unix epoch. |
**Example**
......@@ -128,7 +128,7 @@ Obtains the time elapsed since the Unix epoch. This API uses an asynchronous cal
| Name | Type | Mandatory| Description |
| -------- | ----------- | ---- | ---------------------------------- |
| callback | AsyncCallback&lt;number&gt; | Yes | Callback used to return the time elapsed since the Unix epoch. |
| callback | AsyncCallback&lt;number&gt; | Yes | Callback used to return the time elapsed since the Unix epoch, in milliseconds. |
**Example**
......@@ -158,7 +158,7 @@ Obtains the time elapsed since the Unix epoch. This API uses a promise to return
| Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ------------------------- |
| isNano | boolean | No | Whether the time to return is in nanoseconds.<br>- **true**: The time to return is in nanoseconds.<br>- **false**: The time to return is in milliseconds.|
| isNano | boolean | No | Whether the time to return is in nanoseconds.<br>- **true**: The time to return is in nanoseconds.<br>- **false**: The time to return is in milliseconds.<br/>Default value: **false** |
**Return value**
......@@ -192,7 +192,7 @@ Obtains the time elapsed since system startup, excluding the deep sleep time. Th
| Name | Type | Mandatory| Description |
| -------- | ---------- | ---- | -------------------------- |
| isNano | boolean | Yes | Whether the time to return is in nanoseconds.<br>- **true**: The time to return is in nanoseconds.<br>- **false**: The time to return is in milliseconds.|
| isNano | boolean | Yes | Whether the time to return is in nanoseconds.<br>- **true**: The time to return is in nanoseconds.<br>- **false**: The time to return is in milliseconds. |
| callback | AsyncCallback&lt;number&gt; | Yes | Callback used to return the time.|
**Example**
......@@ -253,7 +253,7 @@ Obtains the time elapsed since system startup, excluding the deep sleep time. Th
| Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ----------------------------------- |
| isNano | boolean | No | Whether the time to return is in nanoseconds.<br>- **true**: The time to return is in nanoseconds.<br>- **false**: The time to return is in milliseconds.|
| isNano | boolean | No | Whether the time to return is in nanoseconds.<br>- **true**: The time to return is in nanoseconds.<br>- **false**: The time to return is in milliseconds.<br/>Default value: **false** |
**Return value**
......@@ -287,7 +287,7 @@ Obtains the time elapsed since system startup, including the deep sleep time. Th
| Name | Type | Mandatory| Description |
| -------- | --------------- | ---- | ------------------------------- |
| isNano | boolean | Yes | Whether the time to return is in nanoseconds.<br>- **true**: The time to return is in nanoseconds.<br>- **false**: The time to return is in milliseconds.|
| isNano | boolean | Yes | Whether the time to return is in nanoseconds.<br>- **true**: The time to return is in nanoseconds.<br>- **false**: The time to return is in milliseconds. |
| callback | AsyncCallback&lt;number&gt; | Yes | Callback used to return the time. |
**Example**
......@@ -348,7 +348,7 @@ Obtains the time elapsed since system startup, including the deep sleep time. Th
| Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ------------------------------- |
| isNano | boolean | No | Whether the time to return is in nanoseconds.<br>- **true**: The time to return is in nanoseconds.<br>- **false**: The time to return is in milliseconds.|
| isNano | boolean | No | Whether the time to return is in nanoseconds.<br>- **true**: The time to return is in nanoseconds.<br>- **false**: The time to return is in milliseconds.<br/>Default value: **false** |
**Return value**
......
......@@ -13,7 +13,7 @@ The **systemTime** module provides system time and time zone features. You can u
import systemTime from '@ohos.systemTime';
```
## systemTime.setTime<sup>(deprecated)</sup>
## systemTime.setTime
setTime(time : number, callback : AsyncCallback&lt;void&gt;) : void
......@@ -191,7 +191,7 @@ Obtains the time elapsed since the Unix epoch. This API uses a promise to return
| Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ------------------------- |
| isNano | boolean | No | Whether the time to return is in nanoseconds.<br>- **true**: in nanoseconds.<br>- **false**: in milliseconds.|
| isNano | boolean | No | Whether the time to return is in nanoseconds.<br>- **true**: in nanoseconds.<br>- **false**: in milliseconds.<br/>Default value: **false** |
**Return value**
......@@ -310,7 +310,7 @@ Obtains the time elapsed since system startup, excluding the deep sleep time. Th
| Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ----------------------------------- |
| isNano | boolean | No | Whether the time to return is in nanoseconds.<br>- **true**: in nanoseconds.<br>- **false**: in milliseconds.|
| isNano | boolean | No | Whether the time to return is in nanoseconds.<br>- **true**: in nanoseconds.<br>- **false**: in milliseconds.<br/>Default value: **false** |
**Return value**
......@@ -429,7 +429,7 @@ Obtains the time elapsed since system startup, including the deep sleep time. Th
| Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ------------------------------- |
| isNano | boolean | No | Whether the time to return is in nanoseconds.<br>- **true**: in nanoseconds.<br>- **false**: in milliseconds.|
| isNano | boolean | No | Whether the time to return is in nanoseconds.<br>- **true**: in nanoseconds.<br>- **false**: in milliseconds.<br/>Default value: **false** |
**Return value**
......
......@@ -231,7 +231,7 @@ Decompresses a file. This API uses an asynchronous callback to return the result
| Name | Type | Mandatory| Description |
| ----------------------- | ------------------- | ---- | ------------------------------------------------------------ |
| inFile | string | Yes | Path of the file to decompress. For details about the path, see [FA Model](js-apis-inner-app-context.md) and [Stage Model](js-apis-inner-application-context.md).|
| inFile | string | Yes | Path of the file to decompress. The file name extension must be .zip. For details about the path, see [FA Model](js-apis-inner-app-context.md) and [Stage Model](js-apis-inner-application-context.md).|
| outFile | string | Yes | Path of the decompressed file. The path must exist in the system. Otherwise, the decompression fails. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model](js-apis-inner-application-context.md).|
| options | [Options](#options) | Yes | Decompression parameters. |
| AsyncCallback<**void**> | callback | No | Callback used to return the result. If the operation is successful, **null** is returned; otherwise, a specific error code is returned. |
......@@ -282,7 +282,7 @@ Decompresses a file. This API uses a promise to return the result.
| Name | Type | Mandatory| Description |
| ------- | ------------------- | ---- | ------------------------------------------------------------ |
| inFile | string | Yes | Path of the file to decompress. For details about the path, see [FA Model](js-apis-inner-app-context.md) and [Stage Model](js-apis-inner-application-context.md).|
| inFile | string | Yes | Path of the file to decompress. The file name extension must be .zip. For details about the path, see [FA Model](js-apis-inner-app-context.md) and [Stage Model](js-apis-inner-application-context.md).|
| outFile | string | Yes | Path of the decompressed file. The path must exist in the system. Otherwise, the decompression fails. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model](js-apis-inner-application-context.md).|
| options | [Options](#options) | Yes | Decompression parameters. |
......
# JavaScript-compatible Web-like Development Paradigm (ArkUI.Lite)
- Framework Overview
- [File Organization](js-framework-file.md)
- ["js" Tag](js-framework-js-tag.md)
- [app.js](js-framework-js-file.md)
- Syntax
- [HML](js-framework-syntax-hml.md)
- [CSS](js-framework-syntax-css.md)
- [JavaScript](js-framework-syntax-js.md)
- Universal Component Information
- [Universal Events](js-common-events.md)
- [Universal Attributes](js-common-attributes.md)
- [Universal Styles](js-common-styles.md)
- [Animation Styles](js-components-common-animation.md)
- [Media Query](js-components-common-mediaquery.md)
- Container Components
- [div](js-components-container-div.md)
- [list](js-components-container-list.md)
- [list-item](js-components-container-list-item.md)
- [stack](js-components-container-stack.md)
- [swiper](js-components-container-swiper.md)
- Basic Components
- [chart](js-components-basic-chart.md)
- [image](js-components-basic-image.md)
- [image-animator](js-components-basic-image-animator.md)
- [input](js-components-basic-input.md)
- [marquee](js-components-basic-marquee.md)
- [picker-view](js-components-basic-picker-view.md)
- [progress](js-components-basic-progress.md)
- [qrcode](js-components-basic-qrcode.md)
- [slider](js-components-basic-slider.md)
- [switch](js-components-basic-switch.md)
- [text](js-components-basic-text.md)
- Canvas Components
- [canvas](js-components-canvas-canvas.md)
- [CanvasRenderingContext2D](js-components-canvas-canvasrenderingcontext2d.md)
# Universal Attributes
## Common Attributes
Common attributes are used to set component identities and appearance.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| id | string | No| Unique ID of the component.|
| style | string | No| Style declaration of the component.|
| class | string | No| Style class of the component, which is used to refer to a style table.|
| ref | string | No| Reference information of child elements, which is registered with the parent component on **$refs**.|
## Rendering Attributes
Rendering attributes are used to set whether a component is rendered.
| Name| Type| Description|
| -------- | -------- | -------- |
| for | Array | Expands the current element based on the configured data list.|
| if | boolean | Whether the element is added or removed.|
| show | boolean | Whether the element is displayed or hidden.|
> **NOTE**
>
> Do not set styles in attribute fields.
# Universal Events
Different from private events, universal events can be bound to most components.
| Name| Parameter| Description|
| -------- | -------- | -------- |
| click | - | Triggered when the component is clicked. |
| longpress | - | Triggered when the component is long pressed. |
| swipe<sup>5+</sup> | SwipeEvent | Triggered when a user quickly swipes on the component. |
**Table 1** SwipeEvent (inherited from BaseEvent)
| Attribute| Type| Description |
| -------- | -------- | -------- |
| direction | string | Swiping direction. The value can be one of the following:<br>- **left**: Swipe left.<br>- **right**: Swipe right.<br>- **up**: Swipe up.<br>- **down**: Swipe down. |
# Universal Styles
You can set universal styles for components in the **style** attribute or **.css** files.
| Name | Type | Default Value | Mandatory | Description |
| ---------------------------------- | ---------------------------------------- | ----- | ---- | ---------------------------------------- |
| width | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | - | No | Component width.<br><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><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 in a declaration.<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 in a declaration. 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).|
| margin-[left\|top\|right\|bottom] | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | 0 | No | Left, top, right, and bottom margins. |
| border-width | &lt;length&gt; | 0 | No | Shorthand attribute to set the margin for all sides. |
| 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. |
| background-color | &lt;color&gt; | - | No | Background color. |
| opacity<sup>5+</sup> | number | 1 | No | Opacity of an element. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent. |
| display | string | flex | No | Type of 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.|
> **NOTE**
>
> The aforementioned universal styles are not mandatory.
>
> Currently, the following color formats are supported:
> - rgb(255, 255, 255)
>
> - rgba(255, 255, 255, 1.0)
>
> - HEX formats: \#rrggbb and \#aarrggbb
>
> - Enumeration format: as listed in Table 1. The enumeration format is not supported in the script.
**Table 1** Color enums
| Name | Hexadecimal Code | Color |
| -------------------- | -------- | ---------------------------------------- |
| aliceblue | \#f0f8ff | ![aliceblue](figures/aliceblue.png) |
| antiquewhite | \#faebd7 | ![antiquewhite](figures/antiquewhite.png) |
| aqua | \#00ffff | ![aqua](figures/aqua.png) |
| aquamarine | \#7fffd4 | ![aquamarine](figures/aquamarine.png) |
| azure | \#f0ffff | ![azure](figures/azure.png) |
| beige | \#f5f5dc | ![beige](figures/beige.png) |
| bisque | \#ffe4c4 | ![bisque](figures/bisque.png) |
| black | \#000000 | ![000000](figures/000000.png) |
| blanchedalmond | \#ffebcd | ![blanchedalmond](figures/blanchedalmond.png) |
| blue | \#0000ff | ![blue](figures/blue.png) |
| blueviolet | \#8a2be2 | ![blueviolet](figures/blueviolet.png) |
| brown | \#a52a2a | ![brown](figures/brown.png) |
| burlywood | \#deB887 | ![burlywood](figures/burlywood.png) |
| cadetblue | \#5f9ea0 | ![cadetblue](figures/cadetblue.png) |
| chartreuse | \#7fff00 | ![chartreuse](figures/chartreuse.png) |
| chocolate | \#d2691e | ![chocolate](figures/chocolate.png) |
| coral | \#ff7f50 | ![coral](figures/coral.png) |
| cornflowerblue | \#6495ed | ![cornflowerblue](figures/cornflowerblue.png) |
| cornsilk | \#fff8dc | ![cornsilk](figures/cornsilk.png) |
| crimson | \#dc143c | ![crimson](figures/crimson.png) |
| cyan | \#00ffff | ![cyan](figures/cyan.png) |
| darkblue | \#00008b | ![darkblue](figures/darkblue.png) |
| darkcyan | \#008b8b | ![darkcyan](figures/darkcyan.png) |
| darkgoldenrod | \#b8860b | ![darkgoldenrod](figures/darkgoldenrod.png) |
| darkgray | \#a9a9a9 | ![darkgray](figures/darkgray.png) |
| darkgreen | \#006400 | ![darkgreen](figures/darkgreen.png) |
| darkgrey | \#a9a9a9 | ![darkgrey](figures/darkgrey.png) |
| darkkhaki | \#bdb76b | ![darkkhaki](figures/darkkhaki.png) |
| darkmagenta | \#8b008b | ![darkmagenta](figures/darkmagenta.png) |
| darkolivegreen | \#556b2f | ![darkolivegreen](figures/darkolivegreen.png) |
| darkorange | \#ff8c00 | ![darkorange](figures/darkorange.png) |
| darkorchid | \#9932cc | ![darkorchid](figures/darkorchid.png) |
| darkred | \#8b0000 | ![darkred](figures/darkred.png) |
| darksalmon | \#e9967a | ![darksalmon](figures/darksalmon.png) |
| darkseagreen | \#8fbc8f | ![darkseagreen](figures/darkseagreen.png) |
| darkslateblue | \#483d8b | ![darkslateblue](figures/darkslateblue.png) |
| darkslategray | \#2f4f4f | ![darkslategray](figures/darkslategray.png) |
| darkslategrey | \#2f4f4f | ![darkslategrey](figures/darkslategrey.png) |
| darkturquoise | \#00ced1 | ![darkturquoise](figures/darkturquoise.png) |
| darkviolet | \#9400d3 | ![darkviolet](figures/darkviolet.png) |
| deeppink | \#ff1493 | ![deeppink](figures/deeppink.png) |
| deepskyblue | \#00bfff | ![deepskyblue](figures/deepskyblue.png) |
| dimgray | \#696969 | ![dimgray](figures/dimgray.png) |
| dimgrey | \#696969 | ![dimgrey](figures/dimgrey.png) |
| dodgerblue | \#1e90ff | ![dodgerblue](figures/dodgerblue.png) |
| firebrick | \#b22222 | ![firebrick](figures/firebrick.png) |
| floralwhite | \#fffaf0 | ![floralwhite](figures/floralwhite.png) |
| forestgreen | \#228b22 | ![forestgreen](figures/forestgreen.png) |
| fuchsia | \#ff00ff | ![fuchsia](figures/fuchsia.png) |
| gainsboro | \#dcdcdc | ![gainsboro](figures/gainsboro.png) |
| ghostwhite | \#f8f8ff | ![ghostwhite](figures/ghostwhite.png) |
| gold | \#ffd700 | ![gold](figures/gold.png) |
| goldenrod | \#daa520 | ![goldenrod](figures/goldenrod.png) |
| gray | \#808080 | ![gray](figures/gray.png) |
| green | \#008000 | ![green](figures/green.png) |
| greenyellow | \#adff2f | ![greenyellow](figures/greenyellow.png) |
| grey | \#808080 | ![grey](figures/grey.png) |
| honeydew | \#f0fff0 | ![honeydew](figures/honeydew.png) |
| hotpink | \#ff69b4 | ![hotpink](figures/hotpink.png) |
| indianred | \#cd5c5c | ![indianred](figures/indianred.png) |
| indigo | \#4b0082 | ![indigo](figures/indigo.png) |
| ivory | \#fffff0 | ![ivory](figures/ivory.png) |
| khaki | \#f0e68c | ![khaki](figures/khaki.png) |
| lavender | \#e6e6fa | ![lavender](figures/lavender.png) |
| lavenderblush | \#fff0f5 | ![lavenderblush](figures/lavenderblush.png) |
| lawngreen | \#7cfc00 | ![lawngreen](figures/lawngreen.png) |
| lemonchiffon | \#fffacd | ![lemonchiffon](figures/lemonchiffon.png) |
| lightblue | \#add8e6 | ![lightblue](figures/lightblue.png) |
| lightcoral | \#f08080 | ![lightcoral](figures/lightcoral.png) |
| lightcyan | \#e0ffff | ![lightcyan](figures/lightcyan.png) |
| lightgoldenrodyellow | \#fafad2 | ![lightgoldenrodyellow](figures/lightgoldenrodyellow.png) |
| lightgray | \#d3d3d3 | ![lightgray](figures/lightgray.png) |
| lightgreen | \#90ee90 | ![lightgreen](figures/lightgreen.png) |
| lightpink | \#ffb6c1 | ![lightpink](figures/lightpink.png) |
| lightsalmon | \#ffa07a | ![lightsalmon](figures/lightsalmon.png) |
| lightseagreen | \#20b2aa | ![lightseagreen](figures/lightseagreen.png) |
| lightskyblue | \#87cefa | ![lightskyblue](figures/lightskyblue.png) |
| lightslategray | \#778899 | ![lightslategray](figures/lightslategray.png) |
| lightslategrey | \#778899 | ![lightslategrey](figures/lightslategrey.png) |
| lightsteelblue | \#b0c4de | ![lightsteelblue](figures/lightsteelblue.png) |
| lightyellow | \#ffffe0 | ![lightyellow](figures/lightyellow.png) |
| lime | \#00ff00 | ![lime](figures/lime.png) |
| limegreen | \#32cd32 | ![limegreen](figures/limegreen.png) |
| linen | \#faf0e6 | ![linen](figures/linen.png) |
| magenta | \#ff00ff | ![magenta](figures/magenta.png) |
| maroon | \#800000 | ![maroon](figures/maroon.png) |
| mediumaquamarine | \#66cdaa | ![mediumaquamarine](figures/mediumaquamarine.png) |
| mediumblue | \#0000cd | ![mediumblue](figures/mediumblue.png) |
| mediumorchid | \#ba55d3 | ![mediumorchid](figures/mediumorchid.png) |
| mediumpurple | \#9370db | ![mediumpurple](figures/mediumpurple.png) |
| mediumseagreen | \#3cb371 | ![mediumseagreen](figures/mediumseagreen.png) |
| mediumslateblue | \#7b68ee | ![mediumslateblue](figures/mediumslateblue.png) |
| mediumspringgreen | \#00fa9a | ![mediumspringgreen](figures/mediumspringgreen.png) |
| mediumturquoise | \#48d1cc | ![mediumturquoise](figures/mediumturquoise.png) |
| mediumvioletred | \#c71585 | ![mediumvioletred](figures/mediumvioletred.png) |
| midnightblue | \#191970 | ![midnightblue](figures/midnightblue.png) |
| mintcream | \#f5fffa | ![mintcream](figures/mintcream.png) |
| mistyrose | \#ffe4e1 | ![mistyrose](figures/mistyrose.png) |
| moccasin | \#ffe4b5 | ![moccasin](figures/moccasin.png) |
| navajowhite | \#ffdead | ![navajowhite](figures/navajowhite.png) |
| navy | \#000080 | ![navy](figures/navy.png) |
| oldlace | \#fdf5e6 | ![oldlace](figures/oldlace.png) |
| olive | \#808000 | ![olive](figures/olive.png) |
| olivedrab | \#6b8e23 | ![olivedrab](figures/olivedrab.png) |
| orange | \#ffa500 | ![orange](figures/orange.png) |
| orangered | \#ff4500 | ![orangered](figures/orangered.png) |
| orchid | \#da70d6 | ![orchid](figures/orchid.png) |
| palegoldenrod | \#eee8aa | ![palegoldenrod](figures/palegoldenrod.png) |
| palegreen | \#98fb98 | ![palegreen](figures/palegreen.png) |
| paleturquoise | \#afeeee | ![paleturquoise](figures/paleturquoise.png) |
| palevioletred | \#db7093 | ![palevioletred](figures/palevioletred.png) |
| papayawhip | \#ffefd5 | ![papayawhip](figures/papayawhip.png) |
| peachpuff | \#ffdab9 | ![peachpuff](figures/peachpuff.png) |
| peru | \#cd853f | ![peru](figures/peru.png) |
| pink | \#ffc0cb | ![pink](figures/pink.png) |
| plum | \#dda0dd | ![plum](figures/plum.png) |
| powderblue | \#b0e0e6 | ![powderblue](figures/powderblue.png) |
| purple | \#800080 | ![purple](figures/purple.png) |
| rebeccapurple | \#663399 | ![rebeccapurple](figures/rebeccapurple.png) |
| red | \#ff0000 | ![red](figures/red.png) |
| rosybrown | \#bc8f8f | ![rosybrown](figures/rosybrown.png) |
| royalblue | \#4169e1 | ![royalblue](figures/royalblue.png) |
| saddlebrown | \#8b4513 | ![saddlebrown](figures/saddlebrown.png) |
| salmon | \#fa8072 | ![salmon](figures/salmon.png) |
| sandybrown | \#f4a460 | ![sandybrown](figures/sandybrown.png) |
| seagreen | \#2e8b57 | ![seagreen](figures/seagreen.png) |
| seashell | \#fff5ee | ![seashell](figures/seashell.png) |
| sienna | \#a0522d | ![sienna](figures/sienna.png) |
| silver | \#c0c0c0 | ![silver](figures/silver.png) |
| skyblue | \#87ceeb | ![skyblue](figures/skyblue.png) |
| slateblue | \#6a5acd | ![slateblue](figures/slateblue.png) |
| slategray | \#708090 | ![slategray](figures/slategray.png) |
| slategrey | \#708090 | ![slategray](figures/slategray.png) |
| snow | \#fffafa | ![snow](figures/snow.png) |
| springgreen | \#00ff7f | ![springgreen](figures/springgreen.png) |
| steelblue | \#4682b4 | ![steelblue](figures/steelblue.png) |
| tan | \#d2b48c | ![tan](figures/tan.png) |
| teal | \#008080 | ![teal](figures/teal.png) |
| thistle | \#d8Bfd8 | ![thistle](figures/thistle.png) |
| tomato | \#ff6347 | ![tomato](figures/tomato.png) |
| turquoise | \#40e0d0 | ![turquoise](figures/turquoise.png) |
| violet | \#ee82ee | ![violet](figures/violet.png) |
| wheat | \#f5deb3 | ![wheat](figures/wheat.png) |
| white | \#ffffff | ![white](figures/white.png) |
| whitesmoke | \#f5f5f5 | ![whitesmoke](figures/whitesmoke.png) |
| yellow | \#ffff00 | ![yellow](figures/yellow.png) |
| yellowgreen | \#9acd32 | ![yellowgreen](figures/yellowgreen.png) |
# chart
The **\<chart>** component displays line charts and bar charts.
> **NOTE**
>
> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
## Child Components
Not supported
## Attributes
| Name | Type | Mandatory | Description |
| -------- | ------------------------- | ---- | ---------------------------------------- |
| type | string | No | Chart type. Dynamic modification is not supported. Available values include:<br>- **bar**: bar chart<br>- **line**: line chart<br>Default value: **line**|
| options | ChartOptions | Yes | Chart parameters. You can set the minimum value, maximum value, scale, and line width of the x-axis or y-axis, whether to display the x-axis and y-axis, and whether the line is smooth. Dynamic modification is not supported.|
| datasets | Array&lt;ChartDataset&gt; | Yes | Data sets. You can set multiple datasets and their background colors. |
| id | string | No | Unique ID of the component. |
| style | string | No | Style declaration of the component. |
| class | string | No | Style class of the component, which is used to refer to a style table. |
| ref | string | No | Reference information of child elements, which is registered with the parent component on **$refs**.|
**Table 1** ChartOptions
| Name | Type | Mandatory | Description |
| ------ | ----------- | ---- | ---------------------------------------- |
| xAxis | ChartAxis | Yes | X-axis parameters. You can set the minimum value, maximum value, and scale of the x-axis, and whether to display the x-axis. |
| yAxis | ChartAxis | Yes | Y-axis parameters. You can set the minimum value, maximum value, and scale of the y-axis, and whether to display the y-axis. |
| series | ChartSeries | No | Data series parameters which cover the following:<br>- Line style, such as the line width and whether the line is smooth.<br>- Style and size of the white point at the start of the line.<br>**NOTE**<br>Only line charts support this attribute.|
**Table 2** ChartDataset
| Name | Type | Default Value | Mandatory | Description |
| --------------------------- | ------------------- | -------- | ---- | -------------------- |
| backgroundColor(deprecated) | &lt;color&gt; | \#ff6384 | No | Color of a line or bar. This attribute is not recommended. |
| strokeColor | &lt;color&gt; | \#ff6384 | No | Line color. Only line charts support this attribute. |
| fillColor | &lt;color&gt; | \#ff6384 | No | Fill color. For line charts, the value indicates the gradient color to fill. |
| data | Array&lt;number&gt; | - | Yes | Data of the drawn line or bar. |
| gradient | boolean | false | No | Whether to display the gradient color. Only line charts support this attribute.|
**Table 3** ChartAxis
| Name | Type | Default Value | Mandatory | Description |
| -------- | ------------- | -------- | ---- | ---------------------------------------- |
| min | number | 0 | No | Minimum value of the axis.<br>Negative numbers are not supported. Only line charts support this attribute. |
| max | number | 100 | No | Maximum value of the axis.<br>Negative numbers are not supported. Only line charts support this attribute. |
| axisTick | number | 10 | No | Number of scales displayed on the axis.<br>**NOTE**<br>The value ranges from 1 to 20. The display effect depends on the calculation result of Number of pixels occupied by the image width/(**max**-**min**).<br>Lite wearables support integer calculation, and an error may occur in the case of inexhaustible division. Specifically, a segment of space may be left at the end of the x-axis.<br>In the bar chart, the number of bars in each group of data is the same as the number of scales, and the bars are displayed at the scales.|
| display | boolean | false | No | Whether to display the axis. |
| color | &lt;color&gt; | \#c0c0c0 | No | Axis color. |
**Table 4** ChartSeries
| Name | Type | Mandatory | Description |
| ----------- | -------------- | ---- | -------------------- |
| lineStyle | ChartLineStyle | No | Line style, such as the line width and whether the line is smooth. |
| headPoint | PointStyle | No | Style and size of the white point at the start of the line. |
| topPoint | PointStyle | No | Style and size of the top point. |
| bottomPoint | PointStyle | No | Style and size of the bottom point. |
| loop | ChartLoop | No | Whether to start drawing again when the screen is looped.|
**Table 5** ChartLineStyle
| Name | Type | Default Value | Mandatory | Description |
| ------ | -------------- | ----- | ---- | ----- |
| width | &lt;length&gt; | 1px | No | Line width.|
| smooth | boolean | false | No | Whether the line is smooth.|
**Table 6** PointStyle
| Name | Type | Default Value | Mandatory | Description |
| ----------- | -------------- | -------- | ---- | ---------------------------------- |
| shape | string | circle | No | Shape of the highlight point. Available values are as follows:<br>- circle|
| size | &lt;length&gt; | 5px | No | Size of the highlight point. |
| strokeWidth | &lt;length&gt; | 1px | No | Stroke width. |
| strokeColor | &lt;color&gt; | \#ff0000 | No | Stroke color. |
| fillColor | &lt;color&gt; | \#ff0000 | No | Fill color. |
| display | boolean | true | No | Whether to display the highlight spot. |
**Table 7** ChartLoop
| Name | Type | Default Value | Mandatory | Description |
| ------ | -------------- | ---- | ---- | ---------------------------------------- |
| margin | &lt;length&gt; | 1 | No | Number of erased points (horizontal distance between the latest drawn point and the earliest point). You are not advised to use **margin** together with **topPoint**, **bottomPoint**, or **headPoint** for mini-, small- and standard-system devices. If you do so, there is a possibility that the point is in the erase area and invisible.|
## Methods
| Methods | Parameter | Description |
| ------ | ---------------------------------------- | ---------------------------------------- |
| append | {<br>serial: number, // Set the data subscript of the line chart to be updated.<br>data: Array&lt;number&gt;, // Set the new data.<br>} | Dynamically add data to an existing data series. The target series is specified based on **serial**, which is the subscript of the datasets array and starts from 0. **datasets[index].data** is not updated. Only line charts support this attribute. The value is incremented by 1 based on the horizontal coordinate and is related to the **xAxis min/max** setting.|
## Events
| 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.|
## Styles
| Name | Type | Default Value | Mandatory | Description |
| ---------------------------------- | ---------------------------------------- | ----- | ---- | ---------------------------------------- |
| width | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | - | No | Component width.<br><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><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).|
| margin-[left\|top\|right\|bottom] | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | 0 | No | Left, top, right, and bottom margins. |
| border-width | &lt;length&gt; | 0 | No | Shorthand attribute to set the margin for all sides. |
| 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. |
| background-color | &lt;color&gt; | - | No | Background color. |
| 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.|
## Example
1. Line chart
```html
<!-- xxx.hml -->
<div class="container">
<chart class="chart" type="line" ref="linechart" options="{{lineOps}}" datasets="{{lineData}}"></chart>
<input class="button" type="button" value="Add data" onclick="addData"/>
</div>
```
```css
/* xxx.css */
.container {
flex-direction: column;
justify-content: center;
align-items: center;
width: 454px;
height: 454px;
background-color: white;
}
.chart {
width: 300px;
height: 300px;
}
.button {
width: 280px;
border-radius: 0px;
}
```
```js
// xxx.js
export default {
data: {
lineData: [
{
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,
}
],
lineOps: {
xAxis: {
min: 0,
max: 20,
display: false,
},
yAxis: {
min: 0,
max: 1000,
display: false,
},
series: {
lineStyle: {
width: "5px",
smooth: true,
},
headPoint: {
shape: "circle",
size: 10,
strokeWidth: 5,
fillColor: '#ffffff',
strokeColor: '#007aff',
display: true,
},
loop: {
margin: 2,
gradient: true,
}
}
},
},
addData() {
this.$refs.linechart.append({
serial: 0,
data: [Math.floor(Math.random() * 400) + 400]
})
}
}
```
![lite_line](figures/lite_line.PNG)
2. Bar chart
```html
<!-- xxx.hml -->
<div class="container">
<chart class="chart" type="bar" id="bar-chart" options="{{barOps}}" datasets="{{barData}}"></chart>
</div>
```
```css
/* xxx.css */
.container {
flex-direction: column;
justify-content: center;
align-items: center;
width: 454px;
height: 454px;
background-color: white;
}
.chart {
width: 300px;
height: 300px;
}
```
```js
// xxx.js
export default {
data: {
barData: [
{
fillColor: '#f07826',
data: [763, 550, 551, 554, 731, 654, 525, 696, 595, 628],
},
{
fillColor: '#cce5ff',
data: [535, 776, 615, 444, 694, 785, 677, 609, 562, 410],
},
{
fillColor: '#ff88bb',
data: [673, 500, 574, 483, 702, 583, 437, 506, 693, 657],
},
],
barOps: {
xAxis: {
min: 0,
max: 20,
display: false,
axisTick: 10
},
yAxis: {
min: 0,
max: 1000,
display: false,
},
},
}
}
```
![lite_bar](figures/lite_bar.PNG)
# image-animator
The **\<image-animator>** component is used to provide an image frame animator.
> **NOTE**
>
> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
## Child Components
Not supported
## Attributes
| Name | Type | Default Value | Mandatory | Description |
| --------------------- | -------------------------- | -------- | ---- | ---------------------------------------- |
| images | Array&lt;ImageFrame&gt; | - | Yes | Image frame information. The frame information includes the image path, size, and location. The supported image formats include PNG, JPG, and BMP. For details about **ImageFrame**, see Table 1.<br>**NOTE**<br>Use data binding, for example, **images = {{images}}**, to specify the image. Declare the corresponding variable in the JavaScript: **images: [{src: "/common/heart-rate01.png"}, {src: "/common/heart-rate02.png"}]**.|
| iteration | number \| string | infinite | No | Number of times that the frame animation is played. **number** indicates a fixed number of playback operations, and **infinite** indicates an unlimited number of playback operations.|
| reverse | boolean | false | No | Playback sequence.<br/>- **true**: Images are played from the last one to the first one.<br/>- **false**: Images are played from the first one to the last one.|
| fixedsize | boolean | true | No | Whether the image size is the same as the component size.<br>- **true**: The image size is the same as the component size. In this case, the width, height, top, and left attributes of the image are invalid.<br>- **false**: The image size is different from the component size. In this case, the width, height, top, and left attributes of each image must be set separately.|
| duration | string | - | Yes | Single video playback duration, in seconds (s) or milliseconds (ms). The default unit is ms. If the value is **0**, no image is played. The value change takes effect only at the start of the next cycle.|
| fillmode<sup>5+</sup> | string | forwards | No | Status of the frame animation after its playback is complete. Available values are as follows:<br>- **none**: restores to the initial status.<br>- **forwards**: retains the ending status defined for the last key frame.|
| id | string | - | No | Unique ID of the component. |
| style | string | - | No | Style declaration of the component. |
| class | string | - | No | Style class of the component, which is used to refer to a style table. |
| ref | string | - | No | Reference information of child elements, which is registered with the parent component on **$refs**.|
**Table 1** ImageFrame
| Name | Type | Default Value | Mandatory | Description |
| ------ | -------------- | ---- | ---- | ---------------- |
| src | &lt;uri&gt; | - | Yes | Image path. |
| width | &lt;length&gt; | 0 | No | Image width. |
| height | &lt;length&gt; | 0 | No | Image height. |
| top | &lt;length&gt; | 0 | No | Vertical coordinate of the image relative to the upper left corner of the component.|
| left | &lt;length&gt; | 0 | No | Horizontal coordinate of the image relative to the upper left corner of the component.|
## Events
| Name | Parameter | Description |
| ------------------ | --------------------------------- | ----------- |
| stop | - | Triggered when the frame animation stops |
| 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
| Name | Type | Default Value | Mandatory | Description |
| ---------------------------------- | ---------------------------------------- | ----- | ---- | ---------------------------------------- |
| width | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | - | No | Component width.<br><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><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).|
| margin-[left\|top\|right\|bottom] | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | 0 | No | Left, top, right, and bottom margins. |
| border-width | &lt;length&gt; | 0 | No | Shorthand attribute to set the margin for all sides. |
| 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. |
| background-color | &lt;color&gt; | - | No | Background color. |
| opacity<sup>5+</sup> | number | 1 | No | Opacity of an element. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent. |
| 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 | left\|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.|
## Methods
| Name | Parameter | Description |
| -------- | ---- | ---------------------------------------- |
| start | - | Starts to play the frame animation of an image. If this method is called again, the playback starts from the first frame. |
| pause | - | Pauses the frame animation playback of an image. |
| stop | - | Stops the frame animation playback of an image. |
| resume | - | Resumes the frame animation playback of an image. |
| getState | - | Obtains the playback state. Available values are as follows:<br>- playing<br>- paused<br>- stopped|
## Example
```html
<!-- xxx.hml -->
<div class="container">
<image-animator class="animator" ref="animator" images="{{frames}}" duration="1s" />
<div class="btn-box">
<input class="btn" type="button" value="start" @click="handleStart" />
<input class="btn" type="button" value="stop" @click="handleStop" />
<input class="btn" type="button" value="pause" @click="handlePause" />
<input class="btn" type="button" value="resume" @click="handleResume" />
</div>
</div>
```
```css
/* xxx.css */
.container {
flex-direction: column;
justify-content: center;
align-items: center;
left: 0px;
top: 0px;
width: 454px;
height: 454px;
}
.animator {
width: 70px;
height: 70px;
}
.btn-box {
width: 264px;
height: 120px;
flex-wrap: wrap;
justify-content: space-around;
align-items: center;
}
.btn {
border-radius: 8px;
width: 120px;
margin-top: 8px;
}
```
```js
//xxx.js
export default {
data: {
frames: [
{
src: "/common/asserts/heart78.png",
},
{
src: "/common/asserts/heart79.png",
},
{
src: "/common/asserts/heart80.png",
},
{
src: "/common/asserts/heart81.png",
},
{
src: "/common/asserts/heart82.png",
},
{
src: "/common/asserts/heart83.png",
},
{
src: "/common/asserts/heart84.png",
},
{
src: "/common/asserts/heart85.png",
},
{
src: "/common/asserts/heart86.png",
},
{
src: "/common/asserts/heart87.png",
},
{
src: "/common/asserts/heart88.png",
},
{
src: "/common/asserts/heart89.png",
},
{
src: "/common/asserts/heart90.png",
},
{
src: "/common/asserts/heart91.png",
},
{
src: "/common/asserts/heart92.png",
},
{
src: "/common/asserts/heart93.png",
},
{
src: "/common/asserts/heart94.png",
},
{
src: "/common/asserts/heart95.png",
},
{
src: "/common/asserts/heart96.png",
},
],
},
handleStart() {
this.$refs.animator.start();
},
handlePause() {
this.$refs.animator.pause();
},
handleResume() {
this.$refs.animator.resume();
},
handleStop() {
this.$refs.animator.stop();
},
};
```
![image-animator](figures/image-animator.gif)
# image
The **\<image>** component is used to render and display images.
> **NOTE**
>
> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
## Child Components
Not supported
## Attributes
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| src | string | No| <br>Image path. The supported image formats include PNG and JPG.|
| id | string | No| Unique ID of the component.|
| style | string | No| Style declaration of the component.|
| class | string | No| Style class of the component, which is used to refer to a style table.|
| ref | string | No| Reference information of child elements, which is registered with the parent component on **$refs**.|
## Events
| 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. |
## Styles
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| width | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | - | No| Component width.<br><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><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).|
| margin-[left\|top\|right\|bottom] | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | 0 | No| Left, top, right, and bottom margins.|
| border-width | &lt;length&gt; | 0 | No| Shorthand attribute to set the margin for all sides.|
| 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. |
| background-color | &lt;color&gt; | - | No| Background color.|
| opacity | number | 1 | No| Opacity of an element. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent.|
| 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| left\|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.|
## Example
```html
<!-- xxx.hml -->
<div class="container">
<image src="common/images/hw_right.png" style="width: 300px; height: 300px; border-color: red; border-width: 2px;">
</image>
</div>
```
```css
/* xxx.css */
.container {
justify-content: center;
align-items: center;
flex-direction: column;
width: 100%;
height: 100%;
}
```
![image](figures/image.png)
# input
The **\<input>** component provides an interactive interface to receive user input. It can be a radio button, check box, or button.
> **NOTE**
>
> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
## Child Components
Not supported
## Attributes
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| type | string | <br>button | No| Type of the component, which cannot be dynamically modified. The options are as follows:<br>- **button**: a button that can be clicked.<br>- **checkbox**: a check box.<br>- **radio**: a radio button that allows users to select one from multiple others with the same name. |
| checked | boolean | false | No| Whether the component is selected. This attribute is valid only when **type** is set to **checkbox** or **radio**.|
| name | string | - | No| Name of the component.|
| value | string | - | No| Value of the component. When **type** is **radio**, this attribute is mandatory and the value must be unique for radio buttons with the same name.|
| id | string | - | No| Unique ID of the component.|
| style | string | - | No| Style declaration of the component.|
| class | string | - | No| Style class of the component, which is used to refer to a style table.|
| ref | string | - | No| Reference information of child elements, which is registered with the parent component on **$refs**.|
## Events
- When **type** is set to **checkbox** or **radio**, the following events are supported.
| Name| Parameter| Description|
| -------- | -------- | -------- |
| change | { checked:true \| false } | Triggered when the checked status of the **checkbox** or **radio** button changes.|
| 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. |
- When **type** is set to **button**, the following events are 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. |
## Styles
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| color | &lt;color&gt; | \#ffffff | No| Text color of the component.|
| font-size | &lt;length&gt; | 30px | No| Font size of the component.|
| width | &lt;length&gt; | - | No| Width of the component. The default value for a button is **100px**.|
| height | &lt;length&gt; | - | No| Height of the component. The default value for a button is **50px**.|
| font-family | string | SourceHanSansSC-Regular | No| Font. Only the **SourceHanSansSC-Regular** font is supported.|
| 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).|
| margin-[left\|top\|right\|bottom] | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | 0 | No| Left, top, right, and bottom margins.|
| border-width | &lt;length&gt; | 0 | No| Shorthand attribute to set the margin for all sides.|
| 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. |
| background-color | &lt;color&gt; | - | No| Background color.|
| 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. |
## Example
1. Common button
```html
<!-- xxx.hml -->
<div class="div-button">
<input class="button" type="button" value="Input-Button"></input>
</div>
```
```css
/* xxx.css */
.div-button {
flex-direction: column;
align-items: center;
width: 100%;
height: 100%;
}
.button {
margin-top: 30px;
width: 280px;
}
```
![input-type-button](figures/input-type-button.png)
2. Check box
```html
<!-- xxx.hml -->
<div class="content">
<input onchange="checkboxOnChange" checked="true" type="checkbox"></input>
<text class="text">{{text}}</text>
</div>
```
```css
/* xxx.css */
.content{
width: 100%;
height: 100%;
flex-direction: column;
align-items: center;
justify-content: center;
}
.text{
font-size: 30px;
text-align: center;
width: 200px;
margin-top: 20px;
height: 100px;
}
```
```javascript
// xxx.js
export default {
data: {
text: "text"
},
checkboxOnChange(e) {
this.text = e.checked;
}
}
```
![input-type-checkbox](figures/input-type-checkbox.gif)
3. Radio button
```html
<!-- xxx.hml -->
<div class="container">
<div class="item">
<input type="radio" checked="true" name="radioSample" value="radio1" onchange="onRadioChange"></input>
<text class="text">radio1</text>
</div>
<div class="item">
<input type="radio" checked="false" name="radioSample" value="radio2" onchange="onRadioChange"></input>
<text class="text">radio2</text>
</div>
<div class="item">
<input type="radio" checked="false" name="radioSample" value="radio3" onchange="onRadioChange"></input>
<text class="text">radio3</text>
</div>
</div>
```
```css
/* xxx.css */
.container {
width: 100%;
height: 100%;
justify-content: center;
align-items: center;
flex-direction: column;
}
.item {
width: 50%;
height: 30%;
justify-content: center;
}
.text {
margin-top: 25%;
font-size: 30px;
text-align: center;
width: 200px;
height: 100px;
}
```
![input-type-radio](figures/input-type-radio.gif)
# marquee
The **\<marquee>** component is used to display a scrolling piece of text.
> **NOTE**
>
> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
## Child Components
Not supported
## Attributes
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| scrollamount | number | 6 | No| Maximum length of each scroll.|
| id | string | - | No| Unique ID of the component.|
| style | string | - | No| Style declaration of the component.|
| class | string | - | No| Style class of the component, which is used to refer to a style table.|
| ref | string | - | No| Reference information of child elements, which is registered with the parent component on **$refs**.|
## Events
| 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. |
## Styles
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| color | &lt;color&gt; | \#ffffff<br><br><br>| No| Font color of the scrolling text.|
| font-size | &lt;length&gt; | <br>30 | No| Font size of the scrolling text.|
| font-family | string | <br><br>SourceHanSansSC-Regular | No| <br><br>Font. Only the **SourceHanSansSC-Regular** font is supported.|
| width | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | - | No| Component width.<br><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><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).|
| margin-[left\|top\|right\|bottom] | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | 0 | No| Left, top, right, and bottom margins.|
| border-width | &lt;length&gt; | 0 | No| Shorthand attribute to set the margin for all sides.|
| 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.|
| background-color | &lt;color&gt; | - | No| Background color.|
| opacity<sup>5+</sup> | number | 1 | No| Opacity of an element. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent.|
| 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| left\|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.|
## Example
```html
<!-- xxx.hml -->
<div class="container">
<marquee class="customMarquee" scrollamount="{{scrollAmount}}">{{marqueeCustomData}}</marquee>
<text class="text" onclick="addSpeed">speed+</text>
<text class="text" onclick="downSpeed">speed-</text>
<text class="text" onclick="changeData">changeData</text>
</div>
```
```css
/* xxx.css */
.container {
flex-direction: column;
width: 100%;
height: 100%;
flex-direction: column;
align-items: center;
}
.customMarquee {
width: 50%;
height: 80px;
padding: 10px;
margin: 20px;
border-width: 4px;
border-color: #ffffff;
border-radius: 20px;
font-size: 38px;
}
.text {
font-size: 30px;
text-align: center;
width: 30%;
height: 10%;
margin-top: 5%;
background-color: #f2f2f2;
border-radius: 40px;
color: #0d81f2;
}
```
```javascript
// xxx.js
export default {
data: {
scrollAmount: 30,
marqueeCustomData: 'Custom marquee Custom marquee Custom marquee'
},
addSpeed() {
this.scrollAmount++;
},
downSpeed() {
this.scrollAmount--;
},
changeData() {
this.marqueeCustomData = 'Change Data Change Data Change Data';
}
}
```
![marquee](figures/marquee.gif)
# picker-view
The **\<picker-view>** component provides the view that shows an embedded scrollable selector on the screen.
> **NOTE**
>
> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
## Child Components
Not supported
## Attributes
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| type | string | text | No| Type of the scrollable selector, which cannot be changed dynamically. Available values are as follows:<br>- **text**: text selector.<br>- **time**: time selector.|
| id | string | - | No| Unique ID of the component.|
| style | string | - | No| Style declaration of the component.|
| class | string | - | No| Style class of the component, which is used to refer to a style table.|
| ref | string | - | No| Reference information of child elements, which is registered with the parent component on **$refs**.|
Text selector (**type** is **text**)
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| range | Array | - | No| Value range of the text selector.<br>Use data binding, for example, **range = {{data}}**, to specify the range. Declare the corresponding variable in the JavaScript: **data: ["15", "20", "25"]**.|
| selected | string | 0 | No| Default value of the text selector. The value is the index of **range**.|
Time selector (**type** is **time**)
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| selected | string | 00:00 | No| Default value of the time selector, in the format of HH:mm.<br>|
## Events
Text selector (**type** is **text**)
| Name| Parameter| Description|
| -------- | -------- | -------- |
| change | { newValue: newValue, newSelected: newSelected } | Triggered when a value is specified for the text selector.|
Time selector (**type** is **time**)
| Name| Parameter| Description|
| -------- | -------- | -------- |
| change | { hour: hour, minute: minute} | Triggered when a value is specified for the time selector. |
## Styles
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| color | &lt;color&gt; | \#808080 | No| Font color of a candidate item.|
| font-size | &lt;length&gt; | 30px | No| Font size of a candidate item. The value is of the length type, in pixels.|
| selected-color | &lt;color&gt; | \#ffffff | No| Font color of the selected item.|
| selected-font-size | &lt;length&gt; | 38px | No| Font size of the selected item. The value is of the length type, in pixels.|
| selected-font-family | string | HYQiHei-65S | No| Font type of the selected item.|
| font-family | string | HYQiHei-65S | No| Font type of an item.|
| 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).|
| margin-[left\|top\|right\|bottom] | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | 0 | No| Left, top, right, and bottom margins.|
| border-width | &lt;length&gt; | 0 | No| Shorthand attribute to set the margin for all sides.|
| 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.|
| background-color | &lt;color&gt; | - | No| Background color.|
| 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. |
## Example
```html
<!-- xxx.hml -->
<div class="container" @swipe="handleSwipe">
<text class="title">
Selected: {{time}}
</text>
<picker-view class="time-picker" type="time" selected="{{defaultTime}}" @change="handleChange"></picker-view>
</div>
```
```css
/* xxx.css */
.container {
flex-direction: column;
justify-content: center;
align-items: center;
left: 0px;
top: 0px;
width: 454px;
height: 454px;
}
.title {
font-size: 30px;
text-align: center;
}
.time-picker {
width: 500px;
height: 400px;
margin-top: 20px;
}
```
```js
/* xxx.js */
export default {
data: {
defaultTime: "",
time: "",
},
onInit() {
this.defaultTime = this.now();
},
handleChange(data) {
this.time = this.concat(data.hour, data.minute);
},
now() {
const date = new Date();
const hours = date.getHours();
const minutes = date.getMinutes();
return this.concat(hours, minutes);
},
fill(value) {
return (value > 9 ? "" : "0") + value;
},
concat(hours, minutes) {
return `${this.fill(hours)}:${this.fill(minutes)}`;
},
}
```
![picker-view](figures/picker-view.png)
# progress
The **\<Progress>** component is used to provide a progress bar that displays the progress of content loading or an operation.
> **NOTE**
>
> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
## Child Components
Not supported
## Attributes
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| type | string | horizontal | No| Type of the progress bar, which cannot be changed dynamically. Available values are as follows:<br>- **horizontal**: linear progress bar.<br>- **arc**: arc progress bar.|
| id | string | - | No| Unique ID of the component.|
| style | string | - | No| Style declaration of the component.|
| class | string | - | No| Style class of the component, which is used to refer to a style table.|
| ref | string | - | No| Reference information of child elements, which is registered with the parent component on **$refs**.|
Different types of progress bars support different attributes.
- When **type** is set to **horizontal**, the following attributes are supported.
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| percent | number | 0 | No| Current progress. The value ranges from 0 to 100.|
- When **type** is set to **arc**, the following attributes are supported.
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| percent | number | 0 | No| Current progress. The value ranges from 0 to 100.|
## Events
| 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. |
## Styles
- When **type** is set to **horizontal**, the following styles are supported.
| Name | Type | Default Value | Mandatory| Description |
| ------------ | -------------- | ---------------------------------------------- | ---- | ------------------ |
| color | &lt;color&gt; | \#6b9ac7 | No | Color of the progress bar.|
| stroke-width | &lt;length&gt; | 32<sup>1-4 </sup>\| 4<sup>5+</sup>px | No | Stroke width of the progress bar.|
- When **type** is set to **arc**, the following styles are supported.
| Name | Type | Default Value| Mandatory| Description |
| ---------------- | -------------- | ------ | ---- | ------------------------------------------------------------ |
| color | &lt;color&gt; | - | No | Color of the arc progress bar. |
| background-color | &lt;color&gt; | - | No | Background color of the arc progress bar. |
| stroke-width | &lt;length&gt; | - | No | Width of the arc progress bar.<br>A larger width value means that the progress bar is closer to the center of the circle. The width is always within the radius range.|
| start-angle | &lt;deg&gt; | 240 | No | Start angle of the arc progress bar, which starts from the direction of zero o'clock. The value ranges from 0 to 360 degrees (clockwise).|
| total-angle | &lt;deg&gt; | 240 | No | Total length of the arc progress bar. The value ranges from –360 to 360. A negative number indicates anticlockwise.|
| center-x | &lt;length&gt; | - | No | Center of the arc progress bar (with the upper left corner of this widget as the coordinate origin). This style must be used together with **center-y** and **radius**.|
| center-y | &lt;length&gt; | - | No | Center of the arc progress bar (with the upper left corner of this widget as the coordinate origin). This style must be used together with **center-x** and **radius**.|
| radius | &lt;length&gt; | - | No | Radius of the arc progress bar. This style must be used together with **center-x** and **center-y**. |
In addition to the preceding styles, the following styles are supported.
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| 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).|
| margin-[left\|top\|right\|bottom] | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | 0 | No| Left, top, right, and bottom margins.|
| border-width | &lt;length&gt; | 0 | No| Shorthand attribute to set the margin for all sides.|
| 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. |
## Example
```html
<!-- xxx.hml -->
<div class="container">
<progress type="horizontal" percent="{{horizontalVal}}" style="height: 10%;width: 40%;" onclick = "changeHorizontal"></progress>
<progress type="arc" class="min-progress" percent="{{arcVal}}" on:click="changeArc"></progress>
</div>
```
```css
/* xxx.css */
.container {
flex-direction: column;
height: 100%;
width: 100%;
align-items: center;
}
.min-progress {
width: 300px;
height: 300px;
}
```
```javascript
// xxx.js
export default {
data: {
arcVal: 0,
horizontalVal: 0
},
changeArc() {
this.arcVal+= 10;
},
changeHorizontal() {
this.horizontalVal+= 10;
}
}
```
![progress](figures/progress.png)
# qrcode
The **\<qrcode>** component is used to generate and display a QR code.
> **NOTE**
>
> This component is supported since API version 5. Updates will be marked with a superscript to indicate their earliest API version.
## Child Components
Not supported
## Attributes
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| value | string | - | Yes| Content used to generate the QR code. The maximum length is 256.|
| id | string | - | No| Unique ID of the component.|
| style | string | - | No| Style declaration of the component.|
| class | string | - | No| Style class of the component, which is used to refer to a style table.|
| ref | string | - | No| Reference information of child elements, which is registered with the parent component on **$refs**.|
## Events
| 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. |
## Styles
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| 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. |
| 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).|
| margin-[left\|top\|right\|bottom] | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | 0 | No| Left, top, right, and bottom margins.|
| border-width | &lt;length&gt; | 0 | No| Shorthand attribute to set the margin for all sides.|
| 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. |
> **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.
>
>- The minimum values of **width** and **height** are 200 px.
## Example
```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>
</div>
```
```css
/* xxx.css */
.container {
width: 100%;
height: 100%;
flex-direction: column;
justify-content: center;
align-items: center;
}
.qrCode {
width: 200px;
height: 200px;
}
.button {
width: 30%;
height: 10%;
margin-top: 5%;
}
```
```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';
}
},
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';
}
}
}
```
![qrcode](figures/qrcode.gif)
# slider
The **\<Slider>** component is used to quickly adjust settings, such as the volume and brightness.
> **NOTE**
>
> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
## Child Components
Not supported
## Attributes
| Name | Type | Default Value | Mandatory | Description |
| ----- | ------ | ---- | ---- | ---------------------------------------- |
| min | number | 0 | No | Minimum value of the slider. |
| max | number | 100 | No | Maximum value of the slider. |
| value | number | 0 | No | Initial value of the slider. |
| id | string | - | No | Unique ID of the component. |
| style | string | - | No | Style declaration of the component. |
| class | string | - | No | Style class of the component, which is used to refer to a style table. |
| ref | string | - | No | Reference information of child elements, which is registered with the parent component on **$refs**.|
## Events
| Name | Parameter | Description |
| ------------------ | --------------------------------- | -------------- |
| change | ChangeEvent | Triggered when the value changes.|
| 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. |
**Table 1** ChangeEvent
| Attribute | Type | Description |
| ---------------------------------------- | ------ | ------------- |
| progress<sup>(deprecated<sup>5+</sup>)</sup> | string | Current value of the slider.|
| value<sup>5+</sup> | number | Current value of the slider.|
## Styles
| Name | Type | Default Value | Mandatory | Description |
| ---------------------------------- | ---------------------------------------- | -------- | ---- | ---------------------------------------- |
| color | &lt;color&gt; | \#000000 | No | Background color of the slider. |
| selected-color | &lt;color&gt; | \#ffffff | No | Selected color of the slider. |
| 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).|
| margin-[left\|top\|right\|bottom] | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | 0 | No | Left, top, right, and bottom margins. |
| border-width | &lt;length&gt; | 0 | No | Shorthand attribute to set the margin for all sides. |
| 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. |
| background-color | &lt;color&gt; | - | No | Background color. |
| 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.|
## Example
```html
<!-- xxx.hml -->
<div class="container">
<text>slider start value is {{startValue}}</text>
<text>slider current value is {{currentValue}}</text>
<text>slider end value is {{endValue}}</text>
<slider min="0" max="100" value="{{value}}" onchange="setvalue" style="width: 20%;height: 10%"></slider>
</div>
```
```css
/* xxx.css */
.container {
flex-direction: column;
justify-content: center;
align-items: center;
width: 100%;
height: 100%;
}
```
```javascript
// xxx.js
export default {
data: {
value: 0,
startValue: 0,
currentValue: 0,
endValue: 100,
},
setvalue(e) {
this.currentValue = e.value;
}
}
```
![slider](figures/slider.png)
# switch
The **\<switch>** component is used to enable or disable a function.
> **NOTE**
>
> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
## Child Components
Not supported
## Attributes
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| checked | boolean | false | No| Whether the component is checked or not.|
| id | string | - | No| Unique ID of the component.|
| style | string | - | No| Style declaration of the component.|
| class | string | - | No| Style class of the component, which is used to refer to a style table.|
| ref | string | - | No| Reference information of child elements, which is registered with the parent component on **$refs**.|
## Events
| Name| Parameter| Description|
| -------- | -------- | -------- |
| change | { checked: checkedValue } | Triggered when the **checked** state changes.|
| 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
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| width | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | - | No| Component width.<br><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><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).|
| margin-[left\|top\|right\|bottom] | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | 0 | No| Left, top, right, and bottom margins.|
| border-width | &lt;length&gt; | 0 | No| Shorthand attribute to set the margin for all sides.|
| 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.|
| background-color | &lt;color&gt; | - | No| Background color.|
| 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| left\|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.|
## Example
```html
<!-- xxx.hml -->
<div class="container">
<div class="box">
<switch checked="true" @change="switchChange"></switch>
<text>{{title}}</text>
</div>
</div>
```
```css
/* xxx.css */
.container {
width: 100%;
height: 100%;
justify-content: center;
align-items: center;
}
.box{
width: 18%;
height: 25%;
flex-direction:column;
justify-content: center;
align-items: center;
}
```
```javascript
// xxx.js
export default {
data: {
title: 'on'
},
switchChange(e){
console.log(e.checked);
if(e.checked){
this.title="on"
}else{
this.title="off"
}
}
}
```
![switch](figures/switch.gif)
# text
The **\<text>** component is used to display a piece of textual information.
> **NOTE**
>
> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
## Child Components
Not supported
## Attributes
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| id | string | - | No| Unique ID of the component.|
| style | string | - | No| Style declaration of the component.|
| class | string | - | No| Style class of the component, which is used to refer to a style table.|
| ref | string | - | No| Reference information of child elements, which is registered with the parent component on **$refs**.|
## Events
| 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.|
## Styles
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| color | &lt;color&gt; | \#ffffff | No| Font color.|
| font-size | &lt;length&gt; | 30px | No| Font size. |
| letter-spacing | &lt;length&gt; | 2px | No| Character spacing (px).|
| text-align | string | left | No| Text alignment mode. Available values are as follows:<br>- **left**: The text is left-aligned.<br>- **center**: The text is center-aligned.<br>- **right**: The text is right-aligned.|
| text-overflow | string | clip | No| Available values are as follows:<br>- **clip**: The text is clipped and displayed based on the size of the parent container.<br>- **ellipsis**: The text is displayed based on the size of the parent container. The text that cannot be displayed is replaced with ellipsis.|
| font-family | string | SourceHanSansSC-Regular | No| Font. Only the **SourceHanSansSC-Regular** font is supported.|
| width | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | 0px | No| Component width.<br>Unit: pixel<br>If this attribute is not set, the default value **0** is used.|
| height | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | 0px | No| Component height.<br>Unit: pixel<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).|
| margin-[left\|top\|right\|bottom] | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | 0 | No| Left, top, right, and bottom margins.|
| border-width | &lt;length&gt; | 0 | No| Shorthand attribute to set the margin for all sides.|
| 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.|
| background-color | &lt;color&gt; | - | No| Background color.|
| opacity<sup>5+</sup> | number | 1 | No| Opacity of an element. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent.|
| 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. |
## Example
```html
<!-- xxx.hml -->
<div class="container">
<text class="title">
Hello {{ title }}
</text>
</div>
```
```CSS
/* xxx.css */
.container {
width: 100%;
height: 100%;
justify-content: center;
align-items: center;
}
.title {
width: 100px;
font-size: 30px;
text-align: center;
color: red;
}
```
```javascript
// xxx.js
export default {
data: {
title: ""
},
onInit() {
this.title = "World";
}
}
```
![text](figures/text.png)
# canvas
The **\<canvas>** component is used for customizing drawings.
> **NOTE**
>
> This component is supported since API version 5. Updates will be marked with a superscript to indicate their earliest API version.
## Child Components
Not supported
## Attributes
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| id | string | - | No| Unique ID of the component.|
| style | string | - | No| Style declaration of the component.|
| class | string | - | No| Style class of the component, which is used to refer to a style table.|
| ref | string | - | No| Reference information of child elements, which is registered with the parent component on **$refs**.|
## Events
| 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.|
## Styles
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| 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).|
| 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).|
| margin-[left\|top\|right\|bottom] | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | 0 | No| Left, top, right, and bottom margins.|
| border-width | &lt;length&gt; | 0 | No| Shorthand attribute to set the margin for all sides.|
| 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.|
| background-color | &lt;color&gt; | - | No| Background color.|
| 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. |
## Methods
| Name| Parameter| Description|
| -------- | -------- | -------- |
| getContext | string | Obtains the context of the drawing on a canvas. The parameter can be set only to **2d**. The return value is a 2D drawing object that provides specific 2D drawing operations. For details, see [CanvasRenderingContext2D](js-components-canvas-canvasrenderingcontext2d.md).|
# CanvasRenderingContext2D
**CanvasRenderingContext2D** allows you to draw rectangles and text on a canvas.
**Example**
```html
<!-- xxx.hml -->
<canvas ref="canvas1" style="width: 200px; height: 150px; background-color: #ffff00;"></canvas>
<input type="button" style="width: 180px; height: 60px;" value="fillStyle" onclick="handleClick" />
```
```javascript
// xxx.js
export default {
handleClick() {
const el = this.$refs.canvas1;
const ctx = el.getContext('2d');
ctx.beginPath();
ctx.arc(100, 75, 50, 0, 6.28);
ctx.stroke();
},
}
```
![en-us_image_0000001431548113](figures/en-us_image_0000001431548113.png)
## fillRect()
Fills a rectangle on the canvas.
**Parameters**
| Parameter| Type| Description|
| -------- | -------- | -------- |
| x | number | X-coordinate of the upper left corner of the rectangle.|
| y | number | Y-coordinate of the upper left corner of the rectangle.|
| width | number | Width of the rectangle.|
| height | number | Height of the rectangle.|
**Example**
![en-us_image_0000001431388525](figures/en-us_image_0000001431388525.png)
```javascript
ctx.fillRect(20, 20, 200, 150);
```
## fillStyle
Sets the style to fill an area.
**Parameters**
| Parameter| Type| Description|
| -------- | -------- | -------- |
| color | &lt;color&gt; | Color used to fill the area|
**Example**
![en-us_image_0000001431388505](figures/en-us_image_0000001431388505.png)
```javascript
ctx.fillStyle = '#0000ff';
ctx.fillRect(20, 20, 150, 100);
```
## strokeRect()
Draws a rectangle stroke on the canvas.
**Parameters**
| Parameter| Type| Description|
| -------- | -------- | -------- |
| x | number | X-coordinate of the upper left corner of the rectangle.|
| y | number | Y-coordinate of the upper left corner of the rectangle.|
| width | number | Width of the rectangle.|
| height | number | Height of the rectangle.|
**Example**
![en-us_image_0000001381268264](figures/en-us_image_0000001381268264.png)
```javascript
ctx.strokeRect(30, 30, 200, 150);
```
## fillText()
Draws filled text on the canvas.
**Parameters**
| Parameter| Type| Description|
| -------- | -------- | -------- |
| text | string | Text to draw.|
| x | number | X-coordinate of the lower left corner of the text.|
| y | number | Y-coordinate of the lower left corner of the text.|
**Example**
![en-us_image_0000001431548109](figures/en-us_image_0000001431548109.png)
```javascript
ctx.font = '35px sans-serif';
ctx.fillText("Hello World!", 20, 60);
```
## lineWidth
Sets the width of a line.
**Parameters**
| Parameter| Type| Description|
| -------- | -------- | -------- |
| lineWidth | number | Line width.|
**Example**
![en-us_image_0000001431548121](figures/en-us_image_0000001431548121.png)
```javascript
ctx.lineWidth = 5;
ctx.strokeRect(25, 25, 85, 105);
```
## strokeStyle
Sets the stroke style.
**Parameters**
| Parameter| Type| Description|
| -------- | -------- | -------- |
| color | &lt;color&gt; | Color of the stroke.|
**Example**
![en-us_image_0000001380789172](figures/en-us_image_0000001380789172.png)
```javascript
ctx.lineWidth = 10;
ctx.strokeStyle = '#0000ff';
ctx.strokeRect(25, 25, 155, 105);
```
### stroke()<sup>5+</sup>
Draws a stroke.
**Example**
![en-us_image_0000001431388513](figures/en-us_image_0000001431388513.png)
```javascript
ctx.moveTo(25, 25);
ctx.lineTo(25, 105);
ctx.strokeStyle = 'rgb(0,0,255)';
ctx.stroke();
```
### beginPath()<sup>5+</sup>
Creates a drawing path.
**Example**
![en-us_image_0000001431548125](figures/en-us_image_0000001431548125.png)
```javascript
ctx.beginPath();
ctx.lineWidth = '6';
ctx.strokeStyle = '#0000ff';
ctx.moveTo(15, 80);
ctx.lineTo(280, 160);
ctx.stroke();
```
### moveTo()<sup>5+</sup>
Moves a drawing path to a target position on the canvas.
**Parameters**
| Parameter| Type| Description|
| -------- | -------- | -------- |
| x | number | X-coordinate of the target position.|
| y | number | Y-coordinate of the target position.|
**Example**
![en-us_image_0000001431388529](figures/en-us_image_0000001431388529.png)
```javascript
ctx.beginPath();
ctx.moveTo(10, 10);
ctx.lineTo(280, 160);
ctx.stroke();
```
### lineTo()<sup>5+</sup>
Connects the current point to a target position using a straight line.
**Parameters**
| Parameter| Type| Description|
| -------- | -------- | -------- |
| x | number | X-coordinate of the target position.|
| y | number | Y-coordinate of the target position.|
**Example**
![en-us_image_0000001431148365](figures/en-us_image_0000001431148365.png)
```javascript
ctx.beginPath();
ctx.moveTo(10, 10);
ctx.lineTo(280, 160);
ctx.stroke();
```
### closePath()<sup>5+</sup>
Draws a closed path.
**Example**
![en-us_image_0000001381268284](figures/en-us_image_0000001381268284.png)
```javascript
ctx.beginPath();
ctx.moveTo(30, 30);
ctx.lineTo(110, 30);
ctx.lineTo(70, 90);
ctx.closePath();
ctx.stroke();
```
## font
Sets the font style.
**Parameters**
| Parameter| Type| Description|
| -------- | -------- | -------- |
| value | string | Font style. **sans-serif**, **serif**, and **monospace** are supported. The default value is **30px HYQiHei-65S**.|
**Example**
![en-us_image_0000001381108328](figures/en-us_image_0000001381108328.png)
```javascript
ctx.font = '30px sans-serif';
ctx.fillText("Hello World", 20, 60);
```
## textAlign
Sets the text alignment mode.
**Parameters**
| Parameter| Type| Description|
| -------- | -------- | -------- |
| align | string | Available values are as follows:<br>- **left** (default): The text is left-aligned.<br>- **right**: The text is right-aligned.<br>- **center**: The text is center-aligned.|
**Example**
![en-us_image_0000001431388517](figures/en-us_image_0000001431388517.png)
```javascript
ctx.strokeStyle = '#0000ff';
ctx.moveTo(140, 10);
ctx.lineTo(140, 160);
ctx.stroke();
ctx.font = '18px sans-serif';
// Show the different textAlign values
ctx.textAlign = 'left';
ctx.fillText('textAlign=left', 140, 100);
ctx.textAlign = 'center';
ctx.fillText('textAlign=center',140, 120);
ctx.textAlign = 'right';
ctx.fillText('textAlign=right',140, 140);
```
## arc()<sup>5+</sup>
Draws an arc on the canvas.
**Parameters**
| Parameter| Type| Description|
| -------- | -------- | -------- |
| x | number | X-coordinate of the center point of the arc.|
| y | number | Y-coordinate of the center point of the arc.|
| radius | number | Radius of the arc.|
| startAngle | number | Start radian of the arc.|
| endAngle | number | End radian of the arc.|
| anticlockwise | boolean | Whether to draw the arc counterclockwise.|
**Example**
![en-us_image_0000001381108320](figures/en-us_image_0000001381108320.png)
```javascript
ctx.beginPath();
ctx.arc(100, 75, 50, 0, 6.28);
ctx.stroke();
```
### rect()<sup>5+</sup>
Creates a rectangle on the canvas.
**Parameters**
| Parameter| Type| Description|
| -------- | -------- | -------- |
| x | number | X-coordinate of the upper left corner of the rectangle.|
| y | number | Y-coordinate of the upper left corner of the rectangle.|
| width | number | Width of the rectangle.|
| height | number | Height of the rectangle.|
**Example**
![en-us_image_0000001381108312](figures/en-us_image_0000001381108312.png)
```javascript
ctx.rect(20, 20, 100, 100); // Create a 100*100 rectangle at (20, 20)
ctx.stroke(); // Draw it
```
# Animation Styles
Components support dynamic rotation, translation, and scaling effects. These effects can be set in the **style** attribute or **.css** files.
| Name | Type | Default Value | Description |
| ------------------------- | ---------------------------------- | ----------- | ---------------------------------------- |
| transform | string | - | Translation, rotation, and scaling attributes. For details, see Table 1. |
| animation-name | string | - | \@keyframes rule. For details, see Table 2. |
| animation-delay | &lt;time&gt; | 0 | Delay for playing the animation, in ms or s, for example, **1000 ms** or **1s**. \|The default unit is ms.|
| animation-duration | &lt;time&gt; | 0 | Animation duration, in ms or s, for example, **1000 ms** or **1s**. \|The default unit is ms.<br>**NOTE**<br>**animation-duration** must be specified. Otherwise, the duration is **0**, which means the animation will not be played.|
| animation-iteration-count | number \| infinite | 1 | Number of times that an animation is played. The animation is played once by default. You can set the value to **infinite** to play the animation infinitely. |
| animation-timing-function | string | <br>linear | Speed curve of an animation, which makes the animation more fluent.<br>Available values are as follows:<br>- **linear**: The animation speed keeps unchanged.<br>- **ease-in**: The animation starts at a low speed. The cubic-bezier curve (0.42, 0.0, 1.0, 1.0) is used<br>- **ease-out**: The animation ends at a low speed. The cubic-bezier curve (0.0, 0.0, 0.58, 1.0) is used.<br>- **ease-in-out**: The animation starts and ends at a low speed. The cubic-bezier curve (0.42, 0.0, 0.58, 1.0) is used.|
| animation-fill-mode | string | none | Start and end styles of the animation.<br>- **none**: No style is applied to the target before or after the animation is executed.<br>- **forwards**: The target keeps the state at the end of the animation (defined in the last key frame) after the animation is executed.|
**Table 1** transform
| Name | Type | Description |
| ---------- | ------------------------------------ | ---------- |
| translateX | &lt;length&gt; | Moves an element along the x-axis.|
| translateY | &lt;length&gt; | Moves an element along the y-axis.|
| rotate | &lt;deg&gt; \| &lt;rad&gt; | Rotates an element. |
> **NOTE**
>
> Only images of the original size can be rotated on lite wearables.
**Table 2** \@keyframes
| Name | Type | Default Value | Description |
| ---------------- | -------------- | ---- | ------------------ |
| background-color | &lt;color&gt; | - | Background color applied to the component after the animation is played. |
| width | &lt;length&gt; | - | Width value applied to the component after the animation is played. |
| height | &lt;length&gt; | - | Height value applied to the component after the animation is played. |
| transform | string | - | Transformation type applied to a component. For details, see Table 1.|
If there is no default value for when an animation will start or end, use **from** and **to** to specify the start and end of the display. The following is an example:
```css
@keyframes Go
{
from {
background-color: #f76160;
}
to {
background-color: #09ba07;
}
}
```
![animation-demo1](figures/animation-demo1.gif)
> **NOTE**
>
> The \@keyframes rule with **from** and **to** defined cannot be dynamically bound to an element.
# Media Query
> **NOTE**
>
> - This API is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
>
> - The **media** attribute uses the actual size, physical pixel, and screen resolution of the device by default.
Media queries are widely used. You can use them to modify the application style based on the device type or specific features and device parameters (such as the screen resolution). Specifically, media queries allow you to design a layout style based on the device and application attributes.
## CSS Syntax Rules
Use **@media** to import query statements. The rule is as follows:
```
@media [media-type] [and|or] [(media-feature)] {
CSS-Code;
}
```
**@media screen and (round-screen: true) { … }**: The condition is met when the device screen is round.
**@media (max-height: 454) { … }**: Range query. CSS level 3 is used.
> **NOTE**
>
> - The following operators are not supported: &lt;=, &gt;=, &lt;, and &gt;.
> - Nested parentheses are supported since API version 9.
> - A media query statement can contain a maximum of 512 characters.
> - A media query condition can contain a maximum of 32 characters.
## Media Type
| Type | Description |
| ------ | -------------- |
| screen | Media query based on screen-related parameters.|
## Media Logical Operation
You can use media logical operators to implement complex media query. The following table describes the available operators.
**Table 1** Media logical operators
| Type | Description |
| --------------- | ---------------------------------------- |
| and | The **and** operator is used to combine multiple media features into one media query, in a logical AND operation. The query is valid only when all media features are true. It can also combine media types and media functions.<br>For example, **screen and (device-type: liteWearable) and (max-height: 454)** evaluates to **true** when the device type is wearable and the maximum height of the application is 454 pixel units.|
| or<sup>9+</sup> | The **or** operator is used to combine multiple media features into one media query, in a logical OR operation. The query is valid if a media feature is true.<br>For example, **screen and (max-height: 454) or (round-screen: true)** evaluates to **true** when the maximum height of the application is 454 pixel units or the device screen is round.|
## Media Features
| Type | Description |
| ---------------- | ---------------------------------------- |
| height | Height of the display area on the application page. |
| min-height | Minimum height of the display area on the application page. |
| max-height | Maximum height of the display area on the application page. |
| width | Width of the display area on the application page. |
| min-width | Minimum width of the display area on the application page. |
| max-width | Maximum width of the display area on the application page. |
| aspect-ratio | Ratio of the width to the height of the display area on the application page.<br>Example: **aspect-ratio: 1/2**|
| min-aspect-ratio | Minimum ratio of the width to the height of the display area on the application page. |
| max-aspect-ratio | Maximum ratio of the width to the height of the display area on the application page. |
| round-screen | Screen type. The value **true** means that the screen is round, and **false** means the opposite.|
## Sample Code for the Common Media Feature
The number and type of attributes must be the same among **.container** blocks. Otherwise, display errors will occur.
```html
<!-- xxx.hml -->
<div>
<div class="container">
<text class="title">Hello World</text>
</div>
</div>
```
```css
/* xxx.css */
.container {
width: 300px;
height: 600px;
background-color: #008000;
}
.title {
font-size: 30px;
text-align: center;
}
@media (device-type: samrtVision) {
.container {
width: 500px;
height: 500px;
background-color: #fa8072;
}
}
@media (device-type: liteWearable) {
.container {
width: 300px;
height: 300px;
background-color: #008b8b;
}
}
```
# div
The **\<div>** component is a basic container that is used as the root node of the page structure or is used to group the content.
> **NOTE**
>
> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
## Child Components
Supported
## Attributes
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| id | string | - | No| Unique ID of the component.|
| style | string | - | No| Style declaration of the component.|
| class | string | - | No| Style class of the component, which is used to refer to a style table.|
| ref | string | - | No| Reference information of child elements, which is registered with the parent component on **$refs**.|
## Events
| 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.|
## Styles
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| flex-direction | string | row | No| Main axis direction of the flex container, which defines how items are placed in the container. Available values are as follows:<br>- **column**: Items are placed vertically from top to bottom.<br>- **row**: Items are placed horizontally from left to right.|
| flex-wrap | string | nowrap | No| Whether items in the flex container are displayed in a single line or multiple lines. The value cannot be dynamically updated. Available values are as follows:<br>- **nowrap**: Flex items are displayed in a single line.<br>- **wrap**: Flex items are displayed in multiple lines.|
| justify-content | string | flex-start | No| How items are aligned along the main axis of the flex container. Available values are as follows:<br>- **flex-start**: Items are packed toward the start edge of the container along the main axis.<br>- **flex-end**: Items are packed toward the end edge of the container along the main axis.<br>- **center**: Items are packed toward the center of the container along the main axis.<br>- **space-between**: Items are positioned with space between the rows.<br>- **space-around**: Items are positioned with space before, between, and after the rows.|
| align-items | string | stretch<sup>5+</sup><br>flex-start<sup>1-4</sup> | No| How items are aligned along the cross axis in a flex container. Available values are as follows:<br>- **stretch**: Items are stretched to the same height or width as the container along the cross axis.<sup>5+</sup><br>- **flex-start**: Items are packed toward the start edge of the cross axis.<br>- **flex-end**: Items are packed toward the end edge of the cross axis.<br>- **center**: Items are packed toward the center of the cross axis.|
| display | string | flex | No| Type of the view box of the item. The value cannot be dynamically updated. Available values are as follows:<br>- **flex**: flexible layout<br>- **none**: not rendered|
| width | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | - | No| Component width.<br><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).|
| margin-[left\|top\|right\|bottom] | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | 0 | No| Left, top, right, and bottom margins.|
| border-width | &lt;length&gt; | 0 | No| Shorthand attribute to set the margin for all sides.|
| 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.|
| background-color | &lt;color&gt; | - | No| Background color.|
| opacity<sup>5+</sup> | number | 1 | No| Opacity of an element. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent.|
| [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. |
## Example
1. Flex style
```html
<!-- xxx.hml -->
<div class="container">
<div class="flex-box">
<div class="flex-item color-primary"></div>
<div class="flex-item color-warning"></div>
<div class="flex-item color-success"></div>
</div>
</div>
```
```css
/* xxx.css */
.container {
flex-direction: column;
justify-content: center;
align-items: center;
width: 454px;
height: 454px;
}
.flex-box {
justify-content: space-around;
align-items: center;
width: 400px;
height: 140px;
background-color: #ffffff;
}
.flex-item {
width: 120px;
height: 120px;
border-radius: 16px;
}
.color-primary {
background-color: #007dff;
}
.color-warning {
background-color: #ff7500;
}
.color-success {
background-color: #41ba41;
}
```
![en-us_image_0000001381108420](figures/en-us_image_0000001381108420.png)
2. Flex wrap style
```html
<!-- xxx.hml -->
<div class="container">
<div class="flex-box">
<div class="flex-item color-primary"></div>
<div class="flex-item color-warning"></div>
<div class="flex-item color-success"></div>
</div>
</div>
```
```css
/* xxx.css */
.container {
flex-direction: column;
justify-content: center;
align-items: center;
width: 454px;
height: 454px;
}
.flex-box {
justify-content: space-around;
align-items: center;
flex-wrap: wrap;
width: 300px;
height: 250px;
background-color: #ffffff;
}
.flex-item {
width: 120px;
height: 120px;
border-radius: 16px;
}
.color-primary {
background-color: #007dff;
}
.color-warning {
background-color: #ff7500;
}
.color-success {
background-color: #41ba41;
}
```
![en-us_image_0000001431148457](figures/en-us_image_0000001431148457.png)
# list-item
**\<list-item>** is a child component of the **[\<list>](js-components-container-list.md)** component and is used to display items in a list.
> **NOTE**
>
> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
## Child Components
Supported
## Attributes
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| id | string | - | No| Unique ID of the component.|
| style | string | - | No| Style declaration of the component.|
| class | string | - | No| Style class of the component, which is used to refer to a style table.|
| ref | string | - | No| Reference information of child elements, which is registered with the parent component on **$refs**.|
## Events
| 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.|
## Styles
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| 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. - 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. - 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.|
| border-width | &lt;length&gt; | 0 | No| Shorthand attribute to set the margin for all sides.|
| 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.|
| background-color | &lt;color&gt; | - | No| Background color.|
| opacity<sup>5+</sup> | number | 1 | No| Opacity of an element. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent.|
| 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|
## Example
See **Example** in [list](js-components-container-list.md).
# list
The **\<list>** component provides a list container that presents a series of list items arranged in a column with the same width. It supports presentations of the same type of data in a multiple and coherent row style, for example, images or text.
> **NOTE**
>
> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
## Child Components
Only [\<list-item>](js-components-container-list-item.md) is supported.
## Attributes
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| id | string | - | No| Unique ID of the component.|
| style | string | - | No| Style declaration of the component.|
| class | string | - | No| Style class of the component, which is used to refer to a style table.|
| ref | string | - | No| Reference information of child elements, which is registered with the parent component on **$refs**.|
## Events
| Name| Parameter| Description|
| -------- | -------- | -------- |
| scrollend | - | Triggered when the list stops scrolling.|
| click | - | Triggered when the list is clicked. |
| longpress | - | Triggered when the list is long pressed. |
| swipe<sup>5+</sup> | [SwipeEvent](js-common-events.md) | Triggered when a user quickly swipes on the list. |
| scrolltop<sup>8+</sup> | - | Triggered when the list is scrolled to the top.|
| scrollbottom<sup>8+</sup> | - | Triggered when the list is scrolled to the bottom.|
## Styles
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| flex-direction | string | column | No| Main axis direction of the flex container. It specifies how items are placed in the flex container.<br>- **column**: Items are placed vertically from top to bottom.<br>- **row**: Items are placed horizontally from left to right.<br>For the **\<list>** component, the default value is **column**. For other components, the default value is **row**. Dynamic modification is not supported.|
| 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).|
| margin-[left\|top\|right\|bottom] | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | 0 | No| Left, top, right, and bottom margins.|
| border-width | &lt;length&gt; | 0 | No| Shorthand attribute to set the margin for all sides.|
| 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.|
| background-color | &lt;color&gt; | - | No| Background color.|
| opacity<sup>5+</sup> | number | 1 | No| Opacity of an element. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent.|
| 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. |
## Methods
| Name| Parameter| Description|
| -------- | -------- | -------- |
| scrollTo | { index: number(position) } | Scrolls the list to the position of the item at the specified index.|
## Example
```html
<!-- index.hml -->
<div class="container">
<list class="todo-wraper">
<list-item for="{{todolist}}" class="todo-item">
<text class="todo-title">{{$item.title}}</text>
<text class="todo-title">{{$item.date}}</text>
</list-item>
</list>
</div>
```
```js
// index.js
export default {
data: {
todolist: [{
title: 'Prepare for the interview',
date: '2021-12-31 10:00:00',
}, {
title: 'Watch the movie',
date: '2021-12-31 20:00:00',
}],
},
}
```
```css
/* index.css */
.container {
display: flex;
justify-content: center;
align-items: center;
left: 0px;
top: 0px;
width: 454px;
height: 454px;
}
.todo-wraper {
width: 454px;
height: 300px;
}
.todo-item {
width: 454px;
height: 80px;
flex-direction: column;
}
.todo-title {
width: 454px;
height: 40px;
text-align: center;
}
```
![list](figures/list.png)
# stack
The **\<stack>** component provides a stack container where child components are successively stacked and the latter one overwrites the previous one.
> **NOTE**
>
> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
## Child Components
Supported.
## Attributes
| Name | Type | Default Value | Mandatory | Description |
| ----- | ------ | ---- | ---- | ---------------------------------------- |
| id | string | - | No | Unique ID of the component. |
| style | string | - | No | Style declaration of the component. |
| class | string | - | No | Style class of the component, which is used to refer to a style table. |
| ref | string | - | No | Reference information of child elements, which is registered with the parent component on **$refs**.|
## Events
| 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.|
## Styles
| Name | Type | Default Value | Mandatory | Description |
| ---------------------------------- | ---------------------------------------- | ----- | ---- | ---------------------------------------- |
| width | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | - | No | Component width.<br><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><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).|
| margin-[left\|top\|right\|bottom] | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | 0 | No | Left, top, right, and bottom margins. |
| border-width | &lt;length&gt; | 0 | No | Shorthand attribute to set the margin for all sides. |
| 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. |
| background-color | &lt;color&gt; | - | No | Background color. |
| opacity<sup>5+</sup> | number | 1 | No | Opacity of an element. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent. |
| 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.|
> **NOTE**
>
> The absolute positioning does not support a percentage. Therefore, **margin** cannot be set for the child components of the **\<stack>** component.
## Example
```html
<!-- xxx.hml -->
<stack class="stack-parent">
<div class="back-child bd-radius"></div>
<div class="positioned-child bd-radius"></div>
<div class="front-child bd-radius"></div>
</stack>
```
```css
/* xxx.css */
.stack-parent {
width: 400px;
height: 400px;
background-color: #ffffff;
border-width: 1px;
border-style: solid;
}
.back-child {
width: 300px;
height: 300px;
background-color: #3f56ea;
}
.front-child {
width: 100px;
height: 100px;
background-color: #00bfc9;
}
.positioned-child {
width: 100px;
height: 100px;
left: 50px;
top: 50px;
background-color: #47cc47;
}
.bd-radius {
border-radius: 16px;
}
```
![en-us_image_0000001380789188](figures/en-us_image_0000001380789188.png)
# swiper
The **\<swiper>** component provides a container that allows users to switch among child components using swipe gestures.
> **NOTE**
>
> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
## Child Components
All child components except **\<list>** are supported.
## Attributes
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| index | number | 0 | No| Index of the child component currently displayed in the container.|
| loop | boolean | true | No| Whether to enable looping. |
| duration | number | - | No| Duration of the autoplay for child component switching.|
| vertical | boolean | false | No| Whether the swipe gesture is performed vertically. A vertical swipe uses the vertical indicator.<br>The value cannot be dynamically updated.|
| id | string | - | No| Unique ID of the component.|
| style | string | - | No| Style declaration of the component.|
| class | string | - | No| Style class of the component, which is used to refer to a style table.|
| ref | string | - | No| Reference information of child elements, which is registered with the parent component on **$refs**.|
## Events
| Name| Parameter| Description|
| -------- | -------- | -------- |
| change | { index: currentIndex } | Triggered when the index of the currently displayed component changes.|
| 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
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| 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).|
| margin-[left\|top\|right\|bottom] | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | 0 | No| Left, top, right, and bottom margins.|
| border-width | &lt;length&gt; | 0 | No| Shorthand attribute to set the margin for all sides.|
| 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.|
| background-color | &lt;color&gt; | - | No| Background color.|
| opacity<sup>5+</sup> | number | 1 | No| Opacity of an element. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent.|
| 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. |
## Example
```html
<!-- xxx.hml -->
<swiper class="container" index="{{index}}">
<div class="swiper-item primary-item">
<text>1</text>
</div>
<div class="swiper-item warning-item">
<text>2</text>
</div>
<div class="swiper-item success-item">
<text>3</text>
</div>
</swiper>
```
```css
/* xxx.css */
.container {
left: 0px;
top: 0px;
width: 454px;
height: 454px;
}
.swiper-item {
width: 454px;
height: 454px;
justify-content: center;
align-items: center;
}
.primary-item {
background-color: #007dff;
}
.warning-item {
background-color: #ff7500;
}
.success-item {
background-color: #41ba41;
}
```
```js
/* xxx.js */
export default {
data: {
index: 1
}
}
```
![swiper](figures/swiper.gif)
# File Organization
## Directory structure
The following figure shows the typical directory structure of the JavaScript module (**entry/src/main/js/module**) for an application with feature abilities (FA) using JavaScript APIs.
**Figure 1** Directory structure
![en-us_image_0000001431388581](figures/en-us_image_0000001431388581.png)
Functions of the files are as follows:
- **.hml** files describe the page layout.
- **.css** files describe the page style.
- **.js** files process the interactions between pages and users.
Functions of the folders are as follows:
- The **app.js** file manages global JS logics and application lifecycle.
- The **pages** directory stores all component pages.
- The **common** directory stores public resource files, such as media resources and **.js** files.
- The **i18n** folder stores resources in different languages, for example, UI strings and image paths.
> **NOTE**
>
> - The **i18n** folder is a reserved one and cannot be renamed.
>
>
> - The folders marked as optional in the directory structure can be created as needed after you create the project in DevEco Studio.
## File Access Rules
Application resources can be accessed via an absolute or relative path. In this development framework, an absolute path starts with a slash (/), and a relative path starts with **./** or **../**. The rules are as follows:
- To reference a code file, use a relative path, for example, **../common/utils.js**.
- To reference a resource file, use an absolute path, for example: **/common/xxx.png**.
- Store code files and resource files in the **common** directory and access the files in a required fashion.
- In a **.css** file, use the **url()** function to create a URL, for example, **url(/common/xxx.png)**.
> **NOTE**
>
> When code file A needs to reference code file B:
>
> - If code files A and B are in the same directory, you can use either a relative or absolute path in code file B to reference resource files.
>
> - If code files A and B are in different directories, you must use an absolute path in code file B to reference resource files, because the directory of code file B changes during Webpack packaging.
>
## Media File Formats
**Table 1** Supported image formats
| Format | Supported Version | File Name Extension|
| ---- | ------------------------ | ------- |
| BMP | API version 4+ | .bmp |
| JPEG | API version 4+ | .jpg |
| PNG | API version 4+ | .png |
## Storage Directory
Since API version 5, the [\<image>](js-components-basic-image.md) component supports access to images in the private directory of an application.
| Directory Type | Prefix | Access Visibility | Description |
| ------ | --------------- | ------ | --------------------------- |
| Private directory of the application| internal://app/ | Current application only| The directory is deleted when the application is uninstalled. Access to the parent directory using **../** is prohibited.|
# app.js
## Application Lifecycle<sup>4+</sup>
You can implement lifecycle logic specific to your application in the **app.js** file. Available application lifecycle functions are as follows:
- **onCreate()**: called when an application is created
- **onDestory()**: called when an application is destroyed
In the following example, logs are printed only in the lifecycle functions.
```js
// app.js
export default {
onCreate() {
console.info('Application onCreate');
},
onDestroy() {
console.info('Application onDestroy');
},
}
```
# "js" Tag
The "js" tag contains the instance name and page route information.
| Tag | Type | Default Value | Mandatory | Description |
| ----- | ------ | ------- | ---- | ----------------------------- |
| name | string | default | Yes | Name of the JavaScript instance. |
| pages | Array | - | Yes | Route information. For details, see ["pages"](#pages).|
> **NOTE**
>
> The "name" and "pages" tags are configured in the "js" tag of the **config.json** file.
## pages
The **"pages"** defines the route information of each page. Each page consists of the page path and page name. The following is an example:
```
{
...
"pages": [
"pages/index/index",
"pages/detail/detail"
]
...
}
```
> **NOTE**
>
>
> - The application home page is fixed to **pages/index/index**.
>
> - The page name should not be a component name, for example, **text.hml** or **button.hml**.
## Example
```
{
"app": {
"bundleName": "com.example.player",
"version": {
"code": 1,
"name": "1.0"
},
"vendor": "example"
}
"module": {
...
"js": [
{
"name": "default",
"pages": [
"pages/index/index",
"pages/detail/detail"
]
}
],
"abilities": [
{
...
}
]
}
}
```
# CSS
Cascading Style Sheets (CSS) is a language used to describe the HML page structure. All HML components have default styles. You can customize styles for these components using CSS to design various pages.
## Style Import
CSS files can be imported using the **\@import** statement. This facilitates module management and code reuse.
## Style Declaration
The **.css** file with the same name as the **.hml** file in each page directory describes the styles of components on the HML page, determining how the components will be displayed.
1. Internal style: The **style** and **class** attributes can be used to specify the component style. Sample code:
```html
<!-- index.hml -->
<div class="container">
<text style="color: red">Hello World</text>
</div>
```
```css
/* index.css */
.container {
justify-content: center;
}
```
2. External style files: You need to import the files. For example, create a **style.css** file in the **common** directory and import the file at the beginning of **index.css**.
```css
/* style.css */
.title {
font-size: 50px;
}
```
```css
/* index.css */
@import '../../common/style.css';
.container {
justify-content: center;
}
```
## Selectors
A CSS selector is used to select elements for which styles need to be added to. The following table lists the supported selectors.
| Selector | Example | Description |
| ------ | --------------------- | ------------------------------------- |
| .class | .container | Selects all components whose **class** is **container**. |
| \#id | \#titleId | Selects all components whose **id** is **titleId**. |
| , | .title, .content | Selects all components whose **class** is **title** or **content**.|
Example:
```html
<!-- Pagelayoutexample.hml -->
<div id="containerId" class="container">
<text id="titleId" class="title">Title</text>
<div class="content">
<text id="contentId">Content</text>
</div>
</div>
```
```css
/* Page style xxx.css */
/* Set the style for the components whose class is title. */
.title {
font-size: 30px;
}
/* Set the style for the components whose id is contentId. */
#contentId {
font-size: 20px;
}
/* Set padding for all components of the title or content class to 5 px. */
.title, .content {
padding: 5px;
}
```
## Pseudo-classes
A CSS pseudo-class is a keyword added to a selector that specifies a special state of the selected elements.
| Name | Available Components | Description |
| -------- | ----------------------------------- | ---------------------------------------- |
| :active | <br>input[type="button"] | Selects the element activated by a user, for example, a pressed button. Only the **background-color** and **background-image** attributes can be set for the pseudo-class selector on lite wearables.|
| :checked | input[type="checkbox", type="radio"]| Selects the element whose **checked** attribute is **true**. Only the **background-color** and **background-image** attributes can be set for the pseudo-class selector on lite wearables.|
The following is an example for you to use the **:active** pseudo-class to control the style when a user presses the button.
```html
<!-- index.hml -->
<div class="container">
<input type="button" class="button" value="Button"></input>
</div>
```
```css
/* index.css */
.button:active {
background-color: #888888;/* After the button is activated, the background color is changed to #888888. */
}
```
## Precompiled Styles
Precompilation is a program that uses specific syntax to generate CSS files. It provides variables and calculation, helping you define component styles more conveniently. Currently, Less, Sass, and Scss are supported. To use precompiled styles, change the suffix of the original **.css** file. For example, change **index.css** to **index.less**, **index.sass**, or **index.scss**.
- The following **index.less** file is changed from **index.css**.
```css
/* index.less */
/* Define a variable. */
@colorBackground: #000000;
.container {
background-color: @colorBackground; /* Use the variable defined in the .less file. */
}
```
- Reference a precompiled style file. For example, if the **style.scss** file is located in the **common** directory, change the original **index.css** file to **index.scss** and import **style.scss**.
```css
/* style.scss */
/* Define a variable. */
$colorBackground: #000000;
```
Reference the precompiled style file in **index.scss**:
```css
/* index.scss */
/* Import style.scss. */
@import '../../common/style.scss';
.container {
background-color: $colorBackground; /* Use the variable defined in style.scss. */
}
```
> **NOTE**
>
> Place precompiled style files in the **common** directory.
# HML
The OpenHarmony Markup Language (HML) is an HTML-like language that allows you to build pages based on components and events. Pages built using HML have advanced capabilities such as data binding, event binding, loop rendering, and conditional rendering.
## HML Page Structure
```html
<!-- xxx.hml -->
<div class="item-container">
<text class="item-title">Image Show</text>
<div class="item-content">
<image src="/common/xxx.png" class="image"></image>
</div>
</div>
```
## Data Binding
```html
<!-- xxx.hml -->
<div onclick="changeText">
<text> {{content[1]}} </text>
</div>
```
```js
// xxx.js
export default {
data: {
content: ['Hello World!', 'Welcome to my world!']
},
changeText: function() {
this.content.splice(1, 1, this.content[0]);
}
}
```
> **NOTE**
> - To make the array data modification take effect, use the **splice** method to change array items.
>
> - ECMAScript 6.0 syntax is not supported in HML.
## Event Binding
The callback bound to an event receives an event object parameter, which can be used to obtain the event information.
```html
<!-- xxx.hml -->
<div>
<!-- Bind an event using @. -->
<div @click="clickfunc"></div>
<!-- Bind an event using on. -->
<div onclick="clickfunc"></div>
<!-- Bind an event using on.<sup>5+</sup> This statement is not recommended. -->
<div onclick="clickfunc"></div>
<!-- Bind an event callback for event bubbling.<sup>5+</sup>-->
<div on:click.bubble="clickfunc"></div>
<!-- on:{event} is equivalent to on:{event}.bubble.<sup>5+</sup> -->
<div on:click="clickfunc"></div>
<!-- Bind an event callback, but stop the event from bubbling upwards.<sup>5+</sup> -->
<div grab:click.bubble="clickfunc"></div>
<!-- grab:{event} is equivalent to grab:{event}.bubble.<sup>5+</sup> -->
<div grab:click="clickfunc"></div>
</div>
```
```js
// xxx.js
export default {
data: {
obj: '',
},
clickfunc: function(e) {
this.obj = 'Hello World';
console.log(e);
},
}
```
> **NOTE**
>
> Event bubbling is supported since API version 5. After you upgrade the SDK and run an existing JavaScript application, events bound using a traditional statement (such as **onclick**) will not bubble. However, if you use the new SDK to repack the JavaScript application, such events will bubble. To avoid service logic errors, replace the traditional statement with one supported by the new SDK. For example, replace **onclick** with **grab:click**.
**Example:**
```html
<!-- xxx.hml -->
<div class="container">
<text class="title">{{count}}</text>
<div class="box">
<input type="button" class="btn" value="increase" onclick="increase" />
<input type="button" class="btn" value="decrease" @click="decrease" />
<!-- Pass additional parameters. -->
<input type="button" class="btn" value="double" @click="multiply(2)" />
<input type="button" class="btn" value="decuple" @click="multiply(10)" />
<input type="button" class="btn" value="square" @click="multiply(count)" />
</div>
</div>
```
```js
// xxx.js
export default {
data: {
count: 0
},
increase() {
this.count++;
},
decrease() {
this.count--;
},
multiply(multiplier) {
this.count = multiplier * this.count;
}
};
```
```css
/* xxx.css */
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
left: 0px;
top: 0px;
width: 454px;
height: 454px;
}
.title {
font-size: 30px;
text-align: center;
width: 200px;
height: 100px;
}
.box {
width: 454px;
height: 200px;
justify-content: center;
align-items: center;
flex-wrap: wrap;
}
.btn {
width: 200px;
border-radius: 0;
margin-top: 10px;
margin-left: 10px;
}
```
## Loop Rendering
```html
<!-- xxx.hml -->
<div class="array-container">
<!-- div loop rendering -->
<!-- By default, $item indicates the element in the array, and $idx indicates the index of the element in the array. -->
<div for="{{array}}" tid="id" onclick="changeText">
<text>{{$idx}}.{{$item.name}}</text>
</div>
<!-- Define the name for an element variable. -->
<div for="{{value in array}}" tid="id" onclick="changeText">
<text>{{$idx}}.{{value.name}}</text>
</div>
<!-- Define an element variable and its index name. -->
<div for="{{(index, value) in array}}" tid="id" onclick="changeText">
<text>{{index}}.{{value.name}}</text>
</div>
</div>
```
```js
// xxx.js
export default {
data: {
array: [
{id: 1, name: 'jack', age: 18},
{id: 2, name: 'tony', age: 18},
],
},
changeText: function() {
if (this.array[1].name === "tony"){
this.array.splice(1, 1, {id:2, name: 'Isabella', age: 18});
} else {
this.array.splice(2, 1, {id:3, name: 'Bary', age: 18});
}
},
}
```
The **tid** attribute accelerates the **for** loop and improves the re-rendering efficiency when data in a loop changes. The **tid** attribute specifies the unique ID of each element in the array. If it is not specified, the index of each element in the array is used as the ID. For example, **tid="id"** indicates that the **id** attribute of each element is its unique ID. The **for** loop supports the following statements:
- for="array": **array** is an array object, whose element variable is **$item** by default.
- for="v in array": **v** is a custom element variable, whose index is **$idx** by default.
- for="(i, v) in array": **i** indicates the element index, and **v** indicates the element variable. All elements of the array object will be looped through.
> **NOTE**
>
> - Each element in the array must have the data attribute specified by **tid**. Otherwise, an exception may occur.
>
> - The attribute specified by **tid** in the array must be unique. Otherwise, performance loss occurs. In the above example, only **id** and **name** can be used as **tid** because they are unique fields.
>
> - The **tid** field does not support expressions.
## Conditional Rendering
There are two ways to implement conditional rendering: **if-elif-else** or **show**. In **if-elif-else**, when the **if** statement evaluates to **false**, the component is not built in the VDOM and is not rendered. For **show**, when show is **false**, the component is not rendered but is built in the VDOM. In addition, the **if-elif-else** statements must be used in sibling nodes. Otherwise, the compilation fails. The following example uses both ways to implement conditional rendering:
```html
<!-- xxx.hml -->
<div class="container">
<button class="btn" type="capsule" value="toggleShow" onclick="toggleShow"></button>
<button class="btn" type="capsule" value="toggleDisplay" onclick="toggleDisplay"></button>
<text if="{{show}}"> Hello-One </text>
<text elif="{{display}}"> Hello-Two </text>
<text else> Hello-World </text>
</div>
```
```css
/* xxx.css */
.container{
flex-direction: column;
align-items: center;
}
.btn{
width: 280px;
font-size: 26px;
margin: 10px 0;
}
```
```js
// xxx.js
export default {
data: {
show: false,
display: true,
},
toggleShow: function() {
this.show = !this.show;
},
toggleDisplay: function() {
this.display = !this.display;
}
}
```
In the optimized rendering (**show**), if **show** is **true**, the node is rendered properly; if it is **false**, the display style will be **none**.
```html
<!-- xxx.hml -->
<div class="container">
<button class="btn" type="capsule" value="toggle" onclick="toggle"></button>
<text show="{{visible}}" > Hello World </text>
</div>
```
```css
/* xxx.css */
.container{
flex-direction: column;
align-items: center;
}
.btn{
width: 280px;
font-size: 26px;
margin: 10px 0;
}
```
```js
// xxx.js
export default {
data: {
visible: false,
},
toggle: function() {
this.visible = !this.visible;
},
}
```
> **NOTE**
>
> Do not use **for** and **if** attributes at the same time in an element.
# JavaScript
You can use a **.js** file in the ECMAScript compliant JavaScript language to define the service logic of an HML page. With dynamic typing, JavaScript can make your application more expressive with a flexible design. The following describes the JavaScript compilation and running.
## Syntax
The ECMAScript 6.0 syntax is supported. Lite wearables only support the following ECMAScript 6.0 syntax:
1. let/const
2. arrow functions
3. class
4. default value
5. destructuring assignment
6. destructuring binding pattern
7. enhanced object initializer
8. for-of
9. rest parameter
10. template strings
- Module declaration
Import functionality modules.
```
import router from '@system.router';
```
- Code reference
Import JavaScript code.
```
import utils from '../../common/utils.js';
```
## Objects
- Page objects
| Attribute | Type | Description |
| ----- | --------------- | ---------------------------------------- |
| data | Object/Function | Data model of the page. If the attribute is of the function type, the return value must be of the object type. The name cannot start with a dollar sign ($) or underscore (_). Do not use reserved words (**for**, **if**, **show**, and **tid**).<br>|
| $refs | Object | DOM elements or child component instances that have registered the **ref** attribute. For an example, see [Obtaining a DOM Element](#obtaining-a-dom-element). |
## Obtaining a DOM Element
Use **$refs** to obtain a DOM element.
```html
<!-- index.hml -->
<div class="container">
<image-animator class="image-player" ref="animator" images="{{images}}" duration="1s" onclick="handleClick"></image-animator>
</div>
```
```js
// index.js
export default {
data: {
images: [
{ src: '/common/frame1.png' },
{ src: '/common/frame2.png' },
{ src: '/common/frame3.png' },
],
},
handleClick() {
const animator = this.$refs.animator; // Obtain the DOM element whose $refs attribute is animator.
const state = animator.getState();
if (state === 'paused') {
animator.resume();
} else if (state === 'stopped') {
animator.start();
} else {
animator.pause();
}
},
};
```
## Lifecycle APIs
- Page lifecycle APIs
| Name | Type | Parameter | Return Value | Description | Triggered When |
| --------- | -------- | ---- | ---- | ------ | ------------------- |
| onInit | Function | N/A | N/A | Listens for page initialization. | Page initialization is complete. This API is called only once in the page lifecycle.|
| onReady | Function | N/A | N/A | Listens for page creation.| A page is created. This API is called only once in the page lifecycle. |
| onShow | Function | N/A | N/A | Listens for page display. | The page is displayed. |
| onHide | Function | N/A | N/A | Listens for page disappearance. | The page disappears. |
| onDestroy | Function | N/A | N/A | Listens for page destruction. | The page is destroyed. |
The lifecycle APIs of page A are called in the following sequence:
- Open page A: onInit() -> onReady() -> onShow()
- Open page B on page A: onHide() -> onDestroy()
- Go back to page A from page B: onInit() -> onReady() -> onShow()
- Exit page A: onHide() -> onDestroy()
- Hide page A: onHide()
- Show background page A on the foreground: onShow()
- Application lifecycle APIs
| Name | Type | Parameter | Return Value | Description | Triggered When |
| --------- | -------- | ---- | ---- | ---- | --------- |
| onCreate | Function | N/A | N/A | Listens for application creation.| The application is created.|
| onDestroy | Function | N/A | N/A | Listens for application exit.| The application exits.|
......@@ -23,9 +23,9 @@ Since API version 9, this API is supported in ArkTS widgets.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| value | number | Yes| Current value of the chart, that is, the position to which the pointer points in the chart. It is used as the initial value of the chart when the component is created.|
| value | number | Yes| Current value of the chart, that is, the position to which the pointer points in the chart. It is used as the initial value of the chart when the component is created.<br>**NOTE**<br>If the value is not within the range defined by the **min** and **max** parameters, the value of **min** is used.|
| min | number | No| Minimum value of the current data segment.<br>Default value: **0**|
| max | number | No| Maximum value of the current data segment.<br>Default value: **100**|
| max | number | No| Maximum value of the current data segment.<br>Default value: **100**<br>**NOTE**<br>If the value of **max** is less than that of **min**, the default values **0** and **100** are used.<br>The values of **max** and **min** can be negative numbers.|
## Attributes
......@@ -36,8 +36,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| value | number | Value of the chart. It can be dynamically changed.<br>Default value: **0**<br>Since API version 9, this API is supported in ArkTS widgets.|
| startAngle | number | Start angle of the chart. The value **0** indicates 0 degrees, and a positive value indicates the clockwise direction.<br>Default value: **0**<br>Since API version 9, this API is supported in ArkTS widgets.|
| endAngle | number | End angle of the chart. The value **0** indicates 0 degrees, and a positive value indicates the clockwise direction.<br>Default value: **360**<br>Since API version 9, this API is supported in ArkTS widgets.|
| colors | Array&lt;[ColorStop](#colorstop)&gt; | Colors of the chart. Colors can be set for individual segments.<br>Since API version 9, this API is supported in ArkTS widgets.|
| strokeWidth | Length | Stroke width of the chart.<br>Since API version 9, this API is supported in ArkTS widgets.|
| colors | Array&lt;[ColorStop](#colorstop)&gt; | Colors of the chart. Colors can be set for individual segments.<br>Default value: **Color.Black**<br>Since API version 9, this API is supported in ArkTS widgets.|
| strokeWidth | Length | Stroke width of the chart.<br>Default value: **4**<br>Unit: vp<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>A value less than 0 evaluates to the default value.<br>The value cannot be in percentage.|
## ColorStop
......@@ -47,7 +47,7 @@ Since API version 9, this API is supported in ArkTS widgets.
| Name | Type | Description |
| --------- | -------------------- | ------------------------------------------------------------ |
| ColorStop | [[ResourceColor](ts-types.md#resourcecolor), number] | Type of the gradient stop. The first parameter indicates the color value. If it is set to a non-color value, the black color is used. The second parameter indicates the color weight. If it is set to a negative number or a non-numeric value, the color weight is 0, which means that the color is not displayed.|
| ColorStop | [[ResourceColor](ts-types.md#resourcecolor), number] | Type of the gradient stop. The first parameter indicates the color value. If it is set to a non-color value, the black color is used. The second parameter indicates the color weight. If it is set to a negative number or a non-numeric value, the color weight is 0.|
## Example
......
......@@ -10,7 +10,7 @@ Use **RenderingContext** to draw rectangles, text, images, and other objects on
## APIs
CanvasRenderingContext2D(setting: RenderingContextSetting)
CanvasRenderingContext2D(settings?: RenderingContextSettings)
Since API version 9, this API is supported in ArkTS widgets.
......@@ -18,7 +18,7 @@ Since API version 9, this API is supported in ArkTS widgets.
| Name | Type | Mandatory | Description |
| ------- | ---------------------------------------- | ---- | ---------------------------------------- |
| setting | [RenderingContextSettings](#renderingcontextsettings) | Yes | See [RenderingContextSettings](#renderingcontextsettings).|
| settings | [RenderingContextSettings](#renderingcontextsettings) | No | See [RenderingContextSettings](#renderingcontextsettings).|
### RenderingContextSettings
......@@ -57,6 +57,8 @@ Since API version 9, this API is supported in ArkTS widgets.
| [shadowOffsetX](#shadowoffsetx) | number | X-axis shadow offset relative to the original object.<br>Since API version 9, this API is supported in ArkTS widgets. |
| [shadowOffsetY](#shadowoffsety) | number | Y-axis shadow offset relative to the original object.<br>Since API version 9, this API is supported in ArkTS widgets. |
| [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | Whether to adjust the image smoothness during image drawing. The value **true** means to enable this feature, and **false** means the opposite.<br>Default value: **true**<br>Since API version 9, this API is supported in ArkTS widgets. |
| [height](#height) | number | Component height.<br>Unit: vp<br>Since API version 9, this API is supported in ArkTS widgets.|
| [width](#width) | number | Component width.<br>Unit: vp<br>Since API version 9, this API is supported in ArkTS widgets.|
> **NOTE**
>
......@@ -652,6 +654,68 @@ struct ImageSmoothingEnabled {
![en-us_image_0000001211898472](figures/en-us_image_0000001211898472.png)
### height
```ts
// xxx.ets
@Entry
@Component
struct HeightExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width(300)
.height(300)
.backgroundColor('#ffff00')
.onReady(() => {
let h = this.context.height
let w = this.context.width
this.context.fillRect(0, 0, 300, h/2)
})
}
.width('100%')
.height('100%')
}
}
```
![en-us_image_canvas_height](figures/en-us_image_canvas_height.png)
### width
```ts
// xxx.ets
@Entry
@Component
struct WidthExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width(300)
.height(300)
.backgroundColor('#ffff00')
.onReady(() => {
let h = this.context.height
let w = this.context.width
this.context.fillRect(0, 0, w/2, 300)
})
}
.width('100%')
.height('100%')
}
}
```
![en-us_image_canvas_width](figures/en-us_image_canvas_width.png)
## Methods
......
......@@ -44,7 +44,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| showSideBar | boolean | Whether to display the sidebar.<br>Default value: **true** |
| controlButton | [ButtonStyle](#buttonstyle) | Attributes of the sidebar control button.|
| showControlButton | boolean | Whether to display the sidebar control button.<br>Default value: **true**|
| sideBarWidth | number \| Length<sup>9+</sup> | Width of the sidebar.<br>Default value: **200**<br>Unit: vp<br>**NOTE**<br>A value less than 0 evaluates to the default value.<br>The value must comply with the width constraints. If it is not within the valid range, the value closest to the set one is used.<br>When set, the width of the sidebar takes precedence over that of the sidebar child components. If it is not set, however, the width of the sidebar child component takes precedence.|
| sideBarWidth | number \| Length<sup>9+</sup> | Width of the sidebar.<br>Default value: **200**<br>Unit: vp<br>**NOTE**<br>A value less than 0 evaluates to the default value.<br>The value must comply with the width constraints. If it is not within the valid range, the value closest to the set one is used.<br>The width of the sidebar, whether it is specified or kept at the default, takes precedence over that of the sidebar child components.|
| minSideBarWidth | number \| Length<sup>9+</sup> | Minimum width of the sidebar.<br>Default value: **200**, in vp<br>**NOTE**<br>A value less than 0 evaluates to the default value.<br>The value cannot exceed the width of the sidebar container itself. Otherwise, the width of the sidebar container itself is used.<br>When set, the minimum width of the sidebar takes precedence over that of the sidebar child components. If it is not set, however, the minimum width of the sidebar child component takes precedence.|
| maxSideBarWidth | number \| Length<sup>9+</sup> | Maximum width of the sidebar.<br>Default value: **280**, in vp<br>**NOTE**<br>A value less than 0 evaluates to the default value.<br>The value cannot exceed the width of the sidebar container itself. Otherwise, the width of the sidebar container itself is used.<br>When set, the maximum width of the sidebar takes precedence over that of the sidebar child components. If it is not set, however, the maximum width of the sidebar child component takes precedence.|
| autoHide<sup>9+</sup> | boolean | Whether to automatically hide the sidebar when it is dragged to be smaller than the minimum width.<br>Default value: **true**<br>**NOTE**<br>The value is subject to the **minSideBarWidth** attribute method. If it is not set in **minSideBarWidth**, the default value is used.<br>Whether the sidebar should be hidden is determined when it is being dragged. When its width is less than the minimum width, the damping effect is required to trigger hiding (a distance out of range).|
......
......@@ -45,7 +45,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| cachedCount<sup>8+</sup> | number | Number of child components to be cached.<br>Default value: **1**<br>**NOTE**<br>**cachedCount** has caching optimized. You are advised not to use it together with [LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md).|
| disableSwipe<sup>8+</sup> | boolean | Whether to disable the swipe feature.<br>Default value: **false** |
| curve<sup>8+</sup> | [Curve](ts-appendix-enums.md#curve) \| string | Animation curve. The ease-in/ease-out curve is used by default. For details about common curves, see [Curve](ts-appendix-enums.md#curve). You can also create custom curves (interpolation curve objects) by using the API provided by the [interpolation calculation](../apis/js-apis-curve.md) module.<br>Default value: **Curve.Linear**|
| indicatorStyle<sup>8+</sup> | {<br>left?: [Length](ts-types.md#length),<br>top?: [Length](ts-types.md#length),<br>right?: [Length](ts-types.md#length),<br>bottom?: [Length](ts-types.md#length),<br>size?: [Length](ts-types.md#length),<br>mask?: boolean,<br>color?: [ResourceColor](ts-types.md),<br>selectedColor?: [ResourceColor](ts-types.md)<br>} | Style of the navigation point indicator.<br>\- **left**: distance between the navigation point indicator and the left edge of the **\<Swiper>** component.<br>\- **top**: distance between the navigation point indicator and the top edge of the **\<Swiper>** component.<br>\- **right**: distance between the navigation point indicator and the right edge of the **\<Swiper>** component.<br>\- **bottom**: distance between the navigation point indicator and the bottom edge of the **\<Swiper>** component.<br>\- **size**: diameter of the navigation point indicator.<br>\- **mask**: whether to enable the mask for the navigation point indicator.<br>\- **color**: color of the navigation point indicator.<br>\- **selectedColor**: color of the selected navigation dot.|
| indicatorStyle<sup>8+</sup> | {<br>left?: [Length](ts-types.md#length),<br>top?: [Length](ts-types.md#length),<br>right?: [Length](ts-types.md#length),<br>bottom?: [Length](ts-types.md#length),<br>size?: [Length](ts-types.md#length),<br>mask?: boolean,<br>color?: [ResourceColor](ts-types.md),<br>selectedColor?: [ResourceColor](ts-types.md)<br>} | Style of the navigation point indicator.<br>\- **left**: distance between the navigation point indicator and the left edge of the **\<Swiper>** component.<br>\- **top**: distance between the navigation point indicator and the top edge of the **\<Swiper>** component.<br>\- **right**: distance between the navigation point indicator and the right edge of the **\<Swiper>** component.<br>\- **bottom**: distance between the navigation point indicator and the bottom edge of the **\<Swiper>** component.<br>\- **size**: diameter of the navigation point indicator. The value cannot be in percentage. Default value: **6vp**<br>\- **mask**: whether to enable the mask for the navigation point indicator.<br>\- **color**: color of the navigation point indicator.<br>\- **selectedColor**: color of the selected navigation dot.|
| displayCount<sup>8+</sup> | number \| string | Number of elements to display per page.<br>Default value: **1**<br>**NOTE**<br>If the value is of the string type, it can only be **'auto'**, whose display effect is the same as that of **SwiperDisplayMode.AutoLinear**.<br>If the value is of the number type, child components stretch (shrink) on the main axis after the swiper width [deducting the result of itemSpace x (displayCount - 1)] is evenly distributed among them on the main axis.|
| effectMode<sup>8+</sup> | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Swipe effect. For details, see **EdgeEffect**.<br>Default value: **EdgeEffect.Spring**<br>**NOTE**<br>The spring effect does not take effect when the controller API is called.|
......
......@@ -10,7 +10,7 @@ Use **OffscreenCanvasRenderingContext2D** to draw rectangles, images, and text o
## APIs
OffscreenCanvasRenderingContext2D(width: number, height: number, setting: RenderingContextSettings)
OffscreenCanvasRenderingContext2D(width: number, height: number, settings?: RenderingContextSettings)
Since API version 9, this API is supported in ArkTS widgets.
......@@ -20,7 +20,7 @@ Since API version 9, this API is supported in ArkTS widgets.
| ------- | ------------------------------------------------------------ | ---- | ------------------------------------ |
| width | number | Yes | Width of the offscreen canvas. |
| height | number | Yes | Height of the offscreen canvas. |
| setting | [RenderingContextSettings](ts-canvasrenderingcontext2d.md#renderingcontextsettings) | Yes | See RenderingContextSettings.|
| settings | [RenderingContextSettings](ts-canvasrenderingcontext2d.md#renderingcontextsettings) | No | See RenderingContextSettings.|
## Attributes
......
......@@ -14,6 +14,7 @@
| flexGrow | number | Percentage of the parent container's remaining space that is allocated to the component.<br>Default value: **0**<br>Since API version 9, this API is supported in ArkTS widgets.|
| flexShrink | number | Percentage of the parent container's shrink size that is allocated to the component.<br>When the parent container is **\<Row>** or **\<Column>**, the default value is **0**.<br> When the parent container is **\<Flex>**, the default value is **1**.<br>Since API version 9, this API is supported in ArkTS widgets.|
| alignSelf | [ItemAlign](ts-appendix-enums.md#itemalign) | Alignment mode of the child components along the cross axis of the parent container. The setting overwrites the **alignItems** setting of the parent container.<br>Default value: **ItemAlign.Auto**<br>Since API version 9, this API is supported in ArkTS widgets.|
| layoutWeight | number \| string | Weight of the component during layout. When the container size is determined, the container space is allocated along the main axis among the component and sibling components based on the layout weight, and the component size setting is ignored.<br>Default value: **0**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute is valid only for the **\<Row>**, **\<Column>**, and **\<Flex>** layouts.<br>The value can be a number greater than or equal to 0 or a string that can be converted to a number.|
## Example
......
......@@ -30,7 +30,7 @@ You can bind a popup to a component, specifying its content, interaction logic,
| Name | Type | Mandatory | Description |
| ---------------------------- | ---------------------------------------- | ---- | ---------------------------------------- |
| builder | [CustomBuilder](ts-types.md#custombuilder8) | Yes | Popup builder. |
| builder | [CustomBuilder](ts-types.md#custombuilder8) | Yes | Popup builder.<br>**NOTE**<br>The **popup** attribute is a universal attribute. A custom popup does not support display of another popup. The **position** attribute cannot be used for the first-layer container under the builder. If the **position** attribute is used, the popup will not be displayed. |
| placement | [Placement](ts-appendix-enums.md#placement8) | No | Preferred position of the popup. If the set position is insufficient for holding the popup, it will be automatically adjusted.<br>Default value: **Placement.Bottom**|
| popupColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the popup. |
| enableArrow | boolean | No | Whether to display an arrow.<br>Since API version 9, if the position set for the popup is not large enough, the arrow will not be displayed. For example, if **placement** is set to **Left**, but the popup height (80 vp) is less than the sum of the arrow width (32 vp) and diameter of popup rounded corner (48 vp), the arrow will not be displayed.<br>Default value: **true**|
......@@ -100,7 +100,7 @@ struct PopupExample {
.bindPopup(this.customPopup, {
builder: this.popupBuilder,
placement: Placement.Top,
maskColor: '0x33000000',
mask: {color:'0x33000000'},
popupColor: Color.Yellow,
enableArrow: true,
showInSubWindow: false,
......
......@@ -18,7 +18,6 @@ The size attributes set the width, height, and margin of a component.
| padding | [Padding](ts-types.md#padding) \| [Length](ts-types.md#length) | Padding of the component.<br>When the parameter is of the **Length** type, the four paddings take effect.<br>Default value: **0**<br>When **padding** is set to a percentage, the width of the parent container is used as the basic value.<br>Since API version 9, this API is supported in ArkTS widgets.|
| margin | [Margin](ts-types.md#margin) \| [Length](ts-types.md#length) | Margin of the component.<br>When the parameter is of the **Length** type, the four margins take effect.<br>Default value: **0**<br>When **margin** is set to a percentage, the width of the parent container is used as the basic value.<br>Since API version 9, this API is supported in ArkTS widgets.|
| constraintSize | {<br>minWidth?: [Length](ts-types.md#length),<br>maxWidth?: [Length](ts-types.md#length),<br>minHeight?: [Length](ts-types.md#length),<br>maxHeight?: [Length](ts-types.md#length)<br>} | Constraint size of the component, which is used to limit the size range during component layout. **constraintSize** takes precedence over **width** and **height**. If the value of **minWidth** is greater than that of **maxWidth**, only the value of **minWidth** takes effect. The same rule applies to **minHeight** and **maxHeight**.<br>Default value:<br>{<br>minWidth: 0,<br>maxWidth: Infinity,<br>minHeight: 0,<br>maxHeight: Infinity<br>}<br>Since API version 9, this API is supported in ArkTS widgets.|
| layoutWeight | number \| string | Weight of the component during layout. When the container size is determined, the container space is allocated along the main axis among the component and sibling components based on the layout weight, and the component size setting is ignored.<br>Default value: **0**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute is valid only for the **\<Row>**, **\<Column>**, and **\<Flex>** layouts.<br>The value can be a number greater than or equal to 0 or a string that can be converted to a number.|
## Example
......
......@@ -4,11 +4,29 @@
>
> This topic describes only module-specific error codes. For details about universal error codes, see [Universal Error Codes](errorcode-universal.md).
## 14800000 Internal Error
**Error Message**
Inner error.
**Description**
An error occurs at the underlying database.
**Possible Causes**
Invalid SQL statement is passed in.
**Solution**
Determine the cause of the error based on the log information.
## 14800010 Invalid RDB Name
**Error Message**
Invalid database name.
Failed to open or delete database by invalid database path.
**Description**
......@@ -16,17 +34,17 @@ The RDB store name is invalid.
**Possible Causes**
The RDB store name is empty or exceeds 1024 bytes.
The RDB store path is invalid.
**Solution**
Check that the RDB store name is not empty and does not exceed 1024 bytes.
Check the RDB store path.
## 14800011 Database File Corrupted
**Error Message**
Database corrupted.
Failed to open database by database corrupted.
**Description**
......
......@@ -21,7 +21,8 @@ When the **compress** API is called, the file to compress does not exist. When t
**Solution**
1. Make sure the source file exists.
2. Make sure the path of the source file exists and the path is the correct sandbox path.
2. Ensure that the source file is in ZIP format.
3. Make sure the path of the source file exists and the path is the correct sandbox path.
## 900002 Invalid Destination File
......
......@@ -8,33 +8,32 @@
- [Multi-Language Capability](js-service-widget-multiple-languages.md)
- [Version Compatibility Adaptation](js-service-widget-version-compatibility.md)
- [Theme Configuration](js-service-widget-theme.md)
- Components
- Universal
- [Universal Attributes](js-service-widget-common-attributes.md)
- [Universal Styles](js-service-widget-common-styles.md)
- [Universal Events](js-service-widget-common-events.md)
- [Gradient Styles](js-service-widget-common-gradient.md)
- [Media Query](js-service-widget-common-mediaquery.md)
- [Custom Font Styles](js-service-widget-common-customizing-font.md)
- [Accessibility](js-service-widget-common-accessibility.md)
- [Atomic Layout](js-service-widget-common-atomic-layout.md)
- Container Components
- [badge](js-service-widget-container-badge.md)
- [div](js-service-widget-container-div.md)
- [list](js-service-widget-container-list.md)
- [list-item](js-service-widget-container-list-item.md)
- [stack](js-service-widget-container-stack.md)
- [swiper](js-service-widget-container-swiper.md)
- Basic Components
- [button](js-service-widget-basic-button.md)
- [calendar](js-service-widget-basic-calendar.md)
- [chart](js-service-widget-basic-chart.md)
- [clock](js-service-widget-basic-clock.md)
- [divider](js-service-widget-basic-divider.md)
- [image](js-service-widget-basic-image.md)
- [input](js-service-widget-basic-input.md)
- [progress](js-service-widget-basic-progress.md)
- [span](js-service-widget-basic-span.md)
- [text](js-service-widget-basic-text.md)
- Universal Component Information
- [Universal Attributes](js-service-widget-common-attributes.md)
- [Universal Styles](js-service-widget-common-styles.md)
- [Universal Events](js-service-widget-common-events.md)
- [Gradient Styles](js-service-widget-common-gradient.md)
- [Media Query](js-service-widget-common-mediaquery.md)
- [Custom Font Styles](js-service-widget-common-customizing-font.md)
- [Accessibility](js-service-widget-common-accessibility.md)
- [Atomic Layout](js-service-widget-common-atomic-layout.md)
- Container Components
- [badge](js-service-widget-container-badge.md)
- [div](js-service-widget-container-div.md)
- [list](js-service-widget-container-list.md)
- [list-item](js-service-widget-container-list-item.md)
- [stack](js-service-widget-container-stack.md)
- [swiper](js-service-widget-container-swiper.md)
- Basic Components
- [button](js-service-widget-basic-button.md)
- [calendar](js-service-widget-basic-calendar.md)
- [chart](js-service-widget-basic-chart.md)
- [clock](js-service-widget-basic-clock.md)
- [divider](js-service-widget-basic-divider.md)
- [image](js-service-widget-basic-image.md)
- [input](js-service-widget-basic-input.md)
- [progress](js-service-widget-basic-progress.md)
- [span](js-service-widget-basic-span.md)
- [text](js-service-widget-basic-text.md)
- [Custom Component Basic Usage](js-service-widget-custom-basic-usage.md)
- [Data Types](js-service-widget-appendix-types.md)
......@@ -2,11 +2,11 @@
## Introduction
ArkUI is a UI development framework that provides what you'll need to develop application UIs in OpenHarmony, including UI components, animations, drawing, interaction events, and JavaScript API extension mechanisms. ArkUI comes with two development paradigms: eTS-based declarative development paradigm (declarative development paradigm for short) and JavaScript-compatible web-like development paradigm (web-like development paradigm for short).
ArkUI is a UI development framework that provides what you'll need to develop application UIs in OpenHarmony, including UI components, animations, drawing, interaction events, and JavaScript API extension mechanisms. ArkUI comes with two development paradigms: ArkTS-based declarative development paradigm (declarative development paradigm for short) and JavaScript-compatible web-like development paradigm (web-like development paradigm for short).
**Framework Structure**
![en-us_image_0000001267647869](../application-dev/ui/figures/en-us_image_0000001267647869.png)
![en-us_image_0000001183709904](../application-dev/ui/figures/arkui-framework.png)
As shown above, the two development paradigms share the UI backend engine and language runtime. The UI backend engine implements the six basic capabilities of ArkUI. The declarative development paradigm does not require the JS Framework for managing the page DOM. As such, it has more streamlined rendering and update links and less memory usage. This makes the declarative development paradigm a better choice for building application UIs.
......
......@@ -449,9 +449,9 @@ ServiceExtensionAbility服务组件在[onConnect()](../reference/apis/js-apis-ap
}
```
## 相关
## 相关
针对ServiceExtensionAbility开发,有以下相关例可供参考:
针对ServiceExtensionAbility开发,有以下相关例可供参考:
- [`AbilityConnectServiceExtension`:Ability与ServiceExtensionAbility通信(ArkTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/IDL/AbilityConnectServiceExtension)
- [`StageModel`:Stage模型(ArkTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/ApplicationModels/StageModel)
......@@ -427,7 +427,7 @@ struct GridRowSample3 {
gutter: {x: {sm: 8, md: 16, lg: 24}, y: {sm: 8, md: 16, lg: 24}}}) {
ForEach(this.bgColors, (bgColor)=>{
GridCol({span: {sm: 2, md: 2, lg: 2}}) {
Row().backgroundColor(bgColor).height(30)
Row().backgroundColor(bgColor).height(30).width('100%')
}
})
}
......@@ -460,7 +460,7 @@ struct GridRowSample4 {
GridCol({span:{xs: 12, sm: 12, md: 12, lg:12}}) {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text("padding").fontSize(24).fontWeight(FontWeight.Medium)
}.backgroundColor('#19000000')
}.backgroundColor('#19000000').width('100%')
}
}
.height(50)
......@@ -483,7 +483,7 @@ struct GridRowSample4 {
GridCol({span:{xs: 12, sm: 12, md: 12, lg:12}}) {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text("margin").fontSize(24).fontWeight(FontWeight.Medium)
}.backgroundColor('#19000000')
}.backgroundColor('#19000000').width('100%')
}
}
.height(50)
......@@ -542,7 +542,7 @@ struct GridRowSample5 {
Text('' + item.index).fontSize(24)
}
.justifyContent(FlexAlign.Center)
.backgroundColor(item.color).height(30)
.backgroundColor(item.color).height(30).width('100%')
}
})
}
......@@ -584,7 +584,7 @@ struct GridRowSample6 {
Text('' + item.index).fontSize(24)
}
.justifyContent(FlexAlign.Center)
.backgroundColor(item.color).height(30)
.backgroundColor(item.color).height(30).width('100%')
}
})
}
......@@ -626,7 +626,7 @@ struct GridRowSample7 {
Text('' + item.index).fontSize(24)
}
.justifyContent(FlexAlign.Center)
.backgroundColor(item.color).height(30)
.backgroundColor(item.color).height(30).width('100%')
}
})
}
......@@ -670,7 +670,7 @@ struct GridRowSample8 {
Text('' + item.index).fontSize(24)
}
.justifyContent(FlexAlign.Center)
.backgroundColor(item.color).height(30)
.backgroundColor(item.color).height(30).width('100%')
}
})
}
......@@ -713,7 +713,7 @@ struct GridRowSample9 {
Text('' + item.index).fontSize(24)
}
.justifyContent(FlexAlign.Center)
.backgroundColor(item.color).height(30)
.backgroundColor(item.color).height(30).width('100%')
}
})
}
......
......@@ -24,7 +24,7 @@ getWantAgent(info: WantAgentInfo, callback: AsyncCallback\<WantAgent\>): void
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------------- | ---- | ----------------------- |
| info | WantAgentInfo | 是 | WantAgent信息。 |
| info | [WantAgentInfo](js-apis-inner-wantAgent-wantAgentInfo.md) | 是 | WantAgent信息。 |
| callback | AsyncCallback\<WantAgent\> | 是 | 创建WantAgent的回调方法。 |
**错误码:**
......@@ -596,7 +596,7 @@ getWant(agent: WantAgent): Promise\<Want\>
| 类型 | 说明 |
| ----------------------------------------------------------- | ------------------------------------------------------------ |
| Promise\<Want\> | 以Promise形式返回获取WantAgent对象的want。 |
| Promise\<[Want](js-apis-app-ability-want.md)\> | 以Promise形式返回获取WantAgent对象的want。 |
**错误码:**
......@@ -841,7 +841,7 @@ trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: AsyncCallback\<Co
| 参数名 | 类型 | 必填 | 说明 |
| ----------- | ----------------------------- | ---- | ------------------------------- |
| agent | WantAgent | 是 | WantAgent对象。 |
| triggerInfo | TriggerInfo | 是 | TriggerInfo对象。 |
| triggerInfo | [TriggerInfo](js-apis-inner-wantAgent-triggerInfo.md) | 是 | TriggerInfo对象。 |
| callback | AsyncCallback\<[CompleteData](#completedata)\> | 否 | 主动激发WantAgent实例的回调方法。 |
**示例:**
......
......@@ -251,7 +251,7 @@ accessSync(path: string): boolean
## fs.close
close(file: File|number): Promise&lt;void&gt;
close(file: number|File): Promise&lt;void&gt;
关闭文件,使用Promise异步回调。
......@@ -261,7 +261,7 @@ close(file: File|number): Promise&lt;void&gt;
| 参数名 | 类型 | 必填 | 说明 |
| ---- | ------ | ---- | ------------ |
| file | [File](#file)\|number | 是 | 已打开的File对象或已打开的文件描述符fd。 |
| file | number\|[File](#file) | 是 | 已打开的File对象或已打开的文件描述符fd。 |
**返回值:**
......@@ -288,7 +288,7 @@ close(file: File|number): Promise&lt;void&gt;
## fs.close
close(file: File|number, callback: AsyncCallback&lt;void&gt;): void
close(file: number|File, callback: AsyncCallback&lt;void&gt;): void
关闭文件,使用callback异步回调。
......@@ -298,7 +298,7 @@ close(file: File|number, callback: AsyncCallback&lt;void&gt;): void
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------- | ---- | ------------ |
| file | [File](#file)\|number | 是 | 已打开的File对象或已打开的文件描述符fd。 |
| file | number\|[File](#file) | 是 | 已打开的File对象或已打开的文件描述符fd。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 异步关闭文件之后的回调。 |
**错误码:**
......@@ -321,7 +321,7 @@ close(file: File|number, callback: AsyncCallback&lt;void&gt;): void
## fs.closeSync
closeSync(file: File|number): void
closeSync(file: number|File): void
以同步方法关闭文件。
......@@ -331,7 +331,7 @@ closeSync(file: File|number): void
| 参数名 | 类型 | 必填 | 说明 |
| ---- | ------ | ---- | ------------ |
| file | [File](#file)\|number | 是 | 已打开的File对象或已打开的文件描述符fd。 |
| file | number\|[File](#file) | 是 | 已打开的File对象或已打开的文件描述符fd。 |
**错误码:**
......@@ -1811,6 +1811,8 @@ listFile(path: string, options?: {
列出文件夹下所有文件名,支持递归列出所有文件名(包含子目录下),支持文件过滤,使用Callback异步回调。
**系统能力**:SystemCapability.FileManagement.File.FileIO
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
......@@ -1866,6 +1868,8 @@ listFileSync(path: string, options?: {
以同步方式列出文件夹下所有文件名,支持递归列出所有文件名(包含子目录下),支持文件过滤。
**系统能力**:SystemCapability.FileManagement.File.FileIO
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
......@@ -1986,7 +1990,7 @@ moveFile(src: string, dest: string, mode?: number, callback: AsyncCallback\<void
## fs.moveFileSync
moveFile(src: string, dest: string, mode?: number): void
moveFileSync(src: string, dest: string, mode?: number): void
以同步方式移动文件。
......@@ -2933,7 +2937,7 @@ lock(exclusive?: boolean): Promise\<void>
**示例:**
```js
let file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
let file = fs.openSync(pathDir + "/test.txt", fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
file.lock(true).then(() => {
console.log("lock file successful");
}).catch((err) => {
......@@ -2963,7 +2967,7 @@ lock(exclusive?: boolean, callback: AsyncCallback\<void>): void
**示例:**
```js
let file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
let file = fs.openSync(pathDir + "/test.txt", fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
file.lock(true, (err) => {
if (err) {
console.info("lock file failed with error message: " + err.message + ", error code: " + err.code);
......@@ -2994,7 +2998,7 @@ tryLock(exclusive?: boolean): void
**示例:**
```js
let file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
let file = fs.openSync(pathDir + "/test.txt", fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
file.tryLock(true);
console.log("lock file successful");
```
......@@ -3014,7 +3018,7 @@ unlock(): void
**示例:**
```js
let file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
let file = fs.openSync(pathDir + "/test.txt", fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
file.tryLock(true);
file.unlock();
console.log("unlock file successful");
......
......@@ -14,7 +14,7 @@ import fileShare from '@ohos.fileshare';
## fileShare.grantUriPermission
grantUriPermission(uri: string, bundleName: string, mode: number, callback: AsyncCallback&lt;void&gt;): void
grantUriPermission(uri: string, bundleName: string, flag: wantConstant.Flags, callback: AsyncCallback&lt;void&gt;): void
对公共目录文件URI进行授权操作,使用callback异步回调。
......@@ -30,7 +30,7 @@ grantUriPermission(uri: string, bundleName: string, mode: number, callback: Asyn
| ------ | ------ | ---- | -------------------------- |
| uri | string | 是 | 公共目录文件URI |
| bundleName | string | 是 | 分享目标的包名 |
| mode | number | 是 | 授权的权限,参考[wantConstant.Flags](js-apis-app-ability-wantConstant.md#wantconstantflags)<br/>wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION:读授权<br/>wantConstant.Flags.FLAG_AUTH_WRITE_URI_PERMISSION:写授权|
| flag | wantConstant.Flags | 是 | 授权的权限,参考[wantConstant.Flags](js-apis-app-ability-wantConstant.md#wantconstantflags)<br/>wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION:读授权<br/>wantConstant.Flags.FLAG_AUTH_WRITE_URI_PERMISSION:写授权|
| callback | AsyncCallback&lt;void&gt; | 是 | 异步授权之后的回调 |
**错误码:**
......@@ -67,7 +67,7 @@ try {
## fileShare.grantUriPermission
grantUriPermission(uri: string, bundleName: string, mode: number): Promise&lt;void&gt;
grantUriPermission(uri: string, bundleName: string, flag: wantConstant.Flags): Promise&lt;void&gt;
将公共目录文件URI进行授权操作,使用Promise异步回调。
......@@ -83,7 +83,7 @@ grantUriPermission(uri: string, bundleName: string, mode: number): Promise&lt;vo
| ------ | ------ | ---- | -------------------------- |
| uri | string | 是 | 公共目录文件URI |
| bundleName | string | 是 | 分享目标的包名 |
| mode | number | 是 | 授权的权限,参考[wantConstant.Flags](js-apis-app-ability-wantConstant.md#wantconstantflags)<br/>wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION:读授权<br/>wantConstant.Flags.FLAG_AUTH_WRITE_URI_PERMISSION:写授权|
| flag | wantConstant.Flags | 是 | 授权的权限,参考[wantConstant.Flags](js-apis-app-ability-wantConstant.md#wantconstantflags)<br/>wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION:读授权<br/>wantConstant.Flags.FLAG_AUTH_WRITE_URI_PERMISSION:写授权|
**返回值:**
......
......@@ -16,7 +16,7 @@ import wantAgent from '@ohos.app.ability.wantAgent';
| 名称 | 类型 | 必填 | 说明 |
| -------------- | ------------------------------- | ---- | ---------------------- |
| wants | Array\<Want\> | 是 | 将被执行的动作列表。 |
| wants | Array\<[Want](js-apis-inner-ability-want.md)\> | 是 | 将被执行的动作列表。 |
| operationType | [wantAgent.OperationType](js-apis-app-ability-wantAgent.md#operationtype) | 是 | 动作类型。 |
| requestCode | number | 是 | 使用者定义的一个私有值。 |
| wantAgentFlags | Array<[wantAgent.WantAgentFlags](js-apis-app-ability-wantAgent.md#wantagentflags)> | 否 | 动作执行属性。 |
......
......@@ -25,7 +25,7 @@ getStatus(options?: GetStatusOptions): void;
**参数:**
| 名称 | 类型 | 必填 | 说明 |
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| options | [GetStatusOptions](#getstatusoptions) | 否 | 包含接口调用结果的对象。可选,默认为空。 |
......@@ -48,7 +48,7 @@ battery.getStatus({
**系统能力:** SystemCapability.PowerManager.BatteryManager.Core
| 名称 | 类型 | 必填 | 说明 |
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------------------- | ---- | ------------------------------------------------------------ |
| success | (data: [BatteryResponse](#batteryresponse)) => void | 否 | 接口调用成功的回调函数,data为[BatteryResponse](#batteryresponse)类型的返回值。 |
| fail | (data: string, code: number) => void | 否 | 接口调用失败的回调函数。data为错误信息,code为错误码。 |
......@@ -60,7 +60,7 @@ battery.getStatus({
**系统能力:** SystemCapability.PowerManager.BatteryManager.Core
| 名称 | 类型 | 可读 | 可写 | 说明 |
| 参数名 | 类型 | 可读 | 可写 | 说明 |
| -------- | -------- | -------- | -------- | -------- |
| charging | boolean | 是 | 否 | 当前电池是否在充电中。 |
| level | number | 是 | 否 | 当前电池的电量,取值范围:0.00&nbsp;-&nbsp;1.00&nbsp;。 |
......@@ -152,7 +152,7 @@ hasRight(deviceName: string): boolean
**示例:**
```js
let devicesName="1-1";
let devicesName = "1-1";
let bool = usb.hasRight(devicesName);
console.log(`${bool}`);
```
......@@ -180,7 +180,7 @@ requestRight(deviceName: string): Promise&lt;boolean&gt;
**示例:**
```js
let devicesName="1-1";
let devicesName = "1-1";
usb.requestRight(devicesName).then((ret) => {
console.log(`requestRight = ${ret}`);
});
......@@ -209,7 +209,7 @@ removeRight(deviceName: string): boolean
**示例:**
```js
let devicesName= "1-1";
let devicesName = "1-1";
if (usb.removeRight(devicesName)) {
console.log(`Succeed in removing right`);
}
......@@ -277,6 +277,16 @@ claimInterface(pipe: USBDevicePipe, iface: USBInterface, force ?: boolean): numb
**示例:**
```js
let devicesList = usb.getDevices();
if (devicesList.length == 0) {
console.log(`device list is empty`);
return;
}
let device = devicesList[0];
usb.requestRight(device.name);
let devicepipe = usb.connectDevice(device);
let interfaces = device.configs[0].interfaces[0];
let ret = usb.claimInterface(devicepipe, interfaces);
console.log(`claimInterface = ${ret}`);
```
......@@ -307,7 +317,18 @@ releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number
**示例:**
```js
let ret = usb.releaseInterface(devicepipe, interfaces);
let devicesList = usb.getDevices();
if (devicesList.length == 0) {
console.log(`device list is empty`);
return;
}
let device = devicesList[0];
usb.requestRight(device.name);
let devicepipe = usb.connectDevice(device);
let interfaces = device.configs[0].interfaces[0];
let ret = usb.claimInterface(devicepipe, interfaces);
ret = usb.releaseInterface(devicepipe, interfaces);
console.log(`releaseInterface = ${ret}`);
```
......@@ -337,6 +358,16 @@ setConfiguration(pipe: USBDevicePipe, config: USBConfiguration): number
**示例:**
```js
let devicesList = usb.getDevices();
if (devicesList.length == 0) {
console.log(`device list is empty`);
return;
}
let device = devicesList[0];
usb.requestRight(device.name);
let devicepipe = usb.connectDevice(device);
let config = device.configs[0];
let ret = usb.setConfiguration(devicepipe, config);
console.log(`setConfiguration = ${ret}`);
```
......@@ -367,7 +398,18 @@ setInterface(pipe: USBDevicePipe, iface: USBInterface): number
**示例:**
```js
let ret = usb.setInterface(devicepipe, interfaces);
let devicesList = usb.getDevices();
if (devicesList.length == 0) {
console.log(`device list is empty`);
return;
}
let device = devicesList[0];
usb.requestRight(device.name);
let devicepipe = usb.connectDevice(device);
let interfaces = device.configs[0].interfaces[0];
let ret = usb.claimInterface(devicepipe, interfaces);
ret = usb.setInterface(devicepipe, interfaces);
console.log(`setInterface = ${ret}`);
```
......@@ -396,6 +438,14 @@ getRawDescriptor(pipe: USBDevicePipe): Uint8Array
**示例:**
```js
let devicesList = usb.getDevices();
if (devicesList.length == 0) {
console.log(`device list is empty`);
return;
}
usb.requestRight(devicesList[0].name);
let devicepipe = usb.connectDevice(devicesList[0]);
let ret = usb.getRawDescriptor(devicepipe);
```
......@@ -424,6 +474,14 @@ getFileDescriptor(pipe: USBDevicePipe): number
**示例:**
```js
let devicesList = usb.getDevices();
if (devicesList.length == 0) {
console.log(`device list is empty`);
return;
}
usb.requestRight(devicesList[0].name);
let devicepipe = usb.connectDevice(devicesList[0]);
let ret = usb.getFileDescriptor(devicepipe);
```
......@@ -462,6 +520,15 @@ let param = {
index: 0,
data: null
};
let devicesList = usb.getDevices();
if (devicesList.length == 0) {
console.log(`device list is empty`);
return;
}
usb.requestRight(devicesList[0].name);
let devicepipe = usb.connectDevice(devicesList[0]);
usb.controlTransfer(devicepipe, param).then((ret) => {
console.log(`controlTransfer = ${ret}`);
})
......@@ -498,8 +565,22 @@ bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, tim
//usb.getDevices 接口返回数据集合,取其中一个设备对象,并获取权限 。
//把获取到的设备对象作为参数传入usb.connectDevice;当usb.connectDevice接口成功返回之后;
//才可以调用第三个接口usb.claimInterface.当usb.claimInterface 调用成功以后,再调用该接口。
let devicesList = usb.getDevices();
if (devicesList.length == 0) {
console.log(`device list is empty`);
return;
}
let device = devicesList[0];
usb.requestRight(device.name);
let devicepipe = usb.connectDevice(device);
let interfaces = device.configs[0].interfaces[0];
let endpoint = device.configs[0].interfaces[0].endpoints[0];
let ret = usb.claimInterface(devicepipe, interfaces);
let buffer = new Uint8Array(128);
usb.bulkTransfer(devicepipe, endpoint, buffer).then((ret) => {
console.log(`bulkTransfer = ${ret}`);
console.log(`bulkTransfer = ${ret}`);
});
```
......@@ -528,6 +609,14 @@ closePipe(pipe: USBDevicePipe): number
**示例:**
```js
let devicesList = usb.getDevices();
if (devicesList.length == 0) {
console.log(`device list is empty`);
return;
}
usb.requestRight(devicesList[0].name);
let devicepipe = usb.connectDevice(devicesList[0]);
let ret = usb.closePipe(devicepipe);
console.log(`closePipe = ${ret}`);
```
......
......@@ -1172,11 +1172,9 @@ import web_webview from '@ohos.web.webview'
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
@State webResult: string = '';
build() {
Column() {
Text(this.webResult).fontSize(20)
Web({ src: $rawfile('index.html'), controller: this.controller })
.javaScriptAccess(true)
.onPageEnd(e => {
......
......@@ -652,6 +652,12 @@ verticalScrollBarAccess(verticalScrollBar: boolean)
</html>
```
### password
password(password: boolean)
设置是否应保存密码。该接口为空接口。
### cacheMode
cacheMode(cacheMode: CacheMode)
......@@ -1218,6 +1224,18 @@ forceDarkAccess(access: boolean)
}
```
### tableData
tableData(tableData: boolean)
设置是否应保存表单数据。该接口为空接口。
### wideViewModeAccess
wideViewModeAccess(wideViewModeAccess: boolean)
设置web是否支持html中meta标签的viewport属性。该接口为空接口。
### pinchSmooth<sup>9+</sup>
pinchSmooth(isEnabled: boolean)
......@@ -1954,6 +1972,26 @@ onRefreshAccessedHistory(callback: (event?: { url: string, isRefreshed: boolean
}
```
### onSslErrorReceive<sup>(deprecated)</sup>
onSslErrorReceive(callback: (event?: { handler: Function, error: object }) => void)
通知用户加载资源时发生SSL错误。
> **说明:**
>
> 从API version 8开始支持,从API version 9开始废弃。建议使用[onSslErrorEventReceive<sup>9+</sup>](#onsslerroreventreceive9)替代。
### onFileSelectorShow<sup>(deprecated)</sup>
onFileSelectorShow(callback: (event?: { callback: Function, fileSelector: object }) => void)
调用此函数以处理具有“文件”输入类型的HTML表单,以响应用户按下的“选择文件”按钮。
> **说明:**
>
> 从API version 8开始支持,从API version 9开始废弃。建议使用[onShowFileSelector<sup>9+</sup>](#onshowfileselector9)替代。
### onRenderExited<sup>9+</sup>
onRenderExited(callback: (event?: { renderExitReason: RenderExitReason }) => void)
......@@ -4709,9 +4747,11 @@ clearHistory(): void
通过WebCookie可以控制Web组件中的cookie的各种行为,其中每个应用中的所有web组件共享一个WebCookie。通过controller方法中的getCookieManager方法可以获取WebCookie对象,进行后续的cookie管理操作。
### setCookie<sup>(deprecated)</sup>
setCookie(): boolean
设置cookie,该方法为同步方法。设置成功返回true,否则返回false。
从API version 9开始不再维护,建议使用[setCookie<sup>9+</sup>](../apis/js-apis-webview.md#setcookie)代替。
**返回值:**
......@@ -4720,57 +4760,16 @@ setCookie(): boolean
| ------- | ------------- |
| boolean | 设置cookie是否成功。 |
**示例:**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController()
build() {
Column() {
Button('setCookie')
.onClick(() => {
let result = this.controller.getCookieManager().setCookie()
console.log("result: " + result)
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### saveCookie<sup>(deprecated)</sup>
saveCookie(): boolean
将当前存在内存中的cookie同步到磁盘中,该方法为同步方法。
从API version 9开始不再维护,建议使用[saveCookieAsync<sup>9+</sup>](../apis/js-apis-webview.md#savecookieasync)代替。
**返回值:**
| 类型 | 说明 |
| ------- | -------------------- |
| boolean | 同步内存cookie到磁盘操作是否成功。 |
**示例:**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController()
build() {
Column() {
Button('saveCookie')
.onClick(() => {
let result = this.controller.getCookieManager().saveCookie()
console.log("result: " + result)
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
| boolean | 同步内存cookie到磁盘操作是否成功。 |
\ No newline at end of file
......@@ -39,10 +39,14 @@ ATM (AccessTokenManager) 是OpenHarmony上基于AccessToken构建的统一的应
![](figures/permission-workflow.jpg)
上图的数字标注,请参考以下说明:
1:开发者可以参考下图,判断应用能否申请目标权限。
![](figures/permission-application-process.png)
上图的数字标注,请参考以下说明:
1:应用APL等级与权限等级的匹配关系请参考[权限等级说明](#权限等级说明)
2:权限的授权方式分为user_grant(用户授权)和system_grant(系统授权),具体请参考[权限类型说明](#权限类型说明)
......@@ -58,6 +62,8 @@ ATM (AccessTokenManager) 是OpenHarmony上基于AccessToken构建的统一的应
![](figures/permission-verify-process.png)
上图的数字标注,请参考以下说明:
1:根据应用当前提供的接口是否涉及敏感的数据或者功能,使用应用权限对当前接口进行访问控制。
2:应用可以在系统已经存在的权限中[访问控制列表(ACL)说明](#访问控制列表acl说明)选择适合的权限。比如应用提供的接口会涉及到联系人信息的话,推荐使用联系人相关的权限对接口进行保护。
......
......@@ -1130,83 +1130,70 @@ function signLongMessagePromise() {
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
// turn string into uint8Arr
// 可理解的字符串转成字节流
function stringToUint8Array(str) {
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
var tmpUint8Array = new Uint8Array(arr);
return tmpUint8Array;
}
// generate dataBlob with given length
function GenDataBlob(dataBlobLen) {
var dataBlob;
if (dataBlobLen == 12) {
dataBlob = {data: stringToUint8Array("my test data")};
} else {
console.error("GenDataBlob: dataBlobLen is invalid");
dataBlob = {data: stringToUint8Array("my test data")};
let arr = [];
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
return dataBlob;
return new Uint8Array(arr);
}
// md with promise async
function doMdByPromise(algName) {
var md;
// 以Promise方式完成摘要
function doMdByPromise() {
let mdAlgName = "SHA256"; // 摘要算法名
let message = "mdTestMessgae"; // 待摘要数据
let md;
let mdOutput;
try {
md = cryptoFramework.createMd(algName);
md = cryptoFramework.createMd(mdAlgName);
} catch (error) {
console.error("[Promise]: error code: " + error.code + ", message is: " + error.message);
return;
}
console.error("[Promise]: Md algName is: " + md.algName);
// 初次update
var promiseMdUpdate = md.update(GenDataBlob(12));
console.info("[Promise]: Md algName is: " + md.algName);
// 数据量较少时,可以只做一次update,将数据全部传入,接口未对入参长度做限制
let promiseMdUpdate = md.update({ data: stringToUint8Array(message) });
promiseMdUpdate.then(() => {
// 可根据情况进行多次update
promiseMdUpdate = md.update(GenDataBlob(12));
return promiseMdUpdate;
}).then(mdOutput => {
var PromiseMdDigest = md.digest();
// 通过digest,返回摘要结果
let PromiseMdDigest = md.digest();
return PromiseMdDigest;
}).then(mdOutput => {
console.error("[Promise]: MD result: " + mdOutput.data);
var mdLen = md.getMdLength();
console.error("[Promise]: MD len: " + mdLen);
}).then(digestOutput => {
mdOutput = digestOutput;
console.info("[Promise]: MD result: " + mdOutput.data);
let mdLen = md.getMdLength();
console.info("[Promise]: MD len: " + mdLen);
}).catch(error => {
console.error("[Promise]: error: " + error.message);
});
}
// md with callback async
function doMdByCallback(algName) {
var md;
// 以Callback方式完成摘要
function doMdByCallback() {
let mdAlgName = "SHA256"; // 摘要算法名
let message = "mdTestMessgae"; // 待摘要数据
let md;
let mdOutput;
try {
md = cryptoFramework.createMd(algName);
md = cryptoFramework.createMd(mdAlgName);
} catch (error) {
console.error("[Callback]: error code: " + error.code + ", message is: " + error.message);
}
console.error("[Callback]: Md algName is: " + md.algName);
// 初次update
md.update(GenDataBlob(12), (err,) => {
console.info("[Callback]: Md algName is: " + md.algName);
// 数据量较少时,可以只做一次update,将数据全部传入,接口未对入参长度做限制
md.update({ data: stringToUint8Array(message) }, (err,) => {
if (err) {
console.error("[Callback]: err: " + err.code);
}
// 可根据情况进行多次update
md.update(GenDataBlob(12), (err1,) => {
md.digest((err1, digestOutput) => {
if (err1) {
console.error("[Callback]: err: " + err1.code);
} else {
mdOutput = digestOutput;
console.info("[Callback]: MD result: " + mdOutput.data);
let mdLen = md.getMdLength();
console.info("[Callback]: MD len: " + mdLen);
}
md.digest((err2, mdOutput) => {
if (err2) {
console.error("[Callback]: err: " + err2.code);
} else {
console.error("[Callback]: MD result: " + mdOutput.data);
var mdLen = md.getMdLength();
console.error("[Callback]: MD len: " + mdLen);
}
});
});
});
}
......@@ -1215,54 +1202,56 @@ function doMdByCallback(algName) {
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
async function updateData(index, obj, data) {
console.error("update " + (index + 1) + " MB data...");
return obj.update(data);
}
// 可理解的字符串转成字节流
function stringToUint8Array(str) {
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) {
let arr = [];
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
var tmpUint8Array = new Uint8Array(arr);
return tmpUint8Array;
return new Uint8Array(arr);
}
function GenDataBlob(dataBlobLen) {
var dataBlob;
if (dataBlobLen == 12) {
dataBlob = {data: stringToUint8Array("my test data")};
} else {
console.error("GenDataBlob: dataBlobLen is invalid");
dataBlob = {data: stringToUint8Array("my test data")};
}
return dataBlob;
}
function LoopMdPromise(algName, loopSize) {
var md;
// 使用Promise方式,完成分段摘要
async function doLoopMdPromise() {
let mdAlgName = "SHA256"; // 摘要算法名
let md;
let mdOutput;
try {
md = cryptoFramework.createMd(algName);
md = cryptoFramework.createMd(mdAlgName);
} catch (error) {
console.error("[Promise]: error code: " + error.code + ", message is: " + error.message);
return;
}
console.error("[Promise]: Md algName is: " + md.algName);
var promiseMdUpdate = md.update(GenDataBlob(12));
promiseMdUpdate.then(() => {
var PromiseMdDigest = md.digest();
return PromiseMdDigest;
}).then(async () => {
for (var i = 0; i < loopSize; i++) {
await updateData(i, md, GenDataBlob(12));
console.info("[Promise]: Md algName is: " + md.algName);
let messageText = "aaaaa.....bbbbb.....ccccc.....ddddd.....eee"; // 假设信息总共43字节
let messageArr = [];
let updateLength = 20; // 假设每20字节分段update一次,实际并无要求
for (let i = 0; i <= messageText.length; i++) {
if ((i % updateLength == 0 || i == messageText.length) && messageArr.length != 0) {
let message = new Uint8Array(messageArr);
let messageBlob = { data : message };
// 使用await处理for循环里的update
try {
await md.update(messageBlob); // 分段update
} catch (error) {
console.error("await update error code: " + error.code + ", message is: " + error.message);
return;
}
messageArr = [];
}
var PromiseMdDigest = md.digest();
return PromiseMdDigest;
}).then(mdOutput => {
console.error("[Promise]: MD result: " + mdOutput.data);
var mdLen = md.getMdLength();
console.error("[Promise]: MD len: " + mdLen);
// 按分割长度,填充messageArr
if (i < messageText.length) {
messageArr.push(messageText.charCodeAt(i));
}
}
let PromiseMdDigest = md.digest();
PromiseMdDigest.then(digestOutput => {
mdOutput = digestOutput;
console.info("[Promise]: MD result: " + mdOutput.data);
let mdLen = md.getMdLength();
console.info("[Promise]: MD len: " + mdLen);
}).catch(error => {
console.error("[Promise]: error: " + error.message);
});
......@@ -1374,77 +1363,72 @@ Mac(message authentication code)可以对消息进行完整性校验,通过使
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
// turn string into uint8Arr
// 可理解的字符串转成字节流
function stringToUint8Array(str) {
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
var tmpUint8Array = new Uint8Array(arr);
return tmpUint8Array;
}
// generate blob with this func
function GenDataBlob(dataBlobLen) {
var dataBlob;
if (dataBlobLen == 12) {
dataBlob = {data: stringToUint8Array("my test data")};
} else {
console.error("GenDataBlob: dataBlobLen is invalid");
dataBlob = {data: stringToUint8Array("my test data")};
let arr = [];
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
return dataBlob;
return new Uint8Array(arr);
}
function doHmacByPromise(algName) {
var mac;
// 以Promise方式完成HMAC
function doHmacByPromise() {
let macAlgName = "SHA256"; // 摘要算法名
let message = "hmacTestMessgae"; // 待hmac数据
let macOutput;
let mac;
try {
mac = cryptoFramework.createMac(algName);
mac = cryptoFramework.createMac(macAlgName);
} catch (error) {
console.error("[Promise]: error code: " + error.code + ", message is: " + error.message);
}
console.error("[Promise]: Mac algName is: " + mac.algName);
var KeyBlob = {
console.info("[Promise]: Mac algName is: " + mac.algName);
let KeyBlob = {
// 128位密钥
data : stringToUint8Array("12345678abcdefgh")
}
var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob);
let symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
// 将二进制密钥转换为算法库密钥
let promiseConvertKey = symKeyGenerator.convertKey(KeyBlob);
promiseConvertKey.then(symKey => {
var promiseMacInit = mac.init(symKey);
let promiseMacInit = mac.init(symKey);
return promiseMacInit;
}).then(() => {
// 初次update
var promiseMacUpdate = mac.update(GenDataBlob(12));
return promiseMacUpdate;
}).then(() => {
// 可根据情况进行多次update
var promiseMacUpdate = mac.update(GenDataBlob(12));
// 数据量较少时,可以只做一次update,将数据全部传入,接口未对入参长度做限制
let promiseMacUpdate = mac.update({ data: stringToUint8Array(message) });
return promiseMacUpdate;
}).then(() => {
var PromiseMacDoFinal = mac.doFinal();
let PromiseMacDoFinal = mac.doFinal();
return PromiseMacDoFinal;
}).then(macOutput => {
console.error("[Promise]: HMAC result: " + macOutput.data);
var macLen = mac.getMacLength();
console.error("[Promise]: MAC len: " + macLen);
}).then(output => {
macOutput = output;
console.info("[Promise]: HMAC result: " + macOutput.data);
let macLen = mac.getMacLength();
console.info("[Promise]: MAC len: " + macLen);
}).catch(error => {
console.error("[Promise]: error: " + error.message);
});
}
// process by callback
function doHmacByCallback(algName) {
var mac;
// 以Callback方式完成HMAC
function doHmacByCallback() {
let macAlgName = "SHA256"; // 摘要算法名
let message = "hmacTestMessgae"; // 待hmac数据
let macOutput;
let mac;
try {
mac = cryptoFramework.createMac(algName);
mac = cryptoFramework.createMac(macAlgName);
} catch (error) {
AlertDialog.show({message: "[Callback]: error code: " + error.code + ", message is: " + error.message});
console.error("[Callback]: error code: " + error.code + ", message is: " + error.message);
}
var KeyBlob = {
console.info("[Promise]: Mac algName is: " + mac.algName);
let KeyBlob = {
// 128位密钥
data : stringToUint8Array("12345678abcdefgh")
}
var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
let symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
// 将二进制密钥转换为算法库密钥
symKeyGenerator.convertKey(KeyBlob, (err, symKey) => {
if (err) {
console.error("[Callback]: err: " + err.code);
......@@ -1453,25 +1437,20 @@ function doHmacByCallback(algName) {
if (err1) {
console.error("[Callback]: err: " + err1.code);
}
// 初次update
mac.update(GenDataBlob(12), (err2, ) => {
// 数据量较少时,可以只做一次update,将数据全部传入,接口未对入参长度做限制
mac.update({ data: stringToUint8Array(message) }, (err2, ) => {
if (err2) {
console.error("[Callback]: err: " + err2.code);
}
// 可根据情况进行多次update
mac.update(GenDataBlob(12), (err3, ) => {
mac.doFinal((err3, output) => {
if (err3) {
console.error("[Callback]: err: " + err3.code);
} else {
macOutput = output;
console.info("[Callback]: HMAC result: " + macOutput.data);
let macLen = mac.getMacLength();
console.info("[Callback]: MAC len: " + macLen);
}
mac.doFinal((err4, macOutput) => {
if (err4) {
console.error("[Callback]: err: " + err4.code);
} else {
console.error("[Callback]: HMAC result: " + macOutput.data);
var macLen = mac.getMacLength();
console.error("[Callback]: MAC len: " + macLen);
}
});
});
});
});
......@@ -1482,61 +1461,67 @@ function doHmacByCallback(algName) {
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
async function updateData(index, obj, data) {
console.error("update " + (index + 1) + " MB data...");
return obj.update(data);
}
function stringToUint8Array(str) {
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) {
let arr = [];
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
var tmpUint8Array = new Uint8Array(arr);
return tmpUint8Array;
}
function GenDataBlob(dataBlobLen) {
var dataBlob;
if (dataBlobLen == 12) {
dataBlob = {data: stringToUint8Array("my test data")};
} else {
console.error("GenDataBlob: dataBlobLen is invalid");
dataBlob = {data: stringToUint8Array("my test data")};
}
return dataBlob;
return new Uint8Array(arr);
}
function LoopHmacPromise(algName, loopSize) {
var mac;
function doLoopHmacPromise() {
let macAlgName = "SHA256"; // 摘要算法名
let macOutput;
let mac;
try {
mac = cryptoFramework.createMac(algName);
mac = cryptoFramework.createMac(macAlgName);
} catch (error) {
console.error("[Promise]: error code: " + error.code + ", message is: " + error.message);
return;
}
console.error("[Promise]: Mac algName is: " + mac.algName);
var KeyBlob = {
console.info("[Promise]: Mac algName is: " + mac.algName);
let KeyBlob = {
// 128位密钥
data : stringToUint8Array("12345678abcdefgh")
}
var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob);
let messageText = "aaaaa.....bbbbb.....ccccc.....ddddd.....eee"; // 假设信息总共43字节
let updateLength = 20; // 假设每20字节分段update一次,实际并无要求
let symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
// 将二进制密钥转换为算法库密钥
let promiseConvertKey = symKeyGenerator.convertKey(KeyBlob);
promiseConvertKey.then(symKey => {
var promiseMacInit = mac.init(symKey);
let promiseMacInit = mac.init(symKey);
return promiseMacInit;
}).then(async () => {
for (var i = 0; i < loopSize; i++) {
await updateData(i, mac, GenDataBlob(12));
let promiseMacUpdate;
let messageArr = [];
for (let i = 0; i <= messageText.length; i++) {
if ((i % updateLength == 0 || i == messageText.length) && messageArr.length != 0) {
let message = new Uint8Array(messageArr);
let messageBlob = { data : message };
// 使用await处理for循环里的update
try {
promiseMacUpdate = await mac.update(messageBlob); // 分段update
} catch (error) {
console.error("await update error code: " + error.code + ", message is: " + error.message);
return;
}
messageArr = [];
}
// 按分割长度,填充messageArr
if (i < messageText.length) {
messageArr.push(messageText.charCodeAt(i));
}
}
var promiseMacUpdate = mac.update(GenDataBlob(12));
return promiseMacUpdate;
}).then(() => {
var PromiseMacDoFinal = mac.doFinal();
let PromiseMacDoFinal = mac.doFinal();
return PromiseMacDoFinal;
}).then(macOutput => {
console.error("[Promise]: HMAC result: " + macOutput.data);
var macLen = mac.getMacLength();
console.error("[Promise]: MAC len: " + macLen);
}).then(output => {
macOutput = output;
console.log("[Promise]: HMAC result: " + macOutput.data);
let macLen = mac.getMacLength();
console.log("[Promise]: MAC len: " + macLen);
}).catch(error => {
console.error("[Promise]: error: " + error.message);
});
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册