@mobilewright/inspector 0.0.59 → 0.0.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/index.d.ts +4 -1
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +42 -8
  4. package/dist/index.js.map +1 -1
  5. package/dist/lib/device-manager.d.ts +24 -9
  6. package/dist/lib/device-manager.d.ts.map +1 -1
  7. package/dist/lib/device-manager.js +95 -14
  8. package/dist/lib/device-manager.js.map +1 -1
  9. package/dist/lib/inspect-screen.d.ts +47 -0
  10. package/dist/lib/inspect-screen.d.ts.map +1 -0
  11. package/dist/lib/inspect-screen.js +104 -0
  12. package/dist/lib/inspect-screen.js.map +1 -0
  13. package/dist/lib/locator-derivation.d.ts +20 -5
  14. package/dist/lib/locator-derivation.d.ts.map +1 -1
  15. package/dist/lib/locator-derivation.js +64 -7
  16. package/dist/lib/locator-derivation.js.map +1 -1
  17. package/dist/lib/timeout.d.ts +3 -0
  18. package/dist/lib/timeout.d.ts.map +1 -0
  19. package/dist/lib/timeout.js +9 -0
  20. package/dist/lib/timeout.js.map +1 -0
  21. package/dist/routes/device-actions.d.ts +7 -0
  22. package/dist/routes/device-actions.d.ts.map +1 -0
  23. package/dist/routes/device-actions.js +79 -0
  24. package/dist/routes/device-actions.js.map +1 -0
  25. package/dist/routes/devices.d.ts +1 -1
  26. package/dist/routes/devices.d.ts.map +1 -1
  27. package/dist/routes/devices.js +10 -11
  28. package/dist/routes/devices.js.map +1 -1
  29. package/dist/routes/inspect.d.ts.map +1 -1
  30. package/dist/routes/inspect.js +22 -92
  31. package/dist/routes/inspect.js.map +1 -1
  32. package/package.json +4 -4
  33. package/public/codegen.html +119 -0
  34. package/public/css/app.css +276 -6
  35. package/public/favicon.ico +0 -0
  36. package/public/fonts/codicon-LICENSE.txt +21 -0
  37. package/public/fonts/codicon.ttf +0 -0
  38. package/public/index.html +5 -2
  39. package/public/js/app.js +253 -51
  40. package/public/js/codegen.js +301 -0
  41. package/public/js/inspect.js +7 -0
  42. package/public/js/view-tree.js +182 -0
  43. package/public/logo.png +0 -0
