1# Service Widget Development in FA Model
2
3
4## Widget Overview
5
6A 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.
7
8A 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.
9
10Before you get started, it would be helpful if you have a basic understanding of the following concepts:
11
12- Widget host: an application that displays the widget content and controls the widget location.
13
14- Widget Manager: a resident agent that provides widget management features such as periodic widget updates.
15
16- 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.
17
18
19## Working Principles
20
21Figure 1 shows the working principles of the widget framework.
22
23**Figure 1** Widget framework working principles in the FA model
24
25![form-extension](figures/form-extension.png)
26
27The widget host consists of the following modules:
28
29- Widget usage: provides operations such as creating, deleting, or updating a widget.
30
31- Communication adapter: provided by the OpenHarmony SDK for communication with the Widget Manager. It sends widget-related operations to the Widget Manager.
32
33The Widget Manager consists of the following modules:
34
35- Periodic updater: starts a scheduled task based on the update policy to periodically update a widget after it is added to the Widget Manager.
36
37- 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.
38
39- 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.
40
41- 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.
42
43- Communication adapter: communicates with the widget host and provider through RPCs.
44
45The widget provider consists of the following modules:
46
47- Widget service: implemented by the widget provider developer to process requests on widget creation, update, and deletion, and to provide corresponding widget services.
48
49- Instance manager: implemented by the widget provider developer for persistent management of widget instances allocated by the Widget Manager.
50
51- Communication adapter: provided by the OpenHarmony SDK for communication with the Widget Manager. It pushes update data to the Widget Manager.
52
53> **NOTE**
54>
55> You only need to develop the widget provider. The system automatically handles the work of the widget host and Widget Manager.
56
57
58## Available APIs
59
60The **FormAbility** has the following APIs.
61
62| API | Description |
63| -------- | -------- |
64| onCreate(want: Want): formBindingData.FormBindingData  | Called to notify the widget provider that a widget has been created. |
65| onCastToNormal(formId: string): void  | Called to notify the widget provider that a temporary widget has been converted to a normal one. |
66| onUpdate(formId: string): void  | Called to notify the widget provider that a widget has been updated. |
67| onVisibilityChange(newStatus: Record<string, number>): void | Called to notify the widget provider of the change in widget visibility. |
68| onEvent(formId: string, message: string): void  | Called to instruct the widget provider to receive and process a widget event. |
69| onDestroy(formId: string): void  | Called to notify the widget provider that a widget has been destroyed. |
70| onAcquireFormState?(want: Want): formInfo.FormState  | Called to instruct the widget provider to receive the status query result of a widget. |
71| onShare?(formId: string): {[key: string]: any}  | Called by the widget provider to receive shared widget data. |
72| onShareForm?(formId: string): Record<string, Object> | Called by the widget provider to receive shared widget data. You are advised to use this API, instead of **onShare()**. If this API is implemented, **onShare()** will not be triggered. |
73
74The **FormProvider** class has the following APIs. For details, see [FormProvider](../reference/apis-form-kit/js-apis-app-form-formProvider.md).
75
76
77| API | Description |
78| -------- | -------- |
79| 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. |
80| setFormNextRefreshTime(formId: string, minute: number): Promise<void>; | Sets the next refresh time for a widget. This API uses a promise to return the result. |
81| updateForm(formId: string, formBindingData: FormBindingData, callback: AsyncCallback<void>): void;  | Updates a widget. This API uses an asynchronous callback to return the result. |
82| updateForm(formId: string, formBindingData: FormBindingData): Promise<void>;  | Updates a widget. This API uses a promise to return the result. |
83
84
85The **FormBindingData** class has the following APIs. For details, see [FormBindingData](../reference/apis-form-kit/js-apis-app-form-formBindingData.md).
86
87
88| API | Description |
89| -------- | -------- |
90| createFormBindingData(obj?: Object \ string): FormBindingData|  | Creates a **FormBindingData** object. |
91
92
93## How to Develop
94
95The widget provider development based on the [FA model](../application-models/fa-model-development-overview.md) involves the following key steps:
96
97- [Implementing Widget Lifecycle Callbacks](#implementing-widget-lifecycle-callbacks): Develop the **FormAbility** lifecycle callback functions.
98
99- [Configuring the Widget Configuration File](#configuring-the-widget-configuration-file): Configure the application configuration file **config.json**.
100
101- [Persistently Storing Widget Data](#persistently-storing-widget-data): Perform persistent management on widget information.
102
103- [Updating Widget Data](#updating-widget-data): Call **updateForm()** to update the information displayed on a widget.
104
105- [Developing the Widget UI Page](#developing-the-widget-ui-page): Use HML+CSS+JSON to develop a JS widget UI page.
106
107- [Developing Widget Events](#developing-widget-events): Add the router and message events for a widget.
108
109
110### Implementing Widget Lifecycle Callbacks
111
112To create a widget in the FA model, implement the widget lifecycle callbacks. Generate a widget template by referring to <!--RP1-->[Developing a Service Widget](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-development-service-widget-0000001263280425)<!--RP1End-->.
113
1141. Import related modules to **form.ts**.
115
116    ```ts
117    import type featureAbility from '@ohos.ability.featureAbility';
118    import type Want from '@ohos.app.ability.Want';
119    import formBindingData from '@ohos.app.form.formBindingData';
120    import formInfo from '@ohos.app.form.formInfo';
121    import formProvider from '@ohos.app.form.formProvider';
122    import dataPreferences from '@ohos.data.preferences';
123    import hilog from '@ohos.hilog';
124    ```
125
1262. Implement the widget lifecycle callbacks in **form.ts**.
127
128    ```ts
129    const TAG: string = '[Sample_FAModelAbilityDevelop]';
130    const domain: number = 0xFF00;
131
132    const DATA_STORAGE_PATH: string = 'form_store';
133    let storeFormInfo = async (formId: string, formName: string, tempFlag: boolean, context: featureAbility.Context): Promise<void> => {
134      // Only the widget ID (formId), widget name (formName), and whether the widget is a temporary one (tempFlag) are persistently stored.
135      let formInfo: Record<string, string | number | boolean> = {
136        'formName': 'formName',
137        'tempFlag': 'tempFlag',
138        'updateCount': 0
139      };
140      try {
141        const storage = await dataPreferences.getPreferences(context, DATA_STORAGE_PATH);
142        // Put the widget information.
143        await storage.put(formId, JSON.stringify(formInfo));
144        hilog.info(domain, TAG, `storeFormInfo, put form info successfully, formId: ${formId}`);
145        await storage.flush();
146      } catch (err) {
147        hilog.error(domain, TAG, `failed to storeFormInfo, err: ${JSON.stringify(err as Error)}`);
148      }
149    };
150
151    let deleteFormInfo = async (formId: string, context: featureAbility.Context) => {
152      try {
153        const storage = await dataPreferences.getPreferences(context, DATA_STORAGE_PATH);
154        // Delete the widget information.
155        await storage.delete(formId);
156        hilog.info(domain, TAG, `deleteFormInfo, del form info successfully, formId: ${formId}`);
157        await storage.flush();
158      } catch (err) {
159        hilog.error(domain, TAG, `failed to deleteFormInfo, err: ${JSON.stringify(err)}`);
160      }
161    }
162
163    class LifeCycle {
164      onCreate: (want: Want) => formBindingData.FormBindingData = (want) => ({ data: '' });
165      onCastToNormal: (formId: string) => void = (formId) => {
166      };
167      onUpdate: (formId: string) => void = (formId) => {
168      };
169      onVisibilityChange: (newStatus: Record<string, number>) => void = (newStatus) => {
170        let obj: Record<string, number> = {
171          'test': 1
172        };
173        return obj;
174      };
175      onEvent: (formId: string, message: string) => void = (formId, message) => {
176      };
177      onDestroy: (formId: string) => void = (formId) => {
178      };
179      onAcquireFormState?: (want: Want) => formInfo.FormState = (want) => (0);
180      onShareForm?: (formId: string) => Record<string, Object> = (formId) => {
181        let obj: Record<string, number> = {
182          'test': 1
183        };
184        return obj;
185      };
186    }
187
188    let obj: LifeCycle = {
189      onCreate(want: Want) {
190        hilog.info(domain, TAG, 'FormAbility onCreate');
191        if (want.parameters) {
192          let formId = String(want.parameters['ohos.extra.param.key.form_identity']);
193          let formName = String(want.parameters['ohos.extra.param.key.form_name']);
194          let tempFlag = Boolean(want.parameters['ohos.extra.param.key.form_temporary']);
195          // Persistently store widget data for subsequent use, such as instance acquisition and update.
196          // Implement this API based on project requirements.
197          hilog.info(domain, TAG, 'FormAbility onCreate' + formId);
198          storeFormInfo(formId, formName, tempFlag, this.context);
199        }
200
201        // Called when the widget is created. The widget provider should return the widget data binding class.
202        let obj: Record<string, string> = {
203          'title': 'titleOnCreate',
204          'detail': 'detailOnCreate'
205        };
206        let formData: formBindingData.FormBindingData = formBindingData.createFormBindingData(obj);
207        return formData;
208      },
209      onCastToNormal(formId: string) {
210        // Called when the widget host converts the temporary widget into a normal one. The widget provider should do something to respond to the conversion.
211        hilog.info(domain, TAG, 'FormAbility onCastToNormal');
212      },
213      onUpdate(formId: string) {
214        // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host.
215        hilog.info(domain, TAG, 'FormAbility onUpdate');
216        let obj: Record<string, string> = {
217          'title': 'titleOnUpdate',
218          'detail': 'detailOnUpdate'
219        };
220        let formData: formBindingData.FormBindingData = formBindingData.createFormBindingData(obj);
221        // Call the updateForm() method to update the widget. Only the data passed through the input parameter is updated. Other information remains unchanged.
222        formProvider.updateForm(formId, formData).catch((error: Error) => {
223          hilog.error(domain, TAG, 'FormAbility updateForm, error:' + JSON.stringify(error));
224        });
225      },
226      onVisibilityChange(newStatus: Record<string, number>) {
227        // 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.
228        hilog.info(domain, TAG, 'FormAbility onVisibilityChange');
229      },
230      onEvent(formId: string, message: string) {
231        // If the widget supports event triggering, override this method and implement the trigger.
232        let obj: Record<string, string> = {
233          'title': 'titleOnEvent',
234          'detail': 'detailOnEvent'
235        };
236        let formData: formBindingData.FormBindingData = formBindingData.createFormBindingData(obj);
237        // Call the updateForm() method to update the widget. Only the data passed through the input parameter is updated. Other information remains unchanged.
238        formProvider.updateForm(formId, formData).catch((error: Error) => {
239          hilog.error(domain, TAG, 'FormAbility updateForm, error:' + JSON.stringify(error));
240        });
241        hilog.info(domain, TAG, 'FormAbility onEvent');
242      },
243      onDestroy(formId: string) {
244        // Delete widget data.
245        hilog.info(domain, TAG, 'FormAbility onDestroy');
246        // Delete the persistent widget instance data.
247        // Implement this API based on project requirements.
248        deleteFormInfo(formId, this.context);
249      },
250      onAcquireFormState(want: Want) {
251        hilog.info(domain, TAG, 'FormAbility onAcquireFormState');
252        return formInfo.FormState.READY;
253      }
254    };
255
256    export default obj;
257    ```
258
259> **NOTE**
260>
261> FormAbility cannot reside in the background. Therefore, continuous tasks cannot be processed in the widget lifecycle callbacks.
262
263### Configuring the Widget Configuration File
264
265The widget configuration file is named **config.json**. Find the **config.json** file for the widget and edit the file depending on your need.
266
267- The **js** module in the **config.json** file provides JavaScript resources of the widget. The internal structure is described as follows:
268    | Name | Description | Data Type | Initial Value Allowed |
269  | -------- | -------- | -------- | -------- |
270  | name | Name of a JavaScript component. The default value is **default**. | String | No |
271  | 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 |
272  | window | Window-related configurations. | Object | Yes |
273  | type | Type of the JavaScript component. The value can be:<br>**normal**: indicates an application instance.<br>**form**: indicates a widget instance. | String | Yes (initial value: **normal**) |
274  | mode | Development mode of the JavaScript component. | Object | Yes (initial value: left empty) |
275
276  Example configuration:
277
278
279  ```json
280  "js": [
281    ...
282    {
283      "name": "widget",
284      "pages": [
285        "pages/index/index"
286      ],
287      "window": {
288        "designWidth": 720,
289        "autoDesignWidth": true
290    	},
291        "type": "form"
292      }
293    ]
294  ```
295
296- The **abilities** module in the **config.json** file corresponds to **FormAbility** of the widget. The internal structure is described as follows:
297    | Name | Description | Data Type | Initial Value Allowed |
298  | -------- | -------- | -------- | -------- |
299  | name | Class name of a widget. The value is a string with a maximum of 127 bytes. | String | No |
300  | 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) |
301  | 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 |
302  | type | Type of the widget. The value can be:<br>**JS**: indicates a JavaScript-programmed widget. | String | No |
303  | 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**) |
304  | 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 |
305  | defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget. | String | No |
306  | 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 |
307  | 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**) |
308  | 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**) |
309  | formConfigAbility | Link to a specific page of the application. The value is a URI. | String | Yes (initial value: left empty) |
310  | formVisibleNotify | Whether the widget is allowed to use the widget visibility notification. | String | Yes (initial value: left empty) |
311  | jsComponentName | Component name of the widget. The value is a string with a maximum of 127 bytes. | String | No |
312  | metaData | Metadata of the widget. This field contains the array of the **customizeData** field. | Object | Yes (initial value: left empty) |
313  | customizeData | Custom information about the widget. | Object array | Yes (initial value: left empty) |
314
315  Example configuration:
316
317
318  ```json
319  "abilities": [
320    ...
321    {
322      "name": ".FormAbility",
323      "srcPath": "FormAbility",
324      "description": "$string:FormAbility_desc",
325      "icon": "$media:icon",
326      "label": "$string:FormAbility_label",
327      "type": "service",
328      "formsEnabled": true,
329      "srcLanguage": "ets",
330      "forms": [
331        {
332          "jsComponentName": "widget",
333          "isDefault": true,
334          "scheduledUpdateTime": "10:30",
335          "defaultDimension": "2*2",
336          "name": "widget",
337          "description": "This is a service widget.",
338          "colorMode": "auto",
339          "type": "JS",
340          "formVisibleNotify": true,
341          "supportDimensions": [
342            "2*2"
343          ],
344          "updateEnabled": true,
345          "updateDuration": 1
346        }
347      ]
348    },
349    ...
350  ]
351  ```
352
353
354### Persistently Storing Widget Data
355
356A 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. You should override **onDestroy** to implement widget data deletion.
357
358
359```ts
360const TAG: string = '[Sample_FAModelAbilityDevelop]';
361const domain: number = 0xFF00;
362
363const DATA_STORAGE_PATH: string = 'form_store';
364let storeFormInfo = async (formId: string, formName: string, tempFlag: boolean, context: featureAbility.Context): Promise<void> => {
365  // Only the widget ID (formId), widget name (formName), and whether the widget is a temporary one (tempFlag) are persistently stored.
366  let formInfo: Record<string, string | number | boolean> = {
367    'formName': 'formName',
368    'tempFlag': 'tempFlag',
369    'updateCount': 0
370  };
371  try {
372    const storage = await dataPreferences.getPreferences(context, DATA_STORAGE_PATH);
373    // Put the widget information.
374    await storage.put(formId, JSON.stringify(formInfo));
375    hilog.info(domain, TAG, `storeFormInfo, put form info successfully, formId: ${formId}`);
376    await storage.flush();
377  } catch (err) {
378    hilog.error(domain, TAG, `failed to storeFormInfo, err: ${JSON.stringify(err as Error)}`);
379  }
380};
381
382let deleteFormInfo = async (formId: string, context: featureAbility.Context) => {
383  try {
384    const storage = await dataPreferences.getPreferences(context, DATA_STORAGE_PATH);
385    // Delete the widget information.
386    await storage.delete(formId);
387    hilog.info(domain, TAG, `deleteFormInfo, del form info successfully, formId: ${formId}`);
388    await storage.flush();
389  } catch (err) {
390    hilog.error(domain, TAG, `failed to deleteFormInfo, err: ${JSON.stringify(err)}`);
391  }
392}
393
394...
395  onCreate(want: Want) {
396    hilog.info(domain, TAG, 'FormAbility onCreate');
397    if (want.parameters) {
398      let formId = String(want.parameters['ohos.extra.param.key.form_identity']);
399      let formName = String(want.parameters['ohos.extra.param.key.form_name']);
400      let tempFlag = Boolean(want.parameters['ohos.extra.param.key.form_temporary']);
401      // Persistently store widget data for subsequent use, such as instance acquisition and update.
402      // Implement this API based on project requirements.
403      hilog.info(domain, TAG, 'FormAbility onCreate' + formId);
404      storeFormInfo(formId, formName, tempFlag, this.context);
405    }
406
407    // Called when the widget is created. The widget provider should return the widget data binding class.
408    let obj: Record<string, string> = {
409      'title': 'titleOnCreate',
410      'detail': 'detailOnCreate'
411    };
412    let formData: formBindingData.FormBindingData = formBindingData.createFormBindingData(obj);
413    return formData;
414  },
415...
416
417let deleteFormInfo = async (formId: string, context: featureAbility.Context): Promise<void> => {
418  try {
419    const storage = await dataPreferences.getPreferences(context, DATA_STORAGE_PATH);
420    // Delete the widget information.
421    await storage.delete(formId);
422    hilog.info(domain, TAG, `deleteFormInfo, del form info successfully, formId: ${formId}`);
423    await storage.flush();
424  } catch (err) {
425    hilog.error(domain, TAG, `failed to deleteFormInfo, err: ${JSON.stringify(err)}`);
426  }
427};
428
429...
430    // Override onDestroy to implement widget data deletion.
431  onDestroy(formId: string) {
432    // Delete widget data.
433    hilog.info(domain, TAG, 'FormAbility onDestroy');
434    // Delete the persistent widget instance data.
435    // Implement this API based on project requirements.
436    deleteFormInfo(formId, this.context);
437  }
438...
439```
440
441For details about how to implement persistent data storage, see [Application Data Persistence Overview](../database/app-data-persistence-overview.md).
442
443The **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.
444
445- Normal widget: a widget persistently used by the widget host, for example, a widget added to the home screen.
446
447- Temporary widget: a widget temporarily used by the widget host, for example, the widget displayed when you swipe up on a widget application.
448
449Converting a temporary widget to a normal one: After you swipe up on a widget application, a temporary widget is displayed. If you touch the pin button on the widget, it is displayed as a normal widget on the home screen.
450
451Data 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.
452
453
454### Updating Widget Data
455
456When an application initiates a scheduled or periodic update, the application obtains the latest data and calls **updateForm()** to update the widget.
457
458
459```ts
460const TAG: string = '[Sample_FAModelAbilityDevelop]';
461const domain: number = 0xFF00;
462
463onUpdate(formId: string) {
464  // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host.
465  hilog.info(domain, TAG, 'FormAbility onUpdate');
466  let obj: Record<string, string> = {
467    'title': 'titleOnUpdate',
468    'detail': 'detailOnUpdate'
469  };
470  let formData: formBindingData.FormBindingData = formBindingData.createFormBindingData(obj);
471  // Call the updateForm() method to update the widget. Only the data passed through the input parameter is updated. Other information remains unchanged.
472  formProvider.updateForm(formId, formData).catch((error: Error) => {
473    hilog.error(domain, TAG, 'FormAbility updateForm, error:' + JSON.stringify(error));
474  });
475}
476```
477
478
479### Developing the Widget UI Page
480
481You can use the web-like paradigm (HML+CSS+JSON) to develop JS widget pages. This section describes how to develop a page shown below.
482
483![widget-development-fa](figures/widget-development-fa.png)
484
485> **NOTE**
486>
487> In the FA model, only the JavaScript-based web-like development paradigm is supported when developing the widget UI.
488
489- HML: uses web-like paradigm components to describe the widget page information.
490
491  ```html
492  <div class="container">
493      <stack>
494          <div class="container-img">
495              <image src="/common/widget.png" class="bg-img"></image>
496              <image src="/common/rect.png" class="bottom-img"></image>
497          </div>
498          <div class="container-inner">
499              <text class="title" onclick="routerEvent">{{title}}</text>
500              <text class="detail_text" onclick="messageEvent">{{detail}}</text>
501          </div>
502      </stack>
503  </div>
504  ```
505
506- CSS: defines style information about the web-like paradigm components in HML.
507
508  ```css
509  .container {
510      flex-direction: column;
511      justify-content: center;
512      align-items: center;
513  }
514
515  .bg-img {
516      flex-shrink: 0;
517      height: 100%;
518      z-index: 1;
519  }
520
521  .bottom-img {
522      position: absolute;
523      width: 150px;
524      height: 56px;
525      top: 63%;
526      background-color: rgba(216, 216, 216, 0.15);
527      filter: blur(20px);
528      z-index: 2;
529  }
530
531  .container-inner {
532      flex-direction: column;
533      justify-content: flex-end;
534      align-items: flex-start;
535      height: 100%;
536      width: 100%;
537      padding: 12px;
538  }
539
540  .title {
541      font-family: HarmonyHeiTi-Medium;
542      font-size: 14px;
543      color: rgba(255,255,255,0.90);
544      letter-spacing: 0.6px;
545  }
546
547  .detail_text {
548      font-family: HarmonyHeiTi;
549      font-size: 12px;
550      color: rgba(255,255,255,0.60);
551      letter-spacing: 0.51px;
552      text-overflow: ellipsis;
553      max-lines: 1;
554      margin-top: 6px;
555  }
556  ```
557
558- JSON: defines data and event interaction on the widget UI page.
559
560  ```json
561  {
562    "data": {
563      "title": "TitleDefault",
564      "detail": "TextDefault"
565    },
566    "actions": {
567      "routerEvent": {
568        "action": "router",
569        "abilityName": "com.samples.famodelabilitydevelop.MainAbility",
570        "params": {
571          "message": "add detail"
572        }
573      },
574      "messageEvent": {
575        "action": "message",
576        "params": {
577          "message": "add detail"
578        }
579      }
580    }
581  }
582  ```
583
584
585### Developing Widget Events
586
587You 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:
588
5891. Set the **onclick** field in the HML file to **routerEvent** or **messageEvent**, depending on the **actions** settings in the JSON file.
590
5912. Set the router event.
592   - **action**: **"router"**, which indicates a router event.
593   - **abilityName**: name of the ability to redirect to (PageAbility component in the FA model and UIAbility component in the stage model). For example, the default UIAbility name created by DevEco Studio in the FA model is com.example.entry.EntryAbility.
594   - **params**: custom parameters passed to 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 EntryAbility in the FA model, **featureAbility.getWant()** can be used to obtain **want** and its **parameters** field.
595
5963. Set the message event.
597   - **action**: **"message"**, which indicates a message event.
598   - **params**: custom parameters of the message event. Set them as required. The value can be obtained from **message** in the widget lifecycle function **onEvent**.
599
600The following is an example:
601
602- HML file:
603
604  ```html
605  <div class="container">
606      <stack>
607          <div class="container-img">
608              <image src="/common/widget.png" class="bg-img"></image>
609              <image src="/common/rect.png" class="bottom-img"></image>
610          </div>
611          <div class="container-inner">
612              <text class="title" onclick="routerEvent">{{title}}</text>
613              <text class="detail_text" onclick="messageEvent">{{detail}}</text>
614          </div>
615      </stack>
616  </div>
617  ```
618
619- CSS file:
620
621  ```css
622  .container {
623      flex-direction: column;
624      justify-content: center;
625      align-items: center;
626  }
627
628  .bg-img {
629      flex-shrink: 0;
630      height: 100%;
631      z-index: 1;
632  }
633
634  .bottom-img {
635      position: absolute;
636      width: 150px;
637      height: 56px;
638      top: 63%;
639      background-color: rgba(216, 216, 216, 0.15);
640      filter: blur(20px);
641      z-index: 2;
642  }
643
644  .container-inner {
645      flex-direction: column;
646      justify-content: flex-end;
647      align-items: flex-start;
648      height: 100%;
649      width: 100%;
650      padding: 12px;
651  }
652
653  .title {
654      font-family: HarmonyHeiTi-Medium;
655      font-size: 14px;
656      color: rgba(255,255,255,0.90);
657      letter-spacing: 0.6px;
658  }
659
660  .detail_text {
661      font-family: HarmonyHeiTi;
662      font-size: 12px;
663      color: rgba(255,255,255,0.60);
664      letter-spacing: 0.51px;
665      text-overflow: ellipsis;
666      max-lines: 1;
667      margin-top: 6px;
668  }
669  ```
670
671- JSON file:
672
673  ```json
674  {
675    "data": {
676      "title": "TitleDefault",
677      "detail": "TextDefault"
678    },
679    "actions": {
680      "routerEvent": {
681        "action": "router",
682        "abilityName": "com.samples.famodelabilitydevelop.MainAbility",
683        "params": {
684          "message": "add detail"
685        }
686      },
687      "messageEvent": {
688        "action": "message",
689        "params": {
690          "message": "add detail"
691        }
692      }
693    }
694  }
695  ```
696