• 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
140import { IntentionCode } from '@ohos.multimodalInput.intentionCode'
141
142class Utils {
143  static rect_left: number
144  static rect_top: number
145  static rect_right: number
146  static rect_bottom: number
147  static rect_value: Record<string, number>
148
149  // Obtain the coordinates of the rectangular area occupied by the component.
150  static getComponentRect(key:string):Record<string, number> {
151    let strJson = getInspectorByKey(key)
152    let obj:Record<string, string> = JSON.parse(strJson)
153    console.info("[getInspectorByKey] current component obj is: " + JSON.stringify(obj))
154    let rectInfo:string[] = JSON.parse('[' + obj.$rect + ']')
155    console.info("[getInspectorByKey] rectInfo is: " + rectInfo)
156    Utils.rect_left = JSON.parse('[' + rectInfo[0] + ']')[0]
157    Utils.rect_top = JSON.parse('[' + rectInfo[0] + ']')[1]
158    Utils.rect_right = JSON.parse('[' + rectInfo[1] + ']')[0]
159    Utils.rect_bottom = JSON.parse('[' + rectInfo[1] + ']')[1]
160    return Utils.rect_value = {
161      "left": Utils.rect_left, "top": Utils.rect_top, "right": Utils.rect_right, "bottom": Utils.rect_bottom
162    }
163  }
164}
165
166@Entry
167@Component
168struct IdExample {
169  @State text: string = ''
170
171  build() {
172    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
173
174      Button() {
175        Text('onKeyTab').fontSize(25).fontWeight(FontWeight.Bold)
176      }.margin({ top: 20 }).backgroundColor('#0D9FFB')
177      .onKeyEvent(() => {
178        this.text = "onKeyTab"
179      })
180
181      Button() {
182        Text('click to start').fontSize(25).fontWeight(FontWeight.Bold)
183      }.margin({ top: 20 })
184      .onClick(() => {
185        console.info(getInspectorByKey("click"))
186        console.info(JSON.stringify(getInspectorTree()))
187        this.text = "Button 'click to start' is clicked"
188        setTimeout(() => {
189          sendEventByKey("longClick", 11, "") // Send a long-click event to the component whose ID is "longClick".
190        }, 2000)
191      }).id('click')
192
193      Button() {
194        Text('longClick').fontSize(25).fontWeight(FontWeight.Bold)
195      }.margin({ top: 20 }).backgroundColor('#0D9FFB')
196      .gesture(
197      LongPressGesture().onActionEnd(() => {
198        console.info('long clicked')
199        this.text = "Button 'longClick' is longclicked"
200        setTimeout(() => {
201          let rect = Utils.getComponentRect('onTouch') // Obtain the coordinates of the rectangular area occupied by the component whose ID is "onTouch".
202          let touchPoint: TouchObject = {
203            id: 1,
204            type: TouchType.Down,
205            x: rect.left + (rect.right - rect.left) / 2, // X coordinate relative to the upper left corner of the component.
206            y: rect.top + (rect.bottom - rect.top) / 2, // Y coordinate relative to the upper left corner of the component.
207            screenX: rect.left + (rect.right - rect.left) / 2, // X coordinate relative to the upper left corner of the application window. This API is deprecated since API version 10. Use windowX instead.
208            screenY: rect.left + (rect.right - rect.left) / 2, // Y coordinate relative to the upper left corner of the application window. This API is deprecated since API version 10. Use windowY instead.
209            windowX: rect.left + (rect.right - rect.left) / 2, // X coordinate relative to the upper left corner of the application window.
210            windowY: rect.left + (rect.right - rect.left) / 2, // Y coordinate relative to the upper left corner of the application window.
211            displayX: rect.left + (rect.right - rect.left) / 2, // X coordinate relative to the upper left corner of the device screen.
212            displayY: rect.left + (rect.right - rect.left) / 2, // Y coordinate relative to the upper left corner of the device screen.
213          }
214          sendTouchEvent(touchPoint) // Send a touch event.
215          touchPoint.type = TouchType.Up
216          sendTouchEvent(touchPoint) // Send a touch event.
217        }, 2000)
218      })).id('longClick')
219
220      Button() {
221        Text('onTouch').fontSize(25).fontWeight(FontWeight.Bold)
222      }.type(ButtonType.Capsule).margin({ top: 20 })
223      .onClick(() => {
224        console.info('onTouch is clicked')
225        this.text = "Button 'onTouch' is clicked"
226        setTimeout(() => {
227          let rect = Utils.getComponentRect('onMouse') // Obtain the coordinates of the rectangular area occupied by the component whose ID is "onMouse".
228          let mouseEvent: MouseEvent = {
229            button: MouseButton.Left,
230            action: MouseAction.Press,
231            x: rect.left + (rect.right - rect.left) / 2, // X coordinate relative to the upper left corner of the component.
232            y: rect.top + (rect.bottom - rect.top) / 2, // Y coordinate relative to the upper left corner of the component.
233            screenX: rect.left + (rect.right - rect.left) / 2, // X coordinate relative to the upper left corner of the application window. This API is deprecated since API version 10. Use windowX instead.
234            screenY: rect.left + (rect.right - rect.left) / 2, // Y coordinate relative to the upper left corner of the application window. This API is deprecated since API version 10. Use windowY instead.
235            windowX: rect.left + (rect.right - rect.left) / 2, // X coordinate relative to the upper left corner of the application window.
236            windowY: rect.left + (rect.right - rect.left) / 2, // Y coordinate relative to the upper left corner of the application window.
237            displayX: rect.left + (rect.right - rect.left) / 2, // X coordinate relative to the upper left corner of the device screen.
238            displayY: rect.left + (rect.right - rect.left) / 2, // Y coordinate relative to the upper left corner of the device screen.
239            stopPropagation: () => {
240            },
241            timestamp: 1,
242            target: {
243              area: {
244                width: 1,
245                height: 1,
246                position: {
247                  x: 1,
248                  y: 1
249                },
250                globalPosition: {
251                  x: 1,
252                  y: 1
253                }
254              }
255            },
256            source: SourceType.Mouse,
257            pressure: 1,
258            tiltX: 1,
259            tiltY: 1,
260            sourceTool: SourceTool.Unknown
261          }
262          sendMouseEvent(mouseEvent) // Send a mouse event.
263        }, 2000)
264      }).id('onTouch')
265
266      Button() {
267        Text('onMouse').fontSize(25).fontWeight(FontWeight.Bold)
268      }.margin({ top: 20 }).backgroundColor('#0D9FFB')
269      .onMouse(() => {
270        console.info('onMouse')
271        this.text = "Button 'onMouse' in onMouse"
272        setTimeout(() => {
273          let keyEvent: KeyEvent = {
274            type: KeyType.Down,
275            keyCode: 2049,
276            keyText: 'tab',
277            keySource: 4,
278            deviceId: 0,
279            metaKey: 0,
280            timestamp: 0,
281            stopPropagation: () => {
282            },
283            intentionCode: IntentionCode.INTENTION_DOWN
284          }
285          sendKeyEvent(keyEvent) // Send a key event.
286        }, 2000)
287      }).id('onMouse')
288
289      Text(this.text).fontSize(25).padding(15)
290    }
291    .width('100%').height('100%')
292  }
293}
294```
295