* 获取扩展上下文(向上遍历多层)
(element)
| 559 | * 获取扩展上下文(向上遍历多层) |
| 560 | */ |
| 561 | function getExpandedContext(element) { |
| 562 | const contextParts = []; |
| 563 | let current = element.parentElement; |
| 564 | let depth = 0; |
| 565 | const maxDepth = 4; |
| 566 | |
| 567 | while (current && depth < maxDepth) { |
| 568 | // 检查是否有有意义的语义信息 |
| 569 | const tagName = current.tagName.toLowerCase(); |
| 570 | |
| 571 | // 跳过无意义的容器 |
| 572 | if (['body', 'html', 'main', 'article', 'section'].includes(tagName)) { |
| 573 | break; |
| 574 | } |
| 575 | |
| 576 | // 检查类名和 ID 中的语义 |
| 577 | const semantic = extractSemanticFromElement(current); |
| 578 | if (semantic) { |
| 579 | contextParts.push(semantic); |
| 580 | } |
| 581 | |
| 582 | // 检查 heading 元素 |
| 583 | const heading = current.querySelector('h1, h2, h3, h4, h5, h6, legend'); |
| 584 | if (heading && !contextParts.includes(heading.innerText.trim())) { |
| 585 | const headingText = heading.innerText.trim(); |
| 586 | if (headingText.length < 100) { |
| 587 | contextParts.push(`[section: ${headingText}]`); |
| 588 | } |
| 589 | } |
| 590 | |
| 591 | current = current.parentElement; |
| 592 | depth++; |
| 593 | } |
| 594 | |
| 595 | return contextParts.join(' | ').substring(0, 300); |
| 596 | } |
| 597 | |
| 598 | /** |
| 599 | * 从元素中提取语义信息(class, id, data-* 属性) |
no test coverage detected