diff --git a/en/application-dev/form/Readme-EN.md b/en/application-dev/form/Readme-EN.md index 2710099a1ede67cd730a092036755223dfbd1f1d..cdf3563b1571d7a967395e38eb2b7a72b61563d2 100644 --- a/en/application-dev/form/Readme-EN.md +++ b/en/application-dev/form/Readme-EN.md @@ -1,39 +1,49 @@ # Form Kit - [Introduction to Form Kit](formkit-overview.md) -- Service Widget Development in Stage Model - - Developing an ArkTS Widget - - [ArkTS Widget Working Principles](arkts-ui-widget-working-principles.md) - - [ArkTS Widget Related Modules](arkts-ui-widget-modules.md) - - ArkTS Widget Development - - [Creating an ArkTS Widget](arkts-ui-widget-creation.md) - - [Configuring Widget Configuration Files](arkts-ui-widget-configuration.md) - - [Widget Lifecycle Management](arkts-ui-widget-lifecycle.md) - - Widget Page Development - - [Widget Page Capability Overview](arkts-ui-widget-page-overview.md) - - [Using Animations in the Widget](arkts-ui-widget-page-animation.md) - - [Applying Custom Drawing in the Widget](arkts-ui-widget-page-custom-drawing.md) - - Widget Event Development - - [Widget Event Capability Overview](arkts-ui-widget-event-overview.md) - - [Launching the UIAbility of the Widget Provider Through the router Event](arkts-ui-widget-event-router.md) - - [Launching the UIAbility of the Widget Provider in the Background Through the call Event](arkts-ui-widget-event-call.md) - - [Updating Widget Content Through the message Event](arkts-ui-widget-event-formextensionability.md) - - [Updating Widget Content Through the router or call Event](arkts-ui-widget-event-uiability.md) - - Widget Data Interaction - - [Updating Widget Content](arkts-ui-widget-interaction-overview.md) - - [Interval-based Widget Updates](arkts-ui-widget-update-by-time.md) - - [Time-specific Widget Updates](arkts-ui-widget-update-by-time-point.md) - - - [Updating Widget Content Through a Proxy](arkts-ui-widget-update-by-proxy.md) - - [Conditional Widget Updates](arkts-ui-widget-update-by-conditions.md) - - [Updating Widget Content by Widget Host (for System Applications Only)](arkts-ui-widget-content-update.md) - - - [Updating Local and Online Images in the Widget](arkts-ui-widget-image-update.md) - - [Updating Widget Content by State](arkts-ui-widget-update-by-status.md) - - Editing the ArkTS Widget Page - - [Overview of ArkTs Widget Page Editing Interaction](arkts-ui-widget-event-formeditextensionability-overview.md) - - [Editing and Updating the Widget Content](arkts-ui-widget-event-formeditextensionability.md) - - - [Widget Host Development (for System Applications Only)](widget-host-development-guide.md) - - - [Developing a JS Widget](js-ui-widget-development.md) -- [Service Widget Development in FA Model](widget-development-fa.md) +- ArkTS Widget Development (Recommended) + - [ArkTS Widget Overview](arkts-form-overview.md) + - [Creating an ArkTS Widget](arkts-ui-widget-creation.md) + - [Configuring ArkTS Widget Configuration Files](arkts-ui-widget-configuration.md) + - [Managing ArkTS Widget Lifecycle](arkts-ui-widget-lifecycle.md) + - [ArkTS Widget Process Model](arkts-ui-widget-process.md) + - ArkTS Widget Provider Development + - ArkTS Widget UI Development + - [Overview of ArkTS Widget UI Development](arkts-ui-widget-page-overview.md) + - [Using Animations in ArkTS Widgets](arkts-ui-widget-page-animation.md) + - [Using Canvas in ArkTS Widgets](arkts-ui-widget-page-custom-drawing.md) + - ArkTS Widget Update + - [Overview of ArkTS Widget Update](arkts-ui-widget-interaction-overview.md) + - [Active Update of ArkTS Widgets](arkts-ui-widget-active-refresh.md) + - [Passive Update of ArkTS Widgets](arkts-ui-widget-passive-refresh.md) + + - [Updating Widget Content Through a Proxy](arkts-ui-widget-update-by-proxy.md) + + - [Updating Local and Online Images in the Widget](arkts-ui-widget-image-update.md) + - [Updating Widget Content by State](arkts-ui-widget-update-by-status.md) + - ArkTS Widget Page Interaction + - [Overview of ArkTS Widget Page Interaction](arkts-ui-widget-event-overview.md) + - [Redirecting to an Application Page (router Event)](arkts-ui-widget-event-router.md) + - [Launching UIAbility to the Background (call Event)](arkts-ui-widget-event-call.md) + - [Transferring Messages to an Application (message Event)](arkts-ui-widget-event-formextensionability.md) + - [Updating Widget Content Through the router or call Event](arkts-ui-widget-event-uiability.md) + - ArkTS Widget Editing + - [Overview of ArkTS Widget Editing](arkts-ui-widget-event-formeditextensionability-overview.md) + - [Widget Editing Development](arkts-ui-widget-event-formeditextensionability.md) + - Widget Addition to Home Screen + - [Adding Widgets to the Home Screen](arkts-ui-widget-open-formmanager.md) + + - [ArkTS Widget Host Development (for System Applications Only)](widget-host-development-guide.md) + + - Interactive Widget Development + - [Overview of Interactive Widgets](arkts-ui-liveform-overview.md) + - [Developing a Fun-based Widget](arkts-ui-liveform-funinteraction-development.md) + - Scene-based Widget + - [Overview of Scene-based Widgets](arkts-ui-liveform-sceneanimation-overview.md) + - [Developing a Scene-based Widget](arkts-ui-liveform-sceneanimation-development.md) + + - [Developing a Scene-based Widget (for System Applications)](arkts-ui-liveform-sceneanimation-development-sys.md) + +- JS Widget Development + - [JS Widget Overview](js-ui-widget-overview.md) + - [Developing a JS Widget (Stage Model)](js-ui-widget-development.md) + - [Developing a JS Widget (FA Model)](widget-development-fa.md) diff --git a/en/application-dev/form/arkts-form-overview.md b/en/application-dev/form/arkts-form-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..d0b9198b8e957faa7f55afa0354673cd74b44f66 --- /dev/null +++ b/en/application-dev/form/arkts-form-overview.md @@ -0,0 +1,85 @@ +# ArkTS Widget Overview +This section describes how to develop an ArkTS widget based on the declarative paradigm. + +## Highlights +1. 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. For details, see Figure 1. + + **Figure 1** Comparison of widget project structures + ![WidgetProject](figures/WidgetProject.png) + +2. Enhanced widget capabilities + + - Animation: ArkTS widgets support the [property animation](../reference/apis-arkui/arkui-ts/ts-animatorproperty.md) and [explicit animation](../reference/apis-arkui/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/apis-arkui/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. + +## How to Implement + +- 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 and controls the widget content, component layout, and component tap events. + +- Widget Manager: a resident agent that manages widgets in the system. It provides [formProvider](../reference/apis-form-kit/js-apis-app-form-formProvider.md) and [formHost](../reference/apis-form-kit/js-apis-app-form-formHost-sys.md) 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 [FormComponent](../reference/apis-arkui/arkui-ts/ts-basic-components-formcomponent-sys.md) on the widget host on a one-to-one basis. The widget rendering service runs the widget page code **widgets.abc** for rendering based on the widget information configured in **form_config.json**, and sends the rendered data to the corresponding [FormComponent](../reference/apis-arkui/arkui-ts/ts-basic-components-formcomponent-sys.md) on the widget host. + +**Figure 2** Implementation principles of ArkTS widgets +![WidgetPrinciple](figures/WidgetPrinciple.png) + +**Figure 3** Working principles of the ArkTS widget rendering service +![WidgetRender](figures/WidgetRender.png) + +Unlike JS widgets, ArkTS widgets support logic code execution. 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 ArkTS virtual machine operating environment, and rendering instances of different widget providers run in different ArkTS 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** object. Use one **globalThis** object for widgets from the same widget provider, and different **globalThis** objects for widgets from different widget providers. + +## ArkTS Widget Types +ArkTS widgets are classified into dynamic widgets and static widgets. + +Compared with dynamic widgets, static widgets have the same overall running framework and rendering process. The main difference is that after the widget rendering service renders the widget content, the widget host uses the last frame of rendered data as a static image, and the widget rendering instance releases all running resources of the widget to save memory. As such, frequent updating of static widgets causes continuous creation and destruction of resources, resulting in increased power consumption.
+ +| Widget Type| Supported Capability| Scenario| Pros and Cons| +| ------- | ------ | ------- | ------- | +| Static widget| Limited to UI components and layout capabilities.| Suitable for presenting static information (with a stable UI), allowing navigation to a specific UIAbility via the **FormLink** component.| Offers basic functionality with efficient memory management.| +| Dynamic widget| Common event and custom animation capabilities in addition to UI components and layout capabilities.| Suitable for scenarios requiring complex logic and interactions, such as updating images or content on a widget.| Provides enhanced capabilities at the cost of high memory overhead.| + +### Dynamic Widget +For dynamic ArkTS widgets, the [postCardAction](../reference/apis-arkui/js-apis-postCardAction.md#postcardaction) API is provided for interaction between the widget internal and the provider application. Currently, this API supports the router, message, and call events and can be called only in the widget. + +**Figure 4** Implementation principles of dynamic widget events +![WidgetPostCardAction](figures/WidgetPostCardAction.png) + +Dynamic widget events are used in the following scenarios: +- router event: used to redirect to a specified UIAbility, enabling the functionality of navigating from a widget to an internal application page after a widget is touched. For non-system applications, this redirection is limited to their own UIAbilities. +- call event: used to launch a specified UIAbility to the background, after which the UIAbility can request the corresponding background continuous task to complete functionalities such as music playback. +- message event: used to launch the FormExtensionAbility, which then notifies the application via the **onFormEvent** callback, thereby fulfilling the functionality of passing messages to the application after a widget is touched. + +### Static Widget +The **FormLink** component is provided for interactions between static widgets and widget providers. It supports three types of events: router, message, and call. +See [FormLink](../reference/apis-arkui/arkui-ts/ts-container-formlink.md). + +## Constraints +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: + +- Currently, widgets can be developed only based on ArkUI. Cross-platform development is not supported. + +- When importing modules, you can import only the modules marked with "supported in ArkTS widgets." If an API that is not supported is used, the widget loading is abnormal. + +- [HAR](../quick-start/har-package.md) can be imported, but [HSP](../quick-start/in-app-hsp.md) cannot. + +- The native programming language cannot be used for development, and the native .so file cannot be loaded. + +- Only partial components, events, animations, data management, state management, and API capabilities of the [declarative paradigm](../ui/arkts-ui-development-overview.md) are supported. For APIs that can be used in ArkTS widgets, the following description will be added: "Widget capability: This API can be used in ArkTS widgets since API version *x*." + +- 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. + +In addition, ArkTS widgets do not support the following features: + +- Instant preview + +- Breakpoint debugging + +- Hot reload + +- setTimeOut + diff --git a/en/application-dev/form/arkts-ui-liveform-funinteraction-development.md b/en/application-dev/form/arkts-ui-liveform-funinteraction-development.md new file mode 100644 index 0000000000000000000000000000000000000000..63a2e37da5bc9580bc8626ddd4f4ab23083172e2 --- /dev/null +++ b/en/application-dev/form/arkts-ui-liveform-funinteraction-development.md @@ -0,0 +1,43 @@ +# Developing a Fun-based Widget + +Currently, fun-based widgets support mini-games developed with quick games. This kind of widget is in the inactive state by default. When a user taps the widget, it switches to the active state and the game begins. During the game, users can tap the pause icon to pause the game. In the paused state, users can resume the game by tapping the resume icon or end the game by tapping the stop icon. +## Basic Concepts + +Fun-based widgets can be in one of the following states: active (game running), paused (game paused), and inactive (game ended). + +### Active State + +In this state, the widget UI is carried by the mini-game page developed by the widget provider using quick games. The system supports an "overflow" effect, allowing game content to render beyond the widget rendering area. + +**Figure 1** Fun-based widget in the active state + +![live-form-running-game.gif](figures/live-form-running-game.gif) + +### Paused State + +In this state, the widget UI is carried by the content in **widgetCard.ets** of the widget provider. Meanwhile, the system renders the resume and stop icons on the widget by default. + +**Figure 2** Fun-based widget in the paused state + +![live-form-pause-game.jpg](figures/live-form-pause-game.jpg) + +### Inactive State + +In this state, the widget behaves like a common widget, complying with the existing widget development specifications. The widget UI is carried by the content in **widgetCard.ets**. + +**Figure 3** Fun-based widget in the inactive state + +![live-form-stop-game.jpg](figures/live-form-stop-game.jpg) + +## Constraints + +1. When a user interacts with a widget, for example, by tapping, long-pressing, or dragging, the interactive target area is always the same size as the widget rendering area. Even if the animation rendering area extends beyond the widget rendering area, the excess part is only used for UI display and does not respond to interactive events. +2. In the active state, interactive events within the widget's rendering area are responded to by the mini-game page developed by the widget provider. In other states, interactive events are responded to by the common widget developed by the widget provider. +3. At a time, only one widget can be in the active or paused state for fun-based interactions. When a user taps a widget to activate it, all other fun-based widgets are automatically switched to the inactive state. +4. For details about other design specifications and restrictions, see "Developing a Creative Widget". + +## How to Develop + +For details about how to develop game content, see "Developing a Game Widget". + +For details about on-device widget configuration and development, see [the configuration of fun-based widgets](arkts-ui-widget-configuration.md#funinteractionparams-field). diff --git a/en/application-dev/form/arkts-ui-liveform-overview.md b/en/application-dev/form/arkts-ui-liveform-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..7e7f7d895f00905fa44e07ffcc08b0be511bcce7 --- /dev/null +++ b/en/application-dev/form/arkts-ui-liveform-overview.md @@ -0,0 +1,27 @@ +# Overview of Interactive Widgets + +Interactive widgets dynamically display static information or images and facilitate human-machine interaction, thereby enhancing information notifications, shallow interactions, and the overall playability experience. + +## Scenarios + +There are two types of interactive widgets: fun-based widget and scene-based widget. + +### Fun-based Widget + +Users can tap a fun-based widget to play mini games. Currently, this feature can be developed only based on quick games. For details, see [Developing a Fun-based Widget](arkts-ui-liveform-funinteraction-development.md). + +**Figure 1** Example of a fun-based widget + +![live-form-game-demo.gif](figures/live-form-game-demo.gif) + +### Scene-based Widget + +Scene-based widgets support scene animations. For example, a weather widget activates and triggers its weather animation effect when the weather changes to a thunderstorm. Once the animation ends, the widget reverts to its original display. For details, see [Overview of Scene-based Widgets](arkts-ui-liveform-sceneanimation-overview.md). + +**Figure 2** Example of a scene-based widget + +![live-form-weather-demo.gif](figures/live-form-weather-demo.gif) + +## Constraints +- As an enhancement of the widget functionality, interactive widgets cannot overly depend on animations. + diff --git a/en/application-dev/form/arkts-ui-liveform-sceneanimation-development-sys.md b/en/application-dev/form/arkts-ui-liveform-sceneanimation-development-sys.md new file mode 100644 index 0000000000000000000000000000000000000000..41d8441efa3c6dd8bcacc5349578037e9fc13d5b --- /dev/null +++ b/en/application-dev/form/arkts-ui-liveform-sceneanimation-development-sys.md @@ -0,0 +1,121 @@ +# Developing a Scene-based Widget (for System Applications) + +For details about the development guidelines of scene-based widgets, see [Developing a Scene-based Widget](arkts-ui-liveform-sceneanimation-development.md). For system applications, scene-based widgets provide two extended capabilities: gesture suspension configuration and long-term widget activation. + +## Available APIs + +The following table lists the key APIs for a scene-based widget. + +**Table 1** Main APIs + +| API | Description | +|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------| +| [formProvider.activateSceneAnimation(formId: string): Promise<void>](../reference/apis-form-kit/js-apis-app-form-formProvider-sys.md#activatesceneanimation20) | Called to switch the interactive widget state to active.| +| [formProvider.deactivateSceneAnimation(formId: string): Promise<void>](../reference/apis-form-kit/js-apis-app-form-formProvider-sys.md#deactivatesceneanimation20) | Called to switch the interactive widget state to inactive.| + + +## Gesture Suspension Configuration +For [scene-based widgets](arkts-ui-liveform-sceneanimation-overview.md), operations such as long-pressing and dragging on the home screen will interrupt the current animation, causing the widget to revert to the inactive state. However, system applications can cancel this limitation by configuring [disabledDesktopBehaviors](arkts-ui-widget-configuration.md#sceneanimationparams-field) in the **form_config.json** file, ensuring smooth animations within the interactive target of the activated widget. +If no configuration is performed, the system does not intercept any valid gesture operations on the home screen by default. Once gestures are intercepted, the corresponding gesture events are handled by the LiveFormExtensionAbility. + +```ts +// entry/src/main/resources/base/profile/form_config.json +{ + "forms": [ + { + // ... + "sceneAnimationParams": { + "abilityName": "MySystemLiveFormExtensionAbility", + "disabledDesktopBehaviors": [ + "SWIPE_DESKTOP", + "PULL_DOWN_SEARCH", + "LONG_CLICK", + "DRAG" + ] + } + } + ] +} +``` + +## Long-term Widget Activation + +For system applications, the widget provider can use APIs to switch widget states. The active duration is not strictly limited, which means a widget can remain active for a long time. You can call [formProvider.activateSceneAnimation](../reference/apis-form-kit/js-apis-app-form-formProvider-sys.md#activatesceneanimation20) and [formProvider.deactivateSceneAnimation](../reference/apis-form-kit/js-apis-app-form-formProvider-sys.md#deactivatesceneanimation20) to activate and deactivate a widget. +After the widget is activated by calling **formProvider.activateSceneAnimation**, the rendering area of the widget animation is the same as that of the widget itself, and the [formProvider.requestOverflow](../reference/apis-form-kit/js-apis-app-form-formProvider.md#formproviderrequestoverflow20) API cannot be called to request animation. + +### How to Develop +1. Import modules. + +```ts +import { formProvider } from '@kit.FormKit'; +import { BusinessError } from '@kit.BasicServicesKit'; +``` + +2. Trigger long-time widget activation. + +```ts +let formId: string = '12400633174999288'; + +try { + formProvider.activateSceneAnimation(formId).then(() => { + console.info('activateSceneAnimation succeed.'); + }).catch((error: BusinessError) => { + console.error(`promise error, code: ${error.code}, message: ${error.message})`); + }); +} catch (error) { + console.error(`catch error, code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message})`); +} +``` + +3. Deactivate the widget. + +```ts +let formId: string = '12400633174999288'; + +try { + formProvider.deactivateSceneAnimation(formId).then(() => { + console.info('deactivateSceneAnimation succeed.'); + }).catch((error: BusinessError) => { + console.error(`promise error, code: ${error.code}, message: ${error.message})`); + }); +} catch (error) { + console.error(`catch error, code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message})`); +} +``` + +4. Adapt LiveFormExtensionAbility. + +To allow the widget provider to accurately control widget state switching and prevent delays caused by complex UI loading, the widget provider should notify the widget host via **session** when transitioning to the active state. After receiving the notification, the widget host starts to load the activated widget UI. + +```ts +// entry/src/main/ets/mysystemliveformextensionability/MySystemLiveFormExtensionAbility.ets +import { formInfo, LiveFormInfo, LiveFormExtensionAbility } from '@kit.FormKit'; +import { UIExtensionContentSession } from '@kit.AbilityKit'; + +export default class MySystemLiveFormExtensionAbility extends LiveFormExtensionAbility { + onLiveFormCreate(liveFormInfo: LiveFormInfo, session: UIExtensionContentSession) { + let storage: LocalStorage = new LocalStorage(); + storage.setOrCreate('session', session); + + // Obtain the widget information. + let formId: string = liveFormInfo.formId as string; + storage.setOrCreate('formId', formId); + let formRect: formInfo.Rect = liveFormInfo.rect; + storage.setOrCreate('formRect', formRect); + let borderRadius: number = liveFormInfo.borderRadius; + storage.setOrCreate('borderRadius', borderRadius); + console.log(`MySystemLiveFormExtensionAbility onSessionCreate formId: ${formId}, borderRadius: ${borderRadius}` + + `, formRect: ${JSON.stringify(formRect)}`); + + // Load the provider page. + session.loadContent('mysystemliveformextensionability/pages/MySystemLiveFormPage', storage); + + // The widget provider needs to notify the widget host via session when the activated page is ready. + session.sendData({['isFormReady']: true}); + } + + onLiveFormDestroy(liveFormInfo: LiveFormInfo) { + console.log(`MySystemLiveFormExtensionAbility onDestroy`); + } +} +``` diff --git a/en/application-dev/form/arkts-ui-liveform-sceneanimation-development.md b/en/application-dev/form/arkts-ui-liveform-sceneanimation-development.md new file mode 100644 index 0000000000000000000000000000000000000000..2c0a94cf68805e426d450f36f41dac46b854c55e --- /dev/null +++ b/en/application-dev/form/arkts-ui-liveform-sceneanimation-development.md @@ -0,0 +1,397 @@ +# Developing a Scene-based Widget + +This document describes the development of a scene-based widget, covering the UI for both inactive and active states, as well as the configuration file. + +## Available APIs + +The following table lists the key APIs for a scene-based widget. + +**Table 1** Main APIs + +| API | Description | +|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------| +| [onLiveFormCreate(liveFormInfo: LiveFormInfo, session: UIExtensionContentSession): void](../reference/apis-form-kit/js-apis-app-form-LiveFormExtensionAbility.md#onliveformcreate) | Called when a widget UI object is created. | +| [onLiveFormDestroy(liveFormInfo: LiveFormInfo): void](../reference/apis-form-kit/js-apis-app-form-LiveFormExtensionAbility.md#onliveformdestroy) | Called when a widget UI object is destroyed and related resources are cleared. | +| [formProvider.requestOverflow(formId: string, overflowInfo: formInfo.OverflowInfo): Promise<void>](../reference/apis-form-kit/js-apis-app-form-formProvider.md#formproviderrequestoverflow20) | Called by the widget provider to request interactive widget animations. | +| [formProvider.cancelOverflow(formId: string): Promise<void>](../reference/apis-form-kit/js-apis-app-form-formProvider.md#formprovidercanceloverflow20) | Called by the widget provider to cancel interactive widget animations.| + +## How to Develop + +### Widget UI in Active State + +1. Create an interactive widget. + + Create an interactive widget through [LiveFormExtensionAbility](../reference/apis-form-kit/js-apis-app-form-LiveFormExtensionAbility.md) and load the widget page. + ```ts + // entry/src/main/ets/myliveformextensionability/MyLiveFormExtensionAbility.ets + import { formInfo, LiveFormInfo, LiveFormExtensionAbility } from '@kit.FormKit'; + import { UIExtensionContentSession } from '@kit.AbilityKit'; + + export default class MyLiveFormExtensionAbility extends LiveFormExtensionAbility { + onLiveFormCreate(liveFormInfo: LiveFormInfo, session: UIExtensionContentSession) { + let storage: LocalStorage = new LocalStorage(); + storage.setOrCreate('session', session); + + // Obtain widget information. + let formId: string = liveFormInfo.formId; + storage.setOrCreate('formId', formId); + let formRect: formInfo.Rect = liveFormInfo.rect; + storage.setOrCreate('formRect', formRect); + let borderRadius: number = liveFormInfo.borderRadius; + storage.setOrCreate('borderRadius', borderRadius); + console.log(`MyLiveFormExtensionAbility onSessionCreate formId: ${formId}, borderRadius: ${borderRadius}` + + `, formRect: ${JSON.stringify(formRect)}`); + + // Load the interactive page. + session.loadContent('myliveformextensionability/pages/MyLiveFormPage', storage); + } + + onLiveFormDestroy(liveFormInfo: LiveFormInfo) { + console.log(`MyLiveFormExtensionAbility onDestroy`); + } + }; + ``` + +2. Implement an interactive widget page. + ```ts + // entry/src/main/ets/myliveformextensionability/pages/MyLiveFormPage.ets + import { formInfo, formProvider } from '@kit.FormKit'; + import { Constants } from '../../common/Constants'; + + const ANIMATION_RECT_SIZE: number = 100; + const END_SCALE: number = 1.5; + const END_TRANSLATE: number = -300; + + @Entry + @Component + struct MyLiveFormPage { + @State columnScale: number = 1.0; + @State columnTranslate: number = 0.0; + + private uiContext: UIContext | undefined = undefined; + private storageForMyLiveFormPage: LocalStorage | undefined = undefined; + private formId: string | undefined = undefined; + private formRect: formInfo.Rect | undefined = undefined; + private formBorderRadius: number | undefined = undefined; + + aboutToAppear(): void { + this.uiContext = this.getUIContext(); + if (!this.uiContext) { + console.warn("no uiContext"); + return; + } + this.initParams(); + } + + private initParams(): void { + this.storageForMyLiveFormPage = this.uiContext?.getSharedLocalStorage(); + this.formId = this.storageForMyLiveFormPage?.get('formId'); + this.formRect = this.storageForMyLiveFormPage?.get('formRect'); + this.formBorderRadius = this.storageForMyLiveFormPage?.get('borderRadius'); + } + + // Execute the animation. + private runAnimation(): void { + this.uiContext?.animateTo({ + duration: Constants.OVERFLOW_DURATION, + curve: Curve.Ease + }, () => { + this.columnScale = END_SCALE; + this.columnTranslate = END_TRANSLATE; + }); + } + + build() { + Stack() { + // Background component, whose size is the same as that of a common widget. + Column() + .width(this.formRect ? this.formRect.width : 0) + .height(this.formRect ? this.formRect.height : 0) + .borderRadius(this.formBorderRadius ? this.formBorderRadius : 0) + .backgroundColor('#2875F5') + + Stack() + .width(ANIMATION_RECT_SIZE) + .height(ANIMATION_RECT_SIZE) + .backgroundColor(Color.White) + .scale({ + x: this.columnScale, + y: this.columnScale, + }) + .translate({ + y: this.columnTranslate + }) + .onAppear(() => { + // Execute the animation when the page is displayed. + this.runAnimation(); + }) + + // Tap the button to call the formProvider.cancelOverflow API to interrupt the current overflow animation and switch the widget to the inactive state. + Button('Cancel the animation forcibly') + .backgroundColor(Color.Grey) + .onClick(() => { + if (!this.formId) { + console.log('MyLiveFormPage formId is empty, cancel overflow failed'); + return; + } + console.log('MyLiveFormPage cancel overflow animation'); + formProvider.cancelOverflow(this.formId); + }) + } + .width('100%') + .height('100%') + } + } + ``` + +3. Configure LiveFormExtensionAbility for interactive widgets. + + Configure LiveFormExtensionAbility in [extensionAbilities](../quick-start/module-configuration-file.md#extensionabilities) of the **module.json5** file. + ```ts + // entry/src/main/module.json5 + ... + "extensionAbilities": [ + { + "name": "MyLiveFormExtensionAbility", + "srcEntry": "./ets/myliveformextensionability/MyLiveFormExtensionAbility.ets", + "description": "MyLiveFormExtensionAbility", + "type": "liveForm" + } + ] + ... + ``` + + At the same time, declare the interactive widget page in the **main_pages.json** file. + + ```ts + // entry/src/main/resources/base/profile/main_pages.json + { + "src": [ + "pages/Index", + "myliveformextensionability/pages/MyLiveFormPage" + ] + } + ``` + +### Widget UI in Inactive State + +1. Implement a widget page in the inactive state. + + The page development process of a widget in the inactive state is the same as that of a common widget and is completed in **widgetCard.ets**, which is automatically generated when a widget is created. For details about the widget creation process, see [Creating an ArkTS Widget](arkts-ui-widget-creation.md). On the inactive widget page, request the widget animation when the widget is tapped. + ```ts + // entry/src/main/ets/widget/pages/WidgetCard.ets + @Entry + @Component + struct WidgetCard { + build() { + Row() { + Column() { + Text('Tap to trigger interactive widget animation') + .fontSize($r('app.float.font_size')) + .fontWeight(FontWeight.Medium) + .fontColor($r('sys.color.font_primary')) + } + .width('100%') + } + .height('100%') + .onClick(() => { + // When a widget is tapped, send a message to EntryFormAbility and call formProvider.requestOverflow in the onFormEvent callback to request the widget animation. + postCardAction(this, { + action: 'message', + abilityName: 'EntryFormAbility', + params: { + message: 'requestOverflow' + } + }); + }) + } + } + ``` + +2. Configure the **form_config.json** file. + + Add the **sceneAnimationParams** configuration item to the **form_config.json** file. + ```ts + // entry/src/main/resources/base/profile/form_config.json + { + "forms": [ + { + "name": "widget", + "displayName": "$string:widget_display_name", + "description": "$string:widget_desc", + "src": "./ets/widget/pages/WidgetCard.ets", + "uiSyntax": "arkts", + "window": { + "designWidth": 720, + "autoDesignWidth": true + }, + "colorMode": "auto", + "isDefault": true, + "updateEnabled": true, + "scheduledUpdateTime": "10:30", + "updateDuration": 1, + "defaultDimension": "2*2", + "supportDimensions": [ + "2*2" + ], + "formConfigAbility": "ability://EntryAbility", + "dataProxyEnabled": false, + "isDynamic": true, + "transparencyEnabled": false, + "metadata": [], + "sceneAnimationParams": { + "abilityName": "MyLiveFormExtensionAbility" + } + } + ] + } + ``` + +### Interactive Widget Animation + +1. Trigger interactive widget animations. + + When adding a widget to the home screen, the interactive widget can obtain the actual widget dimension through the **wantParams** parameter in the [onUpdateForm](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md#formextensionabilityonupdateform) lifecycle callback. The widget provider calculates the animation request range based on this dimension, in vp. For details about the calculation rules, see the [constraints on widget parameter request](arkts-ui-liveform-sceneanimation-overview.md#parameter-request). + ```ts + // entry/src/main/ets/entryformability/EntryFormAbility.ets + import { + formInfo, + formProvider, + FormExtensionAbility, + } from '@kit.FormKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + import { preferences } from '@kit.ArkData'; + import { Constants } from '../common/Constants'; + import { Utils } from '../common/Utils'; + + const DB_NAME: string = 'myStore' + + export default class EntryFormAbility extends FormExtensionAbility { + onUpdateForm(formId: string, wantParams?: Record) { + // When a widget is added to the home screen, the **wantParams** is not empty and will provide the widget dimension information. + if (wantParams) { + this.saveFormSize(formId, wantParams); + } + } + + // Parse the dimension of the widget and save it to the database. + private saveFormSize(formId: string, wantParams: Record) { + let width = 0; + let height = 0; + width = wantParams['ohos.extra.param.key.form_width_vp'] as number; + height = wantParams['ohos.extra.param.key.form_height_vp'] as number; + console.log(`onUpdateForm, formId: ${formId}, size:[${width}, ${height}]`); + let promise: Promise = preferences.getPreferences(this.context, DB_NAME); + + // Write the dimension to the database. + Utils.writeFormSize(promise, formId, width, height); + } + + // Read the dimension from the database. + private async getFormSize(formId: string): Promise { + let storeDB: preferences.Preferences = await preferences.getPreferences(this.context, DB_NAME); + let formCardInfo: string[] = await Utils.readFormSize(formId, storeDB); + return [Number.parseFloat(formCardInfo[0]), Number.parseFloat(formCardInfo[1])]; + } + + async onFormEvent(formId: string, message: string) { + let shortMessage: string = JSON.parse(message)['message']; + + // Trigger the interactive widget animation when the received message is requestOverflow. + if (shortMessage === 'requestOverflow') { + let sizeInfo = await this.getFormSize(formId); + this.requestOverflow(formId, sizeInfo[0], sizeInfo[1]); + return; + } + } + + private requestOverflow(formId: string, formWidth: number, formHeight: number): void { + if (formWidth <= 0 || formHeight <= 0) { + console.log('requestOverflow failed, form size is not correct.'); + return; + } + + // Calculate the animation rendering area of the widget based on the dimension. + let left: number = -Constants.OVERFLOW_LEFT_RATIO * formWidth; + let top: number = -Constants.OVERFLOW_TOP_RATIO * formHeight; + let width: number = Constants.OVERFLOW_WIDTH_RATIO * formWidth; + let height: number = Constants.OVERFLOW_HEIGHT_RATIO * formHeight; + let duration: number = Constants.OVERFLOW_DURATION; + + // Request an interactive widget animation. + try { + formProvider.requestOverflow(formId, { + area: { left: left, top: top, width: width, height: height }, + duration: duration + }).then(() => { + console.log('requestOverflow requestOverflow succeed'); + }).catch((error: BusinessError) => { + console.log(`requestOverflow requestOverflow catch error` + `, code: ${error.code}, message: ${error.message}`); + }) + } catch (e) { + console.log(`requestOverflow call requestOverflow catch error` + `, code: ${e.code}, message: ${e.message}`); + } + } + } + ``` + +2. Implement the tool functions of the interactive widget animation. + + ```ts + // entry/src/main/ets/common/Utils.ets + import { preferences } from '@kit.ArkData'; + import { BusinessError } from '@kit.BasicServicesKit'; + + export class Utils { + // Write the widget dimension to the database. + public static writeFormSize(promise: Promise, formId: string, width: number, + height: number): void { + promise.then(async (storeDB: preferences.Preferences) => { + console.log('writeCardInfoSizeToDB, Succeeded to get preferences.'); + await storeDB.put('width_' + formId, `${width}`); + await storeDB.put('height_' + formId, `${height}`); + await storeDB.flush(); + }).catch((err: BusinessError) => { + console.log(`writeCardInfoSizeToDB, Failed to get preferences. ${JSON.stringify(err)}`); + }); + } + + // Read widget information from the database. + public static async readFormSize(formId: string, storeDB: preferences.Preferences): Promise { + try { + let widthInfo = await storeDB.get('width_' + formId, '-1'); + let heightInfo = await storeDB.get('height_' + formId, '-1'); + console.log(`Succeeded to get cardInfo: ${widthInfo}, ${heightInfo}`); + return [widthInfo.toString(), heightInfo.toString()]; + } catch(err) { + console.log(`Failed to get preferences. ${JSON.stringify(err)}`); + return ['']; + } + } + } + ``` + + ```ts + // entry/src/main/ets/common/Constants.ets + // Develop animation-related constants. + export class Constants { + // The interactive widget animation is out of range. Left offset percentage = Offset value/Widget width + public static readonly OVERFLOW_LEFT_RATIO: number = 0.1; + + // The interactive widget animation is out of range. Top offset percentage = Offset value/Widget height + public static readonly OVERFLOW_TOP_RATIO: number = 0.15; + + // The interactive widget animation is out of range. The width is enlarged by percentage. + public static readonly OVERFLOW_WIDTH_RATIO: number = 1.2; + + // The interactive widget animation is out of range. The height is enlarged by percentage. + public static readonly OVERFLOW_HEIGHT_RATIO: number = 1.3; + + // The interactive widget animation is out of range. Specify the animation duration. + public static readonly OVERFLOW_DURATION: number = 3500; + } + ``` + +## Effect +The following is a demo developed based on the code examples in this document. When the demo is executed, the [formProvider.cancelOverflow](../reference/apis-form-kit/js-apis-app-form-formProvider.md#formprovidercanceloverflow20) API is called to interrupt the current overflow animation and the widget is switched to the inactive state. +![live-form-base-demo.gif](figures/live-form-base-demo.gif) diff --git a/en/application-dev/form/arkts-ui-liveform-sceneanimation-overview.md b/en/application-dev/form/arkts-ui-liveform-sceneanimation-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..9659c12019edefd20825ea9b2d1352a8aba8fdc0 --- /dev/null +++ b/en/application-dev/form/arkts-ui-liveform-sceneanimation-overview.md @@ -0,0 +1,73 @@ +# Overview of Scene-based Widgets + +Scene-based widgets support special effects. For example, you can choose to render the animation beyond the widget rendering area to create an "overflow" effect. + +## Basic Concepts + +A scene-based widget can be in either active state or inactive state. The widget animation can be triggered when the widget is first added to the home screen, when the widget data is interval-based or time-specific updated, or when users interact with the widget (for instance, by tapping). The widget switches to the active state when the animation starts and reverts to the inactive state once the animation ends. + +**Inactive state**: The widget is like a common widget and complies with the existing widget development specifications. The widget UI is carried by the content in **widgetCard.ets** of the widget provider. + +**Active state**: The interactive widget is rendered. The widget UI is rendered on the page of the [LiveFormExtensionAbility](../reference/apis-form-kit/js-apis-app-form-LiveFormExtensionAbility.md) developed by the widget provider. For details, see [Developing a Scene-based Widget](arkts-ui-liveform-sceneanimation-development.md). + +**Figure 1** Switching interactive widget states + +![live-form-status-change.png](figures/live-form-status-change.png) + +**Figure 2** Process of triggering an interactive widget animation + +![live-form-judge.PNG](figures/live-form-judge.PNG) + +## How to Implement + +You can call the [formProvider.requestOverflow](../reference/apis-form-kit/js-apis-app-form-formProvider.md#formproviderrequestoverflow20) API to trigger animations on interactive widgets, for example, when a user taps the widget. The typical timing diagram is as follows. + +**Figure 3** Timing diagram of animations triggered by a tap + +![live-form-click-timeline.png](figures/live-form-click-timeline.png) + +The following figure shows the timing diagram in interval-based and time-specific updates. + +**Figure 4** Timing diagram of animations triggered by interval-based and time-specific updates + +![live-form-update-timeline.png](figures/live-form-update-timeline.png) + +## Constraints + +### Parameter Request +1. The maximum valid duration of the overflow animation is 3500 ms. When the countdown ends, the widget switches back to the inactive state. This applies only to third-party applications. +2. A single widget's animation triggered by interval-based and time-specific updates can occur up to 50 times a day. +3. As illustrated, rectangle ABCD denotes the widget's rendering area, whereas rectangle IJKL indicates the maximum animation area the widget can request. The centers of the two rectangles are aligned. The dimensions meet the requirements described in the following table. + +| Dimension | Length of JK| Length of IJ| +|-------|---------------|---------------| +| 1 * 2 | No greater than 150% of the length of AD.| No greater than 200% of the length of AB.| +| 2 * 2 | No greater than 150% of the length of AD.| No greater than 150% of the length of AB.| +| 2 * 4 | No greater than 125% of the length of AD.| No greater than 150% of the length of AB.| +| 4 * 4 | No greater than 125% of the length of AD.| No greater than 125% of the length of AB.| +| 6 * 4 | No greater than 125% of the length of AD.| No greater than 110% of the length of AB.| + +**Figure 5** Rules for requesting the animation area + +![live-form-overflow-rule.png](figures/live-form-overflow-rule.png) + +Example: On a device, a 2×2 widget measures 158vp × 158vp. Referring to the figure above: +1. AD = 158vp, AB = 158vp, IJ = 158 × 1.5 = 237vp, IL = 158 × 1.5 = 237vp +2. Points I and A are horizontally 39.5vp apart and vertically 39.5vp apart. + +Thus, with A as the origin (X-axis positive to the right, Y-axis positive downward), the valid coordinates for point E in Figure 5 can be (-20, -20). The valid lengths for sides EF and EH can both be 200vp. + +When adding a widget to the home screen, the interactive widget can obtain the actual widget dimension through the **wantParams** parameter in the [onUpdateForm](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md#formextensionabilityonupdateform) lifecycle callback. The widget provider calculates the animation request range based on this dimension. For coordinate calculations, point A in the figure is used as the origin (0,0), and the parameters corresponding to rectangle EFGH are calculated, with units in vp. + +When [formProvider.requestOverflow](../reference/apis-form-kit/js-apis-app-form-formProvider.md#formproviderrequestoverflow20) is called, the animation rendering area (rectangle EFGH) described in [overflowInfo](../reference/apis-form-kit/js-apis-app-form-formInfo.md#overflowinfo20) must meet the following requirements: +1. It completely contains the widget (rectangle ABCD). +2. It does not exceed rectangle IJKL (rectangle IJKL completely contains rectangle EFGH). This applies only to third-party applications. + +For details, see [Developing a Scene-based Widget](arkts-ui-liveform-sceneanimation-development.md). + +### Animation Request +1. At a time, only one widget executes the scene animation. +2. When a user actively triggers an animation effect through actions like tapping, the system prioritizes this request. In this case, the current widget is switched to the active state to execute the animation, and other widgets are forcibly switched to the inactive state. +3. Other triggering modes, for example, triggering an animation via interval-based or time-specific update, are based on the first-come, first-served principle. The system processes only the first valid animation request. Other requests return failure and no cache is performed. +4. Other valid operations (such as tapping an application or widget, swiping pages, pulling down to access full search, dual-center, dragging a widget, and long pressing a widget) on the home screen will interrupt the current animation, and the widget will become inactive again. System applications can suspend some operations on the home screen by configuring the suspend gesture. For details, see [Developing a Scene-based Widget (for System Applications)](arkts-ui-liveform-sceneanimation-development-sys.md). +5. The interactive widget does not respond to the events that exceed the animation rendering area (rectangle ABCD in Figure 5). diff --git a/en/application-dev/form/arkts-ui-widget-active-refresh.md b/en/application-dev/form/arkts-ui-widget-active-refresh.md new file mode 100644 index 0000000000000000000000000000000000000000..a02478472bcef09609fee2b32c82a059092fe10b --- /dev/null +++ b/en/application-dev/form/arkts-ui-widget-active-refresh.md @@ -0,0 +1,91 @@ +# Active Update of ArkTS Widgets + +This section provides the development guidelines for active update. For details about the update process, see [Active Update](./arkts-ui-widget-interaction-overview.md#active-update). + +## Active Update by Widget Provider + +The widget provider can call [updateForm](../reference/apis-form-kit/js-apis-app-form-formProvider.md#formproviderupdateform) to actively update the widget. It is recommended that this API be used with the widget lifecycle callbacks [onFormEvent](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md#formextensionabilityonformevent), [onUpdateForm](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md#formextensionabilityonupdateform), and [onAddForm](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md#formextensionabilityonaddform). + +```ts +import { formBindingData, formProvider } from '@kit.FormKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +let storage = new LocalStorage(); +const TAG: string = 'Index'; +const DOMAIN_NUMBER: number = 0xFF00; + +@Entry(storage) +@Component +struct Index { + @StorageLink('formId') formId: number = 0; + @StorageLink('formData') formData: Object | string = {}; + + build() { + Column() { + Column() { + //... + Button() { + //... + } + .onClick(() => { + console.info(DOMAIN_NUMBER, TAG, `click to check updateForm, formId: ${this.formId}`); + const formInfo: formBindingData.FormBindingData = formBindingData.createFormBindingData(this.formData); + // formId is the ID of the widget to be updated. + formProvider.updateForm(this.formId, formInfo).then(() => { + console.info(DOMAIN_NUMBER, TAG, 'updateForm success.'); + }).catch((error: BusinessError) => { + console.error(DOMAIN_NUMBER, TAG, `updateForm fail, code: ${error?.code}, message: ${error?.message}`); + }) + }) + .margin(5) + } + //... + } + //... + } +} +``` + + +## Active Update by Widget Host (for System Applications Only) + +Due to the time limit of interval-based and time-specific updates, the widget host can call [requestForm](../reference/apis-form-kit/js-apis-app-form-formHost-sys.md#requestform) to request the Widget Manager to actively update the widget. The Widget Manager calls the [onUpdateForm](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md#formextensionabilityonupdateform) lifecycle callback in the FormExtensionAbility of the widget provider. In the callback, the [updateForm](../reference/apis-form-kit/js-apis-app-form-formProvider.md#formproviderupdateform) API can be called to update the widget content. + +```ts +import { formHost } from '@kit.FormKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +let storage = new LocalStorage(); +const TAG: string = 'Index'; +const DOMAIN_NUMBER: number = 0xFF00; + +@Entry(storage) +@Component +struct Index { + @StorageLink('formId') formId: number = 0; + + build() { + Column() { + Column() { + //... + Button() { + //... + } + .onClick(() => { + console.info(DOMAIN_NUMBER, TAG, `click to check requestForm, formId: ${this.formId}`); + // formId is the ID of the widget to be updated. + formHost.requestForm(this.formId.toString()).then(() => { + console.info(DOMAIN_NUMBER, TAG, 'requestForm success.'); + }).catch((error: BusinessError) => { + console.error(DOMAIN_NUMBER, TAG, `requestForm fail, code: ${error?.code}, message: ${error?.message}`); + }) + }) + .margin(5) + } + //... + } + //... + } +} +``` + diff --git a/en/application-dev/form/arkts-ui-widget-configuration.md b/en/application-dev/form/arkts-ui-widget-configuration.md index e74b5752eb44320f7baaa1dbe503de020d802244..b63fe614d04da69572e9f3211d1f71309bfe48b6 100644 --- a/en/application-dev/form/arkts-ui-widget-configuration.md +++ b/en/application-dev/form/arkts-ui-widget-configuration.md @@ -1,10 +1,11 @@ -# Configuring Widget Configuration Files +# Configuring ArkTS Widget Configuration Files -Widget-related configuration includes **FormExtensionAbility** configuration and widget configuration. +Widget-related configuration includes [FormExtensionAbility](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md) configuration and widget configuration. +## FormExtensionAbility Configuration -1. Configure FormExtensionAbility information under **extensionAbilities** in the [module.json5 file](../quick-start/module-configuration-file.md). For a FormExtensionAbility, you must specify **metadata**. Specifically, set **name** to **ohos.extension.form** (fixed), and set **resource** to the index of the widget configuration information. +Configure FormExtensionAbility information under **extensionAbilities** in the [module.json5 file](../quick-start/module-configuration-file.md). For a FormExtensionAbility, you must specify metadata. Specifically, set **name** to **ohos.extension.form** (fixed), and set **resource** to the [index of the widget configuration information](#widget-configuration). Example configuration: @@ -31,8 +32,11 @@ Widget-related configuration includes **FormExtensionAbility** configuration and } } ``` +## Widget Configuration -2. Configure the widget configuration information. In the **metadata** configuration item of FormExtensionAbility, you can specify the resource index of specific configuration information of the widget. For example, if **resource** is set to **$profile:form_config**, **form_config.json** in the **resources/base/profile/** directory of the development view is used as the profile configuration file of the widget. The following table describes the internal structure of the profile configuration file. +In the **metadata** configuration item of FormExtensionAbility, you can specify the resource index of specific configuration information of the widget. For example, if **resource** is set to **$profile:form_config**, **form_config.json** in the **resources/base/profile/** directory of the development view is used as the profile configuration file of the widget. The **form_config.json** configuration file is automatically generated when you [create a widget](./arkts-ui-widget-creation.md). + +### Fields in Configuration File **Table 1** form_config.json file @@ -40,33 +44,35 @@ Widget-related configuration includes **FormExtensionAbility** configuration and | -------- | -------- | -------- | -------- | | forms | Configuration about all application widgets.
A maximum of 16 widgets can be configured. If more than 16 widgets are configured, the first 16 widgets are retained.| Array| No| | name | Name of the widget. The value is a string with a maximum of 127 bytes.| String| No| - | displayName | Display name of the widget. The value can be a string or a resource index to the name in multiple languages. The string must contain 1 to 30 bytes.| String| No| - | description | Description of the widget. The value can be a string or a resource index to descriptions in multiple languages. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| + | displayName | Display name of the widget. It is primarily displayed on the widget management page and should reflect the core functionalities or usage of the widget. The value can be a string or a resource index to the name in multiple languages, with the resource index recommended. The string must contain 1 to 30 bytes.| String| No| + | description | Description of the widget. It is displayed on the widget management page and should reflect the core functionalities of the widget. The value can be a string or a resource index to the name in multiple languages, with the resource index recommended. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| | src | Full path of the UI code corresponding to the widget. For an ArkTS widget, the full path must contain the widget file name extension, for example, **./ets/widget/pages/WidgetCard.ets**. For a JS widget, the full path does not need to contain the widget file name extension, for example, **./js/widget/pages/WidgetCard**.| String| No| | uiSyntax | Type of the widget.
- **arkts**: ArkTS widget
- **hml**: JS widget| String| Yes (initial value: **hml**)| - | [window](#window-field)| Window-related configurations.| Object| Yes (initial value: see Table 2)| + | [window](#window-field)| Window-related configurations.
**NOTE**
This field takes effect only for JS widgets.| Object| Yes (initial value: see Table 2)| | isDefault | Whether the widget is a default one. Each UIAbility has only one default widget.
- **true**: The widget is the default one.
- **false**: The widget is not the default one.| Boolean| No| - | colorMode | Color mode of the widget.
- **auto**: following the system color mode
- **dark**: dark color mode
- **light**: light color mode| String| Yes (initial value: **auto**)| - | supportDimensions | Grid styles supported by the widget.
- **1 * 2**: indicates a grid with one row and two columns.
- **2 * 2**: indicates a grid with two rows and two columns.
- **2 * 4**: indicates a grid with two rows and four columns.
- **4 * 4**: indicates a grid with four rows and four columns.
- **1 * 1**: indicates a round widget with one row and one column.
- **6 * 4**: indicates a grid with six rows and four columns.| String array| No| + | colorMode(deprecated) | Color mode of the widget.
- **auto**: following the system color mode
- **dark**: dark color mode
- **light**: light color mode
**NOTE**
This API is deprecated since API version 20. The color mode follows the system color mode.| String| Yes (initial value: **auto**)| + | supportDimensions | Grid styles supported by the widget.
- **1 * 2**: indicates a grid with one row and two columns.
- **2 * 2**: indicates a grid with two rows and two columns.
- **2 * 4**: indicates a grid with two rows and four columns.
- **4 * 4**: indicates a grid with four rows and four columns.
- **1 * 1**: round widget with one row and one column. This value is configurable only for system applications and takes effect only when the screen is locked.
- **6 * 4**: indicates a grid with six rows and four columns.| String array| No| | defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String| No| | updateEnabled | Whether the widget can be updated periodically.
- **true**: The widget can be updated at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.
- **false**: The widget cannot be updated periodically.| Boolean| No| | scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute.
**NOTE**
**updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| String| Yes (initial value: The widget is not updated at the scheduled time.)| | updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.
If the value is **0**, this field does not take effect.
If the value is a positive integer *N*, the interval is calculated by multiplying *N* and 30 minutes.
**NOTE**
**updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| Number| Yes (initial value: **0**)| | formConfigAbility | Link to a specific page of the application. The value is a URI.| String| Yes (initial value: left empty)| | metadata | Metadata of the widget. For details, see [Metadata](../reference/apis-ability-kit/js-apis-bundleManager-metadata.md).| Object| Yes (initial value: left empty)| - | dataProxyEnabled | Whether the widget supports the update-through-proxy feature.
- **true**: The widget supports the update-through-proxy feature.
- **false**: The widget does not support the update-through-proxy feature.
If this tag is set to **true**, [the settings for the scheduled update time will still take effect, but the settings for the update interval and next update time will not](./arkts-ui-widget-update-by-time.md).| Boolean| Yes (initial value: **false**)| - | [isDynamic](#isdynamic-field)| Whether the widget is a dynamic widget. This tag applies only to ArkTS widgets.
- **true**: The widget is a dynamic widget.
- **false**: The widget is a static widget.
| Boolean| Yes (initial value: **true**)| + | dataProxyEnabled | Whether the widget supports the [update-through-proxy](./arkts-ui-widget-update-by-proxy.md) feature.
- **true**: The widget supports the update-through-proxy feature.
- **false**: The widget does not support the update-through-proxy feature.
If it is set to **true**, the settings for the [interval-based update and next update](./arkts-ui-widget-passive-refresh.md#interval-based-update) will not take effect, and [Time-specific Update](./arkts-ui-widget-passive-refresh.md#time-specific-update) is not affected.| Boolean| Yes (initial value: **false**)| + | [isDynamic](#isdynamic-field)| Whether the widget is a dynamic widget. This field applies only to ArkTS widgets.
- **true**: The widget is a dynamic widget.
- **false**: The widget is a static widget.
| Boolean| Yes (initial value: **true**)| | fontScaleFollowSystem | Whether the font size of the widget changes with the system font size.
- **true**: The font size varies with the system font size.
- **false**: The font size cannot change with the system font size.
| Boolean| Yes (initial value: **true**)| - | supportShapes | Shapes that the widget can be displayed. The options are as follows:
- **rect**: square widget.
- **circle**: circular widget.| String| Yes (initial value: **rect**)| + | supportShapes | Shapes that the widget can be displayed. The options are as follows:
- **rect**: rectangular widget.
- **circle**: circular widget.| String array| Yes (initial value: **rect**)| | previewImages | Preview images of the widget, corresponding to the **supportDimensions** parameter.| String| Yes (mandatory for smart wearables and currently valid only for wearables)| - | formVisibleNotify | Whether the widget is allowed to use the widget visibility notification. This parameter is valid only for widgets of system applications.| Boolean| Yes (initial value: **false**)| - | transparencyEnabled | Whether the widget host is allowed to set the background transparency of the widget. This tag applies only to ArkTS widgets.
- **true**: The widget host is allowed to set the background transparency of the widget.
- **false**: The widget host is not allowed to set the background transparency of the widget.
| Boolean| Yes (initial value: **false**)| + | formVisibleNotify | Whether to notify the widget provider of the visible status change. This field is valid only for widgets of system applications.
- **true**: The widget provider is notified of the status change.
- **false**: The widget provider is not notified of the status change.| Boolean| Yes (initial value: **false**)| + | transparencyEnabled | Whether the widget host is allowed to set the background transparency of the widget. This field applies only to ArkTS widgets.
- **true**: The widget host is allowed to set the background transparency of the widget.
- **false**: The widget host is not allowed to set the background transparency of the widget.
| Boolean| Yes (initial value: **false**)| |enableBlurBackground|Whether a blur background is enabled for the widget.
- **true**: A blur background is enabled.
- **false**: A blur background is disabled.|Boolean|Yes (initial value: **false**)| |renderingMode|Rendering mode of the widget.
- **autoColor**: automatic mode, where the widget is visible in both the lock screen widget center and the home screen widget center/widget management.
- **fullColor**: full-color mode, where the widget is visible in the home screen widget center/widget management.
- **singleColor**: monochrome mode, where the widget is visible in the lock screen widget center. |String|Yes (initial value: **fullColor**)| |multiScheduledUpdateTime|Times for updating the widget. As an additional parameter for single-point update, it follows the 24-hour format, precise to the minute. It allows up to 24 distinct times, with every two times separated by a comma (,).
**NOTE**
It must be used together with **scheduledUpdateTime**.|String|Yes (initial value: The widget is not updated at the scheduled times.)| - |conditionUpdate|Conditional update capabilities supported by the widget (valid only for ArkTS widgets of system applications).
- **network**: Network update is supported.|String|Yes (initial value: an empty string)| + |conditionUpdate|Conditional update capabilities supported by the widget (valid only for ArkTS widgets of system applications). The value can be:
- **network**: Network update is supported.|String|Yes (initial value: an empty string)| + |[funInteractionParams](#funinteractionparams-field)| Extended field of the fun-based widget.| Object| Yes (initial value: left empty) If **funInteractionParams** and **sceneAnimationParams** are both configured, the interactive widget is a fun-based widget.| + |[sceneAnimationParams](#sceneanimationparams-field)| Extended field of the scene-based widget.| Object| Yes (initial value: left empty) If **funInteractionParams** and **sceneAnimationParams** are both configured, the interactive widget is a fun-based widget.| -## isDynamic Field +### isDynamic Field Specifies whether the widget is a dynamic widget. It applies only to ArkTS widgets. @@ -75,7 +81,7 @@ Specifies whether the widget is a dynamic widget. It applies only to ArkTS widge | Static widget| Limited to UI components and layout capabilities.| Suitable for presenting static information (with a stable UI), allowing navigation to a specific UIAbility via the **FormLink** component.| Offers basic functionality with efficient memory management.| | Dynamic widget| Common event and custom animation capabilities in addition to UI components and layout capabilities.| Suitable for scenarios requiring complex logic and interactions, such as updating images or content on a widget.| Provides enhanced capabilities at the cost of high memory overhead.| -## window Field +### window Field Describes the internal structure of a window object. @@ -84,9 +90,50 @@ Describes the internal structure of a window object. | designWidth | Baseline width for page design. The size of an element is scaled by the actual device width.| Number| Yes (initial value: **720px**)| | autoDesignWidth | Whether to automatically calculate the baseline width for page design. If it is set to **true**, the **designWidth** attribute will be ignored, and the baseline width will be calculated based on the device width and screen density.| Boolean| Yes (initial value: **false**)| - Example configuration: +### funInteractionParams Field + +Specifies a fun-based widget. If **funInteractionParams** and **sceneAnimationParams** are both configured, the interactive widget is a fun-based widget. + +| Name | Type | Mandatory| Description | +|-------------------|-----|----|-------------------------------------------------------------------------------------------------------------------------------------| +| abilityName | String| No | LiveFormExtensionAbility name. This parameter is left empty by default. | +| targetBundleName | String| Yes | Main bundle name. | +| subBundleName | String| No | Sub bundle name.| +| keepStateDuration | Number | No | Duration of the activated state when there is no interaction. The default value is **10000**, in ms. The value should be an integer within the range [0, 10000]. If the value exceeds this range, it defaults to 10000 milliseconds. | + +### sceneAnimationParams Field +Specifies a scene-based widget. If **funInteractionParams** and **sceneAnimationParams** are both configured, the interactive widget is a fun-based widget. +| Name | Type | Mandatory| Description| +|---------------------------------------|--------|----|----------------------------| +| abilityName | String| Yes | extensionAbility name of the scene-based widget.| +| disabledDesktopBehaviors | String array| No | The options are **SWIPE_DESKTOP**, **PULL_DOWN_SEARCH**, **LONG_CLICK**, and **DRAG**. You can select one or more options. By default, no operation is disabled.| + + + ```json + { + "forms": [ + { + // ... + "sceneAnimationParams": { + "abilityName": "MyLiveFormExtensionAbility", + "disabledDesktopBehaviors": [ + "SWIPE_DESKTOP", + "PULL_DOWN_SEARCH", + "LONG_CLICK", + "DRAG" + ] + } + } + ] + } + ``` + + +### Configuration File Example + + ```json { "forms": [ @@ -100,7 +147,6 @@ Describes the internal structure of a window object. "designWidth": 720, "autoDesignWidth": true }, - "colorMode": "auto", "renderingMode": "fullColor", "isDefault": true, "updateEnabled": true, @@ -111,11 +157,14 @@ Describes the internal structure of a window object. "2*2" ], "formConfigAbility": "ability://EntryAbility", - "dataProxyEnabled": false, "isDynamic": true, - "transparencyEnabled": false, - "metadata": [] + "metadata": [], + "funInteractionParams": { + "targetBundleName": "com.example.funInteraction", + "subBundleName": "com.example.subFunInteraction" + } } ] } ``` + diff --git a/en/application-dev/form/arkts-ui-widget-creation.md b/en/application-dev/form/arkts-ui-widget-creation.md index 5378d2b21e31b7ea282d27eb79a9b3e4227f6133..a21d1c051820d6c0ca9b1799cd3d16565e1d0e5d 100644 --- a/en/application-dev/form/arkts-ui-widget-creation.md +++ b/en/application-dev/form/arkts-ui-widget-creation.md @@ -1,32 +1,50 @@ # Creating an ArkTS Widget - +## How to Create You can create a widget in either of the following modes: - When creating a project, select **Application**, and then right-click a module folder and choose **New** > **Service Widget** to create a widget. - When creating a project, select **Atomic Service**, and then right-click a module folder and choose **New** > **Service Widget** to create a widget. ![WidgetCreateProject](figures/WidgetCreateProject.png) - -> **NOTE** +>**NOTE** > -> The UI may be different in DevEco Studio of a different version. +>The UI may be different in DevEco Studio of a different version. To create an ArkTS widget in an existing project, perform the following steps: -1. Right-click a module folder and choose **New** > **Service Widget**. +1. Right-click a module folder and choose **New** > **Service Widget**. ![WidgetProjectCreate1](figures/WidgetProjectCreate1.png) -> **NOTE** +>**NOTE** > -> For a project developed using API version 10 or later based on the stage model, you can create a dynamic or static widget from the **Service Widget** menu. You can also change the widget type by setting the **isDynamic** parameter in the [form_config.json file](arkts-ui-widget-configuration.md) of the widget. If **isDynamic** is left unspecified or set to **true**, the widget is a [dynamic widget](./arkts-ui-widget-configuration.md#isdynamic-field). If **isDynamic** is set to **false**, the widget is a [static widget](./arkts-ui-widget-configuration.md#isdynamic-field). - -2. Select a widget template based on the actual service scenario. +>For a project developed using API version 10 or later based on the stage model, you can create a dynamic or static widget from the **Service Widget** menu. You can also change the widget type by setting the **isDynamic** parameter in the [form_config.json file](arkts-ui-widget-configuration.md) of the widget. If **isDynamic** is left unspecified or set to **true**, the widget is a [dynamic widget](./arkts-ui-widget-configuration.md#isdynamic-field). If **isDynamic** is set to **false**, the widget is a [static widget](./arkts-ui-widget-configuration.md#isdynamic-field). +2. Select a widget template based on the actual service scenario. ![WidgetProjectCreate2](figures/WidgetProjectCreate2.png) -3. Set **Language** to **ArkTS** and click **Finish**. - +3. Set **Language** to **ArkTS**, set **Support dimension** to the desired widget size, and then set **Default dimension** to the default widget dimension. You can refer to or modify the widget dimension in the [form_config.json](arkts-ui-widget-configuration.md) file. Then, you can click **Finish** to create an ArkTS widget. ![WidgetProjectCreate3](figures/WidgetProjectCreate3.png) - You are advised to name the widget based on the actual scenario. After an ArkTS widget is created, the following widget-related files are automatically added to the project directory: **EntryFormAbility.ets** (widget lifecycle management file), **WidgetCard.ets** (widget page file), and **form_config.json** (widget configuration file). - + You are advised to name the widget based on the actual scenario. After an ArkTS widget is created, the following widget-related files are automatically added to the project directory: **EntryFormAbility.ets** (widget lifecycle management file), **WidgetCard.ets** (widget page file), and **form_config.json** (widget configuration file). ![WidgetProjectView](figures/WidgetProjectView.png) +## Project Structure +**Figure 1** ArkTS widget project directory and related modules +![WidgetModules](figures/WidgetModules.png) + + +- [FormExtensionAbility](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md): provides lifecycle callbacks invoked when a widget is created, destroyed, or updated. + +- [FormExtensionContext](../reference/apis-form-kit/js-apis-inner-application-formExtensionContext.md): provides context for FormExtensionAbilities. You can use the APIs of this module to start FormExtensionAbilities. + +- [formProvider](../reference/apis-form-kit/js-apis-app-form-formProvider.md): provides capabilities such as obtaining widget information, updating widgets, and setting the widget update time. + +- [formInfo](../reference/apis-form-kit/js-apis-app-form-formInfo.md): provides types and enums related to the widget information and state. + +- [formBindingData](../reference/apis-form-kit/js-apis-app-form-formBindingData.md): provides APIs for widget data binding. You can use the APIs to create a **FormBindingData** object and obtain related information. + +- [Page layout (WidgetCard.ets)](arkts-ui-widget-page-overview.md): provides the widget UI development capability based on ArkUI. + - [General capabilities of ArkTS widgets](arkts-ui-widget-page-overview.md#page-capabilities-supported-by-arkts-widgets): provide components, attributes, and APIs that can be used in ArkTS widgets. + - [Capabilities exclusive to ArkTS widgets](arkts-ui-widget-event-overview.md): include the **postCardAction** API used for interaction between the widget internal and the provider application and can be called only in the widget. + +- [Widget configuration](arkts-ui-widget-configuration.md): includes FormExtensionAbility configuration and widget configuration. + - Configure the FormExtensionAbility information under **extensionAbilities** in the [module.json5 file](../quick-start/module-configuration-file.md). + - Configure the widget configuration information (**WidgetCard.ets**) in the [form_config.json](arkts-ui-widget-configuration.md) file in **resources/base/profile**. diff --git a/en/application-dev/form/arkts-ui-widget-event-call.md b/en/application-dev/form/arkts-ui-widget-event-call.md index 5670888140368057d4a4c43a1efe7ec7bfcdff0b..2cc922760d0b03ccba237ab1e37a5085c233509f 100644 --- a/en/application-dev/form/arkts-ui-widget-event-call.md +++ b/en/application-dev/form/arkts-ui-widget-event-call.md @@ -1,4 +1,4 @@ -# Launching the UIAbility of the Widget Provider in the Background Through the call Event +# Launching UIAbility to the Background (call Event) There may be cases you want to provide in a widget access to features available in your application running in the foreground, for example, the play, pause, and stop buttons in a music application widget. This is where the **call** capability of the [postCardAction](../reference/apis-arkui/js-apis-postCardAction.md#postcardaction) API comes in handy. This capability, when used in a widget, can start the specified UIAbility of the widget provider in the background. It also allows the widget to call the specified method of the application and transfer data so that the application, while in the background, can behave accordingly in response to touching of the buttons on the widget. @@ -10,70 +10,75 @@ There may be cases you want to provide in a widget access to features available ## How to Develop 1. Create a dynamic widget. - Create a dynamic widget named WidgetEventCallCardArkTs. + Create a dynamic widget named WidgetEventCall. 2. Implement page layout. - In this example, two buttons are laid out on the widget page. When one button is clicked, the **postCardAction** API is called to send a call event to the target UIAbility. Note that the **method** parameter in the API indicates the method to call in the target UIAbility. It is mandatory and of the string type. - ```ts - //src/main/ets/widgeteventcallcard/pages/WidgetEventCallCardCard.ets + In this example, two buttons (A and B) are laid out on the widget page. When one button is touched, the **postCardAction** API is called to send a call event to the target UIAbility, with the method to be called defined in the event. Button A and button B correspond to the funA and funB methods, respectively. The funA method carries the **formID** parameter, and the funB method carries the **formID** and **num** parameters. Pass parameters as required during development. In **postCardAction**, the **method** parameter is mandatory and identifies the name of the method to be invoked, which should match the method listened for by the UIAbility in step 3. Other parameters are optional. + ```ts + //src/main/ets/widgeteventcallcard/pages/WidgetEventCall.ets @Entry @Component - struct WidgetEventCallCard { + struct WidgetEventCall { @LocalStorageProp('formId') formId: string = '12400633174999288'; - + private funA: string = 'Button A'; + private funB: string = 'Button B'; + build() { - Column() { - //... - Row() { - Column() { - Button() { - //... + RelativeContainer() { + Button(this.funA) + .id('funA__') + .fontSize($r('app.float.page_text_font_size')) + .fontWeight(FontWeight.Bold) + .alignRules({ + center: { anchor: '__container__', align: VerticalAlign.Center }, + middle: { anchor: '__container__', align: HorizontalAlign.Center } + }) + .onClick(() => { + postCardAction(this, { + action: 'call', + // Only the UIAbility of the current application is allowed. The ability name must be the same as that defined in module.json5. + abilityName: 'WidgetEventCallEntryAbility', + params: { + formId: this.formId, + // Name of the method to be called. + method: 'funA' } - //... - .onClick(() => { - postCardAction(this, { - action: 'call', - abilityName: 'WidgetEventCallEntryAbility', // Only the UIAbility of the current application is allowed. The ability name must be the same as that defined in module.json5. - params: { - formId: this.formId, - method: 'funA' // Set the name of the method to call in the EntryAbility. - } - }); - }) - - Button() { - //... - } - //... - .onClick(() => { - postCardAction(this, { - action: 'call', - abilityName: 'WidgetEventCallEntryAbility', // Only the UIAbility of the current application is allowed. The ability name must be the same as that defined in module.json5. - params: { - formId: this.formId, - method: 'funB', // Set the name of the method to call in the EntryAbility. - num: 1 // Set other parameters to be passed in. - } - }); - }) + }); + }) + Button(this.funB) + .id('funB__') + .fontSize($r('app.float.page_text_font_size')) + .fontWeight(FontWeight.Bold) + .margin({ top: 10 }) + .alignRules({ + top: { anchor: 'funA__', align: VerticalAlign.Bottom }, + middle: { anchor: '__container__', align: HorizontalAlign.Center } + }) + .onClick(() => { + postCardAction(this, { + action: 'call', + abilityName: 'WidgetEventCallEntryAbility', + params: { + formId: this.formId, + // Name of the method to be called. + method: 'funB', + num: 1 } - }.width('100%').height('80%') - .justifyContent(FlexAlign.Center) - } - .width('100%') - .height('100%') - .alignItems(HorizontalAlign.Center) + }); + }) + } + .height('100%') + .width('100%') } } ``` 3. Create a UIAbility. - The UIAbility receives the call event and obtains the transferred parameters. It then executes the target method specified by the **method** parameter. Other data can be obtained through the [readString](../reference/apis-ipc-kit/js-apis-rpc.md#readstring) method. Listen for the method required by the call event in the **onCreate** callback of the UIAbility. + Listen for the call event in the UIAbility, call the corresponding method based on the **method** parameter, and obtain the parameter by using [rpc.Parcelable](../reference/apis-ipc-kit/js-apis-rpc.md#parcelable9). The method in the UIAbility must be the same as that in step 2. ```ts //src/main/ets/widgeteventcallcard/WidgetEventCallEntryAbility/WidgetEventCallEntryAbility.ets import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; - import { promptAction } from '@kit.ArkUI'; import { BusinessError } from '@kit.BasicServicesKit'; import { rpc } from '@kit.IPCKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; @@ -82,7 +87,8 @@ There may be cases you want to provide in a widget access to features available const DOMAIN_NUMBER: number = 0xFF00; const CONST_NUMBER_1: number = 1; const CONST_NUMBER_2: number = 2; - + + // Implementation of the RPC return type, which is used for RPC data serialization and deserialization. class MyParcelable implements rpc.Parcelable { num: number; str: string; @@ -106,24 +112,18 @@ There may be cases you want to provide in a widget access to features available } export default class WidgetEventCallEntryAbility extends UIAbility { - // If the UIAbility is started for the first time, onCreate is triggered after the call event is received. + // If the UIAbility is started, the onCreate lifecycle callback is triggered after the call event is received. onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { try { - // Listen for the method required by the call event. + // Listen for the method required by the call event and call the method. this.callee.on('funA', (data: rpc.MessageSequence) => { // Obtain all parameters passed in the call event. hilog.info(DOMAIN_NUMBER, TAG, `FunACall param: ${JSON.stringify(data.readString())}`); - promptAction.showToast({ - message: 'FunACall param:' + JSON.stringify(data.readString()) - }); return new MyParcelable(CONST_NUMBER_1, 'aaa'); }); this.callee.on('funB', (data: rpc.MessageSequence) => { // Obtain all parameters passed in the call event. hilog.info(DOMAIN_NUMBER, TAG, `FunBCall param: ${JSON.stringify(data.readString())}`); - promptAction.showToast({ - message: 'FunBCall param:' + JSON.stringify(data.readString()) - }); return new MyParcelable(CONST_NUMBER_2, 'bbb'); }); } catch (err) { @@ -144,7 +144,7 @@ There may be cases you want to provide in a widget access to features available ``` 4. Configure the background running permission. - To receive the call event, the widget provider must add the background running permission ([ohos.permission.KEEP_BACKGROUND_RUNNING](../security/AccessToken/permissions-for-all.md#ohospermissionkeep_background_running)) to the top-level module in the **module.json5** file. + To receive the call event, the widget provider must add the background running permission ([ohos.permission.KEEP_BACKGROUND_RUNNING](../security/AccessToken/permissions-for-all.md#ohospermissionkeep_background_running)) to the **module.json5** file. ```ts //src/main/module.json5 "requestPermissions": [ @@ -155,7 +155,7 @@ There may be cases you want to provide in a widget access to features available ``` 5. Configure the UIAbility. - Add the configuration of the WidgetEventCallEntryAbility to the **abilities** array of the top-level module in the **module.json5** file. + Add the WidgetEventCallEntryAbility configuration information to the abilities array in the **module.json5** file. ```ts //src/main/module.json5 "abilities": [ diff --git a/en/application-dev/form/arkts-ui-widget-event-formeditextensionability-overview.md b/en/application-dev/form/arkts-ui-widget-event-formeditextensionability-overview.md index aabcbe27a86925a42d0c0ba2da954e3284581da1..26e40346e191e9669f294a316710a0d37cf4abfb 100644 --- a/en/application-dev/form/arkts-ui-widget-event-formeditextensionability-overview.md +++ b/en/application-dev/form/arkts-ui-widget-event-formeditextensionability-overview.md @@ -1,11 +1,14 @@ -# Overview of ArkTs Widget Page Editing Interaction +# Overview of ArkTS Widget Editing -The home screen provides a unified widget editing page. The widget provider uses the [startSecondPage](../reference/apis-form-kit/js-apis-inner-application-formEditExtensionContext.md#startsecondpage) method provided by FormEditExtensionContext of the [FormEditExtensionAbility](../reference/apis-form-kit/js-apis-app-form-formEditExtensionAbility.md) component to transfer the level-2 editing page information to the home screen. After the home screen opens the level-2 editing page, the page content can be edited. +ArkTS widgets provide the page editing capability to allow users to customize widget content, for example, editing a contact widget, modifying contacts displayed in a widget, and editing a weather widget. + +## How to Implement +The home screen provides a unified widget editing page. The widget provider uses the [startSecondPage](../reference/apis-form-kit/js-apis-inner-application-formEditExtensionContext.md#formeditextensioncontextstartsecondpage) method provided by the FormEditExtensionContext of [FormEditExtensionAbility](../reference/apis-form-kit/js-apis-app-form-formEditExtensionAbility.md) to transfer the level-2 editing page information to the home screen. After the the level-2 editing page is started, the page content can be edited. The following figure shows the widget editing process. -Figure 1 Widget editing process +**Figure 1** Widget editing process ![FormEditExtensionAbility](./figures/Widget-FormEditExtensionAbility.PNG) @@ -13,7 +16,7 @@ Figure 1 Widget editing process 2. After the user identifies that the widget provider inherits [FormEditExtensionAbility](../reference/apis-form-kit/js-apis-app-form-formEditExtensionAbility.md), the level-1 editing page of the widget provider is displayed. -3. The widget provider invokes the [startSecondPage](../reference/apis-form-kit/js-apis-inner-application-formEditExtensionContext.md#startsecondpage) method of [FormEditExtensionContext](../reference/apis-form-kit/js-apis-inner-application-formEditExtensionContext.md) in the callback method [onSessionCreate](../reference/apis-form-kit/js-apis-app-form-formEditExtensionAbility.md#onsessioncreate) of [FormEditExtensionAbility](../reference/apis-form-kit/js-apis-app-form-formEditExtensionAbility.md) to transfer the level-2 page information of the widget provider to be started to the widget management service. +3. The widget provider invokes the [startSecondPage](../reference/apis-form-kit/js-apis-inner-application-formEditExtensionContext.md#formeditextensioncontextstartsecondpage) method of [FormEditExtensionContext](../reference/apis-form-kit/js-apis-inner-application-formEditExtensionContext.md) in the callback method [onSessionCreate](../reference/apis-ability-kit/js-apis-app-ability-uiExtensionAbility.md#onsessioncreate) of [FormEditExtensionAbility](../reference/apis-form-kit/js-apis-app-form-formEditExtensionAbility.md) to transfer the level-2 page information of the widget provider to be started to the widget management service. 4. The widget management service transfers the received level-2 page information of the widget provider to the user. diff --git a/en/application-dev/form/arkts-ui-widget-event-formeditextensionability.md b/en/application-dev/form/arkts-ui-widget-event-formeditextensionability.md index 8d558cfc63f2eb77a035171d8d0d68f47fbcb931..14a51f8ba68b0eb9e0d0429dce1633bd586cd832 100644 --- a/en/application-dev/form/arkts-ui-widget-event-formeditextensionability.md +++ b/en/application-dev/form/arkts-ui-widget-event-formeditextensionability.md @@ -1,9 +1,9 @@ -# Editing and Updating the Widget Content +# Widget Editing Development The home screen provides a unified widget editing page. The widget provider uses [FormEditExtensionAbility](../reference/apis-form-kit/js-apis-app-form-formEditExtensionAbility.md) provided by the widget framework to develop the widget editing function. ## How to Develop -1. In the entry module of the project, create a code file named EntryFormEditAbility. In the EntryFormEditAbility file, implement the [startSecondPage](../reference/apis-form-kit/js-apis-inner-application-formEditExtensionContext.md#startsecondpage) method. In the [onSessionCreate](../reference/apis-form-kit/js-apis-app-form-formEditExtensionAbility.md#onsessioncreate) callback method, load the level-1 widget editing page and transfer the implementation of the **startSecondPage** method to the level-1 widget editing page. +1. In the entry module of the project, create a code file named EntryFormEditAbility. In the EntryFormEditAbility file, implement the [startSecondPage](../reference/apis-form-kit/js-apis-inner-application-formEditExtensionContext.md#formeditextensioncontextstartsecondpage) method. In the [onSessionCreate](../reference/apis-ability-kit/js-apis-app-ability-uiExtensionAbility.md#onsessioncreate) callback method, load the level-1 widget editing page and transfer the implementation of **startSecondPage** to the level-1 widget editing page. ```ts // src/main/ets/entryformeditability/EntryFormEditAbility.ets @@ -15,19 +15,19 @@ import { ExtensionEvent } from '../pages/model/ExtensionEvent'; const TAG: string = 'FormEditDemo[EntryFormEditAbility] -->'; export default class EntryFormEditAbility extends FormEditExtensionAbility { onCreate() { - console.log(`${TAG} onCreate`); + console.info(`${TAG} onCreate`); } onForeground(): void { - console.log(`${TAG} EntryFormEditAbility onForeground.....`); + console.info(`${TAG} EntryFormEditAbility onForeground.....`); } onBackground(): void { - console.log(`${TAG} EntryFormEditAbility onBackground......`); + console.info(`${TAG} EntryFormEditAbility onBackground......`); } onDestroy(): void { - console.log(`${TAG} EntryFormEditAbility onDestroy......`); + console.info(`${TAG} EntryFormEditAbility onDestroy......`); } onSessionCreate(want: Want, session: UIExtensionContentSession) { - console.log(`${TAG} onSessionCreate start..... want: ${JSON.stringify(want)}`); + console.info(`${TAG} onSessionCreate start..... want: ${JSON.stringify(want)}`); let storage: LocalStorage = new LocalStorage(); let extensionEvent: ExtensionEvent = new ExtensionEvent(); extensionEvent.setStartSecondPage(() => this.startSecondPage()); @@ -36,16 +36,16 @@ export default class EntryFormEditAbility extends FormEditExtensionAbility { session.loadContent('pages/Extension', storage); session.setWindowBackgroundColor('#00000000'); } catch (e) { - console.log(`${TAG} EntryFormEditAbility loadContent err, want: ${JSON.stringify(e)}`); + console.error(`${TAG} EntryFormEditAbility loadContent err, want: ${JSON.stringify(e)}`); } } onSessionDestroy(session: UIExtensionContentSession) { - console.log(`${TAG} onSessionDestroy`); + console.info(`${TAG} onSessionDestroy`); } private startSecondPage(): void { const bundleName: string = this.context.extensionAbilityInfo.bundleName; const secPageAbilityName: string = 'FormEditSecPageAbility'; - console.log(`${TAG} startSecondPage. bundleName: ${bundleName}, secPageAbilityName: ${secPageAbilityName}.`); + console.info(`${TAG} startSecondPage. bundleName: ${bundleName}, secPageAbilityName: ${secPageAbilityName}.`); try { this.context.startSecondPage({ bundleName: bundleName, @@ -54,7 +54,7 @@ export default class EntryFormEditAbility extends FormEditExtensionAbility { } }); } catch (err) { - console.log(`${TAG} startSecondPage failed: ${err}`); + console.error(`${TAG} startSecondPage failed: ${err}`); } } }; @@ -68,7 +68,7 @@ export default class EntryFormEditAbility extends FormEditExtensionAbility { import { UIExtensionContentSession } from '@kit.AbilityKit'; import { ExtensionEvent } from './model/ExtensionEvent'; -let storage = LocalStorage.getShared(); +let storage = new LocalStorage(); const TAG: string = 'FormEditDemo[Extension] -->'; @Entry(storage) @Component @@ -77,7 +77,7 @@ struct Extension { private session: UIExtensionContentSession | undefined = storage.get('session'); private extensionEvent: ExtensionEvent | undefined = storage.get('extensionEvent'); onPageShow() { - console.log(`${TAG} onPageShow. extensionEvent: ${JSON.stringify(this.extensionEvent)}, session: ${JSON.stringify(this.session)}.`); + console.info(`${TAG} onPageShow. extensionEvent: ${JSON.stringify(this.extensionEvent)}, session: ${JSON.stringify(this.session)}.`); } build() { Row() { @@ -93,7 +93,7 @@ struct Extension { top: 20 }) .onClick(() => { - console.log(`${TAG} Button onClick`); + console.info(`${TAG} Button onClick`); this.extensionEvent?.startFormEditSecondPage(); }) } @@ -104,7 +104,7 @@ struct Extension { } ``` -3. Add the ExtensionEvent file and use the **startFormEditSecondPage** method to invoke the [startSecondPage](../reference/apis-form-kit/js-apis-inner-application-formEditExtensionContext.md#startsecondpage) method. +3. Add the ExtensionEvent file and use the **startFormEditSecondPage** method to invoke the [startSecondPage](../reference/apis-form-kit/js-apis-inner-application-formEditExtensionContext.md#formeditextensioncontextstartsecondpage) method. ```ts // src/main/ets/widget/pages/model/ExtensionEvent.ets @@ -112,14 +112,14 @@ struct Extension { const TAG: string = 'FormEditDemo[ExtensionEvent] -->'; export class ExtensionEvent { private startSecondPage: () => void = () => { - console.log(`${TAG} startSecondPage is empty!`); + console.info(`${TAG} startSecondPage is empty!`); }; public setStartSecondPage(startSecondPage: () => void) { - console.log(`${TAG} setStartSecondPage`); + console.info(`${TAG} setStartSecondPage`); this.startSecondPage = startSecondPage; } public startFormEditSecondPage(): void { - console.log(`${TAG} startFormEditSecondPage`); + console.info(`${TAG} startFormEditSecondPage`); this.startSecondPage(); } } diff --git a/en/application-dev/form/arkts-ui-widget-event-formextensionability.md b/en/application-dev/form/arkts-ui-widget-event-formextensionability.md index db8e6096e89344f1330123d4a6bcf2d485cc0cb2..6b77e0240223fe8a2df6f5f8b7cddc1fdc979ad1 100644 --- a/en/application-dev/form/arkts-ui-widget-event-formextensionability.md +++ b/en/application-dev/form/arkts-ui-widget-event-formextensionability.md @@ -1,12 +1,12 @@ -# Updating Widget Content Through the message Event +# Transferring Messages to an Application (message Event) -On the widget page, the [postCardAction](../reference/apis-arkui/js-apis-postCardAction.md#postcardaction) API can be used to trigger a message event to start a FormExtensionAbility, which then updates the widget content. The following is an example of this widget update mode. +On the widget page, you can trigger a message event via the [postCardAction](../reference/apis-arkui/js-apis-postCardAction.md#postcardaction) API to launch the [FormExtensionAbility](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md). The FormExtensionAbility then notifies the application through the [onFormEvent](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md#formextensionabilityonformevent) callback. This process enables the functionality of passing messages to the application after a widget is touched. Subsequently, the FormExtensionAbility refreshes the widget content. Below is a simple example. > **NOTE** > > This topic describes development for dynamic widgets. For static widgets, see [FormLink](../reference/apis-arkui/arkui-ts/ts-container-formlink.md). -- On the widget page, register the **onClick** event callback of the button and call the **postCardAction** API in the callback to trigger the message event to start the FormExtensionAbility. Use [LocalStorageProp](../quick-start/arkts-localstorage.md#localstorageprop) to decorate the widget data to be updated. +- On the widget page, register the **onClick** event callback of the button and call the **postCardAction** API in the callback to trigger the message event to start the FormExtensionAbility. Use [LocalStorageProp](../ui/state-management/arkts-localstorage.md#localstorageprop) to decorate the widget data to be updated. ```ts let storageUpdateByMsg = new LocalStorage(); @@ -62,7 +62,7 @@ On the widget page, the [postCardAction](../reference/apis-arkui/js-apis-postCar } ``` -- Call the [updateForm](../reference/apis-form-kit/js-apis-app-form-formProvider.md#updateform) API to update the widget in the **onFormEvent** callback of the FormExtensionAbility. +- Call the [updateForm](../reference/apis-form-kit/js-apis-app-form-formProvider.md#formproviderupdateform) API to update the widget in the **onFormEvent** callback of the FormExtensionAbility. ```ts import { BusinessError } from '@kit.BasicServicesKit'; @@ -74,14 +74,15 @@ On the widget page, the [postCardAction](../reference/apis-arkui/js-apis-postCar export default class EntryFormAbility extends FormExtensionAbility { onFormEvent(formId: string, message: string): void { - // Called when a specified message event defined by the form provider is triggered. + // Called when the message event of the postCardAction API of the widget provider is triggered. hilog.info(DOMAIN_NUMBER, TAG, `FormAbility onFormEvent, formId = ${formId}, message: ${JSON.stringify(message)}`); class FormDataClass { - title: string ='Title Update.'; // It matches the widget layout. + title: string = 'Title Update.'; // It matches the widget layout. detail: string = 'Description update success.'; // It matches the widget layout. } + // Replace it with the actual widget data. let formData = new FormDataClass(); let formInfo: formBindingData.FormBindingData = formBindingData.createFormBindingData(formData); formProvider.updateForm(formId, formInfo).then(() => { @@ -96,6 +97,6 @@ On the widget page, the [postCardAction](../reference/apis-arkui/js-apis-postCar The figure below shows the effect. - | Initial State | After Clicking | + | Initial State | Touch to Refresh | | ------------------------------------------------------- | ----------------------------------------------------- | | ![WidgetUpdateBefore](figures/widget-update-before.PNG) | ![WidgetUpdateAfter](figures/widget-update-after.PNG) | diff --git a/en/application-dev/form/arkts-ui-widget-event-overview.md b/en/application-dev/form/arkts-ui-widget-event-overview.md index 0324425a2285a9ce2c405127a2c226c597e01dac..9140316c89f9d4c3c463698733367d1e8595d9a6 100644 --- a/en/application-dev/form/arkts-ui-widget-event-overview.md +++ b/en/application-dev/form/arkts-ui-widget-event-overview.md @@ -1,16 +1,7 @@ -# Widget Event Capability Overview +# Overview of ArkTS Widget Page Interaction -For dynamic ArkTS widgets, the [postCardAction](../reference/apis-arkui/js-apis-postCardAction.md#postcardaction) API is provided for interaction between the widget internal and the provider application. Currently, this API supports the router, message, and call events and can be called only in the widget. +ArkTS widgets provide page interaction capabilities, including page redirection between widgets and widget providers (such as applications), process startup of widget providers, and message transfer between widgets and widget providers. You can call [postCardAction](../reference/apis-arkui/js-apis-postCardAction.md#postcardaction) to implement a [dynamic widget](arkts-form-overview.md#dynamic-widget) and use [FormLink](../reference/apis-arkui/arkui-ts/ts-container-formlink.md) to implement page interaction of a [static widget](arkts-form-overview.md#static-widget). Both **postCardAction** and **FormLink** support router, message, and call events. The usage scenarios are as follows: -For static ArkTS widgets, the [FormLink](../reference/apis-arkui/arkui-ts/ts-container-formlink.md) component is provided for interaction between the widget internal and the provider application. - -## Dynamic Widget Event Capability -![WidgetPostCardAction](figures/WidgetPostCardAction.png) - -Dynamic widget events are used in the following scenarios: -- Router event: used to redirect to a UIAbility and update the widget content. -- Call event: used to start a UIAbility in the background and update the widget content. -- Message event: used to start a FormExtensionAbility, which then updates the widget content. - -## Static Widget Event Capability -See [FormLink](../reference/apis-arkui/arkui-ts/ts-container-formlink.md). +- [router event](arkts-ui-widget-event-router.md): used to redirect to a specified UIAbility, enabling the functionality of navigating from a widget to an internal application page after a widget is touched. For non-system applications, this redirection is limited to their own UIAbilities. +- [call event](arkts-ui-widget-event-call.md): used to launch a specified UIAbility to the background, after which the UIAbility can request the corresponding background continuous task to complete functionalities such as music playback. +- [message event](arkts-ui-widget-event-formextensionability.md): used to launch the [FormExtensionAbility](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md), which then notifies the application via the [onFormEvent](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md#formextensionabilityonformevent) API callback, thereby fulfilling the functionality of passing messages to the application after a widget is touched. diff --git a/en/application-dev/form/arkts-ui-widget-event-router.md b/en/application-dev/form/arkts-ui-widget-event-router.md index 6ead57b92c8f2e7cfb2d979d5aa588095b747a6f..c47f719230de1fcc40b6ec7887d8c21fc6f500fd 100644 --- a/en/application-dev/form/arkts-ui-widget-event-router.md +++ b/en/application-dev/form/arkts-ui-widget-event-router.md @@ -1,4 +1,4 @@ -# Launching the UIAbility of the Widget Provider Through the router Event +# Redirecting to an Application Page (router Event) The **router** capability of the [postCardAction](../reference/apis-arkui/js-apis-postCardAction.md#postcardaction) API can be used in a dynamic widget to quickly start a specific UIAbility of the widget provider. By leveraging this capability, an application can provide in the widget multiple buttons, each of which targets a different target UIAbility. For example, a camera widget can provide the buttons that redirect the user to the UIAbility for taking a photo and the UIAbility for recording a video. @@ -188,4 +188,4 @@ The **router** capability of the [postCardAction](../reference/apis-arkui/js-api "pages/FunB" ] } - ``` + ``` diff --git a/en/application-dev/form/arkts-ui-widget-event-uiability.md b/en/application-dev/form/arkts-ui-widget-event-uiability.md index 9621eb1d69388e74fb16ce6ab19434702fb4c72e..dd9367f42efb245b8ef897aaac293fc3306a2719 100644 --- a/en/application-dev/form/arkts-ui-widget-event-uiability.md +++ b/en/application-dev/form/arkts-ui-widget-event-uiability.md @@ -63,7 +63,7 @@ With the router event, a touch on the widget can start the associated applicatio } ``` -- In the **onCreate** or **onNewWant** lifecycle callback of the UIAbility, use the input parameter **want** to obtain the ID (**formID**) and other information of the widget, and then call the [updateForm](../reference/apis-form-kit/js-apis-app-form-formProvider.md#updateform) API to update the widget. +- In the **onCreate** or **onNewWant** lifecycle callback of the UIAbility, use the input parameter **want** to obtain the ID (**formID**) and other information of the widget, and then call the [updateForm](../reference/apis-form-kit/js-apis-app-form-formProvider.md#formproviderupdateform) API to update the widget. ```ts import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; @@ -178,7 +178,7 @@ With the router event, a touch on the widget can start the associated applicatio } ``` -- Listen for the method required by the call event in the **onCreate** callback of the UIAbility, and then call the [updateForm](../reference/apis-form-kit/js-apis-app-form-formProvider.md#updateform) API in the corresponding method to update the widget. +- Listen for the method required by the call event in the **onCreate** callback of the UIAbility, and then call the [updateForm](../reference/apis-form-kit/js-apis-app-form-formProvider.md#formproviderupdateform) API in the corresponding method to update the widget. ```ts import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; @@ -260,7 +260,7 @@ With the router event, a touch on the widget can start the associated applicatio } } ``` - To start the UIAbility in the background, you must configure the ohos.permission.KEEP_BACKGROUND_RUNNING permission in the **module.json5** file. + To start the UIAbility in the background, you must configure the `ohos.permission.KEEP_BACKGROUND_RUNNING` permission in the `module.json5` file. ```json "requestPermissions":[ { diff --git a/en/application-dev/form/arkts-ui-widget-interaction-overview.md b/en/application-dev/form/arkts-ui-widget-interaction-overview.md index 75251ccba6230f3281a99a1482a2a5b3aab52c3a..674c4324d3b89e10120e7105991d5f1fb7560860 100644 --- a/en/application-dev/form/arkts-ui-widget-interaction-overview.md +++ b/en/application-dev/form/arkts-ui-widget-interaction-overview.md @@ -1,35 +1,53 @@ -# Updating Widget Content +# Overview of ArkTS Widget Update -The ArkTS widget framework provides the [updateForm](../reference/apis-form-kit/js-apis-app-form-formProvider.md#updateform) API for widget providers and the **requestForm** API for widget hosts to proactively trigger widget page refreshes. It also alerts providers to update widgets based on the scheduled information. +Both the widget host (for example, the home screen) and the widget provider can trigger updates to the widget page. Moreover, the widget framework notifies the widget provider of updates according to the scheduled information. Therefore, widget updates include active updates initiated by the widget provider, active updates initiated by the widget host, and interval-based or time-specific updates. In all these update modes, the widget provider is responsible for pushing the widget data to be updated. -In widget UI code, you can use [LocalStorageProp](../quick-start/arkts-localstorage.md#localstorageprop) to obtain the widget data that requires updating, sent by the provider +## Widget Data Interaction -| API| System Capability| Constraints| -| -------- | -------- | -------- | -| updateForm | No| 1. Invoked by the widget provider.
2. Allows only the widget provider to update its own widgets.| -| requestForm | Yes| 1. Invoked by the widget host.
2. Allows only the widget host to update the widgets added to it.| +The ArkTS widget framework provides the data interaction capability between widget providers (for example, applications) and widgets. The widget transfers data to the widget provider through [postCardAction](../reference/apis-arkui/js-apis-postCardAction.md#postcardaction), and the widget provider can transfer data to the widget through [updateForm](../reference/apis-form-kit/js-apis-app-form-formProvider.md#formproviderupdateform). After the widget provider transfers data to the widget, the data can be used for page update. -**Widget provider proactively updating a widget** +The widget provider and widget are independent of each other. Therefore, data can be transferred only through [LocalStorageProp](../ui/state-management/arkts-localstorage.md#localstorageprop), and the **getContext** method cannot be used. After the widget provider pushes data, the widget UI receives it via **LocalStorageProp**, and converts the received data to a string. + +## Page Update Modes + +Widgets can be updated actively or passively based on the triggering mode. + +### Active Update + +Active updates include the updates triggered by the widget provider and the widget host. For details, see [Active Update of ArkTS Widgets](arkts-ui-widget-active-refresh.md). + +**Figure 1** Flowchart of active update by the widget provider ![updateForm](figures/updateForm.PNG) -If there is a need to update widget data, the widget provider, as long as it is running, can proactively update the widget using the **updateForm** API provided by formProvider. +If there is a need to update widget data, the widget provider, as long as it is running, can proactively update the widget using the [updateForm](../reference/apis-form-kit/js-apis-app-form-formProvider.md#formproviderupdateform) API provided by formProvider. -**Widget host proactively requesting a widget update** +**Figure 2** Flowchart of active update by the widget host ![requestForm](figures/requestForm.PNG) -If changes in system language or color scheme are detected, the widget host, as long as it is running, can proactively request to update the widget using the **requestForm** API provided by formHost. The widget manager then instructs the widget provider to complete the update. +If changes in system language or color scheme are detected, the widget host, as long as it is running, can proactively request to update the widget using the **requestForm** API provided by formHost. The Widget Manager then instructs the widget provider to complete the update. + +### Passive Update -**Widget manager instructing the widget provider to periodically update a widget** +Passive update includes interval-based update, time-specific update, and conditional update. For details, see [Passive Update of ArkTS Widgets](arkts-ui-widget-passive-refresh.md). + +Interval-based update: The widget content will be automatically updated at the specified interval by calling [onUpdateForm](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md#formextensionabilityonupdateform). + +Time-specific update: The widget content will be automatically updated at a designated time every day. + + +Conditional update: The widget is updated when a certain condition is met. Currently, it is triggered when the network status of a device changes from unavailable to available. + + +**Figure 3** Flowchart of interval-based and time-specific updates by the widget provider ![timer_updateForm](figures/timer_updateForm.PNG) Based on the scheduled update information configured by the widget provider, the widget manager determines whether to instruct the provider to update the widget, considering factors such as timing information, widget visibility status, and the number of updates. -The following are the typical use cases of widget updates: +## Constraints + +1. The widget provider is only allowed to update its own widgets. -- [Interval-based Widget Updates](arkts-ui-widget-update-by-time.md) -- [Time-specific Widget Updates](arkts-ui-widget-update-by-time-point.md) -- [Updating Local and Online Images in the Widget](arkts-ui-widget-image-update.md) -- [Updating Widget Content by State](arkts-ui-widget-update-by-status.md) +2. The widget host is only allowed to update the widgets added to it. diff --git a/en/application-dev/form/arkts-ui-widget-lifecycle.md b/en/application-dev/form/arkts-ui-widget-lifecycle.md index 27d47792b54d4cb185c7e9e29c42bfb29cbc2fc4..a36469e87dedff05972c28028adf68c1dbe4ba28 100644 --- a/en/application-dev/form/arkts-ui-widget-lifecycle.md +++ b/en/application-dev/form/arkts-ui-widget-lifecycle.md @@ -1,4 +1,4 @@ -# Widget Lifecycle Management +# Managing ArkTS Widget Lifecycle When creating an ArkTS widget, you need to implement the [FormExtensionAbility](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md) lifecycle APIs. @@ -41,7 +41,7 @@ When creating an ArkTS widget, you need to implement the [FormExtensionAbility]( } onUpdateForm(formId: string): void { - // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host. + // Override this method to support interval-based updates, time-specific updates, or updates requested by the widget host. hilog.info(DOMAIN_NUMBER, TAG, '[EntryFormAbility] onUpdateForm'); let obj: Record = { 'title': 'titleOnUpdateForm', @@ -65,9 +65,9 @@ When creating an ArkTS widget, you need to implement the [FormExtensionAbility]( } onRemoveForm(formId: string): void { - // Delete widget data. + // Remove widget data. hilog.info(DOMAIN_NUMBER, TAG, '[EntryFormAbility] onRemoveForm'); - // Delete the persistent widget instance data. + // Remove the persistent widget instance data. // Implement this API based on project requirements. } @@ -86,4 +86,4 @@ When creating an ArkTS widget, you need to implement the [FormExtensionAbility]( > **NOTE** > -> The FormExtensionAbility cannot reside in the background. It persists for 10 seconds after the lifecycle callback is completed and exits if no new lifecycle callback is invoked during this time frame. This means that continuous tasks cannot be processed in the widget lifecycle callbacks. For the service logic that may take more than 10 seconds to complete, it is recommended that you [start the application](arkts-ui-widget-event-uiability.md) for processing. After the processing is complete, use [updateForm](../reference/apis-form-kit/js-apis-app-form-formProvider.md#updateform) to notify the widget of the update. +> The FormExtensionAbility cannot reside in the background. It persists for 10 seconds after the lifecycle callback is completed and exits if no new lifecycle callback is invoked during this time frame. This means that continuous tasks cannot be processed in the widget lifecycle callbacks. For the service logic that may take more than 10 seconds to complete, it is recommended that you [start the application](arkts-ui-widget-event-overview.md) for processing. After the processing is complete, use [updateForm](../reference/apis-form-kit/js-apis-app-form-formProvider.md#formproviderupdateform) to notify the widget of the update. diff --git a/en/application-dev/form/arkts-ui-widget-open-formmanager.md b/en/application-dev/form/arkts-ui-widget-open-formmanager.md new file mode 100644 index 0000000000000000000000000000000000000000..23a5e530da08a27eca0b9c4330a3512883667c96 --- /dev/null +++ b/en/application-dev/form/arkts-ui-widget-open-formmanager.md @@ -0,0 +1,50 @@ +# Adding Widgets to the Home Screen + +You can add ArkTS widgets of an application to the home screen + +which manages widgets in a unified manner. Applications can call the [openFormManager](../reference/apis-form-kit/js-apis-app-form-formProvider.md#formprovideropenformmanager18) API provided by the [formProvider](../reference/apis-form-kit/js-apis-app-form-formProvider.md) module to start the widget management page where you can add a widget to the home screen by touching **Add to home screen**. + +## How to Develop + +Implement the [openFormManager](../reference/apis-form-kit/js-apis-app-form-formProvider.md#formprovideropenformmanager18) method provided by the [formProvider](../reference/apis-form-kit/js-apis-app-form-formProvider.md) API. + +```ts +// entry/src/main/ets/pages/Index.ets + +import { formProvider } from '@kit.FormKit'; +import { BusinessError } from '@kit.BasicServicesKit'; +import { Want } from '@kit.AbilityKit'; + +@Entry +@Component +struct Index { + + build() { + Row() { + Column() { + // Add a button and call the openFormManager method to start the widget management page. + Button('Start the widget management page.') + .onClick(() => { + const want: Want = { + bundleName: 'com.example.formbutton', + abilityName: 'EntryFormAbility', + parameters: { + 'ohos.extra.param.key.form_dimension': 2, + 'ohos.extra.param.key.form_name': 'widget', + 'ohos.extra.param.key.module_name': 'entry' + }, + }; + try { + formProvider.openFormManager(want); + } catch (error) { + console.error(`catch error, code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message})`); + } + }) + .margin({ top: 10, bottom: 10 }) + } + .width('100%') + } + .height('100%') + } +} +``` diff --git a/en/application-dev/form/arkts-ui-widget-page-animation.md b/en/application-dev/form/arkts-ui-widget-page-animation.md index 44ad8d2d871659480d3590e70fe8ac7c98ed0116..83248f77c1e649aa64e3868e3f473856eab23c89 100644 --- a/en/application-dev/form/arkts-ui-widget-page-animation.md +++ b/en/application-dev/form/arkts-ui-widget-page-animation.md @@ -5,7 +5,7 @@ To make your ArkTS widgets more engaging, you can apply animations to it, includ **Table 1** Restrictions on animation parameters -| Name| Description| Description| +| Name| Description| Restriction| | -------- | -------- | -------- | | duration | Animation playback duration| The maximum value is 1 second. If a larger value is set, the animation is still played for 1 second.| | tempo | Animation playback speed.| Do not set this parameter in the widget. Use the default value 1.| diff --git a/en/application-dev/form/arkts-ui-widget-page-custom-drawing.md b/en/application-dev/form/arkts-ui-widget-page-custom-drawing.md index 38920cdc5aacfe99672410aafba1ef3f2e5c5eea..83aeee2f473d7a94f304e231b1e6dce4f283b0c2 100644 --- a/en/application-dev/form/arkts-ui-widget-page-custom-drawing.md +++ b/en/application-dev/form/arkts-ui-widget-page-custom-drawing.md @@ -1,4 +1,4 @@ -# Applying Custom Drawing in the Widget +# Using Canvas in ArkTS Widgets You can apply custom drawing in your ArkTS widget to create a more vibrant experience. Use the [\](../reference/apis-arkui/arkui-ts/ts-components-canvas-canvas.md) component to create a canvas on the widget, and then use the [CanvasRenderingContext2D](../reference/apis-arkui/arkui-ts/ts-canvasrenderingcontext2d.md) object to draw custom graphics on the canvas. The following code snippet draws a smiling face in the center of a canvas. @@ -85,6 +85,5 @@ struct CustomCanvasDrawingCard { } ``` -The figure below shows the effect. - +The figure below shows the effect. ![WidgetCanvasDemo](figures/WidgetCanvasDemo.jpeg) diff --git a/en/application-dev/form/arkts-ui-widget-page-overview.md b/en/application-dev/form/arkts-ui-widget-page-overview.md index bb0a933130d4728c52cfb0c0893128f4e83d27e7..8f489cb7d20df3d4e92895704a970d2dbc2a0120 100644 --- a/en/application-dev/form/arkts-ui-widget-page-overview.md +++ b/en/application-dev/form/arkts-ui-widget-page-overview.md @@ -1,4 +1,4 @@ -# Overview +# Overview of ArkTS Widget UI Development ArkTS widgets are developed using the general [ArkTS language](../quick-start/arkts-get-started.md). You can use the [declarative paradigm](../ui/arkts-ui-development-overview.md) to develop ArkTS widget pages. The following widget pages are automatically generated by a DevEco Studio template. You can adjust the pages based on the real-world service scenarios. diff --git a/en/application-dev/form/arkts-ui-widget-passive-refresh.md b/en/application-dev/form/arkts-ui-widget-passive-refresh.md new file mode 100644 index 0000000000000000000000000000000000000000..2114de15748f147515a30d11740c91e207e643d4 --- /dev/null +++ b/en/application-dev/form/arkts-ui-widget-passive-refresh.md @@ -0,0 +1,208 @@ +# Passive Update of ArkTS Widgets + +This section provides the development guidelines for passive update. For details about the update process, see [Passive Update](./arkts-ui-widget-interaction-overview.md#passive-update). + +## Interval-based Update + +Form Kit provides the following methods for interval-based update: + +- Setting the update interval: The widget content will be automatically updated at the specified interval by calling [onUpdateForm](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md#formextensionabilityonupdateform). The interval is specified by the `updateDuration` field in the [form_config.json](arkts-ui-widget-configuration.md) file. For example, if `updateDuration` is set to **2**, the widget is updated once an hour. + + ```json + { + "forms": [ + { + "name": "UpdateDuration", + "description": "$string:widget_updateduration_desc", + "src": "./ets/updateduration/pages/UpdateDurationCard.ets", + "uiSyntax": "arkts", + "window": { + "designWidth": 720, + "autoDesignWidth": true + }, + "colorMode": "auto", + "isDefault": true, + "updateEnabled": true, + "scheduledUpdateTime": "10:30", + "updateDuration": 2, + "defaultDimension": "2*2", + "supportDimensions": [ + "2*2" + ] + } + ] + } + ``` + > **NOTE** + > + > 1. To use interval-based update, set the `updateEnabled` field to `true` in the **form_config.json** file. + > + > 2. To reduce the number of passive periodic update times and power consumption of widgets, the update interval can be set from the AppGallery for applications that are being + > or have been installed. + >
● When `updateDuration` is set, + > the widget framework compares the update interval specified in the **form_config.json** file with that configured on AppGallery. The longer of the two intervals is used as the update interval of the widget. + >
● If no update interval is set from the AppGallery, the value in the **form_config.json** file is used. + >
● This rule does not apply when the interval-based update is disabled. + >
● The update interval set from the AppGallery ranges from 1 to 336, in the unit of 30 minutes. That is, the minimum update interval is half an hour (1 x 30 minutes) and the maximum update interval is one week (336 x 30 minutes). + >
● This rule takes effect since API version 11. In earlier versions, the interval-based update follows the settings in the **form_config.json** file. + +- Setting the next update time: The widget will be updated at the next specified time, which is specified by calling [setFormNextRefreshTime](../reference/apis-form-kit/js-apis-app-form-formProvider.md#formprovidersetformnextrefreshtime), at the minimum of 5 minutes. For example, you can configure the widget to update within 5 minutes after the API is called. + + ```ts + import { FormExtensionAbility, formProvider } from '@kit.FormKit'; + import { hilog } from '@kit.PerformanceAnalysisKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + const TAG: string = 'UpdateByTimeFormAbility'; + const FIVE_MINUTE: number = 5; + const DOMAIN_NUMBER: number = 0xFF00; + + export default class UpdateByTimeFormAbility extends FormExtensionAbility { + onFormEvent(formId: string, message: string): void { + // Called when a specified message event defined by the form provider is triggered. + hilog.info(DOMAIN_NUMBER, TAG, `FormAbility onFormEvent, formId = ${formId}, message: ${JSON.stringify(message)}`); + try { + // Configure the widget to update in 5 minutes. + formProvider.setFormNextRefreshTime(formId, FIVE_MINUTE, (err: BusinessError) => { + if (err) { + hilog.info(DOMAIN_NUMBER, TAG, `Failed to setFormNextRefreshTime. Code: ${err.code}, message: ${err.message}`); + return; + } else { + hilog.info(DOMAIN_NUMBER, TAG, 'Succeeded in setFormNextRefreshTiming.'); + } + }); + } catch (err) { + hilog.info(DOMAIN_NUMBER, TAG, `Failed to setFormNextRefreshTime. Code: ${(err as BusinessError).code}, message: ${(err as BusinessError).message}`); + } + } + // ... + } + ``` + +When interval-based update or next update is triggered, the system calls the [onUpdateForm](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md#formextensionabilityonupdateform) lifecycle callback of the FormExtensionAbility. In the callback, [updateForm](../reference/apis-form-kit/js-apis-app-form-formProvider.md#formproviderupdateform) can be used to update the widget. For details about how to use `onUpdateForm`, see [Widget Lifecycle Management](./arkts-ui-widget-lifecycle.md). + +**Constraints** +1. Each widget can be updated at the specified interval for a maximum of 50 times every day, including updates triggered by setting [updateDuration](arkts-ui-widget-configuration.md) or calling [setFormNextRefreshTime](../reference/apis-form-kit/js-apis-app-form-formProvider.md#formprovidersetformnextrefreshtime). When the limit is reached, the widget cannot be updated in this mode again. The number of update times is reset at 00:00 every day. +> +2. A single timer is used for interval-based updates. Therefore, if a widget is configured to update at specified intervals, the first update may have a maximum deviation of 30 minutes. For example, if widget A (updated every half an hour) is added at 03:20 and widget B (also updated every half an hour) is added at 03:40, the first update of widget B has a deviation of 10 minutes to the expected time: The timer starts at 03:20 when widget A is added, triggers an update for widget A at 03:50, and triggers another update for widget B at 04:20 (instead of 04:10 as expected). +> +3. Interval-based updates are triggered only when the widget is visible. If the widget is invisible, the update action and data are recorded. The layout is refreshed once the widget becomes visible. +> +4. If the update-through-proxy feature is enabled, the settings for the update interval and next update time will not take effect. + +## Time-specific Update + +Form Kit provides the following methods for time-specific widget update: + +- Setting a single update time: The widget content will be automatically updated at a designated time every day. This time is specified by the `scheduledUpdateTime` field in the **form_config.json** file. For example, you can configure the widget to update at 10:30 every day. + + + ```json + { + "forms": [ + { + "name": "ScheduledUpdateTime", + "description": "$string:widget_scheupdatetime_desc", + "src": "./ets/scheduledupdatetime/pages/ScheduledUpdateTimeCard.ets", + "uiSyntax": "arkts", + "window": { + "designWidth": 720, + "autoDesignWidth": true + }, + "colorMode": "auto", + "isDefault": true, + "updateEnabled": true, + "scheduledUpdateTime": "10:30", + "updateDuration": 0, + "defaultDimension": "2*2", + "supportDimensions": [ + "2*2" + ] + } + ] + } + ``` + +- Setting multiple update times: The widget content will be automatically updated at several specific times every day. These times are specified by the `multiScheduledUpdateTime` field in the **form_config.json** file. For example, you can configure the widget to update at 11:30 and 16:30 every day. + ```json + { + "forms": [ + { + "name": "ScheduledUpdateTime", + "description": "$string:widget_scheupdatetime_desc", + "src": "./ets/scheduledupdatetime/pages/ScheduledUpdateTimeCard.ets", + "uiSyntax": "arkts", + "window": { + "designWidth": 720, + "autoDesignWidth": true + }, + "colorMode": "auto", + "isDefault": true, + "updateEnabled": true, + "scheduledUpdateTime": "10:30", + "multiScheduledUpdateTime": "11:30,16:30,", + "updateDuration": 0, + "defaultDimension": "2*2", + "supportDimensions": [ + "2*2" + ] + } + ] + } + ``` + +When a time-specific update is triggered, the system calls the [onUpdateForm](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md#formextensionabilityonupdateform) lifecycle callback of the FormExtensionAbility. In the callback, [updateForm](../reference/apis-form-kit/js-apis-app-form-formProvider.md#formproviderupdateform) can be used to update the widget. For details about how to use `onUpdateForm`, see [Widget Lifecycle Management](./arkts-ui-widget-lifecycle.md). + +> **NOTE** +> 1. If both interval-based update (`updateDuration`) and time-specific update (`scheduledUpdateTime`) are configured, the interval-based update takes precedence, and the time-specific update will not be executed. To enable time-specific updates, set `updateDuration` to **0**. +> 2. A maximum of 24 times can be set for `multiScheduledUpdateTime`. +> 3. If both update at a single time and update at multiple times are configured, only the update at multiple times takes effect. +> 4. To ensure forward compatibility, retain the `scheduledUpdateTime` field. + +**Constraints** +1. Interval-based updates are triggered only when the widget is visible. If the widget is invisible, the update action and data are recorded. The layout is refreshed once the widget becomes visible. + + +## Conditional Update + +Form Kit provides the following methods for conditional updates: + +- Network-triggered update: The widget content will be automatically updated by calling [onUpdateForm](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md#formextensionabilityonupdateform) when the network changes. This can be configured by setting the `conditionUpdate` field in the [form_config.json](arkts-ui-widget-configuration.md) file to **network**. + +> **NOTE** +> 1. A widget update is triggered when the device transitions from a no-network state to a connected state. However, an update is not triggered when a user switches between networks (for example, switching between different Wi-Fi networks or between Wi-Fi and cellular data) or goes from Internet connection to no Internet connection. +> +> 2. To minimize the frequency of widget process initiations during frequent network on/off scenarios, a no-network condition is determined after the network has been continuously unavailable for 10 minutes. Upon reconnection, a network-based update is then triggered. +> +> 3. This functionality is valid only for widgets of system applications. + + + ```json + { + "forms": [ + { + "name": "UpdateDuration", + "description": "$string:widget_updateduration_desc", + "src": "./ets/updateduration/pages/UpdateDurationCard.ets", + "uiSyntax": "arkts", + "window": { + "designWidth": 720, + "autoDesignWidth": true + }, + "colorMode": "auto", + "isDefault": true, + "updateEnabled": true, + "scheduledUpdateTime": "10:30", + "updateDuration": 2, + "defaultDimension": "2*2", + "supportDimensions": [ + "2*2" + ], + "conditionUpdate": [ + "network" + ] + } + ] + } + ``` + diff --git a/en/application-dev/form/arkts-ui-widget-process.md b/en/application-dev/form/arkts-ui-widget-process.md new file mode 100644 index 0000000000000000000000000000000000000000..d47d6f32dd9fcb0a6eb2c5a57c0a537f7e430cf7 --- /dev/null +++ b/en/application-dev/form/arkts-ui-widget-process.md @@ -0,0 +1,9 @@ +# ArkTS Widget Process Model +This section describes the processes of a widget from creation to display. For details, see the figure below. + +**Figure 1** Widget process model +![WidgetProject](figures/form-process.png) +- Widget host process: a host process that displays the widget UI, for example, the home screen process. +- Widget rendering process: a process that loads and renders widget UIs in the system. All widgets are rendered in the same process, and different widget UIs are isolated by VMs. +- Widget Manager process: a System Service ([SA](../application-models/serviceability-overview.md)) for unifying the widget lifecycle. +- Widget provider process: an application process that provides widgets, including the main process running the UIAbility of the application and the independent [FormExtensionAbility](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md) process of the widget. The memory of the two processes is isolated, but they share the same file sandbox. diff --git a/en/application-dev/form/arkts-ui-widget-update-by-proxy.md b/en/application-dev/form/arkts-ui-widget-update-by-proxy.md index f389d5b02c27c1b506ab0d7e25e186e5caf13fc3..b670959aaada5789c446af00aa4d6f4c2ca06677 100644 --- a/en/application-dev/form/arkts-ui-widget-update-by-proxy.md +++ b/en/application-dev/form/arkts-ui-widget-update-by-proxy.md @@ -5,12 +5,13 @@ A widget can be updated through a proxy – a system application that has data s ## Implementation Principles **Figure 1** Updating widget content through a proxy + ![UpdateWidgetByProxyPrinciple](figures/UpdateWidgetByProxyPrinciple.png) -Compared with the [implementation of the ArkTS widget](arkts-ui-widget-working-principles.md#implementation-principles) alone, updating through a proxy involves the data management service and data provider. +Compared with the [implementation of the ArkTS widget](arkts-form-overview.md#how-to-implement) alone, updating through a proxy involves the data management service and data provider. - Data management service: provides a mechanism for data sharing among multiple applications. -- Data provider: must be a system application that has data sharing enabled. The shared data is identified through the defined **key** + **subscriberId** combination. +- Data provider: must be a system application that has data sharing enabled. The shared data is identified through the defined `key + subscriberId` combination. > **NOTE** > @@ -18,18 +19,18 @@ Compared with the [implementation of the ArkTS widget](arkts-ui-widget-working-p Processing flow of the widget provider (indicated by the blue arrows in the figure): -1. The widget provider sets the **dataProxyEnabled** field to **true** in the **form_config.json** file to enable the update-through-proxy feature. +1. The widget provider sets the `dataProxyEnabled` field to `true` in the `form_config.json` file to enable the update-through-proxy feature. > **NOTE** > -> After the update-through-proxy feature is enabled, the settings for [updating periodically](arkts-ui-widget-update-by-time.md) do not work. +> After the update-through-proxy feature is enabled, the settings for [interval-based update](arkts-ui-widget-passive-refresh.md#interval-based-update) becomes invalid. -2. In the [onAddForm](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md#onaddform) callback, the widget provider returns the **key** + **subscriberId** combination defined by the data provider to the Widget Manager. +2. In the [onAddForm](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md#formextensionabilityonaddform) callback, the widget provider returns the `key + subscriberId` combination defined by the data provider to the Widget Manager. 3. The Widget Manager parses the subscription information of the widget provider and registers a subscription instance with the data management service. Processing flow of the widget update proxy (indicated by the red arrows in the figure): -1. The data provider uses the **key** + **subscriberId** combination as the data ID to store data to the database. +1. The data provider uses the `key + subscriberId` combination as the data ID to store data to the database. 2. The data management service detects the change in the database and publishes the new data to all currently registered subscription instances. 3. The Widget Manager parses data from the subscription instance and sends the data to the widget rendering service. 4. The widget rendering service runs the widget page code **widgets.abc**, which implements rendering based on the new data and sends the rendered data to the [FormComponent](../reference/apis-arkui/arkui-ts/ts-basic-components-formcomponent-sys.md) corresponding to the widget host. @@ -38,7 +39,7 @@ There are two types of shared data provided by the data provider: - Ephemeral data: data that exists only for a specific period of time and can be subscribed to by system and non-system applications alike. -- Persistent data: data that persists over time and can only be subscribed to by system applications. +- Persistent data: data that can be subscribed to only by system applications. The update-through-proxy configuration varies by the type of shared data. @@ -48,7 +49,7 @@ For details, see [Data Management](../database/share-data-by-silent-access.md). ## Widget Provider Development (Ephemeral Data) -- Set the **dataProxyEnabled** field to **true** in the **form_config.json** file to enable the update-through-proxy feature. +- Set the `dataProxyEnabled` field to `true` in the **form_config.json** file to enable the update-through-proxy feature. When the subscribed ephemeral data is updated, the system automatically updates the widget data. ```json { "forms": [ @@ -75,7 +76,7 @@ For details, see [Data Management](../database/share-data-by-silent-access.md). } ``` -- Configure the subscription information [proxyData](../reference/apis-form-kit/js-apis-app-form-formBindingData.md#proxydata10) in the [onAddForm](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md#onaddform) callback and return the information to the Widget Manager through [formBinding](../reference/apis-form-kit/js-apis-app-form-formBindingData.md#formbindingdata). In this example, **key** is set to **datashareproxy://com.samples.widgetupdatebyproxy/weather** and **subscriberId** is set to **11**. +- Configure the subscription information [proxyData](../reference/apis-form-kit/js-apis-app-form-formBindingData.md#proxydata10) in the [onAddForm](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md#formextensionabilityonaddform) callback and return the information to the Widget Manager through [formBinding](../reference/apis-form-kit/js-apis-app-form-formBindingData.md#formbindingdata). In this example, **key** is set to **datashareproxy://com.samples.widgetupdatebyproxy/weather** and **subscriberId** is set to **11**. > **NOTE** > > The value of **key** can be a URI or a simple string. The default value of **subscriberId** is the value of **formId**. The actual value depends on the definition of the data provider. @@ -104,7 +105,7 @@ For details, see [Data Management](../database/share-data-by-silent-access.md). } ``` -- In the [widget page code file](arkts-ui-widget-creation.md), use the variable in LocalStorage to obtain the subscribed data. The variable in LocalStorage is bound to a string and updates the subscribed data in the key:value pair format. The key must be the same as that subscribed to by the widget provider. In this example, the subscribed data is obtained through **'city'** and displayed in the **Text** component. +- In the [widget page code file](arkts-ui-widget-creation.md), use the variable in LocalStorage to obtain the subscribed data. The variable in LocalStorage is bound to a string and updates the subscribed data in the key:value pair format. The key must be the same as that subscribed to by the widget provider. In this example, the subscribed data is obtained through **'city'** and displayed in the **\** component. ```ts let storageProcess = new LocalStorage(); @@ -130,8 +131,8 @@ For details, see [Data Management](../database/share-data-by-silent-access.md). } ``` -## Widget Provider Development (Persistent Data; for System Applications Only) -- Set the **dataProxyEnabled** field to **true** in the **form_config.json** file to enable the update-through-proxy feature. +## Widget Provider Development (Persistent Data) +- Set the `dataProxyEnabled` field to `true` in the **form_config.json** file to enable the update-through-proxy feature. ```json { "forms": [ @@ -159,7 +160,7 @@ For details, see [Data Management](../database/share-data-by-silent-access.md). } ``` -- Add a subscription template [addTemplate](../reference/apis-arkdata/js-apis-data-dataShare-sys.md#addtemplate10) to the [onAddForm](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md#onaddform) callback and use the template predicates to notify the database of the subscribed data conditions. Then, configure the subscription information [proxyData](../reference/apis-form-kit/js-apis-app-form-formBindingData.md#proxydata10) and return it to the Widget Manager through [formBinding](../reference/apis-form-kit/js-apis-app-form-formBindingData.md#formbindingdata). In the example, the predicate is set to **"list": "select type from TBL00 limit 0,1"**, indicating that the first data record in the **type** column is obtained from the **TBL00** database. The data is returned to the widget page code file **widgets.abc** in {"list":[{"type":"value0"}]} format. When the subscribed persistent data is updated, the system automatically updates the widget data. +- Add a subscription template [addTemplate](../reference/apis-arkdata/js-apis-data-dataShare-sys.md#addtemplate10) to the [onAddForm](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md#formextensionabilityonaddform) callback and use the template predicates to notify the database of the subscribed data conditions. Then, configure the subscription information [proxyData](../reference/apis-form-kit/js-apis-app-form-formBindingData.md#proxydata10) and return it to the Widget Manager through [FormBindingData](../reference/apis-form-kit/js-apis-app-form-formBindingData.md#formbindingdata). In the example, the predicate is set to `"list" : "select type from TBL00 limit 0,1"`, indicating that the first data record in the **type** column is obtained from the **TBL00** database. The data is returned to the widget page code file **widgets.abc** in `{"list":[{"type":"value0"}]}` format. When the subscribed persistent data is updated, the system automatically updates the widget data. > **NOTE** > @@ -202,7 +203,7 @@ For details, see [Data Management](../database/share-data-by-silent-access.md). } ``` -- In the [widget page code file](arkts-ui-widget-creation.md), use the variable in LocalStorage to obtain the subscribed data. The variable in LocalStorage is bound to a string and updates the subscribed data in the key:value pair format. The key must be the same as that subscribed to by the widget provider. In the example, the subscribed data is obtained through **'list'**, and the value of the first element is displayed on the **Text** component. +- In the [widget page code file](arkts-ui-widget-creation.md), use the variable in LocalStorage to obtain the subscribed data. The variable in LocalStorage is bound to a string and updates the subscribed data in the key:value pair format. The key must be the same as that subscribed to by the widget provider. In the example, the subscribed data is obtained through **'list'**, and the value of the first element is displayed on the **\** component. ```ts let storagePersis = new LocalStorage(); diff --git a/en/application-dev/form/arkts-ui-widget-update-by-status.md b/en/application-dev/form/arkts-ui-widget-update-by-status.md index 4905a54afdef26897002e2babb8b790627b140e8..aaef4dd2e875759db5a45afe2c3f0ef3ec70554e 100644 --- a/en/application-dev/form/arkts-ui-widget-update-by-status.md +++ b/en/application-dev/form/arkts-ui-widget-update-by-status.md @@ -1,8 +1,7 @@ # Updating Widget Content by State -There are cases where multiple copies of the same widget are added to the home screen to accommodate different needs. In these cases, the widget content needs to be dynamically updated based on the state. This topic exemplifies how this is implemented. -In the following example, two copies of the weather widget are added to the home screen: one for displaying the weather of London, and the other Beijing, both configured to be updated at 07:00 every morning. The widget provider detects the target city, and then displays the city-specific weather information on the widgets. +There are cases where multiple copies of the same widget are added to the home screen to accommodate different needs. In these cases, the widget content needs to be dynamically updated based on the state. This topic exemplifies how this is implemented. In the following example, two copies of the weather widget are added to the home screen: one for displaying the weather of London, and the other Beijing, both configured to be updated at 07:00 every morning. The widget provider detects the target city, and then displays the city-specific weather information on the widgets. - Widget configuration file: Configure the widget to be automatically updated every 30 minutes. @@ -251,4 +250,4 @@ In the following example, two copies of the weather widget are added to the home > **NOTE** > -> When the local database is used for widget information persistence, it is recommended that [TEMPORARY_KEY](../reference/apis-form-kit/js-apis-app-form-formInfo.md#formparam) be used in the [onAddForm](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md#onaddform) lifecycle callback to determine whether the currently added widget is a normal one. If the widget is a normal one, the widget information is directly persisted. If the widget is a temporary one, the widget information is persisted when the widget is converted to a normal one ([onCastToNormalForm](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md#oncasttonormalform)). In addition, the persistent widget information needs to be deleted when the widget is destroyed ([onRemoveForm](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md#onremoveform)), preventing the database size from continuously increasing due to repeated widget addition and deletion. +> When the local database is used for widget information persistence, it is recommended that [TEMPORARY_KEY](../reference/apis-form-kit/js-apis-app-form-formInfo.md#formparam) be used in the [onAddForm](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md#formextensionabilityonaddform) lifecycle callback to determine whether the currently added widget is a normal one. If the widget is a normal one, the widget information is directly persisted. If the widget is a temporary one, the widget information is persisted when the widget is converted to a normal one ([onCastToNormalForm](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md#formextensionabilityoncasttonormalform)). In addition, the persistent widget information needs to be deleted when the widget is destroyed ([onRemoveForm](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md#formextensionabilityonremoveform)), preventing the database size from continuously increasing due to repeated widget addition and deletion. diff --git a/en/application-dev/form/figures/WidgetTransitionAnimation.gif b/en/application-dev/form/figures/WidgetTransitionAnimation.gif new file mode 100644 index 0000000000000000000000000000000000000000..50803297e76e53ec8f9e69de44eca80da74c2c69 Binary files /dev/null and b/en/application-dev/form/figures/WidgetTransitionAnimation.gif differ diff --git a/en/application-dev/form/figures/form-process.png b/en/application-dev/form/figures/form-process.png new file mode 100644 index 0000000000000000000000000000000000000000..117f773dd6b3ffb44e11628da8c95ff32932c56a Binary files /dev/null and b/en/application-dev/form/figures/form-process.png differ diff --git a/en/application-dev/form/figures/live-form-base-demo.gif b/en/application-dev/form/figures/live-form-base-demo.gif new file mode 100644 index 0000000000000000000000000000000000000000..f9f613aa42ebd9de0e1992ae52b16ce3d7a60fe0 Binary files /dev/null and b/en/application-dev/form/figures/live-form-base-demo.gif differ diff --git a/en/application-dev/form/figures/live-form-click-timeline.png b/en/application-dev/form/figures/live-form-click-timeline.png new file mode 100644 index 0000000000000000000000000000000000000000..5a1d1a0923e5b49ef80a603067ef8525891a2d0b Binary files /dev/null and b/en/application-dev/form/figures/live-form-click-timeline.png differ diff --git a/en/application-dev/form/figures/live-form-game-demo.gif b/en/application-dev/form/figures/live-form-game-demo.gif new file mode 100644 index 0000000000000000000000000000000000000000..9b3781c79187f301bcfc7ca83cc381e30e3969dd Binary files /dev/null and b/en/application-dev/form/figures/live-form-game-demo.gif differ diff --git a/en/application-dev/form/figures/live-form-judge.png b/en/application-dev/form/figures/live-form-judge.png new file mode 100644 index 0000000000000000000000000000000000000000..647bb81aabcb5cf78b53e75a93ac42f83a84b7fc Binary files /dev/null and b/en/application-dev/form/figures/live-form-judge.png differ diff --git a/en/application-dev/form/figures/live-form-overflow-rule.png b/en/application-dev/form/figures/live-form-overflow-rule.png new file mode 100644 index 0000000000000000000000000000000000000000..d62343f5fe74a6559d69d29df03b7545958c78af Binary files /dev/null and b/en/application-dev/form/figures/live-form-overflow-rule.png differ diff --git a/en/application-dev/form/figures/live-form-pause-game.jpg b/en/application-dev/form/figures/live-form-pause-game.jpg new file mode 100644 index 0000000000000000000000000000000000000000..4047a654da2d8c666b22b507beeda2e7c509fe40 Binary files /dev/null and b/en/application-dev/form/figures/live-form-pause-game.jpg differ diff --git a/en/application-dev/form/figures/live-form-running-game.gif b/en/application-dev/form/figures/live-form-running-game.gif new file mode 100644 index 0000000000000000000000000000000000000000..f83b769a9103d6f63384a5e5609348e4ac525b16 Binary files /dev/null and b/en/application-dev/form/figures/live-form-running-game.gif differ diff --git a/en/application-dev/form/figures/live-form-status-change.png b/en/application-dev/form/figures/live-form-status-change.png new file mode 100644 index 0000000000000000000000000000000000000000..ae56a713ba0d2006ecf85d01ee5aacbbc6412717 Binary files /dev/null and b/en/application-dev/form/figures/live-form-status-change.png differ diff --git a/en/application-dev/form/figures/live-form-stop-game.jpg b/en/application-dev/form/figures/live-form-stop-game.jpg new file mode 100644 index 0000000000000000000000000000000000000000..e21bef7ccaf2fd56046c0a23964ff1dd15aca93d Binary files /dev/null and b/en/application-dev/form/figures/live-form-stop-game.jpg differ diff --git a/en/application-dev/form/figures/live-form-update-timeline.png b/en/application-dev/form/figures/live-form-update-timeline.png new file mode 100644 index 0000000000000000000000000000000000000000..e13330236f9dde5312b13a4500ae7890ec86b194 Binary files /dev/null and b/en/application-dev/form/figures/live-form-update-timeline.png differ diff --git a/en/application-dev/form/figures/live-form-weather-demo.gif b/en/application-dev/form/figures/live-form-weather-demo.gif new file mode 100644 index 0000000000000000000000000000000000000000..f972bc04e6152d5a5e69df2376a5232a6f23849e Binary files /dev/null and b/en/application-dev/form/figures/live-form-weather-demo.gif differ diff --git a/en/application-dev/form/formkit-overview.md b/en/application-dev/form/formkit-overview.md index 81e2a40d9e5519a97d576e075dbb6d6c5b8aedd1..5c2bb75903a89a9dcf5da42796e197601123c616 100644 --- a/en/application-dev/form/formkit-overview.md +++ b/en/application-dev/form/formkit-overview.md @@ -2,32 +2,28 @@ Form Kit provides a development framework and APIs for embedding application information into system entries like the home screen and lock screen. It can extract key user information or frequent operations into service widgets (referred to as "widgets"), which can be added to the home screen for easy access to information and direct service interactions. ## Scenarios for Widget Usage -- Devices supported: Widgets can be used on devices such as phones and tablets. +- Supported devices: smartphones, tablets, PCs/2-in-1 devices, smart TVs, smart watches, and head units. This kit is not supported on lite wearables. - Type supported: Both applications and atomic services can develop widgets. - Widget location: Widgets can be added to system applications such as the home screen and lock screen. Currently, they cannot be embedded in common applications. +- To use a widget: -## Widget Architecture -**Figure 1** Widget architecture +1. Touch and hold an application icon on the home screen to display the shortcut menu. +2. Touch **Service widget** to access the widget management page and preview the widget. +3. Touch the **Add to home** button. The widget is then added to the home screen. + +**Figure 1** Typical procedure of using a widget +![WidgetUse](figures/WidgetUse.png) +## Widget Architecture +**Figure 2** Widget architecture ![formKit_l0](figures/formKit_l0.PNG) **Fundamental Concepts in Widget Usage Scenarios** - Widget host: an application that displays the widget content and controls the widget location. It enables direct user interactions and manages widget addition, deletion, and display. An example is the home screen in the preceding figure. - Widget provider: an application or atomic service that provides the widget. It is responsible for implementing the widget features, including designing the UI, updating data, and handling click interactions. - - Widget manager: a system service within the operating system that manages all widget information on the device. As a bridge between widget providers and hosts, it offers capabilities such as querying, adding, and deleting widget information to the hosts, and provides notifications like widget addition, deletion, refresh, and click events to the providers. -Below is the typical procedure of using a widget: - -**Figure 2** Typical procedure of using a widget - -![WidgetUse](figures/WidgetUse.png) - -1. Touch and hold an application icon on the home screen to display the shortcut menu. -2. Touch **Service widget** to access the preview screen. -3. Touch the **Add to home** button. The widget is then added to the home screen. - ## Features - Information display: Key information from applications or atomic services is displayed on the home screen as widgets. The information can be updated periodically so that users can view relevant information at any time. @@ -60,11 +56,4 @@ ArkTS widgets and JS widgets have different implementation principles and featur - Ability Kit: Form Kit relies on the Extension abilities of Ability Kit for its internal implementation and interacts with Ability Kit during lifecycle scheduling. - ArkUI: Form Kit widget hosts can use some components, events, animations, and state management capabilities provided by ArkUI on their pages. -## Constraints -**Constraints on UI Capabilities** - -Given the limited size of widgets, they are designed to convey straightforward and unambiguous information and support simple interactions. As a result, the scope of UI components and animation features available for use in widget development are somewhat restricted. - -**Constraints on Motion Capabilities** - -Widgets offer the functionality for applications and atomic services to maintain a constant presence for information display and updates on interfaces like the home screen. However, the system enforces specific constraints on the frequency of updates and the operational capabilities of widgets running in the background. + diff --git a/en/application-dev/form/js-ui-widget-development.md b/en/application-dev/form/js-ui-widget-development.md index 293bcbeffa65c03e8d439ee6d1d1aa0fca2a36dc..5aed588fd5e45b9dd9be4aeba5ce7b1e58a2471d 100644 --- a/en/application-dev/form/js-ui-widget-development.md +++ b/en/application-dev/form/js-ui-widget-development.md @@ -1,47 +1,5 @@ -# Developing a JS Widget - - -The following describes how to develop JS widgets based on the web-like development paradigm. - - -## Working Principles - -Below shows the working principles of the widget framework. - -**Figure 1** Widget framework working principles in the stage model - -![JSCardPrinciple](figures/JSCardPrinciple.png) - -The widget host consists of the following modules: - -- Widget usage: provides operations such as creating, deleting, or updating a widget. - -- Communication adapter: provided by the SDK for communication with the Widget Manager. It sends widget-related operations to the Widget Manager. - -The Widget Manager consists of the following modules: - -- Periodic updater: starts a scheduled task based on the update policy to periodically update a widget after it is added to the Widget Manager. - -- Cache manager: caches view information of a widget after it is added to the Widget Manager. This enables the cached data to be directly returned when the widget is obtained next time, greatly reducing the latency. - -- Lifecycle manager: suspends update when a widget is switched to the background or is blocked, and updates and/or clears widget data during upgrade and deletion. - -- Object manager: manages RPC objects of the widget host. It is used to verify requests from the widget host and process callbacks after the widget update. - -- Communication adapter: communicates with the widget host and provider through RPCs. - -The widget provider consists of the following modules: - -- Widget service: implemented by the widget provider developer to process requests on widget creation, update, and deletion, and to provide corresponding widget services. - -- Instance manager: implemented by the widget provider developer for persistent management of widget instances allocated by the Widget Manager. - -- Communication adapter: provided by the SDK for communication with the Widget Manager. It pushes update data to the Widget Manager. - -> **NOTE** -> -> You only need to develop the widget provider. The system automatically handles the work of the widget host and Widget Manager. - +# Developing a JS Widget (Stage Model) +The stage model is supported since API version 9. It is the mainstream model with a long evolution plan. This model is object-oriented and provides open application components as classes. You can derive application components for capability expansion. ## Available APIs @@ -49,29 +7,29 @@ The **FormExtensionAbility** class has the following APIs. For details, see [For | Name | Description| | -------- | -------- | -| onAddForm(want: Want): formBindingData.FormBindingData | Called to notify the widget provider that a widget is being created.| -| onCastToNormalForm(formId: string): void | Called to notify the widget provider that a temporary widget is being converted to a normal one.| -| onUpdateForm(formId: string): void | Called to notify the widget provider that a widget is being updated.| -| onChangeFormVisibility(newStatus: Record<string, number>): void | Called to notify the widget provider that the widget visibility status is being changed.| -| onFormEvent(formId: string, message: string): void | Called to instruct the widget provider to process a widget event.| -| onRemoveForm(formId: string): void | Called to notify the widget provider that a widget is being destroyed.| -| onConfigurationUpdate(newConfig: Configuration): void | Called when the configuration of the environment where the widget is running is being updated.| -| onShareForm?(formId: string): Record<string, Object> | Called to notify the widget provider that the widget host is sharing the widget data.| +| onAddForm(want: Want): formBindingData.FormBindingData | Called to notify the widget provider that a widget is being created.| +| onCastToNormalForm(formId: string): void | Called to notify the widget provider that a temporary widget is being converted to a normal one.| +| onUpdateForm(formId: string): void | Called to notify the widget provider that a widget is being updated.| +| onChangeFormVisibility(newStatus: Record<string, number>): void | Called to notify the widget provider that the widget visibility status is being changed.| +| onFormEvent(formId: string, message: string): void | Called to instruct the widget provider to process a widget event.| +| onRemoveForm(formId: string): void | Called to notify the widget provider that a widget is being destroyed.| +| onConfigurationUpdate(newConfig: Configuration): void | Called when the configuration of the environment where the widget is running is being updated.| +| onShareForm?(formId: string): Record<string, Object> | Called to notify the widget provider that the widget host is sharing the widget data.| The **FormProvider** class has the following APIs. For details, see [FormProvider](../reference/apis-form-kit/js-apis-app-form-formProvider.md). | Name| Description| | -------- | -------- | -| setFormNextRefreshTime(formId: string, minute: number, callback: AsyncCallback<void>): void | Sets the next refresh time for a widget. This API uses an asynchronous callback to return the result.| -| setFormNextRefreshTime(formId: string, minute: number): Promise<void> | Sets the next refresh time for a widget. This API uses a promise to return the result.| -| updateForm(formId: string, formBindingData: formBindingData.FormBindingData, callback: AsyncCallback<void>): void | Updates a widget. This API uses an asynchronous callback to return the result.| -| updateForm(formId: string, formBindingData: formBindingData.FormBindingData): Promise<void> | Updates a widget. This API uses a promise to return the result.| +| setFormNextRefreshTime(formId: string, minute: number, callback: AsyncCallback<void>): void | Sets the next refresh time for a widget. This API uses an asynchronous callback to return the result.| +| setFormNextRefreshTime(formId: string, minute: number): Promise<void> | Sets the next refresh time for a widget. This API uses a promise to return the result.| +| updateForm(formId: string, formBindingData: formBindingData.FormBindingData, callback: AsyncCallback<void>): void | Updates a widget. This API uses an asynchronous callback to return the result.| +| updateForm(formId: string, formBindingData: formBindingData.FormBindingData): Promise<void> | Updates a widget. This API uses a promise to return the result.| The **FormBindingData** class has the following APIs. For details, see [FormBindingData](../reference/apis-form-kit/js-apis-app-form-formBindingData.md). | Name| Description| | -------- | -------- | -| createFormBindingData(obj?: Object \| string): FormBindingData | Creates a **FormBindingData** object.| +| createFormBindingData(obj?: Object \| string): FormBindingData | Creates a **FormBindingData** object.| ## How to Develop @@ -400,64 +358,66 @@ You can use the web-like paradigm (HML+CSS+JSON) to develop JS widget pages. Thi - CSS: defines style information about the web-like paradigm components in HML. - ```css - .container { - flex-direction: column; - justify-content: center; - align-items: center; - } - - .bg-img { - flex-shrink: 0; - height: 100%; - } - - .container-inner { - flex-direction: column; - justify-content: flex-end; - align-items: flex-start; - height: 100%; - width: 100%; - padding: 12px; - } - - .title { - font-size: 19px; - font-weight: bold; - color: white; - text-overflow: ellipsis; - max-lines: 1; - } - - .detail_text { - font-size: 16px; - color: white; - opacity: 0.66; - text-overflow: ellipsis; - max-lines: 1; - margin-top: 6px; - } - ``` + + ```css + .container { + flex-direction: column; + justify-content: center; + align-items: center; + } + + .bg-img { + flex-shrink: 0; + height: 100%; + } + + .container-inner { + flex-direction: column; + justify-content: flex-end; + align-items: flex-start; + height: 100%; + width: 100%; + padding: 12px; + } + + .title { + font-size: 19px; + font-weight: bold; + color: white; + text-overflow: ellipsis; + max-lines: 1; + } + + .detail_text { + font-size: 16px; + color: white; + opacity: 0.66; + text-overflow: ellipsis; + max-lines: 1; + margin-top: 6px; + } + ``` - JSON: defines data and event interaction on the widget UI page. - ```json - { - "data": { - "title": "TitleDefault", - "detail": "TextDefault" - }, - "actions": { - "routerEvent": { - "action": "router", - "abilityName": "EntryAbility", - "params": { - "message": "add detail" - } + + ```json + { + "data": { + "title": "TitleDefault", + "detail": "TextDefault" + }, + "actions": { + "routerEvent": { + "action": "router", + "abilityName": "EntryAbility", + "params": { + "message": "add detail" } } } - ``` + } + ``` ### Developing Widget Events @@ -483,6 +443,7 @@ The following are examples: - HML file: + ```html
@@ -501,94 +462,96 @@ The following are examples: - CSS file: - ```css - .container { - flex-direction: column; - justify-content: center; - align-items: center; - } - - .bg-img { - flex-shrink: 0; - height: 100%; - z-index: 1; - } - - .bottom-img { - position: absolute; - width: 150px; - height: 56px; - top: 63%; - background-color: rgba(216, 216, 216, 0.15); - filter: blur(20px); - z-index: 2; - } - - .container-inner { - flex-direction: column; - justify-content: flex-end; - align-items: flex-start; - height: 100%; - width: 100%; - padding: 12px; - } - - .title { - font-family: HarmonyHeiTi-Medium; - font-size: 14px; - color: rgba(255, 255, 255, 0.90); - letter-spacing: 0.6px; - font-weight: 500; - width: 100%; - text-overflow: ellipsis; - max-lines: 1; - } - - .detail_text { - ffont-family: HarmonyHeiTi; - font-size: 12px; - color: rgba(255, 255, 255, 0.60); - letter-spacing: 0.51px; - font-weight: 400; - text-overflow: ellipsis; - max-lines: 1; - margin-top: 6px; - width: 100%; - } - ``` + + ```css + .container { + flex-direction: column; + justify-content: center; + align-items: center; + } + + .bg-img { + flex-shrink: 0; + height: 100%; + z-index: 1; + } + + .bottom-img { + position: absolute; + width: 150px; + height: 56px; + top: 63%; + background-color: rgba(216, 216, 216, 0.15); + filter: blur(20px); + z-index: 2; + } + + .container-inner { + flex-direction: column; + justify-content: flex-end; + align-items: flex-start; + height: 100%; + width: 100%; + padding: 12px; + } + + .title { + font-family: HarmonyHeiTi-Medium; + font-size: 14px; + color: rgba(255, 255, 255, 0.90); + letter-spacing: 0.6px; + font-weight: 500; + width: 100%; + text-overflow: ellipsis; + max-lines: 1; + } + + .detail_text { + ffont-family: HarmonyHeiTi; + font-size: 12px; + color: rgba(255, 255, 255, 0.60); + letter-spacing: 0.51px; + font-weight: 400; + text-overflow: ellipsis; + max-lines: 1; + margin-top: 6px; + width: 100%; + } + ``` - JSON file: - ```json - { - "data": { - "title": "TitleDefault", - "detail": "TextDefault" + + ```json + { + "data": { + "title": "TitleDefault", + "detail": "TextDefault" + }, + "actions": { + "routerEvent": { + "action": "router", + "abilityName": "JSCardEntryAbility", + "params": { + "info": "router info", + "message": "router message" + } }, - "actions": { - "routerEvent": { - "action": "router", - "abilityName": "JSCardEntryAbility", - "params": { - "info": "router info", - "message": "router message" - } - }, - "messageEvent": { - "action": "message", - "params": { - "detail": "message detail" - } + "messageEvent": { + "action": "message", + "params": { + "detail": "message detail" } } } - ``` + } + ``` > **NOTE** > > **JSON Value** in **data** supports multi-level nested data. When updating data, ensure that complete data is carried. -Assume that a widget is displaying the course information of Mr. Zhang on July 18, as shown in the following code snippet. + Assume that a widget is displaying the course information of Mr. Zhang on July 18, as shown in the following code snippet. ```ts "data": { "Day": "07.18", @@ -598,7 +561,7 @@ Assume that a widget is displaying the course information of Mr. Zhang on July 1 } } ``` -To update the widget content to the course information of Mr. Li on July 18, you must pass the complete data as follows, instead of only a single date item such as **name** or **course**: + To update the widget content to the course information of Mr. Li on July 18, you must pass the complete data as follows, instead of only a single date item such as **name** or **course**: ```ts "teacher": { "name": "Mr.Li", @@ -609,53 +572,55 @@ To update the widget content to the course information of Mr. Li on July 18, you - Receive the router event in UIAbility and obtain parameters. - ```ts - import UIAbility from '@ohos.app.ability.UIAbility'; - import AbilityConstant from '@ohos.app.ability.AbilityConstant'; - import Want from '@ohos.app.ability.Want'; - import hilog from '@ohos.hilog'; - - const TAG: string = 'EtsCardEntryAbility'; - const DOMAIN_NUMBER: number = 0xFF00; - - export default class EtsCardEntryAbility extends UIAbility { - onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { - if (want.parameters) { - let params: Record = JSON.parse(JSON.stringify(want.parameters.params)); - // Obtain the info parameter passed in the router event. - if (params.info === 'router info') { - // Execute the service logic. - hilog.info(DOMAIN_NUMBER, TAG, `router info: ${params.info}`); - } - // Obtain the message parameter passed in the router event. - if (params.message === 'router message') { - // Execute the service logic. - hilog.info(DOMAIN_NUMBER, TAG, `router message: ${params.message}`); - } + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility'; + import AbilityConstant from '@ohos.app.ability.AbilityConstant'; + import Want from '@ohos.app.ability.Want'; + import hilog from '@ohos.hilog'; + + const TAG: string = 'EtsCardEntryAbility'; + const DOMAIN_NUMBER: number = 0xFF00; + + export default class EtsCardEntryAbility extends UIAbility { + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { + if (want.parameters) { + let params: Record = JSON.parse(JSON.stringify(want.parameters.params)); + // Obtain the info parameter passed in the router event. + if (params.info === 'router info') { + // Execute the service logic. + hilog.info(DOMAIN_NUMBER, TAG, `router info: ${params.info}`); + } + // Obtain the message parameter passed in the router event. + if (params.message === 'router message') { + // Execute the service logic. + hilog.info(DOMAIN_NUMBER, TAG, `router message: ${params.message}`); } } - }; - ``` + } + }; + ``` - Receive the message event in FormExtensionAbility and obtain parameters. - ```ts - import FormExtension from '@ohos.app.form.FormExtensionAbility'; - import hilog from '@ohos.hilog'; - - const TAG: string = 'FormAbility'; - const DOMAIN_NUMBER: number = 0xFF00; - - export default class FormAbility extends FormExtension { - onFormEvent(formId: string, message: string): void { - // If the widget supports event triggering, override this method and implement the trigger. - hilog.info(DOMAIN_NUMBER, TAG, '[EntryFormAbility] onFormEvent'); - // Obtain the detail parameter passed in the message event. - let msg: Record = JSON.parse(message); - if (msg.detail === 'message detail') { - // Execute the service logic. - hilog.info(DOMAIN_NUMBER, TAG, 'message info:' + msg.detail); - } + + ```ts + import FormExtension from '@ohos.app.form.FormExtensionAbility'; + import hilog from '@ohos.hilog'; + + const TAG: string = 'FormAbility'; + const DOMAIN_NUMBER: number = 0xFF00; + + export default class FormAbility extends FormExtension { + onFormEvent(formId: string, message: string): void { + // If the widget supports event triggering, override this method and implement the trigger. + hilog.info(DOMAIN_NUMBER, TAG, '[EntryFormAbility] onFormEvent'); + // Obtain the detail parameter passed in the message event. + let msg: Record = JSON.parse(message); + if (msg.detail === 'message detail') { + // Execute the service logic. + hilog.info(DOMAIN_NUMBER, TAG, 'message info:' + msg.detail); } - }; - ``` \ No newline at end of file + } + }; + ``` diff --git a/en/application-dev/form/js-ui-widget-overview.md b/en/application-dev/form/js-ui-widget-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..2e3bd6375b07ed745fed4c7ef68d017bb9f1e466 --- /dev/null +++ b/en/application-dev/form/js-ui-widget-overview.md @@ -0,0 +1,41 @@ +# JS Widget Overview + +JS widgets, developed using a web-like paradigm (HML + CSS + JSON), now support two [application models](../application-models/application-models.md): the FA model and the stage model. For details, see [Developing a JS Widget (Stage Model)](js-ui-widget-development.md) and [Developing a JS Widget (FA Model)](widget-development-fa.md). When developing a new widget, you are advised to use the ArkTS declarative syntax to build UIs. For details about the differences between the declarative paradigm and web-like paradigm, see [Introduction to ArkUI](../ui/arkui-overview.md). + +## How to Implement + +Below shows the working principles of the widget framework. + +**Figure 1** Working principles + +![JSCardPrinciple](figures/JSCardPrinciple.png) + +The widget host consists of the following modules: + +- Widget usage: provides operations such as creating, deleting, or updating a widget. + +- Communication adapter: provided by the SDK for communication with the Widget Manager. It sends widget-related operations to the Widget Manager. + +The Widget Manager consists of the following modules: + +- Periodic update: starts a scheduled task based on the update policy to periodically update a widget after it is added to the Widget Manager. + +- Cache manager: caches view information of a widget after it is added to the Widget Manager. This enables the cached data to be directly returned when the widget is obtained next time, greatly reducing the latency. + +- Lifecycle manager: suspends update when a widget is switched to the background or is blocked, and updates and/or clears widget data during upgrade and deletion. + +- Object manager: manages RPC objects of the widget host. It is used to verify requests from the widget host and process callbacks after the widget update. + +- Communication adapter: communicates with the widget host and provider through RPCs. + +The widget provider consists of the following modules: + +- Widget service: implemented by the widget provider developer to process requests on widget creation, update, and deletion, and to provide corresponding widget services. + +- Instance manager: implemented by the widget provider developer for persistent management of widget instances allocated by the Widget Manager. + +- Communication adapter: provided by the SDK for communication with the Widget Manager. It pushes update data to the Widget Manager. + +> **NOTE** +> +> You only need to develop the widget provider. The system automatically handles the work of the widget host and Widget Manager. diff --git a/en/application-dev/form/widget-development-fa.md b/en/application-dev/form/widget-development-fa.md index 3e141b09350e282dcf97dd4fde1c7de73a493bfa..373bf59013aa32a1c3c08f77d82cb10d49661f7b 100644 --- a/en/application-dev/form/widget-development-fa.md +++ b/en/application-dev/form/widget-development-fa.md @@ -1,59 +1,5 @@ -# Service Widget Development in FA Model - - -## Widget Overview - -A service widget (also called widget) is a set of UI components that display important information or operations specific to an application. It provides users with direct access to a desired application service, without the need to open the application first. - -A widget usually appears as a part of the UI of another application (which currently can only be a system application) and provides basic interactive features such as opening a UI page or sending a message. - -Before you get started, it would be helpful if you have a basic understanding of the following concepts: - -- Widget host: an application that displays the widget content and controls the widget location. - -- Widget Manager: a resident agent that provides widget management features such as periodic widget updates. - -- Widget provider: an atomic service that provides the widget content to display and controls how widget components are laid out and how they interact with users. - - -## Working Principles - -Figure 1 shows the working principles of the widget framework. - -**Figure 1** Widget framework working principles in the FA model - -![form-extension](figures/form-extension.png) - -The widget host consists of the following modules: - -- Widget usage: provides operations such as creating, deleting, or updating a widget. - -- Communication adapter: provided by the OpenHarmony SDK for communication with the Widget Manager. It sends widget-related operations to the Widget Manager. - -The Widget Manager consists of the following modules: - -- Periodic updater: starts a scheduled task based on the update policy to periodically update a widget after it is added to the Widget Manager. - -- Cache manager: caches view information of a widget after it is added to the Widget Manager to directly return the cached data when the widget is obtained next time. This reduces the latency greatly. - -- Lifecycle manager: suspends update when a widget is switched to the background or is blocked, and updates and/or clears widget data during upgrade and deletion. - -- Object manager: manages RPC objects of the widget host. It is used to verify requests from the widget host and process callbacks after the widget update. - -- Communication adapter: communicates with the widget host and provider through RPCs. - -The widget provider consists of the following modules: - -- Widget service: implemented by the widget provider developer to process requests on widget creation, update, and deletion, and to provide corresponding widget services. - -- Instance manager: implemented by the widget provider developer for persistent management of widget instances allocated by the Widget Manager. - -- Communication adapter: provided by the OpenHarmony SDK for communication with the Widget Manager. It pushes update data to the Widget Manager. - -> **NOTE** -> -> You only need to develop the widget provider. The system automatically handles the work of the widget host and Widget Manager. - +# Developing a JS Widget (FA Model) +The FA model is supported since API version 7, and no longer recommended. Application components are specified by exporting anonymous objects and fixed entry files. You cannot perform derivation for capability expansion. Now, the stage model is recommended for application development. ## Available APIs @@ -64,7 +10,7 @@ The **FormAbility** has the following APIs. | onCreate(want: Want): formBindingData.FormBindingData | Called to notify the widget provider that a widget has been created.| | onCastToNormal(formId: string): void | Called to notify the widget provider that a temporary widget has been converted to a normal one.| | onUpdate(formId: string): void | Called to notify the widget provider that a widget has been updated.| -| onVisibilityChange(newStatus: Record<string, number>): void | Called to notify the widget provider of the change in widget visibility.| +| onVisibilityChange(newStatus: Record<string, number>): void | Called to notify the widget provider of the change in widget visibility.| | onEvent(formId: string, message: string): void | Called to instruct the widget provider to receive and process a widget event.| | onDestroy(formId: string): void | Called to notify the widget provider that a widget has been destroyed.| | onAcquireFormState?(want: Want): formInfo.FormState | Called to instruct the widget provider to receive the status query result of a widget.| @@ -300,7 +246,7 @@ The widget configuration file is named **config.json**. Find the **config.json** | description | Description of the widget. The value can be a string or a resource index to descriptions in multiple languages. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| | isDefault | Whether the widget is a default one. Each ability has only one default widget.
**true**: The widget is the default one.
**false**: The widget is not the default one.| Boolean| No| | type | Type of the widget. The value can be:
**JS**: indicates a JavaScript-programmed widget.| String| No| - | colorMode | Color mode of the widget.
**auto**: The widget adopts the auto-adaptive color mode.
**dark**: The widget adopts the dark color mode.
**light**: The widget adopts the light color mode.| String| Yes (initial value: **auto**)| + | colorMode(deprecated) | Color mode of the widget.
**auto**: The widget adopts the auto-adaptive color mode.
**dark**: The widget adopts the dark color mode.
**light**: The widget adopts the light color mode.
**NOTE**

This API is deprecated since API version 20. The color mode follows the system color mode.| String| Yes (initial value: **auto**)| | supportDimensions | Grid styles supported by the widget.
**1 * 2**: indicates a grid with one row and two columns.
**2 * 2**: indicates a grid with two rows and two columns.
**2 * 4**: indicates a grid with two rows and four columns.
**4 * 4**: indicates a grid with four rows and four columns.| String array| No| | defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String| No| | updateEnabled | Whether the widget can be updated periodically.
**true**: The widget can be updated at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** takes precedence over **scheduledUpdateTime**.
**false**: The widget cannot be updated periodically.| Boolean| No| @@ -335,7 +281,6 @@ The widget configuration file is named **config.json**. Find the **config.json** "defaultDimension": "2*2", "name": "widget", "description": "This is a service widget.", - "colorMode": "auto", "type": "JS", "formVisibleNotify": true, "supportDimensions": [ diff --git a/en/application-dev/form/widget-host-development-guide.md b/en/application-dev/form/widget-host-development-guide.md index 6f58b68ffa9d6cb9a4b94c5c8ab314a14d4d1eb6..0fd70b9f9fbd49e414043dec8c1c27a5be71e153 100644 --- a/en/application-dev/form/widget-host-development-guide.md +++ b/en/application-dev/form/widget-host-development-guide.md @@ -37,7 +37,7 @@ Carry out the following operations to develop the widget host based on the stage > > - The APIs provided by this component are system APIs. -When a widget is added through **FormComponent**, the [onAddForm](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md#onaddform) API in **FormExtensionAbility** of the widget provider is called. +When a widget is added through **FormComponent**, the [onAddForm](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md#formextensionabilityonaddform) API in **FormExtensionAbility** of the widget provider is called. ### Temporary and Normal Widgets @@ -107,7 +107,6 @@ struct formHostSample { descriptionId: 0, type: formInfo.FormType.eTS, jsComponentName: '', - colorMode: formInfo.ColorMode.MODE_AUTO, isDefault: false, updateEnabled: false, formVisibleNotify: true, @@ -131,14 +130,14 @@ struct formHostSample { try { // Check whether the system is ready. formHost.isSystemReady().then(() => { - console.log('formHost isSystemReady success'); + console.info('formHost isSystemReady success'); // Subscribe to events indicating that a widget becomes invisible and events indicating that a widget becomes visible. let notifyInvisibleCallback = (data: formInfo.RunningFormInfo[]) => { - console.log(`form change invisibility, data: ${JSON.stringify(data)}`); + console.info(`form change invisibility, data: ${JSON.stringify(data)}`); } let notifyVisibleCallback = (data: formInfo.RunningFormInfo[]) => { - console.log(`form change visibility, data: ${JSON.stringify(data)}`); + console.info(`form change visibility, data: ${JSON.stringify(data)}`); } formObserver.on('notifyInvisible', notifyInvisibleCallback); formObserver.on('notifyVisible', notifyVisibleCallback); @@ -152,7 +151,7 @@ struct formHostSample { } catch (errData) { let message = (errData as BusinessError).message; let errCode = (errData as BusinessError).code; - console.log(`errData is errCode:${errCode} message:${message}`); + console.error(`errData is errCode:${errCode} message:${message}`); } // Subscribe to bundle update events. try { @@ -163,7 +162,7 @@ struct formHostSample { } catch (errData) { let message = (errData as BusinessError).message; let errCode = (errData as BusinessError).code; - console.log(`errData is errCode:${errCode} message:${message}`); + console.error(`errData is errCode:${errCode} message:${message}`); } // Subscribe to bundle uninstall events. try { @@ -174,7 +173,7 @@ struct formHostSample { } catch (errData) { let message = (errData as BusinessError).message; let errCode = (errData as BusinessError).code; - console.log(`errData is errCode:${errCode} message:${message}`); + console.error(`errData is errCode:${errCode} message:${message}`); } }).catch((error: BusinessError) => { console.error(`error, code: ${error.code}, message: ${error.message}`); @@ -188,7 +187,7 @@ struct formHostSample { aboutToDisappear(): void { // Delete all widgets. this.formIds.forEach((id) => { - console.log('delete all form') + console.info('delete all form') formHost.deleteForm(id); }); // Unsubscribe from bundle installation events. @@ -197,7 +196,7 @@ struct formHostSample { } catch (errData) { let message = (errData as BusinessError).message; let errCode = (errData as BusinessError).code; - console.log(`errData is errCode:${errCode} message:${message}`); + console.error(`errData is errCode:${errCode} message:${message}`); } // Unsubscribe from bundle update events. try { @@ -205,7 +204,7 @@ struct formHostSample { } catch (errData) { let message = (errData as BusinessError).message; let errCode = (errData as BusinessError).code; - console.log(`errData is errCode:${errCode} message:${message}`); + console.error(`errData is errCode:${errCode} message:${message}`); } // Unsubscribe from bundle uninstall events. try { @@ -213,7 +212,7 @@ struct formHostSample { } catch (errData) { let message = (errData as BusinessError).message; let errCode = (errData as BusinessError).code; - console.log(`errData is errCode:${errCode} message:${message}`); + console.error(`errData is errCode:${errCode} message:${message}`); } // Unsubscribe from events indicating that a widget becomes invisible and events indicating that a widget becomes visible. formObserver.off('notifyInvisible'); @@ -227,7 +226,7 @@ struct formHostSample { let formHapRecordMap: HashMap = new HashMap(); this.formInfoRecord = []; formHost.getAllFormsInfo().then((formList: Array) => { - console.log('getALlFormsInfo size:' + formList.length) + console.info('getALlFormsInfo size:' + formList.length) for (let formItemInfo of formList) { let formBundleName = formItemInfo.bundleName; if (formHapRecordMap.hasKey(formBundleName)) { @@ -276,8 +275,8 @@ struct formHostSample { Button($r('app.string.selectAddForm')) .enabled(this.showFormPicker) .onClick(() => { - console.info("TextPickerDialog: show()") - TextPickerDialog.show({ + console.info("showTextPickerDialog") + this.getUIContext().showTextPickerDialog({ range: this.formInfoRecord, selected: this.pickDialogIndex, canLoop: false, @@ -337,12 +336,12 @@ struct formHostSample { .borderRadius(10) .borderWidth(1) .onAcquired((form: FormCallbackInfo) => { - console.log(`onAcquired: ${JSON.stringify(form)}`) + console.info(`onAcquired: ${JSON.stringify(form)}`) this.selectFormId = form.id.toString(); this.formIds.add(this.selectFormId); }) .onRouter(() => { - console.log(`onRouter`) + console.info(`onRouter`) }) .onError((error) => { console.error(`onError: ${JSON.stringify(error)}`) @@ -350,7 +349,7 @@ struct formHostSample { }) .onUninstall((info: FormCallbackInfo) => { this.showForm = false; - console.error(`onUninstall: ${JSON.stringify(info)}`) + console.info(`onUninstall: ${JSON.stringify(info)}`) this.formIds.remove(this.selectFormId); }) @@ -395,7 +394,7 @@ struct formHostSample { if (error) { console.error(`deleteForm error, code: ${error.code}, message: ${error.message}`); } else { - console.log('formHost deleteForm success'); + console.info('formHost deleteForm success'); } }); } catch (error) { diff --git a/en/application-dev/reference/apis-form-kit/Readme-EN.md b/en/application-dev/reference/apis-form-kit/Readme-EN.md index 3aeb89e9b83a731b582c4989103099100787a541..feb028ddda05fdebf74bc3f6f13849c0b20368d8 100644 --- a/en/application-dev/reference/apis-form-kit/Readme-EN.md +++ b/en/application-dev/reference/apis-form-kit/Readme-EN.md @@ -6,6 +6,7 @@ - [@ohos.app.form.formInfo (FormInfo)](js-apis-app-form-formInfo.md) - [@ohos.app.form.formProvider (FormProvider)](js-apis-app-form-formProvider.md) - [@ohos.app.form.FormEditExtensionAbility (FormEditExtensionAbility)](js-apis-app-form-formEditExtensionAbility.md) + - [@ohos.app.form.LiveFormExtensionAbility (LiveFormExtensionAbility)](js-apis-app-form-LiveFormExtensionAbility.md) - [@ohos.app.form.formAgent (FormAgent) (System API)](js-apis-app-form-formAgent-sys.md) - [@ohos.app.form.FormExtensionAbility (FormExtensionAbility) (System API)](js-apis-app-form-formExtensionAbility-sys.md) @@ -17,6 +18,7 @@ - application - [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) - [FormEditExtensionContext](js-apis-inner-application-formEditExtensionContext.md) + - [LiveFormExtensionContext](js-apis-application-LiveFormExtensionContext.md) - [FormExtensionContext (System API)](js-apis-inner-application-formExtensionContext-sys.md) diff --git a/en/application-dev/reference/apis-form-kit/errorcode-form.md b/en/application-dev/reference/apis-form-kit/errorcode-form.md index 709aa6075e891300b399bd855a5bc34fba0698d9..69683a50f00a906234fadfe934842b8e4d6e9455 100644 --- a/en/application-dev/reference/apis-form-kit/errorcode-form.md +++ b/en/application-dev/reference/apis-form-kit/errorcode-form.md @@ -4,24 +4,6 @@ > > This topic describes only module-specific error codes. For details about universal error codes, see [Universal Error Codes](../errorcode-universal.md). -## 16500001 Internal Error - -**Error Message** - -Internal error. - -**Description** - -A common kernel error, for example, a malloc failure, occurs. - -**Possible Causes** - -The memory is insufficient. - -**Solution** - -Analyze the memory usage of the entire process, and check whether memory leakage occurs. - ## 16500050 IPC Failure **Error Message** @@ -149,42 +131,43 @@ The widget does not belong to the application. 1. Check the ownership of the widget ID. 2. Upgrade the application permission to **SystemApp**. -## 16501004 Ability Not Installed +## 16501006 Failed to Connect to the Widget Rendering Service **Error Message** -The ability is not installed. +FormRenderService is stopped. Connect to the service again. **Description** -The specified ability is not installed. +This error code is reported when the widget rendering service fails to be connected. **Possible Causes** -The specified ability is not installed. +The service is busy. **Solution** -Pass in valid **abilityName** and **bundleName**. +Try again later. -## 16501005 Failed to Connect to FormRenderService +## 16501007 Untrusted Widget **Error Message** -Failed to connect to FormRenderService. +Form is not trust. **Description** -The FormRenderService fails to be connected. +The widget is not trusted. **Possible Causes** -The service is busy. +The widget code has problems such as infinite loop and memory leakage, causing system exceptions. **Solution** -Try again later. +Check whether the widget code has an infinite loop or memory leakage. + ## 16501008 Adding a Widget to the Home Screen Times Out **Error Message** @@ -202,3 +185,158 @@ The service is busy. **Solution** Try again later. + + +## 16501010 Failed to Set the Background Image of the Interactive Widget + +**Error Message** + +Failed to set the live form background image. + +**Description** + +This error code is reported when the background image resource is invalid. + +**Possible Causes** + +The background image resource is invalid. + +**Solution** + +Check whether the background image resource is valid. + +## 16501011 Interactive Capabilities Not Supported + +**Error Message** + +The form can not support this operation, please check your fom_config's sceneAnimationParams configuration infomation is correct or not. + +**Description** + +This error code is reported when the current widget does not support interactive capabilities. + +**Possible Causes** + +The interactive widget animation is requested by a common widget, or the current interactive widget is incorrectly configured. + +**Solution** + +Check whether the configured [sceneAnimationParams](../../form/arkts-ui-widget-configuration.md#sceneanimationparams-field) of the current widget is correct. + +## 2293761 Internal Service Error + +**Error Message** + +Some internal server error occurs. + +**Description** + +An internal error occurs when the system executes the current request. + +**Possible Causes** + +An internal service execution exception occurs. + +**Solution** + +1. Restart the system and try again. +2. If the restart still fails, submit an [online ticket](https://developer.huawei.com/consumer/en/support/feedback/#) to obtain help. + +## 2293766 Requested Bundle Name Not Exist + +**Error Message** + +The requested bundle name does not exist. + +**Description** + +The requested bundle name does not exist. This is an internal error. + +**Possible Causes** + +An error occurs when the bundle management module obtains the bundle name of the requester. This is an internal service execution exception. + +**Solution** + +1. Restart the system and try again. +2. If the restart still fails, submit an [online ticket](https://developer.huawei.com/consumer/en/support/feedback/#) to obtain help. + +## 2293767 Invalid Parameter + +**Error Message** + +Invalid params received on operating form. + +**Description** + +Invalid input parameters are passed when the API is called. + +**Possible Causes** + +1. Mandatory parameters are not transferred. +2. The parameter type is incorrect. +3. The number of parameters is incorrect. +4. The input parameter is empty, for example, an empty string (''). +5. Incorrect parameter format. +6. Invalid parameter value. The input parameter must be the same as the corresponding configuration in [app.json5](../../quick-start/app-configuration-file.md) and [Configuring Widget Configuration Files](../../form/arkts-ui-widget-configuration.md). + +**Solution** + +Check the possible causes to determine whether mandatory parameters are transferred and whether the transferred parameter types are correct. + +## 2293795 Failed to Obtain the Bundle Manager Service + +**Error Message** + +Get bms rpc failed. + +**Description** + +Failed to obtain the Bundle Manager service. + +**Possible Causes** + +An internal service execution exception occurs. + +**Solution** + +1. Restart the system and try again. +2. If the restart still fails, submit an [online ticket](https://developer.huawei.com/consumer/en/support/feedback/#) to obtain help. + +## 2293798 Failed to Obtain the Widget Manager Service + +**Error Message** + +Get fms rpc failed. + +**Description** + +Failed to obtain the Widget Manager service. + +**Possible Causes** + +An internal service execution exception occurs. + +**Solution** + +1. Restart the system and try again. +2. If the restart still fails, submit an [online ticket](https://developer.huawei.com/consumer/en/support/feedback/#) to obtain help. + +## 2293802 Failed to Obtain the System Manager Service + +**Error Message** + +Get system manager service failed. + +**Description** + +Failed to obtain the System Manager service. + +**Possible Causes** + +An internal service execution exception occurs. + +**Solution** + +1. Restart the system and try again. +2. If the restart still fails, submit an [online ticket](https://developer.huawei.com/consumer/en/support/feedback/#) to obtain help. diff --git a/en/application-dev/reference/apis-form-kit/js-apis-app-form-LiveFormExtensionAbility.md b/en/application-dev/reference/apis-form-kit/js-apis-app-form-LiveFormExtensionAbility.md new file mode 100644 index 0000000000000000000000000000000000000000..8fefaf3c724eae04a9e5f36899c4f38970c4b080 --- /dev/null +++ b/en/application-dev/reference/apis-form-kit/js-apis-app-form-LiveFormExtensionAbility.md @@ -0,0 +1,110 @@ +# @ohos.app.form.LiveFormExtensionAbility (LiveFormExtensionAbility) + +The **LiveFormExtensionAbility** module, inherited from [ExtensionAbility](../apis-ability-kit/js-apis-app-ability-extensionAbility.md), provides interactive widget functions, including creating and destroying interactive widgets. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 20. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> The APIs of this module can be used only in the stage model. + +## Modules to Import + +```ts +import { LiveFormExtensionAbility } from '@kit.FormKit'; +``` +## LiveFormExtensionAbility +Interactive widget extension class. It provides APIs for the widget provider to receive notifications about widget creation and destruction. + +### Properties + +**Model restriction**: This API can be used only in the stage model. + +**System capability**: SystemCapability.Ability.Form + +**Atomic service API**: This API can be used in atomic services since API version 20. + +| Name| Type | Read-Only| Optional |Description| +| ------ | ------ | ---- | ---- | ---- | +| context | [LiveFormExtensionContext](./js-apis-application-LiveFormExtensionContext.md) | No | No|Context of the **LiveFormExtensionAbility**. This context is inherited from [ExtensionContext](../apis-ability-kit/js-apis-inner-application-extensionContext.md).| + +### onLiveFormCreate + +onLiveFormCreate(liveFormInfo: LiveFormInfo, session: UIExtensionContentSession): void + +Called after the UI content of **LiveFormExtensionAbility** is created. + +**Model restriction**: This API can be used only in the stage model. + +**System capability**: SystemCapability.Ability.Form + +**Atomic service API**: This API can be used in atomic services since API version 20. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| liveFormInfo | [LiveFormInfo](#liveforminfo) | Yes| Interactive widget information, including the widget ID.| +| session | [UIExtensionContentSession](../apis-ability-kit/js-apis-app-ability-uiExtensionContentSession.md) | Yes| UI information.| + +**Example** + +```ts +import { UIExtensionContentSession } from '@kit.AbilityKit'; +import { LiveFormExtensionAbility, LiveFormInfo } from '@kit.FormKit'; + +const TAG: string = '[testTag] LiveFormExtAbility'; + +export default class LiveFormExtAbility extends LiveFormExtensionAbility { + onLiveFormCreate(liveFormInfo: LiveFormInfo, session: UIExtensionContentSession) { + console.info(TAG, `onLiveFormCreate, liveFormInfo: ${JSON.stringify(liveFormInfo)}`); + } +} +``` + +### onLiveFormDestroy + +onLiveFormDestroy(liveFormInfo: LiveFormInfo): void + +Called to clear resources when this **LiveFormExtensionAbility** is destroyed. + +**Model restriction**: This API can be used only in the stage model. + +**System capability**: SystemCapability.Ability.Form + +**Atomic service API**: This API can be used in atomic services since API version 20. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| liveFormInfo | [LiveFormInfo](#liveforminfo) | Yes| Interactive widget information, including the widget ID.| + +**Example** + +```ts +import { LiveFormExtensionAbility, LiveFormInfo } from '@kit.FormKit'; + +const TAG: string = '[testTag] LiveFormExtAbility'; + +export default class LiveFormExtAbility extends LiveFormExtensionAbility { + onLiveFormDestroy(liveFormInfo: LiveFormInfo) { + console.info(TAG, `onLiveFormDestroy, liveFormInfo: ${JSON.stringify(liveFormInfo)}`); + } +} +``` +### LiveFormInfo + +Defines the interactive widget information. + +**Model restriction**: This API can be used only in the stage model. + +**System capability**: SystemCapability.Ability.Form + +**Atomic service API**: This API can be used in atomic services since API version 20. + +| Name| Type| Read-Only| Optional| Description| +| ------ | ------ | ---- | ---- | -------- | +| formId | string | No| No| Widget ID.| +| rect | [formInfo.Rect](js-apis-app-form-formInfo.md#rect20) | No| No| Widget location and dimension.| +| borderRadius | number | No| No| Widget corner radius. The value must be greater than 0, in vp.| diff --git a/en/application-dev/reference/apis-form-kit/js-apis-app-form-formBindingData.md b/en/application-dev/reference/apis-form-kit/js-apis-app-form-formBindingData.md index e48c0e4f1ff4db0ec10391a3cd4365fd354eaffe..c90b85541379d5d5c9986d4446e0fa01285e2731 100644 --- a/en/application-dev/reference/apis-form-kit/js-apis-app-form-formBindingData.md +++ b/en/application-dev/reference/apis-form-kit/js-apis-app-form-formBindingData.md @@ -56,7 +56,7 @@ Creates a **FormBindingData** object. | Name| Type | Mandatory| Description | | ------ | -------------- | ---- | ------------------------------------------------------------ | -| obj | Object\|string | No | Data to be displayed on the widget. The value can be an object containing multiple key-value pairs or a string in JSON format. The image data is identified by **'formImages'**, and the content is multiple key-value pairs, each of which consists of an image identifier and image file descriptor. The final format is {'formImages': {'key1': fd1, 'key2': fd2}}.| +| obj | Object\|string | No | Data to be displayed on the widget. The value can be an object containing multiple key-value pairs or a string in JSON format. The image data is identified by **'formImages'**, and the content is multiple key-value pairs, each of which consists of an image identifier and image file descriptor. The final format is {'formImages': {'key1': fd1, 'key2': fd2}}.
**NOTE**
During [widget update](../../form/arkts-ui-widget-interaction-overview.md), when the widget UI receives widget data through @LocalStorageProp, the **FormBindingData** object is serialized, that is, the widget data is converted into the string type. Since API version 20, the maximum number of image files is 20, and the total memory size of all images cannot exceed 10 MB. If the total memory size exceeds 10 MB, the images will be displayed abnormally. In API version 19 and earlier versions, the maximum number of image files is 5, and the maximum memory size of each image is 2 MB.| **Return value** @@ -71,7 +71,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message| | -------- | -------- | -| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3.Parameter verification failed | +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3.Parameter verification failed. | **Example** diff --git a/en/application-dev/reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md b/en/application-dev/reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md index fab6917cd6a3b4e79cc0a198a013fd28d3bedaaf..24e967cd7f953de2d0279830868deaac7321aa7f 100644 --- a/en/application-dev/reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md +++ b/en/application-dev/reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md @@ -56,7 +56,7 @@ Called to notify the widget provider that a widget is being created. | Name| Type | Mandatory| Description | | ------ | -------------------------------------- | ---- | ------------------------------------------------------------ | -| want | [Want](../apis-ability-kit/js-apis-app-ability-want.md) | Yes | Want information of the widget. You can set the **parameters** field to one or more values enumerated in [widget parameters](./js-apis-app-form-formInfo.md#forminfoformparam), such as widget ID, widget name, and widget style. The information must be managed as persistent data to facilitate subsequent widget update and deletion.| +| want | [Want](../apis-ability-kit/js-apis-app-ability-want.md) | Yes | Want information of the widget. You can set the **parameters** field to one or more values enumerated in [widget parameters](./js-apis-app-form-formInfo.md#formparam), such as widget ID, widget name, and widget style. The information must be managed as persistent data to facilitate subsequent widget update and deletion.| **Return value** @@ -326,7 +326,7 @@ Called to notify the widget provider that the widget host is requesting the widg | Type | Description | | ------------------------------------------------------------ | ----------------------------------------------------------- | -| [formInfo.FormState](js-apis-app-form-formInfo.md#forminfoformstate) | Enumerated values of the current widget status.| +| [formInfo.FormState](js-apis-app-form-formInfo.md#formstate) | Enumerated values of the current widget status.| **Example** @@ -365,3 +365,39 @@ export default class MyFormExtensionAbility extends FormExtensionAbility { } } ``` + +### FormExtensionAbility.onFormLocationChanged20+ + +onFormLocationChanged(formId: string, newFormLocation: formInfo.FormLocation): void + +Called when the widget location changes. + +**Model restriction**: This API can be used only in the stage model. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| formId | string | Yes| Widget ID.| +| newFormLocation | [formInfo.FormLocation](js-apis-app-form-formInfo.md#formlocation20) | Yes| Enumerated value of the latest widget location.| + +**Example** + +```ts +import { formBindingData, FormExtensionAbility, formInfo } from '@kit.FormKit'; +import { Want } from '@kit.AbilityKit'; + +export default class EntryFormAbility extends FormExtensionAbility { + onAddForm(want: Want) { + let formData: Record = { + 'data': 'addForm' + }; + return formBindingData.createFormBindingData(formData); + } + onFormLocationChanged(formId: string, newFormLocation: formInfo.FormLocation) { + console.info("EntryFormAbility onFormLocationChanged current location: " + newFormLocation); + } +} +``` diff --git a/en/application-dev/reference/apis-form-kit/js-apis-app-form-formHost-sys.md b/en/application-dev/reference/apis-form-kit/js-apis-app-form-formHost-sys.md index d6efd088caa8d2c26e49e8fb00bc535113257d2a..293355d4c5d22412354d42f982e448347999a32b 100644 --- a/en/application-dev/reference/apis-form-kit/js-apis-app-form-formHost-sys.md +++ b/en/application-dev/reference/apis-form-kit/js-apis-app-form-formHost-sys.md @@ -2181,7 +2181,7 @@ Sets a router proxy for widgets and obtains the Want information required for re > **NOTE** > >- Generally, for a widget added to the home screen, in the case of router-based redirection, the widget framework checks whether the destination is proper and whether the widget has the redirection permission, and then triggers redirection accordingly. For a widget that is added to a widget host and has a router proxy configured, in the case of router-based redirection, the widget framework does not trigger redirection for the widget. Instead, it returns the **want** parameter containing the destination to the widget host. Therefore, if the widget host wants to use the Want information for redirection, it must have the application redirection permission. For details, see -[UIAbilityContext.startAbility()](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability). +[UIAbilityContext.startAbility()](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#startability). > >- Only one router proxy can be set for a widget. If multiple proxies are set, only the last proxy takes effect. @@ -2221,7 +2221,7 @@ import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct CardExample { - private context = getContext(this) as common.UIAbilityContext; + private context = this.getUIContext().getHostContext() as common.UIAbilityContext; @State formId: number = 0; @State fwidth: number = 420; @State fheight: number = 280; @@ -2273,7 +2273,7 @@ Sets a router proxy for widgets and obtains the Want information required for re > **NOTE** > ->- Generally, for a widget added to the home screen, in the case of router-based redirection, the widget framework checks whether the destination is proper and whether the widget has the redirection permission, and then triggers redirection accordingly. For a widget that is added to a widget host and has a router proxy configured, in the case of router-based redirection, the widget framework does not trigger redirection for the widget. Instead, it returns the **want** parameter containing the destination to the widget host. Therefore, if the widget host wants to use the Want information for redirection, it must have the application redirection permission. For details, see [UIAbilityContext.startAbility()](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability). +>- Generally, for a widget added to the home screen, in the case of router-based redirection, the widget framework checks whether the destination is proper and whether the widget has the redirection permission, and then triggers redirection accordingly. For a widget that is added to a widget host and has a router proxy configured, in the case of router-based redirection, the widget framework does not trigger redirection for the widget. Instead, it returns the **want** parameter containing the destination to the widget host. Therefore, if the widget host wants to use the Want information for redirection, it must have the application redirection permission. For details, see [UIAbilityContext.startAbility()](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#startability). > >- Only one router proxy can be set for a widget. If multiple proxies are set, only the last proxy takes effect. @@ -2320,7 +2320,7 @@ import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct CardExample { - private context = getContext(this) as common.UIAbilityContext; + private context = this.getUIContext().getHostContext() as common.UIAbilityContext; @State formId: number = 0; @State fwidth: number = 420; @State fheight: number = 280; @@ -2748,7 +2748,7 @@ Updates the widget location. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | formId | string | Yes | Widget ID.| -| location |[formInfo.FormLocation](js-apis-app-form-formInfo-sys.md#formlocation) | Yes| Widget location.| +| location |[formInfo.FormLocation](js-apis-app-form-formInfo-sys.md#formlocation12) | Yes| Widget location.| **Error codes** @@ -2796,7 +2796,7 @@ Sets the result for the operation of adding a widget to the home screen. | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------ | | formId | string | Yes | Widget ID. | -| result | [PublishFormResult](js-apis-app-form-formInfo-sys.md#publishformresult) | Yes | Result of the operation.| +| result | [formInfo.PublishFormResult](js-apis-app-form-formInfo-sys.md#publishformresult12) | Yes | Result of the operation.| **Error codes** @@ -2886,3 +2886,167 @@ try { } ``` + +## formHost.on('formOverflow')20+ + +on(type: 'formOverflow', callback: Callback<formInfo.OverflowRequest>): void + +Subscribes to the interactive widget animation request event. + +**System capability**: SystemCapability.Ability.Form + +**System API**: This is a system API. + +**Parameters** + +| Name| Type | Mandatory| Description| +|----------|--------|---|---------------------------------------| +| type | string | Yes| Event type. Only **'formOverflow'** is supported, indicating the interactive widget animation request.| +| callback | Callback<[formInfo.OverflowRequest](js-apis-app-form-formInfo-sys.md#overflowrequest20)> | Yes| Callback used by the widget host to process the animation request.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| Error Code ID| Error Message | +|-------|-----------------------------------------------------------------------------------------------------------| +| 202 | The application is not a system application. | +| 801 | Capability not supported.function formOverflow can not work correctly due to limited device capabilities. | + +**Example** + +```ts +import { formHost, formInfo } from '@kit.FormKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +try { + formHost.on('formOverflow', (request: formInfo.OverflowRequest) => { + console.log(`formHost on formOverflow, formId is ${request.formId}`); + }); +} catch (error) { + console.error(`catch error, code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}`); +} +``` + +## formHost.off('formOverflow')20+ + +off(type: 'formOverflow', callback?: Callback<formInfo.OverflowRequest>): void + +Unsubscribes from the interactive widget animation request event. + +**System capability**: SystemCapability.Ability.Form + +**System API**: This is a system API. + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ |----|----------------------------------------| +| type | string | Yes | Event type. Only **'formOverflow'** is supported, indicating the interactive widget animation request.| +| callback |Callback<[formInfo.OverflowRequest](js-apis-app-form-formInfo-sys.md#overflowrequest20)> | No | Callback function, which corresponds to the subscribed interactive widget animation request. By default, all registered interactive widget animation request events are deregistered.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| Error Code ID| Error Message | +| --- |-----------------------------------------------------------------------------------------------------------| +| 202 | The application is not a system application. | +| 801 | Capability not supported.function formOverflow can not work correctly due to limited device capabilities. | + +**Example** + +```ts +import { formHost, formInfo } from '@kit.FormKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +try { + formHost.off('formOverflow', (request: formInfo.OverflowRequest) => { + console.log(`formHost off formOverflow, formId is ${request.formId}`); + }); +} catch (error) { + console.error(`catch error, code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}`); +} +``` + +## formHost.on('changeSceneAnimationState')20+ + +on(type: 'changeSceneAnimationState', callback: Callback<formInfo.ChangeSceneAnimationStateRequest>): void + +Subscribes to the event of switching the interactive widget state. An interactive widget can be in the active or inactive state. In the inactive state, the interactive widget is the same as a common widget. In the active state, the interactive widget can start the **LiveFormExtensionAbility** process developed by the widget host to implement interactive widget animations. + +**System capability**: SystemCapability.Ability.Form + +**System API**: This is a system API. + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- |------------------------------------------------------| +| type | string | Yes | Event type. The event **'changeSceneAnimationState'** is triggered when the interactive widget state is switched.| +| callback |Callback<[formInfo.ChangeSceneAnimationStateRequest](js-apis-app-form-formInfo-sys.md#changesceneanimationstaterequest20)> | Yes| Callback function, which is used by the widget host to process the state switching request.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| Error Code ID| Error Message | +|-------|-----------------------------------------------------------------------------------------------------------| +| 202 | The application is not a system application. | +| 801 | Capability not supported.function formOverflow can not work correctly due to limited device capabilities. | + +**Example** + +```ts +import { formHost, formInfo } from '@kit.FormKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +try { + formHost.on('changeSceneAnimationState', (request: formInfo.ChangeSceneAnimationStateRequest): void => { + console.log(`formHost on changeSceneAnimationState, formId is ${request.formId}`); + }); +} catch (error) { + console.error(`catch error, code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}`); +} +``` + +## formHost.off('changeSceneAnimationState')20+ + +off(type: 'changeSceneAnimationState', callback: Callback<formInfo.changeSceneAnimationState>): void + +Unsubscribes from the event of switching the interactive widget state. An interactive widget can be in the active or inactive state. In the inactive state, the interactive widget is the same as a common widget. In the active state, the interactive widget can start the **LiveFormExtensionAbility** process developed by the widget host to implement interactive widget animations. + +**System capability**: SystemCapability.Ability.Form + +**System API**: This is a system API. + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ |----| ------- | +| type | string | Yes | Event type. The event **'changeSceneAnimationState'** is triggered when the interactive widget state is switched.| +| callback |Callback<[formInfo.ChangeSceneAnimationStateRequest](js-apis-app-form-formInfo-sys.md#changesceneanimationstaterequest20)> | No | Callback function, which corresponds to the request for switching the state of a subscribed interactive widget. By default, all registered interactive widget state switching events are deregistered.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| Error Code ID| Error Message| +| -------- | -------- | +| 202 | The application is not a system application. | +| 801 | Capability not supported.function formOverflow can not work correctly due to limited device capabilities. | + +**Example** + +```ts +import { formHost, formInfo } from '@kit.FormKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +try { + formHost.off('changeSceneAnimationState', (request: formInfo.ChangeSceneAnimationStateRequest): void => { + console.log(`formHost off changeSceneAnimationState, formId is ${request.formId}`); + }); +} catch (error) { + console.error(`catch error, code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}`); +} +``` diff --git a/en/application-dev/reference/apis-form-kit/js-apis-app-form-formInfo-sys.md b/en/application-dev/reference/apis-form-kit/js-apis-app-form-formInfo-sys.md index 8a706e67b229da121600a0098baadd6c2a885416..66b5d59670b7d80951c40f0ea11cc24693b72162 100644 --- a/en/application-dev/reference/apis-form-kit/js-apis-app-form-formInfo-sys.md +++ b/en/application-dev/reference/apis-form-kit/js-apis-app-form-formInfo-sys.md @@ -13,6 +13,18 @@ The **formInfo** module provides types and enums related to the widget informati import { formInfo } from '@kit.FormKit'; ``` +## FormInfo + +Defines the widget information. + +**System capability**: SystemCapability.Ability.Form + +| Name | Type | Readable | Writable | Description | +| ----------- | -------- | -------- | -------------------- | ------------------------------------------------------------ | +| previewImages18+ | Array<number> | Yes| No| Resource IDs of the preview images of the widget.
**Atomic service API**: This API can be used in atomic services since API version 18.| +| enableBlurBackground18+ | boolean | Yes | No | Whether the widget uses a blur background.| +| renderingMode18+|[RenderingMode](./js-apis-app-form-formInfo-sys.md#renderingmode18)|Yes|No|Widget rendering mode.| + ## FormParam @@ -71,11 +83,11 @@ Defines the information about the widget provider. | Name | Type | Readable | Writable | Description | | ----------- | -------- | -------- | -------------------- | ------------------------------------------------------------ | -| bundleName | string | Yes | No | Name of the bundle to which the widget provider belongs. | -| formName | string | Yes | No | Widget name. | -| moduleName | string | Yes | No | Name of the module to which the widget belongs. | -| abilityName | string | Yes | No | Name of the ability to which the widget belongs. | -| isUnusedIncluded11+ | boolean | Yes | No | Whether an unused widget is included. | +| bundleName | string | Yes | Yes | Name of the bundle to which the widget provider belongs. | +| formName | string | Yes | Yes | Widget name. | +| moduleName | string | Yes | Yes | Name of the module to which the widget belongs. | +| abilityName | string | Yes | Yes | Name of the ability to which the widget belongs. | +| isUnusedIncluded11+ | boolean | Yes | Yes | Whether an unused widget is included.
- **true**: An unused widget is included.
- **false** (default): There is no unused widget.
| ## FormInfoFilter @@ -133,3 +145,72 @@ Enumerates the result codes that may be used for the operation of adding a widge | NO_SPACE | 1 | There is no space for adding widgets. | | PARAM_ERROR | 2 | Parameter check fails. | | INTERNAL_ERROR | 3 | An internal error occurs during widget processing.| + +## RenderingMode18+ + +Enumerates the rendering modes supported by the widget. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| AUTO_COLOR | 0 | Auto mode. | +| FULL_COLOR | 1 | Full-color mode. | +| SINGLE_COLOR | 2 | Single-color mode. | + +## OverflowRequest20+ + +Defines the request for interactive widget animations. + +**System capability**: SystemCapability.Ability.Form + +**System API**: This is a system API. + +| Name| Type| Read-Only| Optional| Description| +|-----|-----|----|----|-----| +| formId | string | Yes | No | Widget ID.| +| isOverflow | boolean | Yes | No | Animation request type. The value **true** indicates the interactive widget requests to trigger the animation; the value **false** indicates the interactive widget requests to cancel the animation.| +| overflowInfo | [formInfo.OverflowInfo](js-apis-app-form-formInfo.md#overflowinfo20) | Yes| Yes| Animation request parameters, including the animation duration (unit: ms) and animation area (the upper left corner of the widget is used as the origin of the animation area, in vp). The default value is empty.| + +## ChangeSceneAnimationStateRequest20+ + +Defines the request for switching the status of an interactive widget. An interactive widget can be in the active or inactive state. In the inactive state, the interactive widget is the same as a common widget. In the active state, the interactive widget can start the **LiveFormExtensionAbility** process developed by the widget host to implement interactive widget animations. + +**System capability**: SystemCapability.Ability.Form + +**System API**: This is a system API. + +| Name| Type| Read-Only| Optional| Description| +|-----|-----|-----|-----|----------------------------------------| +| formId | string | Yes| No| Widget ID. | +| state | number | Yes| No| Status switching request type. The value **1** indicates that the switching request is activated, and the value **0** indicates that the switching request is deactivated.| + +## FunInteractionParams20+ + +Defines the parameters for a fun-based widget. + +**System capability**: SystemCapability.Ability.Form + +**System API**: This is a system API. + +| Name| Type| Read-Only| Optional| Description | +|-----|-----|----|-----|--------------------------------------------------------------------------------------------------------------------------------------| +| abilityName | string | Yes | Yes | ExtensionAbility name of the interaction scenario. This parameter is left empty by default.| +| targetBundleName | string | Yes | No | Bundle name. | +| subBundleName | string | Yes | No | Sub bundle name.| +| keepStateDuration | number | Yes | Yes | Duration of the activated state when there is no interaction. The default value is **10000**, in ms. The value should be an integer within the range [0, 10000]. If the value exceeds this range, it defaults to 10000 milliseconds.| + +## SceneAnimationParams20+ + +Defines the parameters for a scene-based widget. + +**System capability**: SystemCapability.Ability.Form + +**System API**: This is a system API. + +| Name| Type| Read-Only| Optional| Description | +|-----|-----|------|----|-------------------------------------------------------------------------------------------------------------------------------------------------| +| abilityName | string | Yes| No | ExtensionAbility name, for example, LiveFormExtensionAbility name of the widget provider. | +| disabledDesktopBehaviors | string | Yes| Yes | The options are **SWIPE_DESKTOP**, **PULL_DOWN_SEARCH**, **LONG_CLICK**, and **DRAG**. You can select one or more options. Use a vertical bar (\|) in between| to concatenate two different operations, for example, SWIPE_DESKTOP\|PULL_DOWN_SEARCH| By default, no operation is disabled.| diff --git a/en/application-dev/reference/apis-form-kit/js-apis-app-form-formInfo.md b/en/application-dev/reference/apis-form-kit/js-apis-app-form-formInfo.md index ec7bc3abe671d0857eebfec3c154b00fad25fdfb..dfe4c2546bbcd8b664f63e6d1094185646d21f47 100644 --- a/en/application-dev/reference/apis-form-kit/js-apis-app-form-formInfo.md +++ b/en/application-dev/reference/apis-form-kit/js-apis-app-form-formInfo.md @@ -12,7 +12,7 @@ The **formInfo** module provides types and enums related to the widget informati import { formInfo } from '@kit.FormKit'; ``` -## formInfo.FormInfo +## FormInfo Defines the widget information. @@ -23,14 +23,14 @@ Defines the widget information. | bundleName | string | Yes | No | Name of the bundle to which the widget belongs.
**Atomic service API**: This API can be used in atomic services since API version 11.| | moduleName | string | Yes | No | Name of the module to which the widget belongs.
**Atomic service API**: This API can be used in atomic services since API version 11.| | abilityName | string | Yes | No | Name of the ability to which the widget belongs.
**Atomic service API**: This API can be used in atomic services since API version 11. | -| name | string | Yes | No | Name of an application or atomic service.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| displayName11+ | string | Yes | No | Widget name.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| name | string | Yes | No | Widget name.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| displayName11+ | string | Yes | No | Widget display name.
**Atomic service API**: This API can be used in atomic services since API version 11.| | displayNameId11+ | number | Yes | No | ID of the widget name displayed during widget preview.
**Atomic service API**: This API can be used in atomic services since API version 11.| | description | string | Yes | No | Description of the widget.
**Atomic service API**: This API can be used in atomic services since API version 11.| | descriptionId10+ | number | Yes | No | ID of the widget description.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| type | [FormType](#forminfoformtype) | Yes | No | Type of the widget. Currently, JS and ArkTS widgets are supported.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| type | [FormType](#formtype) | Yes | No | Type of the widget. Currently, JS and ArkTS widgets are supported.
**Atomic service API**: This API can be used in atomic services since API version 11.| | jsComponentName | string | Yes | No | Name of the component used in the JS widget.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| colorMode | [ColorMode](#forminfocolormode) | Yes | No | Color mode of the widget.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| colorMode(deprecated) | [ColorMode](#colormodedeprecated) | Yes | No | Color mode of the widget.
**Atomic service API**: This API can be used in atomic services since API version 11.| | isDefault | boolean | Yes | No | Whether the widget is the default one.
**Atomic service API**: This API can be used in atomic services since API version 11.| | updateEnabled | boolean | Yes | No | Whether the widget is updatable.
**Atomic service API**: This API can be used in atomic services since API version 11.| | formVisibleNotify | boolean | Yes | No | Whether to send a notification when the widget is visible.
**Atomic service API**: This API can be used in atomic services since API version 11.| @@ -38,16 +38,13 @@ Defines the widget information. | formConfigAbility | string | Yes | No | Configuration ability of the widget, that is, the ability corresponding to the option in the selection box displayed when the widget is long pressed.
**Atomic service API**: This API can be used in atomic services since API version 11.| | updateDuration | number | Yes | No | Update period of the widget.
**Atomic service API**: This API can be used in atomic services since API version 11.| | defaultDimension | number | Yes | No | Widget specifications.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| supportDimensions | Array<number> | Yes | No | Dimensions supported by the widget. For details, see [FormDimension](#forminfoformdimension).
**Atomic service API**: This API can be used in atomic services since API version 11.| +| supportDimensions | Array<number> | Yes | No | Dimensions supported by the widget. For details, see [FormDimension](#formdimension).
**Atomic service API**: This API can be used in atomic services since API version 11.| | customizeData | Record\ | Yes | No | Custom data of the widget.
**Atomic service API**: This API can be used in atomic services since API version 11.| | isDynamic10+ | boolean | Yes | No | Whether the widget is a dynamic widget.
ArkTS widgets are classified into dynamic and static widgets. JS widgets are all dynamic widgets.
**Atomic service API**: This API can be used in atomic services since API version 11.| | transparencyEnabled11+ | boolean | Yes | No | Whether the widget supports the setting of the background transparency.
For ArkTS widgets, the support for the background transparency setting depends on user configurations. For JS widgets, the background transparency setting is not supported.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| supportedShapes12+ | Array<number> | Yes | No | Shapes supported by the widget. For details about the available shapes, see [FormShape12+](#forminfoformshape12).
**Atomic service API**: This API can be used in atomic services since API version 12. | -| previewImages18+ | Array<number> | Yes| No| Resource IDs of the preview images of the widget.
**Atomic service API**: This API can be used in atomic services since API version 18. -| enableBlurBackground18+ | boolean | Yes | No | Whether the widget uses a blur background.
**Atomic service API**: This API can be used in atomic services since API version 18.| -|renderingMode18+|[RenderingMode](#forminforenderingmode18)|Yes|No|Widget rendering mode.
**Atomic service API**: This API can be used in atomic services since API version 18.| +| supportedShapes12+ | Array<number> | Yes | No | Shapes supported by the widget. For details about the available shapes, see [FormShape12+](#formshape12).
**Atomic service API**: This API can be used in atomic services since API version 12. | -## formInfo.FormType +## FormType Enumerates the widget types. @@ -60,7 +57,9 @@ Enumerates the widget types. | JS | 1 | JS widget. | | eTS | 2 | ArkTS widget.| -## formInfo.ColorMode +## ColorMode(deprecated) + +This API is supported since API version 11 and deprecated since API version 20. The color mode follows the system color mode. Enumerates the color modes supported by the widget. @@ -74,7 +73,7 @@ Enumerates the color modes supported by the widget. | MODE_DARK | 0 | Dark mode. | | MODE_LIGHT | 1 | Light mode. | -## formInfo.FormStateInfo +## FormStateInfo Describes the widget state information. @@ -84,10 +83,10 @@ Describes the widget state information. | Name | Type | Readable | Writable | Description | | ----------- | -------- | -------- | -------------------- | ------------------------------------------------------------ | -| formState | [FormState](#forminfoformstate) | Yes | No | Widget state. | +| formState | [FormState](#formstate) | Yes | No | Widget state. | | want | [Want](../apis-ability-kit/js-apis-app-ability-want.md) | Yes | No | Want text. | -## formInfo.FormState +## FormState Enumerates the widget states. @@ -101,7 +100,7 @@ Enumerates the widget states. | DEFAULT | 0 | Default state. | | READY | 1 | Ready state. | -## formInfo.FormParam +## FormParam Enumerates the widget parameters. @@ -110,7 +109,7 @@ Enumerates the widget parameters. | Name | Value | Description | | ----------- | ---- | ------------ | | IDENTITY_KEY | 'ohos.extra.param.key.form_identity' | Widget ID.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| DIMENSION_KEY | 'ohos.extra.param.key.form_dimension' | Widget dimension.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| DIMENSION_KEY | 'ohos.extra.param.key.form_dimension' | Widget dimension. For details, see [FormDimension](#formdimension).
**Atomic service API**: This API can be used in atomic services since API version 11.| | NAME_KEY | 'ohos.extra.param.key.form_name' | Widget name.
**Atomic service API**: This API can be used in atomic services since API version 11.| | MODULE_NAME_KEY | 'ohos.extra.param.key.module_name' | Name of the module to which the widget belongs.
**Atomic service API**: This API can be used in atomic services since API version 11.| | WIDTH_KEY | 'ohos.extra.param.key.form_width' | Widget width.
**Atomic service API**: This API can be used in atomic services since API version 11.| @@ -122,11 +121,11 @@ Enumerates the widget parameters. | PARAM_FORM_CUSTOMIZE_KEY10+ | 'ohos.extra.param.key.form_customize' | Custom data.
**Atomic service API**: This API can be used in atomic services since API version 11.| | FORM_RENDERING_MODE_KEY11+ | 'ohos.extra.param.key.form_rendering_mode' | Widget rendering mode.
**Atomic service API**: This API can be used in atomic services since API version 12.| | HOST_BG_INVERSE_COLOR_KEY12+ | 'ohos.extra.param.key.host_bg_inverse_color' | Inverse background color of the widget client.
**Atomic service API**: This API can be used in atomic services since API version 12.| -| FORM_LOCATION_KEY12+ | 'ohos.extra.param.key.form_location' | Widget location.
OTHER -1 (other locations)
DESKTOP 0 (desktop)
FORM_CENTER 1 (widget center of the desktop)
FORM_MANAGER 2 (widget manager of the desktop)
NEGATIVE_SCREEN 3 (minus-one screen)
FORM_CENTER_NEGATIVE_SCREEN 4 (widget center of the minus-one screen)
FORM_MANAGER_NEGATIVE_SCREEN 5 (widget manager of the minus-one screen)
SCREEN_LOCK 6 (lock screen)
AI_SUGGESTION 7 (Celia suggestions area) +| FORM_LOCATION_KEY12+ | 'ohos.extra.param.key.form_location' | Widget location.
OTHER -1 (Other locations)
DESKTOP 0 (Home screen)
FORM_CENTER 1 (Widget center of the home screen)
FORM_MANAGER 2 (Widget Manager of the home screen)
NEGATIVE_SCREEN 3 (Minus-one screen)
FORM_CENTER_NEGATIVE_SCREEN 4 (Widget center of the minus-one screen)
FORM_MANAGER_NEGATIVE_SCREEN 5 (Widget Manager of the minus-one screen)
SCREEN_LOCK 6 (Screen lock)
AI_SUGGESTION 7 (Celia suggestions area)| | FORM_PERMISSION_NAME_KEY12+ | 'ohos.extra.param.key.permission_name' | Name of the permission.
**Atomic service API**: This API can be used in atomic services since API version 12.| | FORM_PERMISSION_GRANTED_KEY12+ | 'ohos.extra.param.key.permission_granted' | Whether the permission is granted.
**Atomic service API**: This API can be used in atomic services since API version 12.| -## formInfo.FormDimension +## FormDimension Enumerates the widget dimensions. @@ -144,7 +143,7 @@ Enumerates the widget dimensions. | DIMENSION_2_318+ | 8 | 2 x 3.
**Atomic service API**: This API can be used for wearable devices in atomic services since API version 18.| | DIMENSION_3_318+ | 9 | 3 x 3.
**Atomic service API**: This API can be used for wearable devices in atomic services since API version 18.| -## formInfo.FormShape12+ +## FormShape12+ Enumerates the widget shapes. @@ -155,7 +154,7 @@ Enumerates the widget shapes. | RECT | 1 | Rectangle.
**Atomic service API**: This API can be used in atomic services since API version 12.| | CIRCLE | 2 | Circle.
**Atomic service API**: This API can be used in atomic services since API version 12.| -## formInfo.FormInfoFilter +## FormInfoFilter Defines the widget information filter. Only the widget information that meets the filter is returned. @@ -169,7 +168,7 @@ Defines the widget information filter. Only the widget information that meets th -## formInfo.VisibilityType +## VisibilityType Enumerates the visibility types of the widget. @@ -184,7 +183,7 @@ Enumerates the visibility types of the widget. | FORM_INVISIBLE | 2 | The widget is invisible.| -## formInfo.LaunchReason10+ +## LaunchReason10+ Enumerates the reasons for creating a widget. @@ -197,16 +196,38 @@ Enumerates the reasons for creating a widget. | FORM_DEFAULT | 1 | The widget is created by default.| | FORM_SHARE | 2 | The widget is created for sharing.| -## formInfo.RenderingMode18+ +## OverflowInfo20+ + +Describes the widget animation information. + +**System capability**: SystemCapability.Ability.Form + +| Name| Type| Read-Only| Optional | Description | +|-----|-----|------|-----|---------------------------------| +| area | [Rect](#rect20) | Yes| No | Overflow animation area. The upper left corner of the widget is used as the origin, in vp. | +| duration | number | Yes| No | Animation duration. The value is an integer greater than 0 and less than or equal to 3,500, in milliseconds.| -Enumerates the rendering modes supported by the widget. +## Rect20+ -**Atomic service API**: This API can be used in atomic services since API version 18. +Defines the common rectangular area information, including the widget position and animation area. **System capability**: SystemCapability.Ability.Form -| Name | Value | Description | -| ----------- | ---- | ------------ | -| AUTO_COLOR | 0 | Auto mode. | -| FULL_COLOR | 1 | Full-color mode. | -| SINGLE_COLOR | 2 | Single-color mode. | +| Name| Type| Read-Only| Optional | Description| +|-----|-----|------|-----|-------| +| left | number | Yes| No | X coordinate of the upper left vertex of the rectangle, in vp.| +| top | number | Yes| No | Y coordinate of the upper left vertex of the rectangle, in vp.| +| width | number | Yes| No | Width of the rectangle, in vp.| +| height | number | Yes| No | Height of the rectangle, in vp.| +## FormLocation20+ + +Enumerates the widget locations. + +**System capability**: SystemCapability.Ability.Form + +| Name | Value | Description | +| ---------------------------- | ---- | -------------------------------- | +| DESKTOP | 0 | The widget is located on the home screen. | +| FORM_CENTER | 1 | The widget is located in the widget center of the home screen. | +| FORM_MANAGER | 2 | The widget is located in the Widget Manager of the home screen. | + diff --git a/en/application-dev/reference/apis-form-kit/js-apis-app-form-formProvider-sys.md b/en/application-dev/reference/apis-form-kit/js-apis-app-form-formProvider-sys.md index 66bdc2d7d39890286d3050069b989bff3f4b03a7..61c5e28fa91623b4a10af85fc58a89f5ca91a905 100644 --- a/en/application-dev/reference/apis-form-kit/js-apis-app-form-formProvider-sys.md +++ b/en/application-dev/reference/apis-form-kit/js-apis-app-form-formProvider-sys.md @@ -1,6 +1,6 @@ # @ohos.app.form.formProvider (formProvider) (System API) -The **FormProvider** module provides APIs related to the widget provider. You can use the APIs to update a widget, set the next refresh time for a widget, obtain widget information, and request a widget release. +The **formProvider** module provides APIs to obtain widget information, update widgets, set the update time, and request a widget release. > **NOTE** > @@ -323,3 +323,117 @@ try { console.error(`catch error, code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message})`); } ``` + +## activateSceneAnimation20+ + +activateSceneAnimation(formId: string): Promise<void> + +Requests to activate a widget. This API takes effect only for [scene-based widgets](../../form/arkts-ui-widget-configuration.md#sceneanimationparams-field). This API uses a promise to return the result. An interactive widget can be in the active or inactive state. In the inactive state, the widget is the same as a common widget. In the active state, the widget can start the **LiveFormExtensionAbility** process developed by the widget host to implement animations. + +**System capability**: SystemCapability.Ability.Form + +**System API**: This is a system API. + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- |-------| +| formId | string | Yes| Widget ID.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Form Error Codes](errorcode-form.md). + +| Error Code ID| Error Message| +| -------- | -------- | +| 202 | The application is not a system application. | +| 801 | Capability not supported.function activateSceneAnimation can not work correctly due to limited device capabilities. | +| 16500050 | IPC connection error. | +| 16500060 | Service connection error. | +| 16500100 | Failed to obtain the configuration information. | +| 16501000 | An internal functional error occurred. | +| 16501001 | The ID of the form to be operated does not exist. | +| 16501003 | The form cannot be operated by the current application. | +| 16501011 | The form can not support this operation, please check your fom_config's sceneAnimationParams configuration infomation is correct or not. | + +**Example** + +```ts +import { formProvider } from '@kit.FormKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +let formId: string = '12400633174999288'; + +try { + formProvider.activateSceneAnimation(formId).then(() => { + console.info('activateSceneAnimation succeed.'); + }).catch((error: BusinessError) => { + console.error(`promise error, code: ${error.code}, message: ${error.message})`); + }); +} catch (error) { + console.error(`catch error, code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message})`); +} +``` + +## deactivateSceneAnimation20+ + +deactivateSceneAnimation(formId: string): Promise<void> + +Requests to deactivate a widget. This API takes effect only for [scene-based widgets](../../form/arkts-ui-widget-configuration.md#sceneanimationparams-field). This API uses a promise to return the result. An interactive widget can be in the active or inactive state. In the inactive state, the widget is the same as a common widget. In the active state, the widget can start the **LiveFormExtensionAbility** process developed by the widget host to implement animations. + +**System capability**: SystemCapability.Ability.Form + +**System API**: This is a system API. + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- |-------| +| formId | string | Yes| Widget ID.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Form Error Codes](errorcode-form.md). + +| Error Code ID| Error Message| +| -------- | -------- | +| 202 | The application is not a system application. | +| 801 | Capability not supported.function deactivateSceneAnimation can not work correctly due to limited device capabilities. | +| 16500050 | IPC connection error. | +| 16500060 | Service connection error. | +| 16500100 | Failed to obtain the configuration information. | +| 16501000 | An internal functional error occurred. | +| 16501001 | The ID of the form to be operated does not exist. | +| 16501003 | The form cannot be operated by the current application. | +| 16501011 | The form can not support this operation, please check your fom_config's sceneAnimationParams configuration infomation is correct or not. | + +**Example** + +```ts +import { formProvider } from '@kit.FormKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +let formId: string = '12400633174999288'; + +try { + formProvider.deactivateSceneAnimation(formId).then(() => { + console.info('deactivateSceneAnimation succeed.'); + }).catch((error: BusinessError) => { + console.error(`promise error, code: ${error.code}, message: ${error.message})`); + }); +} catch (error) { + console.error(`catch error, code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message})`); +} +``` diff --git a/en/application-dev/reference/apis-form-kit/js-apis-app-form-formProvider.md b/en/application-dev/reference/apis-form-kit/js-apis-app-form-formProvider.md index a0c4fcf20c6b22644433b9873d5ef230de267964..0040829018f6c1ad8ff932704b9141f029161225 100644 --- a/en/application-dev/reference/apis-form-kit/js-apis-app-form-formProvider.md +++ b/en/application-dev/reference/apis-form-kit/js-apis-app-form-formProvider.md @@ -1,6 +1,6 @@ # @ohos.app.form.formProvider (formProvider) -The **FormProvider** module provides APIs related to the widget provider. You can use the APIs to update a widget, set the next refresh time for a widget, obtain widget information, and request a widget release. +The **formProvider** module provides APIs to obtain widget information, update widgets, and set the update time. > **NOTE** > @@ -387,3 +387,329 @@ try { console.error(`catch error, code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message})`); } ``` + +## formProvider.openFormEditAbility18+ + +openFormEditAbility(abilityName: string, formId: string, isMainPage?: boolean): void + +Opens the widget editing page. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ |----|----------------------------------------------------| +| abilityName | string | Yes | Ability name on the editing page. | +| formId | string | Yes | Widget ID. | +| isMainPage | boolean | No | Whether the page is the main editing page. The value **true** (default) means that the page is the main editing page; the value **false** means the opposite.
| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Form Error Codes](errorcode-form.md). + +| Error Code ID | Error Message| +|----------| -------- | +| 801 | Capability not supported.function openFormEditAbility can not work correctly due to limited device capabilities. | +| 16500050 | IPC connection error. | +| 16500100 | Failed to obtain the configuration information. | +| 16501000 | An internal functional error occurred. | +| 16501003 | The form cannot be operated by the current application. | +| 16501007 | Form is not trust. | + +**Example** + +```ts +import { router } from '@kit.ArkUI'; + +const TAG: string = 'FormEditDemo-Page] -->'; + +@Entry +@Component +struct Page { + @State message: string = 'Hello World'; + + aboutToAppear(): void { + console.log(`${TAG} aboutToAppear.....`); + } + + build() { + RelativeContainer() { + Text(this.message) + .id('PageHelloWorld') + .fontSize(50) + .fontWeight(FontWeight.Bold) + .alignRules({ + center: { anchor: '__container__', align: VerticalAlign.Top }, + middle: { anchor: '__container__', align: HorizontalAlign.Center } + }) + .onClick(() => { + console.log(`${TAG} onClick.....`); + formProvider.openFormEditAbility('ability://EntryFormEditAbility', '1386529921'); + }) + } + .height('100%') + .width('100%') + } +} +``` + +## formProvider.openFormManager18+ + +openFormManager(want: Want): void + +Opens the Widget Manager page. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name | Type | Mandatory| Description | +|------| ------ | ---- |---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| want | [Want](../apis-ability-kit/js-apis-app-ability-want.md) | Yes | Parameter that must contain the following fields:
**bundleName**: bundle name of widget.
**abilityName**: ability name of the widget.
**parameters**:
- **ohos.extra.param.key.form_dimension**: [Widget dimension](js-apis-app-form-formInfo.md#formdimension).
- **ohos.extra.param.key.form_name**: Widget name.
- **ohos.extra.param.key.module_name**: module name of the widget.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Form Error Codes](errorcode-form.md). + +| Error Code ID| Error Message| +| -------- | -------- | +| 16500050 | IPC connection error. | +| 16500100 | Failed to obtain the configuration information. | +| 16501000 | An internal functional error occurred. | + +**Example** + +```ts +import { formProvider } from '@kit.FormKit'; +import { BusinessError } from '@kit.BasicServicesKit'; +import { Want } from '@kit.AbilityKit'; + +const want: Want = { + bundleName: 'com.example.formbutton', + abilityName: 'EntryFormAbility', + parameters: { + 'ohos.extra.param.key.form_dimension': 2, + 'ohos.extra.param.key.form_name': 'widget', + 'ohos.extra.param.key.module_name': 'entry' + }, +}; +try { + formProvider.openFormManager(want); +} catch (error) { + console.error(`catch error, code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message})`); +} +``` + +## formProvider.getPublishedFormInfoById18+ + +getPublishedFormInfoById(formId: string): Promise<formInfo.FormInfo> + +Obtains the information of the widget that has been added to the home screen on the device. This API uses a promise to return the result. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ |----| ------- | +| formId | string | Yes| Widget ID.| + +**Return value** + +| Type | Description | +|-------------------------------------------------------------------| ---------------------------------- | +| Promise<[formInfo.FormInfo](js-apis-app-form-formInfo.md#forminfo)> | Promise used to return the information obtained.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Form Error Codes](errorcode-form.md). + +| Error Code ID| Error Message| +| -------- | -------- | +| 16500050 | IPC connection error. | +| 16500100 | Failed to obtain the configuration information. | +| 16501000 | An internal functional error occurred. | + +**Example** + +```ts +import { formInfo, formProvider } from '@kit.FormKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +const formId: string = '388344236'; +try { + formProvider.getPublishedFormInfoById(formId).then((data: formInfo.FormInfo) => { + console.log(`formProvider getPublishedFormInfoById, data: ${JSON.stringify(data)}`); + }).catch((error: BusinessError) => { + console.error(`promise error, code: ${error.code}, message: ${error.message})`); + }); +} catch (error) { + console.error(`catch error, code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message})`); +} +``` + +## formProvider.getPublishedFormInfos18+ + +getPublishedFormInfos(): Promise<Array<formInfo.FormInfo>> + +Obtains the information of all widgets that have been added to the home screen on the device. This API uses a promise to return the result. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Ability.Form + +**Return value** + +| Type | Description | +| ------------ | ---------------------------------- | +| Promise<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | Promise used to return the information obtained.| + +**Error codes** + +For details about the error codes, see [Form Error Codes](errorcode-form.md). + +| Error Code ID| Error Message| +| -------- | -------- | +| 16500050 | IPC connection error. | +| 16500100 | Failed to obtain the configuration information. | +| 16501000 | An internal functional error occurred. | + +**Example** + +```ts +import { formInfo, formProvider } from '@kit.FormKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +try { + formProvider.getPublishedFormInfos().then((data: formInfo.FormInfo[]) => { + console.log(`formProvider getPublishedFormInfos, data: ${JSON.stringify(data)}`); + }).catch((error: BusinessError) => { + console.error(`promise error, code: ${error.code}, message: ${error.message})`); + }); +} catch (error) { + console.error(`catch error, code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message})`); +} +``` + +## formProvider.requestOverflow20+ + +requestOverflow(formId: string, overflowInfo: formInfo.OverflowInfo): Promise<void> + +Requests an animation. This API takes effect only for [scene-based widgets](../../form/arkts-ui-widget-configuration.md#sceneanimationparams-field). This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ |--------------------------------------------------------------------| ---- |-----------| +| formId | string | Yes| Widget ID.| +| overflowInfo | [formInfo.OverflowInfo](js-apis-app-form-formInfo.md#overflowinfo20) | Yes| Animation request parameter information.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Form Error Codes](errorcode-form.md). + +| Error Code ID| Error Message| +| -------- | -------- | +| 801 | Capability not supported.function requestOverflow can not work correctly due to limited device capabilities. | +| 16500050 | IPC connection error. | +| 16500060 | Service connection error. | +| 16500100 | Failed to obtain the configuration information. | +| 16501000 | An internal functional error occurred. | +| 16501001 | The ID of the form to be operated does not exist. | +| 16501003 | The form cannot be operated by the current application. | +| 16501011 | The form can not support this operation, please check your fom_config's sceneAnimationParams configuration infomation is correct or not. | + +**Example** + +```ts +import { formInfo, formProvider } from '@kit.FormKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +let formId: string = '12400633174999288'; +let overflowInfo: formInfo.OverflowInfo = { + area: { + left: -10, + top: -10, + width: 180, + height: 180 + }, + duration: 1000, +}; + +try { + formProvider.requestOverflow(formId, overflowInfo).then(() => { + console.info('requestOverflow succeed.'); + }).catch((error: BusinessError) => { + console.error(`promise error, code: ${error.code}, message: ${error.message})`); + }); +} catch (error) { + console.error(`catch error, code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message})`); +} +``` + +## formProvider.cancelOverflow20+ + +cancelOverflow(formId: string): Promise<void> + +Cancels an animation. This API takes effect only for [scene-based widgets](../../form/arkts-ui-widget-configuration.md#sceneanimationparams-field). This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- |-------| +| formId | string | Yes| Widget ID.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Form Error Codes](errorcode-form.md). + +| Error Code ID| Error Message| +| -------- | -------- | +| 801 | Capability not supported.function cancelOverflow can not work correctly due to limited device capabilities. | +| 16500050 | IPC connection error. | +| 16500060 | Service connection error. | +| 16500100 | Failed to obtain the configuration information. | +| 16501000 | An internal functional error occurred. | +| 16501001 | The ID of the form to be operated does not exist. | +| 16501003 | The form cannot be operated by the current application. | +| 16501011 | The form can not support this operation, please check your fom_config's sceneAnimationParams configuration infomation is correct or not. | + +**Example** + +```ts +import { formProvider } from '@kit.FormKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +let formId: string = '12400633174999288'; + +try { + formProvider.cancelOverflow(formId).then(() => { + console.info('cancelOverflow succeed.'); + }).catch((error: BusinessError) => { + console.error(`promise error, code: ${error.code}, message: ${error.message})`); + }); +} catch (error) { + console.error(`catch error, code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message})`); +} +``` diff --git a/en/application-dev/reference/apis-form-kit/js-apis-application-LiveFormExtensionContext.md b/en/application-dev/reference/apis-form-kit/js-apis-application-LiveFormExtensionContext.md new file mode 100644 index 0000000000000000000000000000000000000000..2bdf3fa45eaca97c4c8fcbcd9133c46f0fb6cdfb --- /dev/null +++ b/en/application-dev/reference/apis-form-kit/js-apis-application-LiveFormExtensionContext.md @@ -0,0 +1,81 @@ +# LiveFormExtensionContext + +**LiveFormExtensionContext**, inherited from [ExtensionContext](../apis-ability-kit/js-apis-inner-application-extensionContext.md), is the context of [LiveFormExtensionAbility](./js-apis-app-form-LiveFormExtensionAbility.md). + +> **NOTE** +> +> The initial APIs of this module are supported since API version 20. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> The APIs of this module can be used only in the stage model. + +## Modules to Import +```ts +import { LiveFormExtensionAbility } from '@kit.FormKit'; +``` + +## LiveFormExtensionContext + +Provides APIs to access specific **LiveFormExtensionAbility** resources. + +### setBackgroundImage + +setBackgroundImage(res: Resource): Promise<void> + +Sets the background image of an interactive widget. This API uses a promise to return the result. + +**Model restriction**: This API can be used only in the stage model. + +**System capability**: SystemCapability.Ability.Form + +**Atomic service API**: This API can be used in atomic services since API version 20. + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------- | +| res | [Resource](../apis-localization-kit/js-apis-resource.md) | Yes| Background image resources, including the resource ID and resource type.| + +**Return value** + +| Type | Description | +| ------------ | ---------------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Form Error Codes](errorcode-form.md) and [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 801 | Capability not supported. Failed to call the API due to limited device capabilities. | +| 16501010 | Failed to set the live form background image. | + +**Example** + +```ts +import { UIExtensionContentSession } from '@kit.AbilityKit'; +import { BusinessError } from '@kit.BasicServicesKit'; +import { LiveFormExtensionAbility, LiveFormInfo } from '@kit.FormKit'; + +const TAG: string = '[testTag]LiveFormExtAbility'; + +export default class LiveFormExtAbility extends LiveFormExtensionAbility { + onLiveFormCreate(liveFormInfo: LiveFormInfo, session: UIExtensionContentSession): void { + try { + // Add the background image to the scr/main/resources/base/media directory. Otherwise, an error will be reported due to missing resources. + this.context.setBackgroundImage($r('app.media.backgroundImage')) + .then(() => { + // Carry out normal service processing. + console.info(TAG, 'setBackgroundImage succeed'); + }) + .catch((err: BusinessError) => { + // Process service logic errors. + console.error(TAG, `setBackgroundImage failed, code is ${err?.code}, message is ${err?.message}`); + }); + } catch (err) { + // Handle input parameter errors. + console.error(TAG, `setBackgroundImage failed, code is ${err?.code}, message is ${err?.message}`); + } + } +}; +``` diff --git a/en/application-dev/reference/apis-form-kit/js-apis-inner-application-formEditExtensionContext.md b/en/application-dev/reference/apis-form-kit/js-apis-inner-application-formEditExtensionContext.md index 26e0d7d4172e86bf114655cfcc14a41391d7767d..42b9f73cb054e3ccf04e5353bb4b1c1e088418b3 100644 --- a/en/application-dev/reference/apis-form-kit/js-apis-inner-application-formEditExtensionContext.md +++ b/en/application-dev/reference/apis-form-kit/js-apis-inner-application-formEditExtensionContext.md @@ -14,7 +14,7 @@ You can use **FormEditExtensionContext** to access specific **FormEditExtensionA ```ts import { FormEditExtensionAbility } from '@kit.FormKit'; ``` -## FormEditExtensionAbility.startSecondPage +## FormEditExtensionContext.startSecondPage startSecondPage(want: Want): Promise<[AbilityResult](../apis-ability-kit/js-apis-inner-ability-abilityResult.md)> @@ -22,8 +22,6 @@ Starts the widget provider page to be edited. **Model restriction**: This API can be used only in the stage model. -**Atomic service API**: This API can be used in atomic services since API version 18. - **System capability**: SystemCapability.Ability.Form **Parameters** @@ -44,7 +42,6 @@ For details about the error codes, see [Form Error Codes](errorcode-form.md) and | ID| Error Message | | -------- | ------------------------------------------------------------ | | 202 | The application is not a system application. | -| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3.Parameter verification failed. | | 16500050 | An IPC connection error happened. | | 16501000 | An internal functional error occurred. | | 16500100 | Failed to obtain the configuration information. | diff --git a/en/application-dev/reference/apis-form-kit/js-apis-inner-application-formExtensionContext-sys.md b/en/application-dev/reference/apis-form-kit/js-apis-inner-application-formExtensionContext-sys.md index bc58f407466610c1db71b65e1c175e3b39b9f166..81a30f25ea7e8d5b433dfd292968423f20fb06d4 100644 --- a/en/application-dev/reference/apis-form-kit/js-apis-inner-application-formExtensionContext-sys.md +++ b/en/application-dev/reference/apis-form-kit/js-apis-inner-application-formExtensionContext-sys.md @@ -1,6 +1,6 @@ # FormExtensionContext (System API) -The FormExtensionContext module, inherited from [ExtensionContext](../apis-ability-kit/js-apis-inner-application-extensionContext.md), provides the context environment for the [FormExtensionAbility](js-apis-app-form-formExtensionAbility.md). +The **FormExtensionContext** module, inherited from [ExtensionContext](../apis-ability-kit/js-apis-inner-application-extensionContext.md), provides the context environment for the [FormExtensionAbility](js-apis-app-form-formExtensionAbility.md). You can use the APIs of this module to start a FormExtensionAbility. @@ -172,7 +172,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3.Parameter verification failed. | | 16000001 | The specified ability does not exist. | | 16000002 | Incorrect ability type. | -| 16000004 | Can not start invisible component. | +| 16000004 | Cannot start an invisible component. | | 16000005 | The specified process does not have the permission. | | 16000006 | Cross-user operations are not allowed. | | 16000008 | The crowdtesting application expires. | diff --git a/en/application-dev/reference/apis-form-kit/js-apis-inner-application-formExtensionContext.md b/en/application-dev/reference/apis-form-kit/js-apis-inner-application-formExtensionContext.md index 30e95385c3e776760cc77bf27fd4d80114f3549f..0273c6351bce9899861056d5aae9b64659356a72 100644 --- a/en/application-dev/reference/apis-form-kit/js-apis-inner-application-formExtensionContext.md +++ b/en/application-dev/reference/apis-form-kit/js-apis-inner-application-formExtensionContext.md @@ -9,10 +9,18 @@ You can use the APIs of this module to start a FormExtensionAbility. > 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. > The APIs of this module can be used only in the stage model. +## Modules to Import + +```ts +import { FormExtensionAbility } from '@kit.FormKit'; +``` + ## FormExtensionContext -The FormExtensionContext module provides the context environment for the [FormExtensionAbility](js-apis-app-form-formExtensionAbility.md). +**FormExtensionContext** is the context of [FormExtensionAbility](js-apis-app-form-formExtensionAbility.md). **System capability**: SystemCapability.Ability.Form -**Atomic service API**: This API can be used in atomic services since API version 11. \ No newline at end of file +**Model restriction**: This API can be used only in the stage model. + +**Atomic service API**: This API can be used in atomic services since API version 11.