• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Component ID
2
3**id** identifies a component uniquely within an application. This module provides APIs for obtaining the attributes of or sending events to the component with the specified ID.
4
5>  **NOTE**
6>
7> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
8
9
10## Attributes
11
12| Name  | Type    | Description                        |
13| -----| -------- | ----------------------------- |
14| id   | string   | Unique ID you assigned to the component.<br>Default value: **''**<br>Since API version 9, this API is supported in ArkTS widgets.|
15
16
17## APIs
18
19
20### getInspectorByKey<sup>9+</sup>
21
22getInspectorByKey(id: string): string
23
24Obtains all attributes of the component with the specified ID, excluding the information about child components.
25
26This API is used only for test purposes.
27
28**Parameters**
29
30| Name  | Type     | Mandatory    | Description       |
31| ---- | -------- | ---- | -------------|
32| id   | string   | Yes   | ID of the component whose attributes are to be obtained.|
33
34**Return value**
35
36| Type       | Description            |
37| -------| -------------- |
38| string | JSON string of the component attribute list.|
39
40### getInspectorTree<sup>9+</sup>
41
42getInspectorTree(): Object
43
44Obtains the component tree and component attributes.
45
46This API is used only for test purposes.
47
48**Return value**
49
50| Type    | Description                           |
51| ------ | --------------------------- |
52| Object | JSON object of the component tree and component attribute list.|
53
54### sendEventByKey<sup>9+</sup>
55
56sendEventByKey(id: string, action: number, params: string): boolean
57
58Sends an event to the component with the specified ID.
59
60This API is used only for test purposes.
61
62**Parameters**
63
64| Name      | Type     | Mandatory      | Description                        |
65| ------ | -------| ---- | -------------------------- |
66| id     | string | Yes   | ID of the component to which the event is to be sent.                     |
67| action | number | Yes   | Type of the event to be sent. The options are as follows:<br>- **10**: click event.<br>- **11**: long-click event.|
68| params | string | Yes   | Event parameters. If there is no parameter, pass an empty string **""**.           |
69
70**Return value**
71
72| Type         | Description                        |
73| -------- | --------------------------|
74| boolean  | Returns **true** if the component with the specified ID is found; returns **false** otherwise.|
75
76### sendTouchEvent<sup>9+</sup>
77
78sendTouchEvent(event: TouchObject): boolean
79
80Sends a touch event.
81
82This API is used only for test purposes.
83
84**Parameters**
85
86| Name     | Type           | Mandatory | Description                                                        |
87| ----- | ----------- | ---- | ------------------------------------------------------------ |
88| event | [TouchObject](ts-universal-events-touch.md#touchobject) | Yes   | Location where a touch event is triggered. For details, see [TouchEvent](ts-universal-events-touch.md#touchevent).|
89
90**Return value**
91
92| Type     | Description                        |
93| ------- | ---------------------------|
94| boolean | Returns **true** if the event is sent successfully; returns **false** otherwise.|
95
96### sendKeyEvent<sup>9+</sup>
97
98sendKeyEvent(event: KeyEvent): boolean
99
100Sends a key event.
101
102This API is used only for test purposes.
103
104**Parameters**
105
106| Name   | Type    | Mandatory     | Description                                                        |
107| ----- | -------- | ----  | ------------------------------------------------------------ |
108| event | [KeyEvent](ts-universal-events-key.md#keyevent) | Yes    | Key event. For details, see [KeyEvent](ts-universal-events-key.md#keyevent).|
109
110**Return value**
111
112| Type     | Description                          |
113| ------- | ------------------------------|
114| boolean | Returns **true** if the event is sent successfully; returns **false** otherwise.|
115
116### sendMouseEvent<sup>9+</sup>
117
118sendMouseEvent(event: MouseEvent): boolean
119
120Sends a mouse event.
121
122This API is used only for test purposes.
123
124**Parameters**
125
126| Name    | Type      | Mandatory      | Description                                    |
127| ----- | ---------- | ----  | --------------------------------------- |
128| event | [MouseEvent](ts-universal-mouse-key.md#mouseevent) | Yes   | Mouse event. For details, see [MouseEvent](ts-universal-mouse-key.md#mouseevent).|
129
130**Return value**
131
132| Type     | Description                                |
133| ------- | ---------------------------------- |
134| boolean | Returns **true** if the event is sent successfully; returns **false** otherwise.|
135
136## Example
137
138```ts
139// xxx.ets
140class Utils {
141  static rect_left
142  static rect_top
143  static rect_right
144  static rect_bottom
145  static rect_value
146
147  // Obtain the coordinates of the rectangular area occupied by the component.
148  static getComponentRect(key) {
149    let strJson = getInspectorByKey(key)
150    let obj = JSON.parse(strJson)
151    console.info("[getInspectorByKey] current component obj is: " + JSON.stringify(obj))
152    let rectInfo = JSON.parse('[' + obj.$rect + ']')
153    console.info("[getInspectorByKey] rectInfo is: " + rectInfo)
154    this.rect_left = JSON.parse('[' + rectInfo[0] + ']')[0]
155    this.rect_top = JSON.parse('[' + rectInfo[0] + ']')[1]
156    this.rect_right = JSON.parse('[' + rectInfo[1] + ']')[0]
157    this.rect_bottom = JSON.parse('[' + rectInfo[1] + ']')[1]
158    return this.rect_value = {
159      "left": this.rect_left, "top": this.rect_top, "right": this.rect_right, "bottom": this.rect_bottom
160    }
161  }
162}
163
164@Entry
165@Component
166struct IdExample {
167  @State text: string = ''
168
169  build() {
170    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
171
172      Button() {
173        Text('onKeyTab').fontSize(25).fontWeight(FontWeight.Bold)
174      }.margin({ top: 20 }).backgroundColor('#0D9FFB')
175      .onKeyEvent(() => {
176        this.text = "onKeyTab"
177      })
178
179      Button() {
180        Text('click to start').fontSize(25).fontWeight(FontWeight.Bold)
181      }.margin({ top: 20 })
182      .onClick(() => {
183        console.info(getInspectorByKey("click"))
184        console.info(JSON.stringify(getInspectorTree()))
185        this.text = "Button 'click to start' is clicked"
186        setTimeout(() => {
187          sendEventByKey("longClick", 11, "") // Send a long-click event to the component whose ID is "longClick".
188        }, 2000)
189      }).id('click')
190
191      Button() {
192        Text('longClick').fontSize(25).fontWeight(FontWeight.Bold)
193      }.margin({ top: 20 }).backgroundColor('#0D9FFB')
194      .gesture(
195      LongPressGesture().onActionEnd(() => {
196        console.info('long clicked')
197        this.text = "Button 'longClick' is longclicked"
198        setTimeout(() => {
199          let rect = Utils.getComponentRect('onTouch') // Obtain the coordinates of the rectangular area occupied by the component whose ID is "onTouch".
200          let touchPoint: TouchObject = {
201            id: 1,
202            x: rect.left + (rect.right - rect.left) / 2, // X coordinate of the component center.
203            y: rect.top + (rect.bottom - rect.top) / 2, // Y coordinate of the component center.
204            type: TouchType.Down,
205            screenX: rect.left + (rect.right - rect.left) / 2, // X coordinate of the component center.
206            screenY: rect.left + (rect.right - rect.left) / 2, // Y coordinate of the component center.
207          }
208          sendTouchEvent(touchPoint) // Send a touch event.
209          touchPoint.type = TouchType.Up
210          sendTouchEvent(touchPoint) // Send a touch event.
211        }, 2000)
212      })).id('longClick')
213
214      Button() {
215        Text('onTouch').fontSize(25).fontWeight(FontWeight.Bold)
216      }.type(ButtonType.Capsule).margin({ top: 20 })
217      .onClick(() => {
218        console.info('onTouch is clicked')
219        this.text = "Button 'onTouch' is clicked"
220        setTimeout(() => {
221          let rect = Utils.getComponentRect('onMouse') // Obtain the coordinates of the rectangular area occupied by the component whose ID is "onMouse".
222          let mouseEvent: MouseEvent = {
223            button: MouseButton.Left,
224            action: MouseAction.Press,
225            x: rect.left + (rect.right - rect.left) / 2, // X coordinate of the component center.
226            y: rect.top + (rect.bottom - rect.top) / 2, // Y coordinate of the component center.
227            screenX: rect.left + (rect.right - rect.left) / 2, // X coordinate of the component center.
228            screenY: rect.top + (rect.bottom - rect.top) / 2, // Y coordinate of the component center.
229            timestamp: 1,
230            target: {
231              area: {
232                width: 1,
233                height: 1,
234                position: {
235                  x: 1,
236                  y: 1
237                },
238                globalPosition: {
239                  x: 1,
240                  y: 1
241                }
242              }
243            },
244            source: SourceType.Mouse,
245            pressure: 1,
246            tiltX: 1,
247            tiltY: 1,
248            sourceTool: SourceTool.Unknown
249          }
250          sendMouseEvent(mouseEvent) // Send a mouse event.
251        }, 2000)
252      }).id('onTouch')
253
254      Button() {
255        Text('onMouse').fontSize(25).fontWeight(FontWeight.Bold)
256      }.margin({ top: 20 }).backgroundColor('#0D9FFB')
257      .onMouse(() => {
258        console.info('onMouse')
259        this.text = "Button 'onMouse' in onMouse"
260        setTimeout(() => {
261          let keyEvent: KeyEvent = {
262            type: KeyType.Down,
263            keyCode: 2049,
264            keyText: 'tab',
265            keySource: 4,
266            deviceId: 0,
267            metaKey: 0,
268            timestamp: 0
269          }
270          sendKeyEvent(keyEvent) // Send a key event.
271        }, 2000)
272      }).id('onMouse')
273
274      Text(this.text).fontSize(25).padding(15)
275    }
276    .width('100%').height('100%')
277  }
278}
279```
280