1# Developing a JS Widget 2 3 4The following describes how to develop JS widgets based on the web-like development paradigm. 5 6 7## Working Principles 8 9Below shows the working principles of the widget framework. 10 11**Figure 1** Widget framework working principles in the stage model 12 13![JSCardPrinciple](figures/JSCardPrinciple.png) 14 15The widget host consists of the following modules: 16 17- Widget usage: provides operations such as creating, deleting, or updating a widget. 18 19- Communication adapter: provided by the OpenHarmony SDK for communication with the Widget Manager. It sends widget-related operations to the Widget Manager. 20 21The Widget Manager consists of the following modules: 22 23- Periodic updater: starts a scheduled task based on the update policy to periodically update a widget after it is added to the Widget Manager. 24 25- 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. 26 27- 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. 28 29- 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. 30 31- Communication adapter: communicates with the widget host and provider through RPCs. 32 33The widget provider consists of the following modules: 34 35- Widget service: implemented by the widget provider developer to process requests on widget creation, update, and deletion, and to provide corresponding widget services. 36 37- Instance manager: implemented by the widget provider developer for persistent management of widget instances allocated by the Widget Manager. 38 39- Communication adapter: provided by the OpenHarmony SDK for communication with the Widget Manager. It pushes update data to the Widget Manager. 40 41> **NOTE** 42> You only need to develop the widget provider. The system automatically handles the work of the widget host and Widget Manager. 43 44 45## Available APIs 46 47The **FormExtensionAbility** class has the following APIs. For details, see [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md). 48 49| Name| Description| 50| -------- | -------- | 51| onAddForm(want: Want): formBindingData.FormBindingData | Called to notify the widget provider that a widget has been created.| 52| onCastToNormalForm(formId: string): void | Called to notify the widget provider that a temporary widget has been converted to a normal one.| 53| onUpdateForm(formId: string): void | Called to notify the widget provider that a widget has been updated.| 54| onChangeFormVisibility(newStatus: { [key: string]: number }): void | Called to notify the widget provider of the change in widget visibility.| 55| onFormEvent(formId: string, message: string): void | Called to instruct the widget provider to receive and process a widget event.| 56| onRemoveForm(formId: string): void | Called to notify the widget provider that a widget has been destroyed.| 57| onConfigurationUpdate(config: Configuration): void | Called when the configuration of the environment where the widget is running is updated.| 58| onShareForm?(formId: string): { [key: string]: any } | Called by the widget provider to receive shared widget data.| 59 60The **FormProvider** class has the following APIs. For details, see [FormProvider](../reference/apis/js-apis-app-form-formProvider.md). 61 62| Name| Description| 63| -------- | -------- | 64| 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.| 65| setFormNextRefreshTime(formId: string, minute: number): Promise<void>; | Sets the next refresh time for a widget. This API uses a promise to return the result.| 66| updateForm(formId: string, formBindingData: FormBindingData, callback: AsyncCallback<void>): void; | Updates a widget. This API uses an asynchronous callback to return the result.| 67| updateForm(formId: string, formBindingData: FormBindingData): Promise<void>; | Updates a widget. This API uses a promise to return the result.| 68 69The **FormBindingData** class has the following APIs. For details, see [FormBindingData](../reference/apis/js-apis-app-form-formBindingData.md). 70 71| Name| Description| 72| -------- | -------- | 73| createFormBindingData(obj?: Object \| string): FormBindingData | Creates a **FormBindingData** object.| 74 75 76## How to Develop 77 78The widget provider development based on the [stage model](stage-model-development-overview.md) involves the following key steps: 79 80- [Creating a FormExtensionAbility Instance](#creating-a-formextensionability-instance): Develop the lifecycle callback functions of FormExtensionAbility. 81 82- [Configuring the Widget Configuration Files](#configuring-the-widget-configuration-files): Configure the application configuration file **module.json5** and profile configuration file. 83 84- [Persistently Storing Widget Data](#persistently-storing-widget-data): This operation is a form of widget data exchange. 85 86- [Updating Widget Data](#updating-widget-data): Call **updateForm()** to update the information displayed on a widget. 87 88- [Developing the Widget UI Page](#developing-the-widget-ui-page): Use HML+CSS+JSON to develop a JS widget UI page. 89 90- [Developing Widget Events](#developing-widget-events): Add the router and message events for a widget. 91 92 93### Creating a FormExtensionAbility Instance 94 95To create a widget in the stage model, implement the lifecycle callbacks of **FormExtensionAbility**. Generate a widget template by referring to [Developing a Service Widget](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-development-service-widget-0000001263280425). 96 971. Import related modules to **EntryFormAbility.ts**. 98 99 100 ```ts 101 import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; 102 import formBindingData from '@ohos.app.form.formBindingData'; 103 import formInfo from '@ohos.app.form.formInfo'; 104 import formProvider from '@ohos.app.form.formProvider'; 105 import dataStorage from '@ohos.data.storage'; 106 ``` 107 1082. Implement the FormExtension lifecycle callbacks in **EntryFormAbility.ts**. 109 110 111 ```ts 112 export default class EntryFormAbility extends FormExtensionAbility { 113 onAddForm(want) { 114 console.info('[EntryFormAbility] onAddForm'); 115 // Called when the widget is created. The widget provider should return the widget data binding class. 116 let obj = { 117 "title": "titleOnCreate", 118 "detail": "detailOnCreate" 119 }; 120 let formData = formBindingData.createFormBindingData(obj); 121 return formData; 122 } 123 onCastToNormalForm(formId) { 124 // Called when the widget host converts the temporary widget into a normal one. The widget provider should do something to respond to the conversion. 125 console.info('[EntryFormAbility] onCastToNormalForm'); 126 } 127 onUpdateForm(formId) { 128 // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host. 129 console.info('[EntryFormAbility] onUpdateForm'); 130 let obj = { 131 "title": "titleOnUpdate", 132 "detail": "detailOnUpdate" 133 }; 134 let formData = formBindingData.createFormBindingData(obj); 135 formProvider.updateForm(formId, formData).catch((error) => { 136 console.info('[EntryFormAbility] updateForm, error:' + JSON.stringify(error)); 137 }); 138 } 139 onChangeFormVisibility(newStatus) { 140 // Called when the widget host initiates an event about visibility changes. The widget provider should do something to respond to the notification. This callback takes effect only for system applications. 141 console.info('[EntryFormAbility] onChangeFormVisibility'); 142 } 143 onFormEvent(formId, message) { 144 // If the widget supports event triggering, override this method and implement the trigger. 145 console.info('[EntryFormAbility] onFormEvent'); 146 } 147 onRemoveForm(formId) { 148 // Delete widget data. 149 console.info('[EntryFormAbility] onRemoveForm'); 150 } 151 onConfigurationUpdate(config) { 152 console.info('[EntryFormAbility] nConfigurationUpdate, config:' + JSON.stringify(config)); 153 } 154 onAcquireFormState(want) { 155 return formInfo.FormState.READY; 156 } 157 } 158 ``` 159 160> **NOTE** 161> FormExtensionAbility cannot reside in the background. Therefore, continuous tasks cannot be processed in the widget lifecycle callbacks. 162 163 164### Configuring the Widget Configuration Files 165 1661. Configure ExtensionAbility 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. 167 Example configuration: 168 169 170 ```json 171 { 172 "module": { 173 ... 174 "extensionAbilities": [ 175 { 176 "name": "EntryFormAbility", 177 "srcEntry": "./ets/entryformability/EntryFormAbility.ts", 178 "label": "$string:EntryFormAbility_label", 179 "description": "$string:EntryFormAbility_desc", 180 "type": "form", 181 "metadata": [ 182 { 183 "name": "ohos.extension.form", 184 "resource": "$profile:form_config" 185 } 186 ] 187 } 188 ] 189 } 190 } 191 ``` 192 1932. 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 field structure. 194 195 **Table 1** Widget profile configuration file 196 197 | Field| Description| Data Type| Default Value Allowed| 198 | -------- | -------- | -------- | -------- | 199 | name | Class name of the widget. The value is a string with a maximum of 127 bytes.| String| No| 200 | 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)| 201 | src | Full path of the UI code corresponding to the widget.| String| No| 202 | window | Window-related configurations.| Object| Yes| 203 | isDefault | Whether the widget is a default one. Each UIAbility has only one default widget.<br>- **true**: The widget is the default one.<br>- **false**: The widget is not the default one.| Boolean| No| 204 | colorMode | Color mode of the widget.<br>- **auto**: auto-adaptive color mode<br>- **dark**: dark color mode<br>- **light**: light color mode| String| Yes (initial value: **auto**)| 205 | 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| 206 | defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String| No| 207 | 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| 208 | 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**)| 209 | 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**)| 210 | formConfigAbility | Link to a specific page of the application. The value is a URI.| String| Yes (initial value: left empty)| 211 | formVisibleNotify | Whether the widget is allowed to use the widget visibility notification.| String| Yes (initial value: left empty)| 212 | metaData | Metadata of the widget. This field contains the array of the **customizeData** field.| Object| Yes (initial value: left empty)| 213 214 Example configuration: 215 216 217 ```json 218 { 219 "forms": [ 220 { 221 "name": "widget", 222 "description": "This is a service widget.", 223 "src": "./js/widget/pages/index/index", 224 "window": { 225 "designWidth": 720, 226 "autoDesignWidth": true 227 }, 228 "colorMode": "auto", 229 "isDefault": true, 230 "updateEnabled": true, 231 "scheduledUpdateTime": "10:30", 232 "updateDuration": 1, 233 "defaultDimension": "2*2", 234 "supportDimensions": [ 235 "2*2" 236 ] 237 } 238 ] 239 } 240 ``` 241 242 243### Persistently Storing Widget Data 244 245A 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. 246 247 248```ts 249const DATA_STORAGE_PATH = "/data/storage/el2/base/haps/form_store"; 250async function storeFormInfo(formId: string, formName: string, tempFlag: boolean) { 251 // Only the widget ID (formId), widget name (formName), and whether the widget is a temporary one (tempFlag) are persistently stored. 252 let formInfo = { 253 "formName": formName, 254 "tempFlag": tempFlag, 255 "updateCount": 0 256 }; 257 try { 258 const storage = await dataStorage.getStorage(DATA_STORAGE_PATH); 259 // put form info 260 await storage.put(formId, JSON.stringify(formInfo)); 261 console.info(`[EntryFormAbility] storeFormInfo, put form info successfully, formId: ${formId}`); 262 await storage.flush(); 263 } catch (err) { 264 console.error(`[EntryFormAbility] failed to storeFormInfo, err: ${JSON.stringify(err)}`); 265 } 266} 267 268export default class EntryFormAbility extends FormExtension { 269 ... 270 onAddForm(want) { 271 console.info('[EntryFormAbility] onAddForm'); 272 273 let formId = want.parameters["ohos.extra.param.key.form_identity"]; 274 let formName = want.parameters["ohos.extra.param.key.form_name"]; 275 let tempFlag = want.parameters["ohos.extra.param.key.form_temporary"]; 276 // Persistently store widget data for subsequent use, such as instance acquisition and update. 277 // Implement this API based on project requirements. 278 storeFormInfo(formId, formName, tempFlag); 279 280 let obj = { 281 "title": "titleOnCreate", 282 "detail": "detailOnCreate" 283 }; 284 let formData = formBindingData.createFormBindingData(obj); 285 return formData; 286 } 287} 288``` 289 290You should override **onRemoveForm** to implement widget data deletion. 291 292 293```ts 294const DATA_STORAGE_PATH = "/data/storage/el2/base/haps/form_store"; 295async function deleteFormInfo(formId: string) { 296 try { 297 const storage = await dataStorage.getStorage(DATA_STORAGE_PATH); 298 // del form info 299 await storage.delete(formId); 300 console.info(`[EntryFormAbility] deleteFormInfo, del form info successfully, formId: ${formId}`); 301 await storage.flush(); 302 } catch (err) { 303 console.error(`[EntryFormAbility] failed to deleteFormInfo, err: ${JSON.stringify(err)}`); 304 } 305} 306 307... 308 309export default class EntryFormAbility extends FormExtension { 310 ... 311 onRemoveForm(formId) { 312 console.info('[EntryFormAbility] onRemoveForm'); 313 // Delete the persistent widget instance data. 314 // Implement this API based on project requirements. 315 deleteFormInfo(formId); 316 } 317} 318``` 319 320For details about persistence, see [Application Data Persistence Overview](../database/app-data-persistence-overview.md). 321 322The **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. 323 324- Normal widget: a widget persistently used by the widget host 325 326- Temporary widget: a widget temporarily used by the widget host 327 328Data 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. 329 330 331### Updating Widget Data 332 333When an application initiates a scheduled or periodic update, the application obtains the latest data and calls **updateForm()** to update the widget. 334 335 336```ts 337onUpdateForm(formId) { 338 // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host. 339 console.info('[EntryFormAbility] onUpdateForm'); 340 let obj = { 341 "title": "titleOnUpdate", 342 "detail": "detailOnUpdate" 343 }; 344 let formData = formBindingData.createFormBindingData(obj); 345 // Call the updateForm() method to update the widget. Only the data passed through the input parameter is updated. Other information remains unchanged. 346 formProvider.updateForm(formId, formData).catch((error) => { 347 console.info('[EntryFormAbility] updateForm, error:' + JSON.stringify(error)); 348 }); 349} 350``` 351 352 353### Developing the Widget UI Page 354 355You can use the web-like paradigm (HML+CSS+JSON) to develop JS widget pages. This section describes how to develop a page shown below. 356 357![WidgetCardPage](figures/WidgetCardPage.png) 358 359- HML: uses web-like paradigm components to describe the widget page information. 360 361 362 ```html 363 <div class="container"> 364 <stack> 365 <div class="container-img"> 366 <image src="/common/widget.png" class="bg-img"></image> 367 </div> 368 <div class="container-inner"> 369 <text class="title">{{title}}</text> 370 <text class="detail_text" onclick="routerEvent">{{detail}}</text> 371 </div> 372 </stack> 373 </div> 374 ``` 375 376- CSS: defines style information about the web-like paradigm components in HML. 377 378 379 ```css 380 .container { 381 flex-direction: column; 382 justify-content: center; 383 align-items: center; 384 } 385 386 .bg-img { 387 flex-shrink: 0; 388 height: 100%; 389 } 390 391 .container-inner { 392 flex-direction: column; 393 justify-content: flex-end; 394 align-items: flex-start; 395 height: 100%; 396 width: 100%; 397 padding: 12px; 398 } 399 400 .title { 401 font-size: 19px; 402 font-weight: bold; 403 color: white; 404 text-overflow: ellipsis; 405 max-lines: 1; 406 } 407 408 .detail_text { 409 font-size: 16px; 410 color: white; 411 opacity: 0.66; 412 text-overflow: ellipsis; 413 max-lines: 1; 414 margin-top: 6px; 415 } 416 ``` 417 418- JSON: defines data and event interaction on the widget UI page. 419 420 421 ```json 422 { 423 "data": { 424 "title": "TitleDefault", 425 "detail": "TextDefault" 426 }, 427 "actions": { 428 "routerEvent": { 429 "action": "router", 430 "abilityName": "EntryAbility", 431 "params": { 432 "message": "add detail" 433 } 434 } 435 } 436 } 437 ``` 438 439 440### Developing Widget Events 441 442You can set router and message events for components on a widget. The router event applies to UIAbility redirection, and the message event applies to custom click events. 443 444The key steps are as follows: 445 4461. Set the **onclick** field in the HML file to **routerEvent** or **messageEvent**, depending on the **actions** settings in the JSON file. 447 4482. Set the router event. 449 450 - **action**: **"router"**, which indicates a router event. 451 - **abilityName**: name of the UIAbility to redirect to (PageAbility component in the FA model and UIAbility component in the stage model). For example, the default UIAbility name of the stage model created by DevEco Studio is EntryAbility. 452 - **params**: custom parameters passed to the target UIAbility. Set them as required. The value can be obtained from **parameters** in **want** used for starting the target UIAbility. For example, in the lifecycle function **onCreate** of the main ability in the stage model, you can obtain **want** and its **parameters** field. 453 4543. Set the message event. 455 456 - **action**: **"message"**, which indicates a message event. 457 - **params**: custom parameters of the message event. Set them as required. The value can be obtained from **message** in the widget lifecycle function **onFormEvent()**. 458 459The following is an example: 460 461- HML file: 462 463 464 ```html 465 <div class="container"> 466 <stack> 467 <div class="container-img"> 468 <image src="/common/widget.png" class="bg-img"></image> 469 </div> 470 <div class="container-inner"> 471 <text class="title" onclick="routerEvent">{{title}}</text> 472 <text class="detail_text" onclick="messageEvent">{{detail}}</text> 473 </div> 474 </stack> 475 </div> 476 ``` 477 478- CSS file: 479 480 481 ```css 482 .container { 483 flex-direction: column; 484 justify-content: center; 485 align-items: center; 486 } 487 488 .bg-img { 489 flex-shrink: 0; 490 height: 100%; 491 } 492 493 .container-inner { 494 flex-direction: column; 495 justify-content: flex-end; 496 align-items: flex-start; 497 height: 100%; 498 width: 100%; 499 padding: 12px; 500 } 501 502 .title { 503 font-size: 19px; 504 font-weight: bold; 505 color: white; 506 text-overflow: ellipsis; 507 max-lines: 1; 508 } 509 510 .detail_text { 511 font-size: 16px; 512 color: white; 513 opacity: 0.66; 514 text-overflow: ellipsis; 515 max-lines: 1; 516 margin-top: 6px; 517 } 518 ``` 519 520- JSON file 521 522 523 ```json 524 { 525 "data": { 526 "title": "TitleDefault", 527 "detail": "TextDefault" 528 }, 529 "actions": { 530 "routerEvent": { 531 "action": "router", 532 "abilityName": "EntryAbility", 533 "params": { 534 "info": "router info", 535 "message": "router message" 536 } 537 }, 538 "messageEvent": { 539 "action": "message", 540 "params": { 541 "detail": "message detail" 542 } 543 } 544 } 545 } 546 ``` 547 548- Receive the router event and obtain parameters in UIAbility. 549 550 551 ```ts 552 import UIAbility from '@ohos.app.ability.UIAbility' 553 554 export default class EntryAbility extends UIAbility { 555 onCreate(want, launchParam) { 556 let params = JSON.parse(want.parameters.params); 557 // Obtain the info parameter passed in the router event. 558 if (params.info === "router info") { 559 // do something 560 // console.info("router info:" + params.info) 561 } 562 // Obtain the message parameter passed in the router event. 563 if (params.message === "router message") { 564 // do something 565 // console.info("router message:" + params.message) 566 } 567 } 568 ... 569 }; 570 ``` 571 572- Receive the message event in FormExtensionAbility and obtain parameters. 573 574 575 ```ts 576 import FormExtension from '@ohos.app.form.FormExtensionAbility'; 577 578 export default class FormAbility extends FormExtension { 579 ... 580 onFormEvent(formId, message) { 581 // Obtain the detail parameter passed in the message event. 582 let msg = JSON.parse(message) 583 if (msg.detail === "message detail") { 584 // do something 585 // console.info("message info:" + msg.detail) 586 } 587 } 588 ... 589 }; 590 ``` 591