-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathsnapshotFormatter.ts
More file actions
80 lines (73 loc) · 1.92 KB
/
snapshotFormatter.ts
File metadata and controls
80 lines (73 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import type {TextSnapshot, TextSnapshotNode} from '../McpContext.js';
export function formatSnapshotNode(
root: TextSnapshotNode,
snapshot?: TextSnapshot,
depth = 0,
): string {
let result = '';
const attributes = getAttributes(root);
const line =
' '.repeat(depth * 2) +
attributes.join(' ') +
(root.id === snapshot?.selectedElementUid
? ' [selected in the DevTools Elements panel]'
: '') +
'\n';
result += line;
for (const child of root.children) {
result += formatSnapshotNode(child, snapshot, depth + 1);
}
return result;
}
function getAttributes(serializedAXNodeRoot: TextSnapshotNode): string[] {
const attributes = [`uid=${serializedAXNodeRoot.id}`];
if (serializedAXNodeRoot.role) {
// To match representation in DevTools.
attributes.push(
serializedAXNodeRoot.role === 'none'
? 'ignored'
: serializedAXNodeRoot.role,
);
}
if (serializedAXNodeRoot.name) {
attributes.push(`"${serializedAXNodeRoot.name}"`);
}
const excluded = new Set([
'id',
'role',
'name',
'elementHandle',
'children',
'backendNodeId',
]);
const booleanPropertyMap: Record<string, string> = {
disabled: 'disableable',
expanded: 'expandable',
focused: 'focusable',
selected: 'selectable',
};
for (const attr of Object.keys(serializedAXNodeRoot).sort()) {
if (excluded.has(attr)) {
continue;
}
const value = (serializedAXNodeRoot as unknown as Record<string, unknown>)[
attr
];
if (typeof value === 'boolean') {
if (booleanPropertyMap[attr]) {
attributes.push(booleanPropertyMap[attr]);
}
if (value) {
attributes.push(attr);
}
} else if (typeof value === 'string' || typeof value === 'number') {
attributes.push(`${attr}="${value}"`);
}
}
return attributes;
}