browser-snapshot-helpers.ts 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. import type { AccessibilityNode, RawDomNode } from './browser-snapshot.js';
  2. import type { ElementRecord, Rect } from './browser-state.js';
  3. const INTERACTIVE_ROLES = new Set([
  4. 'button',
  5. 'link',
  6. 'textbox',
  7. 'searchbox',
  8. 'checkbox',
  9. 'radio',
  10. 'switch',
  11. 'combobox',
  12. 'listbox',
  13. 'spinbutton',
  14. 'slider',
  15. 'option',
  16. 'menuitem',
  17. 'tab',
  18. ]);
  19. const INTERACTIVE_TAGS = new Set([
  20. 'button',
  21. 'input',
  22. 'textarea',
  23. 'select',
  24. 'a',
  25. 'summary',
  26. 'option',
  27. ]);
  28. const MAX_EXPOSED_TAG_LENGTH = 80;
  29. const MAX_EXPOSED_ROLE_LENGTH = 120;
  30. const MAX_EXPOSED_TYPE_LENGTH = 120;
  31. const MAX_EXPOSED_SELECTOR_LENGTH = 500;
  32. const MAX_EXPOSED_TEXT_LENGTH = 300;
  33. const MAX_EXPOSED_ATTRIBUTES = 20;
  34. const MAX_EXPOSED_ATTRIBUTE_KEY_LENGTH = 120;
  35. const MAX_EXPOSED_ATTRIBUTE_VALUE_LENGTH = 300;
  36. const MAX_EXPOSED_PARENT_REGIONS = 16;
  37. export function exposeElement(
  38. element: ElementRecord,
  39. viewport: { width: number; height: number },
  40. frameRef?: string,
  41. ): Record<string, unknown> & { ref: string } {
  42. const coordinateSpace = element.coordinateSpace ?? 'main-frame-viewport';
  43. const hasViewportRect = coordinateSpace === 'main-frame-viewport';
  44. const actionable = element.isInteractable === true;
  45. return {
  46. ref: element.ref,
  47. tag: element.tag.slice(0, MAX_EXPOSED_TAG_LENGTH),
  48. role: element.role.slice(0, MAX_EXPOSED_ROLE_LENGTH),
  49. type: element.type.slice(0, MAX_EXPOSED_TYPE_LENGTH),
  50. ...(element.selector
  51. ? { selector: element.selector.slice(0, MAX_EXPOSED_SELECTOR_LENGTH) }
  52. : {}),
  53. text: element.text.slice(0, MAX_EXPOSED_TEXT_LENGTH),
  54. ...(hasViewportRect ? { rect: { ...element.rect } } : {}),
  55. coordinateSpace,
  56. inViewport:
  57. hasViewportRect &&
  58. element.rect.x < viewport.width &&
  59. element.rect.y < viewport.height &&
  60. element.rect.x + element.rect.width > 0 &&
  61. element.rect.y + element.rect.height > 0,
  62. actionable,
  63. pointerActionable: actionable && hasViewportRect,
  64. attributes: Object.fromEntries(
  65. Object.entries(element.attributes)
  66. .slice(0, MAX_EXPOSED_ATTRIBUTES)
  67. .map(([key, value]) => [
  68. key.slice(0, MAX_EXPOSED_ATTRIBUTE_KEY_LENGTH),
  69. value.slice(0, MAX_EXPOSED_ATTRIBUTE_VALUE_LENGTH),
  70. ]),
  71. ),
  72. ...(element.frameId && frameRef ? { frame: frameRef } : {}),
  73. ...(element.parentRegionPath
  74. ? {
  75. parentRegionPath: element.parentRegionPath
  76. .slice(0, MAX_EXPOSED_PARENT_REGIONS)
  77. .map((region) => ({
  78. role: region.role.slice(0, MAX_EXPOSED_ROLE_LENGTH),
  79. ...(region.name ? { name: region.name.slice(0, MAX_EXPOSED_TEXT_LENGTH) } : {}),
  80. })),
  81. }
  82. : {}),
  83. };
  84. }
  85. export function buildParentRegionPath(
  86. node: RawDomNode,
  87. byNodeId: Map<number, RawDomNode>,
  88. parents: Map<number, number>,
  89. axByBackend: Map<number, AccessibilityNode>,
  90. ): Array<{ role: string; name?: string }> {
  91. const path: Array<{ role: string; name?: string }> = [];
  92. let parentId = parents.get(node.nodeId);
  93. while (parentId !== undefined) {
  94. const parent = byNodeId.get(parentId);
  95. if (!parent) break;
  96. const attributes = attributeMap(parent.attributes);
  97. const role = elementRole(
  98. parent,
  99. attributes,
  100. parent.backendNodeId ? axByBackend.get(parent.backendNodeId) : undefined,
  101. );
  102. if (
  103. role === 'region' ||
  104. role === 'form' ||
  105. role === 'main' ||
  106. role === 'dialog' ||
  107. role === 'article'
  108. ) {
  109. const name = structuralRegionName(
  110. attributes,
  111. parent.backendNodeId ? axByBackend.get(parent.backendNodeId) : undefined,
  112. );
  113. path.unshift({ role, ...(name ? { name } : {}) });
  114. }
  115. parentId = parents.get(parent.nodeId);
  116. }
  117. return path;
  118. }
  119. function structuralRegionName(attributes: Record<string, string>, ax?: AccessibilityNode): string {
  120. return (ax?.name?.value || attributes['aria-label'] || attributes.title || attributes.name || '')
  121. .replace(/\s+/gu, ' ')
  122. .trim()
  123. .slice(0, 200);
  124. }
  125. export function hasArea(rect: Rect): boolean {
  126. return rect.width > 0 && rect.height > 0;
  127. }
  128. export function isInActionViewport(
  129. rect: Rect,
  130. viewport: { width: number; height: number },
  131. ): boolean {
  132. return rect.x < viewport.width && rect.x + rect.width > 0;
  133. }
  134. export function isVirtualEditorProxy(
  135. node: RawDomNode,
  136. attributes: Record<string, string>,
  137. byNodeId: Map<number, RawDomNode>,
  138. parents: Map<number, number>,
  139. ): boolean {
  140. const tag = node.nodeName.toLowerCase();
  141. if ((tag !== 'textarea' && tag !== 'input') || attributes.inputmode?.toLowerCase() !== 'none')
  142. return false;
  143. let parentId = parents.get(node.nodeId);
  144. while (parentId !== undefined) {
  145. const parent = byNodeId.get(parentId);
  146. if (!parent) break;
  147. if (hasClass(attributeMap(parent.attributes).class, 'dcg-mq-editable-field')) return true;
  148. parentId = parents.get(parent.nodeId);
  149. }
  150. return false;
  151. }
  152. export function hasClass(value: string | undefined, className: string): boolean {
  153. return (value ?? '').split(/\s+/u).includes(className);
  154. }
  155. export function visibleText(
  156. node: RawDomNode,
  157. attributes: Record<string, string>,
  158. ax?: AccessibilityNode,
  159. ): string {
  160. return (
  161. ax?.name?.value ||
  162. attributes['aria-label'] ||
  163. attributes.placeholder ||
  164. textContent(node) ||
  165. attributes.title ||
  166. ''
  167. )
  168. .replace(/\s+/gu, ' ')
  169. .trim()
  170. .slice(0, 300);
  171. }
  172. export function nameForNode(
  173. node: RawDomNode,
  174. attributes: Record<string, string>,
  175. ax?: AccessibilityNode,
  176. ): string {
  177. return visibleText(node, attributes, ax).slice(0, 200);
  178. }
  179. function textContent(node: RawDomNode): string {
  180. return [
  181. node.nodeValue ?? '',
  182. ...(node.children ?? []).map(textContent),
  183. ...(node.shadowRoots ?? []).map(textContent),
  184. node.contentDocument ? textContent(node.contentDocument) : '',
  185. ].join(' ');
  186. }
  187. export function elementRole(
  188. node: RawDomNode,
  189. attributes: Record<string, string>,
  190. ax?: AccessibilityNode,
  191. ): string {
  192. const explicit = attributes.role?.trim().toLowerCase();
  193. if (explicit) return explicit;
  194. const accessible = ax?.role?.value?.trim().toLowerCase();
  195. if (accessible && accessible !== 'generic') return accessible;
  196. switch (node.nodeName.toLowerCase()) {
  197. case 'a':
  198. return 'link';
  199. case 'button':
  200. return 'button';
  201. case 'textarea':
  202. return 'textbox';
  203. case 'select':
  204. return 'combobox';
  205. case 'input':
  206. return inputRole(attributes.type);
  207. case 'main':
  208. return 'main';
  209. case 'nav':
  210. return 'navigation';
  211. case 'form':
  212. return 'form';
  213. case 'dialog':
  214. return 'dialog';
  215. case 'article':
  216. return 'article';
  217. case 'h1':
  218. case 'h2':
  219. case 'h3':
  220. case 'h4':
  221. case 'h5':
  222. case 'h6':
  223. return 'heading';
  224. case 'ul':
  225. case 'ol':
  226. return 'list';
  227. case 'li':
  228. return 'listitem';
  229. case 'table':
  230. return 'table';
  231. case 'tr':
  232. return 'row';
  233. case 'td':
  234. case 'th':
  235. return 'cell';
  236. default:
  237. return 'generic';
  238. }
  239. }
  240. function inputRole(type = ''): string {
  241. switch (type.toLowerCase()) {
  242. case 'checkbox':
  243. return 'checkbox';
  244. case 'radio':
  245. return 'radio';
  246. case 'search':
  247. return 'searchbox';
  248. case 'range':
  249. return 'slider';
  250. case 'button':
  251. case 'submit':
  252. case 'reset':
  253. return 'button';
  254. default:
  255. return 'textbox';
  256. }
  257. }
  258. export function elementType(tag: string, role: string, attributes: Record<string, string>): string {
  259. if (tag === 'input') return attributes.type || role;
  260. if (tag === 'textarea') return 'textarea';
  261. return role || tag;
  262. }
  263. export function isInteractive(
  264. node: RawDomNode,
  265. attributes: Record<string, string>,
  266. role: string,
  267. ): boolean {
  268. if (attributes.hidden !== undefined || attributes['aria-hidden'] === 'true') return false;
  269. return (
  270. INTERACTIVE_TAGS.has(node.nodeName.toLowerCase()) ||
  271. INTERACTIVE_ROLES.has(role) ||
  272. attributes.contenteditable === 'true' ||
  273. attributes.tabindex !== undefined
  274. );
  275. }
  276. export function attributeMap(attributes?: string[]): Record<string, string> {
  277. const result: Record<string, string> = {};
  278. for (let index = 0; index + 1 < (attributes?.length ?? 0); index += 2) {
  279. const key = attributes?.[index];
  280. const value = attributes?.[index + 1];
  281. if (key && value !== undefined) result[key.toLowerCase()] = value;
  282. }
  283. return result;
  284. }
  285. export function safeAttributes(attributes: Record<string, string>): Record<string, string> {
  286. const allowed = new Set([
  287. 'id',
  288. 'aria-label',
  289. 'aria-labelledby',
  290. 'aria-describedby',
  291. 'placeholder',
  292. 'title',
  293. 'type',
  294. 'name',
  295. 'href',
  296. 'role',
  297. 'contenteditable',
  298. 'autocomplete',
  299. 'inputmode',
  300. ]);
  301. return Object.fromEntries(Object.entries(attributes).filter(([key]) => allowed.has(key)));
  302. }