1# FA Widget Development 2 3## Widget Overview 4A 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. 5 6A 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. 7 8Basic concepts: 9- Widget provider: an atomic service that controls what and how content is displayed in a widget and interacts with users. 10- Widget host: an application that displays the widget content and controls the position where the widget is displayed in the host application. 11- Widget Manager: a resident agent that manages widgets added to the system and provides functions such as periodic widget update. 12 13> **NOTE** 14> 15> 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. 16 17You only need to develop widget content as the widget provider. The system automatically handles the work done by the widget host and Widget Manager. 18 19The widget provider controls the widget content to display, component layout, and click events bound to components. 20 21## Development Overview 22 23In FA widget development, you need to carry out the following operations as a widget provider based on the [Feature Ability (FA) model](fa-brief.md). 24 25- Develop the lifecycle callbacks in **LifecycleForm**. 26- Create a **FormBindingData** instance. 27- Update a widget through **FormProvider**. 28- Develop the widget UI pages. 29 30## Available APIs 31 32The table below describes the lifecycle callbacks provided in **LifecycleForm**. 33 34**Table 1** LifecycleForm APIs 35 36| API | Description | 37| :----------------------------------------------------------- | :------------------------------------------- | 38| onCreate(want: Want): formBindingData.FormBindingData | Called to notify the widget provider that a **Form** instance (widget) has been created. | 39| onCastToNormal(formId: string): void | Called to notify the widget provider that a temporary widget has been converted to a normal one.| 40| onUpdate(formId: string): void | Called to notify the widget provider that a widget has been updated. | 41| onVisibilityChange(newStatus: { [key: string]: number }): void | Called to notify the widget provider of the change in widget visibility. | 42| onEvent(formId: string, message: string): void | Called to instruct the widget provider to receive and process a widget event. | 43| onDestroy(formId: string): void | Called to notify the widget provider that a **Form** instance (widget) has been destroyed. | 44| onAcquireFormState?(want: Want): formInfo.FormState | Called when the widget provider receives the status query result of a widget. | 45 46For details about the **FormProvider** APIs, see [FormProvider](../reference/apis/js-apis-formprovider.md). 47 48**Table 2** FormProvider APIs 49 50| API | Description | 51| :----------------------------------------------------------- | :------------------------------------------------ | 52| 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. | 53| setFormNextRefreshTime(formId: string, minute: number): Promise<void>; | Sets the next refresh time for a widget. This API uses a promise to return the result.| 54| updateForm(formId: string, 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): Promise<void>; | Updates a widget. This API uses a promise to return the result. | 56 57## How to Develop 58 59### Creating LifecycleForm 60 61To create a widget in the FA model, you need to implement the lifecycles of **LifecycleForm**. The sample code is as follows: 62 631. Import the required modules. 64 65 ```javascript 66 import formBindingData from '@ohos.application.formBindingData' 67 import formInfo from '@ohos.application.formInfo' 68 import formProvider from '@ohos.application.formProvider' 69 ``` 70 712. Implement the lifecycle callbacks of **LifecycleForm**. 72 73 ```javascript 74 export default { 75 onCreate(want) { 76 console.log('FormAbility onCreate'); 77 // Persistently store widget information for subsequent use, such as widget instance retrieval or update. 78 let obj = { 79 "title": "titleOnCreate", 80 "detail": "detailOnCreate" 81 }; 82 let formData = formBindingData.createFormBindingData(obj); 83 return formData; 84 }, 85 onCastToNormal(formId) { 86 // Called when the widget host converts the temporary widget into a normal one. The widget provider should do something to respond to the conversion. 87 console.log('FormAbility onCastToNormal'); 88 }, 89 onUpdate(formId) { 90 // To support scheduled update, periodic update, or update requested by the widget host, override this method for widget data update. 91 console.log('FormAbility onUpdate'); 92 let obj = { 93 "title": "titleOnUpdate", 94 "detail": "detailOnUpdate" 95 }; 96 let formData = formBindingData.createFormBindingData(obj); 97 formProvider.updateForm(formId, formData).catch((error) => { 98 console.log('FormAbility updateForm, error:' + JSON.stringify(error)); 99 }); 100 }, 101 onVisibilityChange(newStatus) { 102 // Called when the widget host initiates an event about visibility changes. The widget provider should do something to respond to the notification. 103 console.log('FormAbility onVisibilityChange'); 104 }, 105 onEvent(formId, message) { 106 // If the widget supports event triggering, override this method and implement the trigger. 107 console.log('FormAbility onEvent'); 108 }, 109 onDestroy(formId) { 110 // Delete widget data. 111 console.log('FormAbility onDestroy'); 112 }, 113 onAcquireFormState(want) { 114 console.log('FormAbility onAcquireFormState'); 115 return formInfo.FormState.READY; 116 }, 117 } 118 ``` 119 120### Configuring the Widget Configuration File 121 122Configure the **config.json** file for the widget. 123 124- The **js** module in the **config.json** file provides the JavaScript resources of the widget. The internal structure is described as follows: 125 126 | Field| Description | Data Type| Default | 127 | -------- | ------------------------------------------------------------ | -------- | ------------------------ | 128 | name | Name of a JavaScript component. The default value is **default**. | String | No | 129 | pages | Route information about all pages in the JavaScript component, including the page path and page name. The value is an array, in which each element represents a page. The first element in the array represents the home page of the JavaScript FA.| Array | No | 130 | window | Window-related configurations. | Object | Yes | 131 | type | Type of the JavaScript component. Available values are as follows:<br>**normal**: indicates that the JavaScript component is an application instance.<br>**form**: indicates that the JavaScript component is a widget instance.| String | Yes (initial value: **normal**)| 132 | mode | Development mode of the JavaScript component. | Object | Yes (initial value: left empty) | 133 134 A configuration example is as follows: 135 136 ```json 137 "js": [{ 138 "name": "widget", 139 "pages": ["pages/index/index"], 140 "window": { 141 "designWidth": 720, 142 "autoDesignWidth": true 143 }, 144 "type": "form" 145 }] 146 ``` 147 148- The **abilities** module in the **config.json** file corresponds to the **LifecycleForm** of the widget. The internal structure is described as follows: 149 150 | Field | Description | Data Type | Default | 151 | ------------------- | ------------------------------------------------------------ | ---------- | ------------------------ | 152 | name | Class name of the widget. The value is a string with a maximum of 127 bytes. | String | No | 153 | 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) | 154 | 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 | 155 | type | Type of the widget. Available values are as follows:<br>**JS**: indicates a JavaScript-programmed widget. | String | No | 156 | 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**)| 157 | 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 | 158 | defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String | No | 159 | 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 preferentially recommended.<br>**false**: The widget cannot be updated periodically.| Boolean | No | 160 | 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**) | 161 | 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**) | 162 | formConfigAbility | Link to a specific page of the application. The value is a URI. | String | Yes (initial value: left empty) | 163 | formVisibleNotify | Whether the widget is allowed to use the widget visibility notification. | String | Yes (initial value: left empty) | 164 | jsComponentName | Component name of the widget. The value is a string with a maximum of 127 bytes. | String | No | 165 | metaData | Metadata of the widget. This field contains the array of the **customizeData** field. | Object | Yes (initial value: left empty) | 166 | customizeData | Custom information about the widget. | Object array | Yes (initial value: left empty) | 167 168 A configuration example is as follows: 169 170 ```json 171 "abilities": [{ 172 "name": "FormAbility", 173 "description": "This is a FormAbility", 174 "formsEnabled": true, 175 "icon": "$media:icon", 176 "label": "$string:form_FormAbility_label", 177 "srcPath": "FormAbility", 178 "type": "service", 179 "srcLanguage": "ets", 180 "formsEnabled": true, 181 "forms": [{ 182 "colorMode": "auto", 183 "defaultDimension": "2*2", 184 "description": "This is a widget.", 185 "formVisibleNotify": true, 186 "isDefault": true, 187 "jsComponentName": "widget", 188 "name": "widget", 189 "scheduledUpdateTime": "10:30", 190 "supportDimensions": ["2*2"], 191 "type": "JS", 192 "updateEnabled": true 193 }] 194 }] 195 ``` 196 197 198### Persistently Storing Widget Data 199 200Mostly, 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 a widget. 201 202```javascript 203 onCreate(want) { 204 console.log('FormAbility onCreate'); 205 206 let formId = want.parameters["ohos.extra.param.key.form_identity"]; 207 let formName = want.parameters["ohos.extra.param.key.form_name"]; 208 let tempFlag = want.parameters["ohos.extra.param.key.form_temporary"]; 209 // Persistently store widget information for subsequent use, such as widget instance retrieval or update. 210 // The storeFormInfo API is not implemented here. 211 storeFormInfo(formId, formName, tempFlag, want); 212 213 let obj = { 214 "title": "titleOnCreate", 215 "detail": "detailOnCreate" 216 }; 217 let formData = formBindingData.createFormBindingData(obj); 218 return formData; 219 } 220``` 221 222You should override **onDestroy** to delete widget data. 223 224```javascript 225 onDestroy(formId) { 226 console.log('FormAbility onDestroy'); 227 228 // You need to implement the code for deleting the persistent widget instance. 229 // The deleteFormInfo API is not implemented here. 230 deleteFormInfo(formId); 231 } 232``` 233 234For details about the persistence method, see [Lightweight Data Store Development](../database/database-storage-guidelines.md). 235 236Note that the **Want** passed by the widget host to the widget provider contains a flag that indicates whether the requested widget is a temporary one. 237 238- Normal widget: a widget that will be persistently used by the widget host 239 240- Temporary widget: a widget that is temporarily used by the widget host 241 242Data of a temporary widget is not persistently stored. If the widget framework is killed and restarted, data of a temporary widget will be deleted. However, the widget provider is not notified of which widget is deleted, and still keeps the data. Therefore, the widget provider should implement data clearing. In addition, the widget host may convert a temporary widget into a normal one. If the conversion is successful, the widget provider should process the widget ID and store the data persistently. This prevents the widget provider from deleting persistent data when clearing temporary widgets. 243 244### Updating Widget Data 245 246When 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 code snippet is as follows: 247 248```javascript 249onUpdate(formId) { 250 // To support scheduled update, periodic update, or update requested by the widget host, override this method for widget data update. 251 console.log('FormAbility onUpdate'); 252 let obj = { 253 "title": "titleOnUpdate", 254 "detail": "detailOnUpdate" 255 }; 256 let formData = formBindingData.createFormBindingData(obj); 257 // Call the updateForm method to update the widget. Only the data passed through the input parameter is updated. Other information remains unchanged. 258 formProvider.updateForm(formId, formData).catch((error) => { 259 console.log('FormAbility updateForm, error:' + JSON.stringify(error)); 260 }); 261} 262``` 263 264### Developing Widget UI Pages 265 266You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programmed widget. 267 268> **NOTE** 269> 270> Currently, only the JavaScript-based web-like development paradigm can be used to develop the widget UI. 271 272 - In the HML file: 273 ```html 274 <div class="container"> 275 <stack> 276 <div class="container-img"> 277 <image src="/common/widget.png" class="bg-img"></image> 278 </div> 279 <div class="container-inner"> 280 <text class="title">{{title}}</text> 281 <text class="detail_text" onclick="routerEvent">{{detail}}</text> 282 </div> 283 </stack> 284 </div> 285 ``` 286 287 - In the CSS file: 288 289 ```css 290.container { 291 flex-direction: column; 292 justify-content: center; 293 align-items: center; 294} 295 296.bg-img { 297 flex-shrink: 0; 298 height: 100%; 299} 300 301.container-inner { 302 flex-direction: column; 303 justify-content: flex-end; 304 align-items: flex-start; 305 height: 100%; 306 width: 100%; 307 padding: 12px; 308} 309 310.title { 311 font-size: 19px; 312 font-weight: bold; 313 color: white; 314 text-overflow: ellipsis; 315 max-lines: 1; 316} 317 318.detail_text { 319 font-size: 16px; 320 color: white; 321 opacity: 0.66; 322 text-overflow: ellipsis; 323 max-lines: 1; 324 margin-top: 6px; 325} 326 ``` 327 328 - In the JSON file: 329 ```json 330 { 331 "data": { 332 "title": "TitleDefault", 333 "detail": "TextDefault" 334 }, 335 "actions": { 336 "routerEvent": { 337 "action": "router", 338 "abilityName": "com.example.entry.MainAbility", 339 "params": { 340 "message": "add detail" 341 } 342 } 343 } 344 } 345 ``` 346 347Now you've got a widget shown below. 348 349 350 351### Developing Widget Events 352 353You 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: 354 3551. Set **onclick** in the HML file to **routerEvent** or **messageEvent**, depending on the **actions** settings in the JSON file. 3562. For the router event, set the following attributes: 357 - **action**: **"router"**. 358 - **abilityName**: target ability name, for example, **com.example.entry.MainAbility**, which is the default main ability name in DevEco Studio for the FA model. 359 - **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 FA model, **featureAbility.getWant()** can be used to obtain **want** and its **parameters** field. 3603. For the message event, set the following attributes: 361 - **action**: **"message"**. 362 - **params**: custom parameters of the message event. Set them as required. The value can be obtained from **message** in the widget lifecycle function **onEvent**. 363 364The code snippet is as follows: 365 366 - In the HML file: 367 ```html 368 <div class="container"> 369 <stack> 370 <div class="container-img"> 371 <image src="/common/widget.png" class="bg-img"></image> 372 </div> 373 <div class="container-inner"> 374 <text class="title" onclick="routerEvent">{{title}}</text> 375 <text class="detail_text" onclick="messageEvent">{{detail}}</text> 376 </div> 377 </stack> 378 </div> 379 ``` 380 381 - In the JSON file: 382 ```json 383 { 384 "data": { 385 "title": "TitleDefault", 386 "detail": "TextDefault" 387 }, 388 "actions": { 389 "routerEvent": { 390 "action": "router", 391 "abilityName": "com.example.entry.MainAbility", 392 "params": { 393 "message": "add detail" 394 } 395 }, 396 "messageEvent": { 397 "action": "message", 398 "params": { 399 "message": "add detail" 400 } 401 } 402 } 403 } 404 ```