• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Stage Widget Development
2
3## Widget Overview
4
5A 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.
6
7A 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.
8
9Before you get started, it would be helpful if you have a basic understanding of the following concepts:
10
11- 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.
12- Widget host: an application that displays the widget content and controls the widget location.
13- Widget Manager: a resident agent that provides widget management features such as periodic widget updates.
14
15> **NOTE**
16>
17> The widget host and provider do not need to be running all the time. The Widget Manager will start the widget provider to obtain widget information when a widget is added, deleted, or updated.
18
19You only need to develop the widget provider. The system automatically handles the work of the widget host and Widget Manager.
20
21The widget provider controls the widget content to display, the layout of components used in the widget, and click events bound to the components.
22
23## When to Use
24
25Carry out the following operations to develop the widget provider based on the [stage model](stage-brief.md):
26
271. Implement lifecycle callbacks by using the **FormExtension** APIs.
282. Create a **FormBindingData** instance.
293. Update a widget by using the **FormProvider** APIs.
304. Develop the widget UI page.
31
32## Available APIs
33
34The **FormExtension** class has the following APIs. For details, see [FormExtension](../reference/apis/js-apis-app-form-formExtensionAbility.md).
35
36**Table 1** FormExtension APIs
37
38| API                                                      | Description                                        |
39| :----------------------------------------------------------- | :------------------------------------------- |
40| onCreate(want: Want): formBindingData.FormBindingData        | Called to notify the widget provider that a widget has been created.          |
41| onCastToNormal(formId: string): void                         | Called to notify the widget provider that a temporary widget has been converted to a normal one.|
42| onUpdate(formId: string): void                               | Called to notify the widget provider that a widget has been updated.          |
43| onVisibilityChange(newStatus: { [key: string]: number }): void | Called to notify the widget provider of the change in widget visibility.        |
44| onEvent(formId: string, message: string): void               | Called to instruct the widget provider to receive and process a widget event.      |
45| onDestroy(formId: string): void                              | Called to notify the widget provider that a widget has been destroyed.          |
46| onConfigurationUpdated(config: Configuration): void;         | Called when the configuration of the environment where the widget is running is updated.                      |
47
48The **FormExtension** class also has a member context, that is, the **FormExtensionContext** class. For details, see [FormExtensionContext](../reference/apis/js-apis-inner-application-formExtensionContext.md).
49
50**Table 2** FormExtensionContext APIs
51
52| API                                                      | Description                                                        |
53| :----------------------------------------------------------- | :----------------------------------------------------------- |
54| startAbility(want: Want, callback: AsyncCallback<void>): void | Starts an ability. This API uses an asynchronous callback to return the result. (This is a system API and cannot be called by third-party applications.)|
55| startAbility(want: Want): Promise<void>                | Starts an ability. This API uses a promise to return the result. (This is a system API and cannot be called by third-party applications.)|
56
57The table below describes the **FormProvider** APIs. For details, see [FormProvider](../reference/apis/js-apis-application-formProvider.md).
58
59**Table 3** FormProvider APIs
60
61| API                                                      | Description                                             |
62| :----------------------------------------------------------- | :------------------------------------------------ |
63| 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.                   |
64| setFormNextRefreshTime(formId: string, minute: number): Promise<void>; | Sets the next refresh time for a widget. This API uses a promise to return the result.|
65| updateForm(formId: string, formBindingData: FormBindingData, callback: AsyncCallback<void>): void; | Updates a widget. This API uses an asynchronous callback to return the result.                                 |
66| updateForm(formId: string, formBindingData: FormBindingData): Promise<void>; | Updates a widget. This API uses a promise to return the result.              |
67
68## How to Develop
69
70### Creating a FormExtension Instance
71
72To create a widget in the stage model, you need to implement lifecycle callbacks using the **FormExtension** APIs. The code snippet is as follows:
73
741. Import the required modules.
75
76   ```javascript
77   import FormExtension from '@ohos.application.FormExtension'
78   import formBindingData from '@ohos.application.formBindingData'
79   import formInfo from '@ohos.application.formInfo'
80   import formProvider from '@ohos.application.formProvider'
81   ```
82
832. Implement lifecycle callbacks for the widget.
84
85   ```javascript
86   export default class FormAbility extends FormExtension {
87       onCreate(want) {
88           console.log('FormAbility onCreate');
89           // Persistently store widget information for subsequent use, such as widget instance retrieval or update.
90           let obj = {
91               "title": "titleOnCreate",
92               "detail": "detailOnCreate"
93           };
94           let formData = formBindingData.createFormBindingData(obj);
95           return formData;
96       }
97       onCastToNormal(formId) {
98           // Called when the widget host converts the temporary widget into a normal one. The widget provider should do something to respond to the conversion.
99           console.log('FormAbility onCastToNormal');
100       }
101       onUpdate(formId) {
102           // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host.
103           console.log('FormAbility onUpdate');
104           let obj = {
105               "title": "titleOnUpdate",
106               "detail": "detailOnUpdate"
107           };
108           let formData = formBindingData.createFormBindingData(obj);
109           formProvider.updateForm(formId, formData).catch((error) => {
110               console.log('FormAbility updateForm, error:' + JSON.stringify(error));
111           });
112       }
113       onVisibilityChange(newStatus) {
114           // Called when the widget host initiates an event about visibility changes. The widget provider should do something to respond to the notification.
115           console.log('FormAbility onVisibilityChange');
116       }
117       onEvent(formId, message) {
118           // If the widget supports event triggering, override this method and implement the trigger.
119           console.log('FormAbility onEvent');
120       }
121       onDestroy(formId) {
122           // Delete widget data.
123           console.log('FormAbility onDestroy');
124       }
125       onConfigurationUpdated(config) {
126           console.log('FormAbility onConfigurationUpdated, config:' + JSON.stringify(config));
127       }
128   }
129   ```
130
131### Configuring the Widget Configuration File
132
133- Configure Extension ability information under **extensionAbilities** in the **module.json5** file. The internal field structure is described as follows:
134
135  | Name   | Description                                                        | Data Type  | Default Value Allowed          |
136  | ----------- | ------------------------------------------------------------ | ---------- | -------------------- |
137  | name        | Name of the Extension ability. This field must be specified.                | String    | No                  |
138  | srcEnty    | Path of the Extension ability lifecycle code. This field must be specified.| String    | No                  |
139  | description | Description of the Extension ability. The value can be a string or a resource index to descriptions in multiple languages.| String    | Yes (initial value: left empty)|
140  | icon        | Index of the Extension ability icon file.                  | String    | Yes (initial value: left empty)|
141  | label       | Descriptive information about the Extension ability presented externally. The value can be a string or a resource index to the description.| String    | Yes (initial value: left empty)|
142  | type        | Type of the Extension ability. In the current development scenario, set this field to **form**.| String    | No                  |
143  | permissions | Permissions required for abilities of another application to call the current ability.        | String array| Yes (initial value: left empty)|
144  | metadata    | Metadata (configuration information) of the Extension ability.| Object      | Yes (initial value: left empty)  |
145
146  For a Form Extension ability, you must specify **metadata**. Specifically, set **name** to **ohos.extension.form** (fixed), and set **resource** to the index of the widget configuration information.
147
148  Example configuration:
149
150     ```json
151  "extensionAbilities": [{
152      "name": "FormAbility",
153      "srcEnty": "./ets/FormAbility/FormAbility.ts",
154      "label": "$string:form_FormAbility_label",
155      "description": "$string:form_FormAbility_desc",
156      "type": "form",
157      "metadata": [{
158          "name": "ohos.extension.form",
159          "resource": "$profile:form_config"
160      }]
161  }]
162     ```
163
164- Configure the widget configuration information. **resource** in **metadata** specifies the index of the widget configuration information. For example, **$profile:form_config** means that **form_config.json** in the **resources/base/profile/** directory of the development view is used as the widget profile configuration file.
165
166  The internal field structure is described as follows:
167
168  | Name           | Description                                                        | Data Type  | Default Value Allowed              |
169  | ------------------- | ------------------------------------------------------------ | ---------- | ------------------------ |
170  | name                | Class name of the widget. The value is a string with a maximum of 127 bytes.                   | String    | No                      |
171  | 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)      |
172  | src                 | Full path of the UI code corresponding to the widget.                            | String    | No                      |
173  | window              | Window-related configurations.                              | Object      | Yes                  |
174  | isDefault           | Whether the widget is a default one. Each ability has only one default widget.<br>**true**: The widget is the default one.<br>**false**: The widget is not the default one.| Boolean    | No                      |
175  | colorMode           | Color mode of the widget.<br>**auto**: The widget adopts the auto-adaptive color mode.<br>**dark**: The widget adopts the dark color mode.<br>**light**: The widget adopts the light color mode.| String    | Yes (initial value: **auto**)|
176  | supportDimensions   | Grid styles supported by the widget.<br>**1 * 2**: indicates a grid with one row and two columns.<br>**2 * 2**: indicates a grid with two rows and two columns.<br>**2 * 4**: indicates a grid with two rows and four columns.<br>**4 * 4**: indicates a grid with four rows and four columns.| String array| No                      |
177  | defaultDimension    | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String    | No                      |
178  | updateEnabled       | Whether the widget can be updated periodically.<br>**true**: The widget can be updated at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** takes precedence over **scheduledUpdateTime**.<br>**false**: The widget cannot be updated periodically.| Boolean  | No                      |
179  | scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute.<br>**updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| String    | Yes (initial value: **0:0**) |
180  | updateDuration      | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.<br>If the value is **0**, this field does not take effect.<br>If the value is a positive integer *N*, the interval is calculated by multiplying *N* and 30 minutes.<br>**updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| Number      | Yes (initial value: **0**)   |
181  | formConfigAbility   | Link to a specific page of the application. The value is a URI.                       | String    | Yes (initial value: left empty)    |
182  | formVisibleNotify   | Whether the widget is allowed to use the widget visibility notification.                        | String    | Yes (initial value: left empty)    |
183  | metaData            | Metadata of the widget. This field contains the array of the **customizeData** field.           | Object      | Yes (initial value: left empty)    |
184
185     Example configuration:
186
187     ```json
188  {
189      "forms": [{
190          "name": "widget",
191          "description": "This is a widget.",
192          "src": "./js/widget/pages/index/index",
193          "window": {
194              "autoDesignWidth": true,
195              "designWidth": 720
196          },
197          "isDefault": true,
198          "colorMode": "auto",
199          "supportDimensions": ["2*2"],
200          "defaultDimension": "2*2",
201          "updateEnabled": true,
202          "scheduledUpdateTime": "10:30",
203          "formConfigAbility": "ability://ohos.samples.FormApplication.MainAbility"
204      }]
205  }
206     ```
207
208
209### Persistently Storing Widget Data
210
211A widget provider is usually started when it is needed to provide information about a widget. The Widget Manager supports multi-instance management and uses the widget ID to identify an instance. If the widget provider supports widget data modification, it must persistently store the data based on the widget ID, so that it can access the data of the target widget when obtaining, updating, or starting a widget.
212
213```javascript
214       onCreate(want) {
215           console.log('FormAbility onCreate');
216
217           let formId = want.parameters["ohos.extra.param.key.form_identity"];
218           let formName = want.parameters["ohos.extra.param.key.form_name"];
219           let tempFlag = want.parameters["ohos.extra.param.key.form_temporary"];
220           // Persistently store widget data for subsequent use, such as widget instance retrieval or update.
221           // The storeFormInfo API is not implemented here.
222           storeFormInfo(formId, formName, tempFlag, want);
223
224           let obj = {
225               "title": "titleOnCreate",
226               "detail": "detailOnCreate"
227           };
228           let formData = formBindingData.createFormBindingData(obj);
229           return formData;
230       }
231```
232
233You should override **onDestroy** to implement widget data deletion.
234
235```javascript
236       onDestroy(formId) {
237           console.log('FormAbility onDestroy');
238
239           // You need to implement the code for deleting the persistent widget data.
240           // The deleteFormInfo API is not implemented here.
241           deleteFormInfo(formId);
242       }
243```
244
245For details about how to implement persistent data storage, see [Lightweight Data Store Development](../database/database-preference-guidelines.md).
246
247The **Want** object passed in by the widget host to the widget provider contains a flag that specifies whether the requested widget is normal or temporary.
248
249- Normal widget: a widget persistently used by the widget host
250
251- Temporary widget: a widget temporarily used by the widget host
252
253Data of a temporary widget will be deleted on the Widget Manager if the widget framework is killed and restarted. The widget provider, however, is not notified of the deletion and still keeps the data. Therefore, the widget provider needs to clear the data of temporary widgets proactively if the data has been kept for a long period of time. If the widget host has converted a temporary widget into a normal one, the widget provider should change the widget data from temporary storage to persistent storage. Otherwise, the widget data may be deleted by mistake.
254
255### Updating Widget Data
256
257When an application initiates a scheduled or periodic update, the application obtains the latest data and calls **updateForm** to update the widget. The code snippet is as follows:
258
259```javascript
260onUpdate(formId) {
261    // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host.
262    console.log('FormAbility onUpdate');
263    let obj = {
264        "title": "titleOnUpdate",
265        "detail": "detailOnUpdate"
266    };
267    let formData = formBindingData.createFormBindingData(obj);
268    // Call the updateForm() method to update the widget. Only the data passed through the input parameter is updated. Other information remains unchanged.
269    formProvider.updateForm(formId, formData).catch((error) => {
270        console.log('FormAbility updateForm, error:' + JSON.stringify(error));
271    });
272}
273```
274
275### Developing the Widget UI Page
276
277You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programmed widget.
278
279> **NOTE**
280>
281> Only the JavaScript-based web-like development paradigm is supported when developing the widget UI.
282
283   - HML file:
284   ```html
285   <div class="container">
286       <stack>
287           <div class="container-img">
288               <image src="/common/widget.png" class="bg-img"></image>
289           </div>
290           <div class="container-inner">
291               <text class="title">{{title}}</text>
292               <text class="detail_text" onclick="routerEvent">{{detail}}</text>
293           </div>
294       </stack>
295   </div>
296   ```
297
298   - CSS file:
299
300   ```css
301.container {
302    flex-direction: column;
303    justify-content: center;
304    align-items: center;
305}
306
307.bg-img {
308    flex-shrink: 0;
309    height: 100%;
310}
311
312.container-inner {
313    flex-direction: column;
314    justify-content: flex-end;
315    align-items: flex-start;
316    height: 100%;
317    width: 100%;
318    padding: 12px;
319}
320
321.title {
322    font-size: 19px;
323    font-weight: bold;
324    color: white;
325    text-overflow: ellipsis;
326    max-lines: 1;
327}
328
329.detail_text {
330    font-size: 16px;
331    color: white;
332    opacity: 0.66;
333    text-overflow: ellipsis;
334    max-lines: 1;
335    margin-top: 6px;
336}
337   ```
338
339   - JSON file:
340   ```json
341   {
342     "data": {
343       "title": "TitleDefault",
344       "detail": "TextDefault"
345     },
346     "actions": {
347       "routerEvent": {
348         "action": "router",
349         "abilityName": "MainAbility",
350         "params": {
351           "message": "add detail"
352         }
353       }
354     }
355   }
356   ```
357
358Now you've got a widget shown below.
359
360![fa-form-example](figures/fa-form-example.png)
361
362### Developing Widget Events
363
364You can set router and message events for components on a widget. The router event applies to ability redirection, and the message event applies to custom click events. The key steps are as follows:
365
3661. Set the **onclick** field in the HML file to **routerEvent** or **messageEvent**, depending on the **actions** settings in the JSON file.
3672. Set the router event.
368   - **action**: **"router"**, which indicates a router event.
369   - **abilityName**: target ability name, for example, **MainAbility**, which is the default main ability name in DevEco Studio for the stage model.
370   - **params**: custom parameters of the target ability. Set them as required. The value can be obtained from **parameters** in **want** used for starting the target ability. For example, in the lifecycle function **onCreate** of the main ability in the stage model, you can obtain **want** and its **parameters** field.
3713. Set the message event.
372   - **action**: **"message"**, which indicates a message event.
373   - **params**: custom parameters of the message event. Set them as required. The value can be obtained from **message** in the widget lifecycle function **onEvent**.
374
375The code snippet is as follows:
376
377   - HML file:
378   ```html
379   <div class="container">
380       <stack>
381           <div class="container-img">
382               <image src="/common/widget.png" class="bg-img"></image>
383           </div>
384           <div class="container-inner">
385               <text class="title" onclick="routerEvent">{{title}}</text>
386               <text class="detail_text" onclick="messageEvent">{{detail}}</text>
387           </div>
388       </stack>
389   </div>
390   ```
391
392   - JSON file:
393   ```json
394   {
395     "data": {
396       "title": "TitleDefault",
397       "detail": "TextDefault"
398     },
399     "actions": {
400       "routerEvent": {
401         "action": "router",
402         "abilityName": "MainAbility",
403         "params": {
404           "message": "add detail"
405         }
406       },
407       "messageEvent": {
408         "action": "message",
409         "params": {
410           "message": "add detail"
411         }
412       }
413     }
414   }
415   ```
416