@mobilewright/inspector 0.0.60 → 0.0.62

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 (42) 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 +48 -0
  10. package/dist/lib/inspect-screen.d.ts.map +1 -0
  11. package/dist/lib/inspect-screen.js +105 -0
  12. package/dist/lib/inspect-screen.js.map +1 -0
  13. package/dist/lib/locator-derivation.d.ts +17 -2
  14. package/dist/lib/locator-derivation.d.ts.map +1 -1
  15. package/dist/lib/locator-derivation.js +26 -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 +105 -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 +3 -3
  33. package/public/codegen.html +161 -0
  34. package/public/css/app.css +337 -2
  35. package/public/fonts/codicon-LICENSE.txt +21 -0
  36. package/public/fonts/codicon.ttf +0 -0
  37. package/public/index.html +3 -2
  38. package/public/js/app.js +203 -55
  39. package/public/js/codegen.js +425 -0
  40. package/public/js/inspect.js +7 -0
  41. package/public/js/view-tree.js +182 -0
  42. package/public/logo.png +0 -0
@@ -0,0 +1,425 @@
1
+ import { DetailPane, Inspector, ScreenshotPane, applyTheme, escQ, locatorCode, makeResizable } from './app.js'
2
+ import { ViewTreePane } from './view-tree.js'
3
+
4
+ // What the generated code runs under: the @mobilewright/test runner, or a plain script using the library.
5
+ // Recorded lines are the same for both, since each exposes `device` and `screen`; only the wrapper differs.
6
+ const TARGETS = {
7
+ test: {
8
+ render: (platform, body) => `import { test, expect } from '@mobilewright/test';
9
+
10
+ test('test', async ({ device, screen }) => {
11
+ ${body}});
12
+ `,
13
+ bodyEnd: '});',
14
+ indent: ' ',
15
+ },
16
+ library: {
17
+ render: (platform, body) => `import { ${platform}, expect } from 'mobilewright';
18
+
19
+ const device = await ${platform}.launch();
20
+ const { screen } = device;
21
+
22
+ ${body}await device.close();
23
+ `,
24
+ bodyEnd: 'await device.close();',
25
+ indent: '',
26
+ },
27
+ }
28
+
29
+ const DEFAULT_TARGET = 'test'
30
+
31
+ const DEFAULT_PLATFORM = 'ios'
32
+
33
+ const TREE_OPEN_STORAGE_KEY = 'mobilewright-codegen-tree-open'
34
+
35
+ const TARGET_STORAGE_KEY = 'mobilewright-codegen-target'
36
+
37
+ const COPIED_FEEDBACK_MS = 1500
38
+
39
+ const ERROR_TOAST_MS = 5000
40
+
41
+ const GESTURE_NAMES = { tap: 'Tap', doubleTap: 'Double tap', longPress: 'Long press' }
42
+
43
+ // The Inspector hides its detail pane on every refresh, which continuous refresh would do constantly,
44
+ // so it gets a no-op stand-in and the Recorder drives the real DetailPane itself.
45
+ const noDetailPane = { onClose() {}, show() {}, hide() {} }
46
+
47
+ // Only elements whose locator the query engine resolves back to them can be recorded by locator.
48
+ function hasRecordableLocator(el) {
49
+ return Boolean(el.locator && el.match)
50
+ }
51
+
52
+ // What each click mode records. Text and value mirror locator.getText() / getValue() in core,
53
+ // so the generated assertion compares against exactly what the test will read.
54
+ const CLICK_MODES = {
55
+ tap: {
56
+ accepts: hasRecordableLocator,
57
+ },
58
+ assertText: {
59
+ accepts: el => hasRecordableLocator(el) && textOf(el) !== '',
60
+ code: el => `await expect(screen.${locatorCode(el)}).toHaveText('${escQ(textOf(el))}');`,
61
+ },
62
+ assertValue: {
63
+ accepts: el => hasRecordableLocator(el) && el.value !== null,
64
+ code: el => `await expect(screen.${locatorCode(el)}).toHaveValue('${escQ(String(el.value))}');`,
65
+ },
66
+ }
67
+
68
+ function textOf(el) {
69
+ return String(el.text ?? el.label ?? el.value ?? '')
70
+ }
71
+
72
+ function canFill(el) {
73
+ return el.isEditable && hasArea(el) && hasRecordableLocator(el)
74
+ }
75
+
76
+ function hasArea(el) {
77
+ return Boolean(el.bounds && el.bounds.width > 0 && el.bounds.height > 0)
78
+ }
79
+
80
+ function readTarget() {
81
+ try {
82
+ const target = localStorage.getItem(TARGET_STORAGE_KEY)
83
+ return target in TARGETS ? target : DEFAULT_TARGET
84
+ } catch {
85
+ return DEFAULT_TARGET
86
+ }
87
+ }
88
+
89
+ function renderSource(target, platform, lines) {
90
+ const { render, indent } = TARGETS[target]
91
+ return render(platform, lines.map(line => `${indent}${line}\n`).join(''))
92
+ }
93
+
94
+ function readTreeOpen() {
95
+ try {
96
+ return localStorage.getItem(TREE_OPEN_STORAGE_KEY) === 'true'
97
+ } catch {
98
+ return false
99
+ }
100
+ }
101
+
102
+ function centerOf({ x, y, width, height }) {
103
+ return { x: Math.round(x + width / 2), y: Math.round(y + height / 2) }
104
+ }
105
+
106
+ function insertBeforeBodyEnd(source, bodyEnd, line) {
107
+ const end = source.lastIndexOf(bodyEnd)
108
+ if (end === -1) {
109
+ return source + line + '\n'
110
+ }
111
+ return source.slice(0, end) + line + '\n' + source.slice(end)
112
+ }
113
+
114
+ class Recorder {
115
+ #editor = document.getElementById('code-editor')
116
+ #recordBtn = document.getElementById('record-btn')
117
+ #errorToast = document.getElementById('error-toast')
118
+ #errorToastTimer = null
119
+ // Every control above the device screen, and the subset that are hardware buttons.
120
+ #deviceControls = [...document.querySelectorAll('.device-btn')]
121
+ #hardwareButtons = [...document.querySelectorAll('.device-btn[data-button]')]
122
+ #assertButtons = [...document.querySelectorAll('.assert-btn')]
123
+ #treeBtn = document.getElementById('tree-btn')
124
+ #copyBtn = document.getElementById('copy-btn')
125
+ #treePane = document.getElementById('tree-pane')
126
+ #geoForm = document.getElementById('geo-popover')
127
+ #urlForm = document.getElementById('url-popover')
128
+ #fillForm = document.getElementById('fill-popover')
129
+ #fillBtn = document.getElementById('fill-btn')
130
+ #detailPane = new DetailPane()
131
+ #gestureButtons = [...document.querySelectorAll('.gesture-btn[data-gesture]')]
132
+ #detailElement = null
133
+ // The element Fill was clicked for; kept apart since a refresh can change the detail element meanwhile.
134
+ #fillElement = null
135
+ #viewTree
136
+ #isRecording = true
137
+ #clickMode = 'tap'
138
+ #inspector
139
+ #targetSelect = document.getElementById('target-select')
140
+ #target = readTarget()
141
+ #platform = DEFAULT_PLATFORM
142
+ // Every recorded line, so switching target can rebuild the source around them.
143
+ #lines = []
144
+
145
+ constructor() {
146
+ const screenshotPane = new ScreenshotPane({ showAllHighlights: false })
147
+ const viewTree = new ViewTreePane(document.getElementById('view-tree'))
148
+ this.#viewTree = viewTree
149
+ this.#inspector = new Inspector({
150
+ screenshotPane,
151
+ elementsPane: viewTree,
152
+ detailPane: noDetailPane,
153
+ onActiveDeviceChange: device => {
154
+ this.#enableDeviceControlsFor(device)
155
+ this.#setPlatform(device?.platform ?? this.#platform)
156
+ },
157
+ continuousRefresh: true,
158
+ })
159
+ this.#targetSelect.value = this.#target
160
+ this.#renderSource()
161
+ this.#targetSelect.addEventListener('change', () => this.#setTarget(this.#targetSelect.value))
162
+ this.#recordBtn.addEventListener('click', () => this.#setRecording(!this.#isRecording))
163
+ for (const btn of this.#assertButtons) {
164
+ btn.addEventListener('click', () => this.#setClickMode(this.#clickMode === btn.dataset.mode ? 'tap' : btn.dataset.mode))
165
+ }
166
+ // Shift targets any element, since Shift-click only finds it in the view tree.
167
+ const acceptsFor = isShift => isShift ? hasArea : CLICK_MODES[this.#clickMode].accepts
168
+ screenshotPane.onScreenHover((x, y, isShift) => {
169
+ screenshotPane.showHoverBox(x === null ? null : screenshotPane.elementAt(x, y, acceptsFor(isShift)))
170
+ })
171
+ screenshotPane.onScreenTap((x, y, isShift) => {
172
+ if (isShift) {
173
+ this.#revealInTree(screenshotPane.elementAt(x, y, hasArea))
174
+ return
175
+ }
176
+ const el = screenshotPane.elementAt(x, y, CLICK_MODES[this.#clickMode].accepts)
177
+ if (el) {
178
+ this.#clickElement(el)
179
+ return
180
+ }
181
+ if (this.#clickMode === 'tap') {
182
+ this.#perform('Tap', '/api/tap', { x, y }, `await screen.tap(${x}, ${y});`)
183
+ }
184
+ })
185
+ viewTree.onElementHover(el => screenshotPane.showHoverBox(el && hasArea(el) ? el : null))
186
+ viewTree.onRowClick(el => {
187
+ // An armed assertion takes the click; otherwise the row just shows its details.
188
+ if (this.#clickMode !== 'tap') {
189
+ this.#clickElement(el)
190
+ return
191
+ }
192
+ viewTree.selectElement(el)
193
+ this.#showDetail(el)
194
+ })
195
+ viewTree.onSelectedElementChange(el => this.#showDetail(el))
196
+ this.#detailPane.onClose(() => {
197
+ this.#detailElement = null
198
+ viewTree.clearSelection()
199
+ })
200
+ for (const btn of this.#gestureButtons) {
201
+ btn.addEventListener('click', () => this.#performGesture(btn.dataset.gesture, this.#detailElement))
202
+ }
203
+ this.#treeBtn.addEventListener('click', () => this.#setTreeOpen(this.#treePane.hidden))
204
+ this.#copyBtn.addEventListener('click', () => this.#copyTest())
205
+ this.#setTreeOpen(readTreeOpen())
206
+ for (const btn of this.#hardwareButtons) {
207
+ const button = btn.dataset.button
208
+ btn.addEventListener('click', () => this.#perform(btn.title, '/api/press-button', { button }, `await screen.pressButton('${button}');`))
209
+ }
210
+ this.#geoForm.addEventListener('submit', e => {
211
+ e.preventDefault()
212
+ const latitude = Number(this.#geoForm.elements.latitude.value)
213
+ const longitude = Number(this.#geoForm.elements.longitude.value)
214
+ this.#setGeolocation({ latitude, longitude }, `await device.setGeolocation({ latitude: ${latitude}, longitude: ${longitude} });`)
215
+ })
216
+ document.getElementById('geo-reset-btn').addEventListener('click', () => {
217
+ this.#setGeolocation(null, 'await device.setGeolocation(null);')
218
+ })
219
+ this.#urlForm.addEventListener('submit', e => {
220
+ e.preventDefault()
221
+ this.#openUrl(this.#urlForm.elements.url.value.trim())
222
+ })
223
+ this.#fillForm.addEventListener('submit', e => {
224
+ e.preventDefault()
225
+ this.#fill(this.#fillElement, this.#fillForm.elements.text.value)
226
+ })
227
+ this.#fillBtn.addEventListener('click', () => {
228
+ this.#fillElement = this.#detailElement
229
+ })
230
+ }
231
+
232
+ // Same outcome whether the element was clicked on the screenshot or in the view tree.
233
+ #clickElement(el) {
234
+ const mode = CLICK_MODES[this.#clickMode]
235
+ if (this.#clickMode !== 'tap') {
236
+ // Assertions only read the screen; an element without text/value does nothing.
237
+ if (mode.accepts(el)) {
238
+ if (this.#isRecording) {
239
+ this.#appendLine(mode.code(el))
240
+ }
241
+ this.#setClickMode('tap')
242
+ }
243
+ return
244
+ }
245
+ this.#performGesture('tap', el)
246
+ }
247
+
248
+ // Performs the gesture at the element's center, the same point the locator action hits when
249
+ // the test runs; records it by locator when there is one, by coordinates otherwise.
250
+ #performGesture(gesture, el) {
251
+ if (!el || !hasArea(el)) {
252
+ return
253
+ }
254
+ const center = centerOf(el.bounds)
255
+ const code = hasRecordableLocator(el)
256
+ ? `await screen.${locatorCode(el)}.${gesture}();`
257
+ : `await screen.${gesture}(${center.x}, ${center.y});`
258
+ this.#perform(GESTURE_NAMES[gesture], '/api/tap', { ...center, gesture }, code)
259
+ }
260
+
261
+ // Shift-click: select the element in the view tree and show its details, without touching the device.
262
+ #revealInTree(el) {
263
+ if (!el) {
264
+ return
265
+ }
266
+ this.#setTreeOpen(true)
267
+ this.#viewTree.selectElement(el)
268
+ this.#showDetail(el)
269
+ }
270
+
271
+ #showDetail(el) {
272
+ this.#detailElement = el
273
+ if (!el) {
274
+ this.#detailPane.hide()
275
+ return
276
+ }
277
+ this.#detailPane.show(el)
278
+ for (const btn of this.#gestureButtons) {
279
+ btn.disabled = !hasArea(el)
280
+ }
281
+ // Only text fields can be filled, and the screen has no typing API, so fill is recorded by locator.
282
+ this.#fillBtn.disabled = !canFill(el)
283
+ }
284
+
285
+ async #openUrl(url) {
286
+ this.#urlForm.hidePopover()
287
+ await this.#perform('Open URL', '/api/open-url', { url }, `await device.openUrl('${escQ(url)}');`)
288
+ }
289
+
290
+ // Taps, clears and types at the element's center, the same steps locator.fill() takes.
291
+ async #fill(el, text) {
292
+ this.#fillForm.hidePopover()
293
+ this.#fillForm.reset()
294
+ if (!el || !canFill(el)) {
295
+ return
296
+ }
297
+ const code = `await screen.${locatorCode(el)}.fill('${escQ(text)}');`
298
+ await this.#perform('Fill', '/api/fill', { ...centerOf(el.bounds), text }, code)
299
+ }
300
+
301
+ async #setGeolocation(geolocation, codeLine) {
302
+ this.#geoForm.hidePopover()
303
+ await this.#perform('Set location', '/api/geolocation', { geolocation }, codeLine)
304
+ }
305
+
306
+ async #copyTest() {
307
+ const icon = this.#copyBtn.querySelector('.codicon')
308
+ try {
309
+ await navigator.clipboard.writeText(this.#editor.value)
310
+ } catch (err) {
311
+ this.#showError(`Copy failed: ${err.message}`)
312
+ return
313
+ }
314
+ icon.classList.replace('codicon-files', 'codicon-check')
315
+ this.#copyBtn.title = 'Copied'
316
+ setTimeout(() => {
317
+ icon.classList.replace('codicon-check', 'codicon-files')
318
+ this.#copyBtn.title = 'Copy test'
319
+ }, COPIED_FEEDBACK_MS)
320
+ }
321
+
322
+ #setTreeOpen(isOpen) {
323
+ this.#treePane.hidden = !isOpen
324
+ this.#treeBtn.setAttribute('aria-pressed', String(isOpen))
325
+ try {
326
+ localStorage.setItem(TREE_OPEN_STORAGE_KEY, String(isOpen))
327
+ } catch {
328
+ // storage unavailable (private mode); the toggle still works for this page
329
+ }
330
+ }
331
+
332
+ // One assertion per click on an assert button, then back to tapping, like Playwright's recorder.
333
+ #setClickMode(clickMode) {
334
+ this.#clickMode = clickMode
335
+ for (const btn of this.#assertButtons) {
336
+ btn.setAttribute('aria-pressed', String(btn.dataset.mode === clickMode))
337
+ }
338
+ document.body.dataset.clickMode = clickMode
339
+ }
340
+
341
+ #showError(message) {
342
+ this.#errorToast.textContent = message
343
+ this.#errorToast.hidden = false
344
+ clearTimeout(this.#errorToastTimer)
345
+ this.#errorToastTimer = setTimeout(() => {
346
+ this.#errorToast.hidden = true
347
+ }, ERROR_TOAST_MS)
348
+ }
349
+
350
+ // Inserted into the editor rather than re-rendered, so edits made by hand are kept.
351
+ #appendLine(codeLine) {
352
+ const { bodyEnd, indent } = TARGETS[this.#target]
353
+ this.#lines.push(codeLine)
354
+ this.#editor.value = insertBeforeBodyEnd(this.#editor.value, bodyEnd, `${indent}${codeLine}`)
355
+ }
356
+
357
+ // Rebuilds the whole source from the recorded lines; edits made by hand are lost.
358
+ #renderSource() {
359
+ this.#editor.value = renderSource(this.#target, this.#platform, this.#lines)
360
+ }
361
+
362
+ #setTarget(target) {
363
+ this.#target = target
364
+ try {
365
+ localStorage.setItem(TARGET_STORAGE_KEY, target)
366
+ } catch {
367
+ // storage unavailable (private mode); the choice still applies to this page
368
+ }
369
+ this.#renderSource()
370
+ }
371
+
372
+ // The library script launches by platform, so its source follows the selected device.
373
+ #setPlatform(platform) {
374
+ if (platform === this.#platform) {
375
+ return
376
+ }
377
+ this.#platform = platform
378
+ if (this.#target === 'library') {
379
+ this.#renderSource()
380
+ }
381
+ }
382
+
383
+ #setRecording(isRecording) {
384
+ this.#isRecording = isRecording
385
+ this.#recordBtn.setAttribute('aria-pressed', String(isRecording))
386
+ this.#recordBtn.title = isRecording ? 'Stop recording' : 'Start recording'
387
+ }
388
+
389
+ // iOS has no back or app-switch button, so those stay disabled there.
390
+ #enableDeviceControlsFor(device) {
391
+ for (const btn of this.#deviceControls) {
392
+ const isAndroidOnly = 'androidOnly' in btn.dataset
393
+ btn.disabled = !device || (isAndroidOnly && device.platform !== 'android')
394
+ }
395
+ }
396
+
397
+ // Runs an action on the device, records its code line, then refreshes the screenshot.
398
+ async #perform(actionName, url, body, codeLine) {
399
+ try {
400
+ const res = await fetch(url, {
401
+ method: 'POST',
402
+ headers: { 'Content-Type': 'application/json' },
403
+ body: JSON.stringify(body),
404
+ })
405
+ if (!res.ok) {
406
+ const err = await res.json()
407
+ throw new Error(err.error ?? res.statusText)
408
+ }
409
+ } catch (err) {
410
+ this.#showError(`${actionName} failed: ${err.message}`)
411
+ return
412
+ }
413
+ if (this.#isRecording) {
414
+ this.#appendLine(codeLine)
415
+ }
416
+ await this.#inspector.refresh()
417
+ }
418
+ }
419
+
420
+ makeResizable(document.getElementById('screenshot-splitter'), document.getElementById('screenshot-pane'), '--screenshot-width', 1)
421
+ makeResizable(document.getElementById('tree-splitter'), document.getElementById('tree-pane'), '--tree-width', -1)
422
+ makeResizable(document.getElementById('detail-splitter'), document.getElementById('detail-pane'), '--detail-height', -1, 'y')
423
+
424
+ applyTheme(localStorage.getItem('mobilewright-inspector-theme') || 'void')
425
+ 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