Class: HeadlessBrowserTool::Tools::SearchPageTool

Inherits:
BaseTool
  • Object
show all
Defined in:
lib/headless_browser_tool/tools/search_page_tool.rb

Instance Method Summary collapse

Instance Method Details

#execute(query:, case_sensitive: false, regex: false, context_lines: 2, highlight: false) ⇒ Object



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
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/headless_browser_tool/tools/search_page_tool.rb', line 20

def execute(query:, case_sensitive: false, regex: false, context_lines: 2, highlight: false)
  # Get page text content
  page_text = browser.text
  lines = page_text.split("\n")

  # Build search pattern
  pattern = if regex
              Regexp.new(query, case_sensitive ? nil : Regexp::IGNORECASE)
            else
              escaped_query = Regexp.escape(query)
              Regexp.new(escaped_query, case_sensitive ? nil : Regexp::IGNORECASE)
            end

  # Find matches with line numbers
  matches = []
  lines.each_with_index do |line, index|
    next unless line =~ pattern

    match_info = {
      line_number: index + 1,
      line: line,
      matches: line.scan(pattern)
    }

    # Add context
    if context_lines.positive?
      start_idx = [0, index - context_lines].max
      end_idx = [lines.length - 1, index + context_lines].min
      match_info[:context] = {
        before: lines[start_idx...index],
        after: lines[(index + 1)..end_idx]
      }
    end

    matches << match_info
  end

  # Highlight in browser if requested
  if highlight && matches.any?
    highlight_script = build_highlight_script(query, regex, case_sensitive)
    browser.execute_script(highlight_script)
  end

  # Build result
  result = {
    query: query,
    total_matches: matches.size,
    matches: matches.map do |match|
      output = {
        line_number: match[:line_number],
        line: match[:line].strip,
        occurrences: match[:matches].size
      }

      if match[:context]
        output[:context] = {
          before: match[:context][:before].map(&:strip),
          after: match[:context][:after].map(&:strip)
        }
      end

      output
    end
  }

  # Also search in HTML attributes and hidden text if no matches in visible text
  if matches.empty?
    html_matches = search_html(pattern)
    result[:html_matches] = html_matches if html_matches.any?
  end

  result
end