@@ -0,0 +1,301 @@
1
+ import { DetailPane, Inspector, ScreenshotPane, applyTheme, escQ, locatorCode, makeResizable } from './app.js'
2
+ import { ViewTreePane } from './view-tree.js'
3
+
4
+ const INITIAL_SOURCE = `import { test, expect } from '@mobilewright/test';
5
+
6
+ test('test', async ({ device, screen }) => {
7
+ });
8
+ `
9
+
10
+ const TEST_BODY_END = '});'
11
+
12
+ const TREE_OPEN_STORAGE_KEY = 'mobilewright-codegen-tree-open'
13
+
14
+ const COPIED_FEEDBACK_MS = 1500
15
+
16
+ const GESTURE_NAMES = { tap: 'Tap', doubleTap: 'Double tap', longPress: 'Long press' }
17
+
18
+ // The Inspector hides its detail pane on every refresh, which continuous refresh would do constantly,
19
+ // so it gets a no-op stand-in and the Recorder drives the real DetailPane itself.
20
+ const noDetailPane = { onClose() {}, show() {}, hide() {} }
21
+
22
+ // Only elements whose locator the query engine resolves back to them can be recorded by locator.
23
+ function hasRecordableLocator(el) {
24
+ return Boolean(el.locator && el.match)
25
+ }
26
+
27
+ // What each click mode records. Text and value mirror locator.getText() / getValue() in core,
28
+ // so the generated assertion compares against exactly what the test will read.
29
+ const CLICK_MODES = {
30
+ tap: {
31
+ accepts: hasRecordableLocator,
32
+ },
33
+ assertText: {
34
+ accepts: el => hasRecordableLocator(el) && textOf(el) !== '',
35
+ code: el => `await expect(screen.${locatorCode(el)}).toHaveText('${escQ(textOf(el))}');`,
36
+ },
37
+ assertValue: {
38
+ accepts: el => hasRecordableLocator(el) && el.value !== null,
39
+ code: el => `await expect(screen.${locatorCode(el)}).toHaveValue('${escQ(String(el.value))}');`,
40
+ },
41
+ }
42
+
43
+ function textOf(el) {
44
+ return String(el.text ?? el.label ?? el.value ?? '')
45
+ }
46
+
47
+ function hasArea(el) {
48
+ return Boolean(el.bounds && el.bounds.width > 0 && el.bounds.height > 0)
49
+ }
50
+
51
+ function readTreeOpen() {
52
+ try {
53
+ return localStorage.getItem(TREE_OPEN_STORAGE_KEY) === 'true'
54
+ } catch {
55
+ return false
56
+ }
57
+ }
58
+
59
+ function centerOf({ x, y, width, height }) {
60
+ return { x: Math.round(x + width / 2), y: Math.round(y + height / 2) }
61
+ }
62
+
63
+ function insertBeforeTestBodyEnd(source, line) {
64
+ const end = source.lastIndexOf(TEST_BODY_END)
65
+ if (end === -1) {
66
+ return source + line + '\n'
67
+ }
68
+ return source.slice(0, end) + line + '\n' + source.slice(end)
69
+ }
70
+
71
+ class Recorder {
72
+ #editor = document.getElementById('code-editor')
73
+ #recordBtn = document.getElementById('record-btn')
74
+ #statusBar = document.getElementById('status-bar')
75
+ // Every control above the device screen, and the subset that are hardware buttons.
76
+ #deviceControls = [...document.querySelectorAll('.device-btn')]
77
+ #hardwareButtons = [...document.querySelectorAll('.device-btn[data-button]')]
78
+ #assertButtons = [...document.querySelectorAll('.assert-btn')]
79
+ #treeBtn = document.getElementById('tree-btn')
80
+ #copyBtn = document.getElementById('copy-btn')
81
+ #treePane = document.getElementById('tree-pane')
82
+ #geoForm = document.getElementById('geo-popover')
83
+ #detailPane = new DetailPane()
84
+ #gestureButtons = [...document.querySelectorAll('.gesture-btn')]
85
+ #detailElement = null
86
+ #viewTree
87
+ #isRecording = true
88
+ #clickMode = 'tap'
89
+ #inspector
90
+
91
+ constructor() {
92
+ const screenshotPane = new ScreenshotPane({ showAllHighlights: false })
93
+ const viewTree = new ViewTreePane(document.getElementById('view-tree'))
94
+ this.#viewTree = viewTree
95
+ this.#inspector = new Inspector({
96
+ screenshotPane,
97
+ elementsPane: viewTree,
98
+ detailPane: noDetailPane,
99
+ onActiveDeviceChange: device => this.#enableDeviceControlsFor(device),
100
+ continuousRefresh: true,
101
+ })
102
+ this.#editor.value = INITIAL_SOURCE
103
+ this.#recordBtn.addEventListener('click', () => this.#setRecording(!this.#isRecording))
104
+ for (const btn of this.#assertButtons) {
105
+ btn.addEventListener('click', () => this.#setClickMode(this.#clickMode === btn.dataset.mode ? 'tap' : btn.dataset.mode))
106
+ }
107
+ // Shift targets any element, since Shift-click only finds it in the view tree.
108
+ const acceptsFor = isShift => isShift ? hasArea : CLICK_MODES[this.#clickMode].accepts
109
+ screenshotPane.onScreenHover((x, y, isShift) => {
110
+ screenshotPane.showHoverBox(x === null ? null : screenshotPane.elementAt(x, y, acceptsFor(isShift)))
111
+ })
112
+ screenshotPane.onScreenTap((x, y, isShift) => {
113
+ if (isShift) {
114
+ this.#revealInTree(screenshotPane.elementAt(x, y, hasArea))
115
+ return
116
+ }
117
+ const el = screenshotPane.elementAt(x, y, CLICK_MODES[this.#clickMode].accepts)
118
+ if (el) {
119
+ this.#clickElement(el)
120
+ return
121
+ }
122
+ if (this.#clickMode === 'tap') {
123
+ this.#perform('Tap', '/api/tap', { x, y }, `await screen.tap(${x}, ${y});`)
124
+ }
125
+ })
126
+ viewTree.onElementHover(el => screenshotPane.showHoverBox(el && hasArea(el) ? el : null))
127
+ viewTree.onRowClick(el => {
128
+ // An armed assertion takes the click; otherwise the row just shows its details.
129
+ if (this.#clickMode !== 'tap') {
130
+ this.#clickElement(el)
131
+ return
132
+ }
133
+ viewTree.selectElement(el)
134
+ this.#showDetail(el)
135
+ })
136
+ viewTree.onSelectedElementChange(el => this.#showDetail(el))
137
+ this.#detailPane.onClose(() => {
138
+ this.#detailElement = null
139
+ viewTree.clearSelection()
140
+ })
141
+ for (const btn of this.#gestureButtons) {
142
+ btn.addEventListener('click', () => this.#performGesture(btn.dataset.gesture, this.#detailElement))
143
+ }
144
+ this.#treeBtn.addEventListener('click', () => this.#setTreeOpen(this.#treePane.hidden))
145
+ this.#copyBtn.addEventListener('click', () => this.#copyTest())
146
+ this.#setTreeOpen(readTreeOpen())
147
+ for (const btn of this.#hardwareButtons) {
148
+ const button = btn.dataset.button
149
+ btn.addEventListener('click', () => this.#perform(btn.title, '/api/press-button', { button }, `await screen.pressButton('${button}');`))
150
+ }
151
+ this.#geoForm.addEventListener('submit', e => {
152
+ e.preventDefault()
153
+ const latitude = Number(this.#geoForm.elements.latitude.value)
154
+ const longitude = Number(this.#geoForm.elements.longitude.value)
155
+ this.#setGeolocation({ latitude, longitude }, `await device.setGeolocation({ latitude: ${latitude}, longitude: ${longitude} });`)
156
+ })
157
+ document.getElementById('geo-reset-btn').addEventListener('click', () => {
158
+ this.#setGeolocation(null, 'await device.setGeolocation(null);')
159
+ })
160
+ }
161
+
162
+ // Same outcome whether the element was clicked on the screenshot or in the view tree.
163
+ #clickElement(el) {
164
+ const mode = CLICK_MODES[this.#clickMode]
165
+ if (this.#clickMode !== 'tap') {
166
+ // Assertions only read the screen; an element without text/value does nothing.
167
+ if (mode.accepts(el)) {
168
+ if (this.#isRecording) {
169
+ this.#appendLine(mode.code(el))
170
+ }
171
+ this.#setClickMode('tap')
172
+ }
173
+ return
174
+ }
175
+ this.#performGesture('tap', el)
176
+ }
177
+
178
+ // Performs the gesture at the element's center, the same point the locator action hits when
179
+ // the test runs; records it by locator when there is one, by coordinates otherwise.
180
+ #performGesture(gesture, el) {
181
+ if (!el || !hasArea(el)) {
182
+ return
183
+ }
184
+ const center = centerOf(el.bounds)
185
+ const code = hasRecordableLocator(el)
186
+ ? `await screen.${locatorCode(el)}.${gesture}();`
187
+ : `await screen.${gesture}(${center.x}, ${center.y});`
188
+ this.#perform(GESTURE_NAMES[gesture], '/api/tap', { ...center, gesture }, code)
189
+ }
190
+
191
+ // Shift-click: select the element in the view tree and show its details, without touching the device.
192
+ #revealInTree(el) {
193
+ if (!el) {
194
+ return
195
+ }
196
+ this.#setTreeOpen(true)
197
+ this.#viewTree.selectElement(el)
198
+ this.#showDetail(el)
199
+ }
200
+
201
+ #showDetail(el) {
202
+ this.#detailElement = el
203
+ if (!el) {
204
+ this.#detailPane.hide()
205
+ return
206
+ }
207
+ this.#detailPane.show(el)
208
+ for (const btn of this.#gestureButtons) {
209
+ btn.disabled = !hasArea(el)
210
+ }
211
+ }
212
+
213
+ async #setGeolocation(geolocation, codeLine) {
214
+ this.#geoForm.hidePopover()
215
+ await this.#perform('Set location', '/api/geolocation', { geolocation }, codeLine)
216
+ }
217
+
218
+ async #copyTest() {
219
+ const icon = this.#copyBtn.querySelector('.codicon')
220
+ try {
221
+ await navigator.clipboard.writeText(this.#editor.value)
222
+ } catch (err) {
223
+ this.#statusBar.textContent = `Copy failed: ${err.message}`
224
+ this.#statusBar.className = 'error'
225
+ return
226
+ }
227
+ icon.classList.replace('codicon-files', 'codicon-check')
228
+ this.#copyBtn.title = 'Copied'
229
+ setTimeout(() => {
230
+ icon.classList.replace('codicon-check', 'codicon-files')
231
+ this.#copyBtn.title = 'Copy test'
232
+ }, COPIED_FEEDBACK_MS)
233
+ }
234
+
235
+ #setTreeOpen(isOpen) {
236
+ this.#treePane.hidden = !isOpen
237
+ this.#treeBtn.setAttribute('aria-pressed', String(isOpen))
238
+ try {
239
+ localStorage.setItem(TREE_OPEN_STORAGE_KEY, String(isOpen))
240
+ } catch {
241
+ // storage unavailable (private mode); the toggle still works for this page
242
+ }
243
+ }
244
+
245
+ // One assertion per click on an assert button, then back to tapping, like Playwright's recorder.
246
+ #setClickMode(clickMode) {
247
+ this.#clickMode = clickMode
248
+ for (const btn of this.#assertButtons) {
249
+ btn.setAttribute('aria-pressed', String(btn.dataset.mode === clickMode))
250
+ }
251
+ document.body.dataset.clickMode = clickMode
252
+ }
253
+
254
+ #appendLine(codeLine) {
255
+ this.#editor.value = insertBeforeTestBodyEnd(this.#editor.value, ` ${codeLine}`)
256
+ }
257
+
258
+ #setRecording(isRecording) {
259
+ this.#isRecording = isRecording
260
+ this.#recordBtn.setAttribute('aria-pressed', String(isRecording))
261
+ this.#recordBtn.title = isRecording ? 'Stop recording' : 'Start recording'
262
+ }
263
+
264
+ // iOS has no back or app-switch button, so those stay disabled there.
265
+ #enableDeviceControlsFor(device) {
266
+ for (const btn of this.#deviceControls) {
267
+ const isAndroidOnly = 'androidOnly' in btn.dataset
268
+ btn.disabled = !device || (isAndroidOnly && device.platform !== 'android')
269
+ }
270
+ }
271
+
272
+ // Runs an action on the device, records its code line, then refreshes the screenshot.
273
+ async #perform(actionName, url, body, codeLine) {
274
+ try {
275
+ const res = await fetch(url, {
276
+ method: 'POST',
277
+ headers: { 'Content-Type': 'application/json' },
278
+ body: JSON.stringify(body),
279
+ })
280
+ if (!res.ok) {
281
+ const err = await res.json()
282
+ throw new Error(err.error ?? res.statusText)
283
+ }
284
+ } catch (err) {
285
+ this.#statusBar.textContent = `${actionName} failed: ${err.message}`
286
+ this.#statusBar.className = 'error'
287
+ return
288
+ }
289
+ if (this.#isRecording) {
290
+ this.#appendLine(codeLine)
291
+ }
292
+ await this.#inspector.refresh()
293
+ }
294
+ }
295
+
296
+ makeResizable(document.getElementById('screenshot-splitter'), document.getElementById('screenshot-pane'), '--screenshot-width', 1)
297
+ makeResizable(document.getElementById('tree-splitter'), document.getElementById('tree-pane'), '--tree-width', -1)
298
+ makeResizable(document.getElementById('detail-splitter'), document.getElementById('detail-pane'), '--detail-height', -1, 'y')
299
+
300
+ applyTheme(localStorage.getItem('mobilewright-inspector-theme') || 'void')
301
+ new Recorder()
@@ -0,0 +1,7 @@
1
+ import { Inspector, applyTheme, makeResizable } from './app.js'
2
+
3
+ makeResizable(document.getElementById('screenshot-splitter'), document.getElementById('screenshot-pane'), '--screenshot-width', 1)
4
+ makeResizable(document.getElementById('detail-splitter'), document.getElementById('detail-pane'), '--detail-width', -1)
5
+
6
+ applyTheme(localStorage.getItem('mobilewright-inspector-theme') || 'void')
7
+ new Inspector()
@@ -0,0 +1,182 @@
1
+ // Collapsible view-tree sidebar for codegen. Plugs into Inspector as its elements pane:
2
+ // Inspector calls render() with each new element list (depth-first, each with a depth).
3
+
4
+ const INDENT_PX = 14
5
+
6
+ // Stable across refreshes: the element's position among its siblings, all the way up.
7
+ // Keeps collapsed branches collapsed when the screen changes a little.
8
+ function pathKeysOf(elements) {
9
+ const keys = []
10
+ const stack = [] // [{ depth, key, childCount }]
11
+ let rootCount = 0
12
+ for (const el of elements) {
13
+ while (stack.length && stack[stack.length - 1].depth >= el.depth) {
14
+ stack.pop()
15
+ }
16
+ const parent = stack[stack.length - 1]
17
+ const siblingIndex = parent ? parent.childCount++ : rootCount++
18
+ const key = `${parent?.key ?? ''}/${siblingIndex}:${el.type}`
19
+ keys.push(key)
20
+ stack.push({ depth: el.depth, key, childCount: 0 })
21
+ }
22
+ return keys
23
+ }
24
+
25
+ function nameOf(el) {
26
+ return el.label ?? el.text ?? (el.value !== null ? String(el.value) : null)
27
+ }
28
+
29
+ export class ViewTreePane {
30
+ #container
31
+ #rows = [] // [{ el, row, key, hasChildren }]
32
+ #collapsedKeys = new Set()
33
+ #onHoverCb = null
34
+ #onClickCb = null
35
+ #onSelectedChangeCb = null
36
+ #selectedKey = null
37
+
38
+ constructor(container) {
39
+ this.#container = container
40
+ this.#container.setAttribute('role', 'tree')
41
+ }
42
+
43
+ onElementHover(cb) { this.#onHoverCb = cb }
44
+ onRowClick(cb) { this.#onClickCb = cb }
45
+ // Fires after each render with the selected element's fresh snapshot, or null once it is gone.
46
+ onSelectedElementChange(cb) { this.#onSelectedChangeCb = cb }
47
+
48
+ // Selects the element's row, expanding any collapsed ancestors and scrolling it into view.
49
+ selectElement(el) {
50
+ const index = this.#rows.findIndex(r => r.el === el)
51
+ if (index === -1) {
52
+ this.clearSelection()
53
+ return
54
+ }
55
+ this.#selectedKey = this.#rows[index].key
56
+ this.#expandAncestorsOf(index)
57
+ this.#markSelected()
58
+ this.#rows[index].row.scrollIntoView({ block: 'nearest' })
59
+ }
60
+
61
+ // Rows are depth-first, so each ancestor is the nearest earlier row one level shallower.
62
+ #expandAncestorsOf(index) {
63
+ let depth = this.#rows[index].el.depth
64
+ for (let i = index - 1; i >= 0 && depth > 0; i--) {
65
+ if (this.#rows[i].el.depth < depth) {
66
+ this.#collapsedKeys.delete(this.#rows[i].key)
67
+ depth = this.#rows[i].el.depth
68
+ }
69
+ }
70
+ this.#applyCollapsed()
71
+ }
72
+
73
+ clearSelection() {
74
+ this.#selectedKey = null
75
+ this.#markSelected()
76
+ }
77
+
78
+ // Elements-pane interface Inspector expects; the tree has no selection or visibility toggles.
79
+ onElementClick() {}
80
+ onToggleHidden() {}
81
+ setSelectedIndex() {}
82
+ updateRowVisibility() {}
83
+
84
+ render(elements) {
85
+ this.#container.innerHTML = ''
86
+ const keys = pathKeysOf(elements)
87
+ this.#rows = elements.map((el, i) => {
88
+ const hasChildren = elements[i + 1]?.depth > el.depth
89
+ const row = this.#buildRow(el, keys[i], hasChildren)
90
+ this.#container.appendChild(row)
91
+ return { el, row, key: keys[i], hasChildren }
92
+ })
93
+ this.#applyCollapsed()
94
+ this.#markSelected()
95
+ if (this.#selectedKey) {
96
+ const selected = this.#rows.find(r => r.key === this.#selectedKey)
97
+ if (!selected) {
98
+ this.#selectedKey = null
99
+ }
100
+ this.#onSelectedChangeCb?.(selected?.el ?? null)
101
+ }
102
+ }
103
+
104
+ #markSelected() {
105
+ for (const { row, key } of this.#rows) {
106
+ row.classList.toggle('selected', key === this.#selectedKey)
107
+ row.setAttribute('aria-selected', String(key === this.#selectedKey))
108
+ }
109
+ }
110
+
111
+ #buildRow(el, key, hasChildren) {
112
+ const row = document.createElement('div')
113
+ row.className = 'tree-row'
114
+ row.setAttribute('role', 'treeitem')
115
+ row.setAttribute('aria-level', String(el.depth + 1))
116
+ row.style.paddingLeft = `${el.depth * INDENT_PX}px`
117
+ if (!el.isVisible) {
118
+ row.classList.add('offscreen')
119
+ }
120
+
121
+ // Leaves get a plain spacer: a disabled button would swallow clicks meant for the row.
122
+ const twisty = document.createElement(hasChildren ? 'button' : 'span')
123
+ twisty.className = 'tree-twisty codicon'
124
+ if (hasChildren) {
125
+ twisty.tabIndex = -1
126
+ twisty.setAttribute('aria-label', 'Toggle children')
127
+ twisty.addEventListener('click', e => {
128
+ e.stopPropagation()
129
+ this.#toggle(key)
130
+ })
131
+ }
132
+ row.appendChild(twisty)
133
+
134
+ const type = document.createElement('span')
135
+ type.className = 'tree-type'
136
+ type.textContent = el.type
137
+ row.appendChild(type)
138
+
139
+ const name = nameOf(el)
140
+ if (name) {
141
+ const nameEl = document.createElement('span')
142
+ nameEl.className = 'tree-name'
143
+ nameEl.textContent = ` - ${name}`
144
+ row.appendChild(nameEl)
145
+ }
146
+
147
+ row.title = name ? `${el.type} - ${name}` : el.type
148
+ row.addEventListener('mouseenter', () => this.#onHoverCb?.(el))
149
+ row.addEventListener('mouseleave', () => this.#onHoverCb?.(null))
150
+ row.addEventListener('click', () => this.#onClickCb?.(el))
151
+ return row
152
+ }
153
+
154
+ #toggle(key) {
155
+ if (this.#collapsedKeys.has(key)) {
156
+ this.#collapsedKeys.delete(key)
157
+ } else {
158
+ this.#collapsedKeys.add(key)
159
+ }
160
+ this.#applyCollapsed()
161
+ }
162
+
163
+ // Hide every row below a collapsed ancestor; rows are depth-first, so descendants are contiguous.
164
+ #applyCollapsed() {
165
+ let hideDeeperThan = Infinity
166
+ for (const { el, row, key, hasChildren } of this.#rows) {
167
+ if (el.depth <= hideDeeperThan) {
168
+ hideDeeperThan = Infinity
169
+ }
170
+ row.hidden = el.depth > hideDeeperThan
171
+ const isCollapsed = hasChildren && this.#collapsedKeys.has(key)
172
+ if (hasChildren) {
173
+ row.setAttribute('aria-expanded', String(!isCollapsed))
174
+ row.firstChild.classList.toggle('codicon-chevron-right', isCollapsed)
175
+ row.firstChild.classList.toggle('codicon-chevron-down', !isCollapsed)
176
+ }
177
+ if (!row.hidden && isCollapsed) {
178
+ hideDeeperThan = el.depth
179
+ }
180
+ }
181
+ }
182
+ }
Binary file