• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Stage Widget Development
2
3## Widget Overview
4
5A widget is a set of UI components used to display important information or operations for an application. It provides users with direct access to a desired application service, without requiring them to open the application.
6
7A widget displays brief information about an application on the UI of another application (host application, currently system applications only) and provides basic interactive functions such as opening a UI page or sending a message.
8
9Basic concepts:
10
11- Widget provider: an atomic service that controls what and how content is displayed in a widget and interacts with users.
12- Widget host: an application that displays the widget content and controls the position where the widget is displayed in the host application.
13- Widget Manager: a resident agent that manages widgets added to the system and provides functions such as periodic widget update.
14
15> **NOTE**
16>
17> The widget host and provider do not keep running all the time. The Widget Manager starts the widget provider to obtain widget information when a widget is added, deleted, or updated.
18
19You only need to develop widget content as the widget provider. The system automatically handles the work done by the widget host and Widget Manager.
20
21The widget provider controls the widget content to display, component layout, and click events bound to components.
22
23## When to Use
24
25Stage widget development refers to the development conducted by the widget provider based on the [stage model](stage-brief.md). As a widget provider, you need to carry out the following operations:
26
27- Develop the lifecycle callbacks in **FormExtension**.
28- Create a **FormBindingData** instance.
29- Update a widget through **FormProvider**.
30- 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-formextension.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 **Form** instance (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 **Form** instance (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-formextensioncontext.md).
49
50**Table 2** FormExtensionContext APIs
51
52| API                                                      | Description                                                        |
53| :----------------------------------------------------------- | :----------------------------------------------------------- |
54| updateForm(formId: string, formBindingData: formBindingData.FormBindingData, callback: AsyncCallback\<void>): void | Updates a widget. This API uses an asynchronous callback to return the result.|
55| updateForm(formId: string, formBindingData: formBindingData.FormBindingData): Promise\<void>                | Updates a widget. This API uses a promise to return the result.|
56
57For details about the **FormProvider** APIs, see [FormProvider](../reference/apis/js-apis-formprovider.md).
58
59**Table 3** FormProvider APIs
60
61| API                                                      | Description                                             |
62| :----------------------------------------------------------- | :------------------------------------------------ |
63| setFormNextRefreshTime(formId: string, minute: number, callback: AsyncCallback&lt;void&gt;): 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&lt;void&gt;; | 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&lt;void&gt;): void; | Updates a widget. This API uses an asynchronous callback to return the result.                                 |
66| updateForm(formId: string, formBindingData: FormBindingData): Promise&lt;void&gt;; | 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, implement the lifecycle callbacks of **FormExtension**. The sample code 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 the lifecycle callbacks of **FormExtension**.
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           // To support scheduled update, periodic update, or update requested by the widget host, override this method for widget data update.
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  | Field   | Description                                                        | Data Type  | Default          |
136  | ----------- | ------------------------------------------------------------ | ---------- | -------------------- |
137  | name        | Name of the Extension ability. This field must be specified.                | String    | No                  |
138  | srcEntrance | 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  A configuration example is as follows:
149
150     ```json
151  "extensionAbilities": [{
152      "name": "FormAbility",
153      "srcEntrance": "./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  | Field           | Description                                                        | Data Type  | Default              |
169  | ------------------- | ------------------------------------------------------------ | ---------- | ------------------------ |
170  | name                | Class name of a 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. Available values are as follows:<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. Available values are as follows:<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. Available values are as follows:<br>**true**: The widget can be updated periodically, depending on the update way you select, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** is recommended.<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>This parameter has a lower priority than **updateDuration**. 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>This parameter has a higher priority than **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     A configuration example is as follows:
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
211Mostly, the widget provider is started only when it needs to obtain 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 the 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 delete widget data.
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 the persistence method, see [Lightweight Data Store Development](../database/database-storage-guidelines.md).
246
247Note that the **Want** passed by the widget host to the widget provider contains a temporary flag, indicating whether the requested widget is a temporary one.
248
249- Normal widget: a widget that will be persistently used by the widget host
250
251- Temporary widget: a widget that is temporarily used by the widget host
252
253Data of a temporary widget is not persistently stored. If it is deleted from the Widget Manager due to exceptions, such as crash of the widget framework, the widget provider will not be notified of which widget is deleted, and still keeps the data. In light of this, the widget provider should implement data clearing. If the widget host successfully converts a temporary widget into a normal one, the widget provider should also process the widget ID and store the data persistently. This prevents the widget provider from deleting the widget data when clearing temporary widgets.
254
255### Updating Widget Data
256
257When a widget application initiates a data update upon a scheduled or periodic update, the application obtains the latest data and calls **updateForm** to update the widget. The sample code is as follows:
258
259```javascript
260onUpdate(formId) {
261    // To support scheduled update, periodic update, or update requested by the widget host, override this method for widget data update.
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> Currently, only the JavaScript-based web-like development paradigm can be used to develop the widget UI.
282
283   - In the 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   - In the 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   - In the 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 **onclick** in the HML file to **routerEvent** or **messageEvent**, depending on the **actions** settings in the JSON file.
3672. For the router event, set the following attributes:
368   - **action**: **"router"**.
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. For the message event, set the following attributes:
372   - **action**: **"message"**.
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 following is an example:
376
377   - In the 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   - In the 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   ```