Class: RailsAiContext::Tools::GetView

Inherits:
BaseTool
  • Object
show all
Defined in:
lib/rails_ai_context/tools/get_view.rb

Constant Summary collapse

PHLEX_HELPERS =

Extract helper method calls from Phlex views

%w[
  link_to image_tag content_for button_to form_with form_for
  content_tag tag number_to_currency number_to_human
  time_ago_in_words distance_of_time_in_words
  truncate pluralize raw sanitize dom_id
].freeze

Constants inherited from BaseTool

BaseTool::SESSION_CONTEXT, BaseTool::SHARED_CACHE

Class Method Summary collapse

Methods inherited from BaseTool

abstract!, abstract?, cache_key, cached_context, config, extract_method_source_from_file, extract_method_source_from_string, find_closest_match, fuzzy_find_key, inherited, not_found_response, paginate, rails_app, registered_tools, reset_all_caches!, reset_cache!, session_queries, session_record, session_reset!, set_call_params, text_response

Class Method Details

.call(controller: nil, path: nil, detail: "standard", server_context: nil) ⇒ Object



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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/rails_ai_context/tools/get_view.rb', line 31

def self.call(controller: nil, path: nil, detail: "standard", server_context: nil)
  data = cached_context[:view_templates]

  # Fall back to reading from disk if introspector not in preset
  if data.nil? || data[:error]
    return read_from_disk(controller: controller, path: path, detail: detail)
  end

  templates = data[:templates] || {}
  partials = data[:partials] || {}

  # Specific path — return file content
  if path
    return read_view_file(path)
  end

  # Filter by controller (also checks partials for directories like "shared/")
  # Special case: "layouts" reads from app/views/layouts/ (excluded from normal listing)
  if controller&.downcase == "layouts"
    return list_layouts(detail)
  end

  if controller
    # Normalize: accept "CooksController", "cooks", "cooks_controller", "Bonus::CooksController"
    ctrl_lower = controller.underscore.delete_suffix("_controller")
    ctrl_lower_alt = controller.downcase.delete_suffix("controller")
    filtered_templates = templates.select { |k, _|
      k_down = k.downcase
      k_down.start_with?(ctrl_lower + "/") || k_down.start_with?(ctrl_lower_alt + "/")
    }
    filtered_partials = partials.select { |k, _|
      k_down = k.downcase
      k_down.start_with?(ctrl_lower + "/") || k_down.start_with?(ctrl_lower_alt + "/")
    }

    if filtered_templates.empty? && filtered_partials.empty?
      all_dirs = (templates.keys + partials.keys).map { |k| k.split("/").first }.uniq.sort
      suggestion = find_closest_match(ctrl_lower, all_dirs)
      hint = suggestion ? " Did you mean '#{suggestion}'?" : ""
      return text_response("No views for '#{controller}'.#{hint} Directories with views: #{all_dirs.join(', ')}")
    end

    templates = filtered_templates
    partials = filtered_partials
  end

  case detail
  when "summary"
    all_dirs = (templates.keys + partials.keys).map { |k| k.split("/").first }.uniq.sort
    lines = [ "# Views (#{templates.size} templates, #{partials.size} partials)", "" ]
    all_dirs.each do |ctrl|
      ctrl_templates = templates.select { |k, _| k.start_with?("#{ctrl}/") }
      ctrl_partials = partials.select { |k, _| k.start_with?("#{ctrl}/") }
      file_count = ctrl_templates.size + ctrl_partials.size
      # Skip redundant section header when filtered to a single controller
      lines << "## #{ctrl}/ (#{file_count} files)" unless controller && all_dirs.size == 1
      ctrl_templates.sort.each do |name, meta|
        parts = meta[:partials]&.any? ? " renders: #{meta[:partials].join(', ')}" : ""
        stim = meta[:stimulus]&.any? ? " stimulus: #{meta[:stimulus].join(', ')}" : ""
        comps = meta[:components]&.any? ? " components: #{meta[:components].join(', ')}" : ""
        phlex_tag = meta[:phlex] ? " [phlex]" : ""
        lines << "- #{name} (#{meta[:lines]} lines#{phlex_tag})#{parts}#{comps}#{stim}"
      end
      ctrl_partials.sort.each do |name, meta|
        lines << "- #{name} (#{meta[:lines]} lines)"
      end
      lines << ""
    end
    text_response(lines.join("\n"))

  when "standard"
    all_dirs = (templates.keys + partials.keys).map { |k| k.split("/").first }.uniq.sort
    lines = [ "# Views (#{templates.size} templates, #{partials.size} partials)", "" ]

    # Form builders and component usage from views introspector
    form_builders = data[:form_builders_detected]
    component_usage = data[:component_usage]
    if form_builders&.any?
      lines << "**Form builders:** #{form_builders.join(', ')}" << ""
    end
    if component_usage&.any?
      lines << "**ViewComponents:** #{component_usage.first(10).join(', ')}" << ""
    end

    all_dirs.each do |ctrl|
      ctrl_templates = templates.select { |k, _| k.start_with?("#{ctrl}/") }
      ctrl_partials = partials.select { |k, _| k.start_with?("#{ctrl}/") }
      next if ctrl_templates.empty? && ctrl_partials.empty?

      lines << "## #{ctrl}/" unless controller && all_dirs.size == 1
      ctrl_templates.sort.each do |name, meta|
        detail_parts = []
        extra = (name)

        if meta[:phlex]
          # Phlex views: show components, helpers, stimulus, ivars
          # Prefer introspector-level data, fall back to extract_view_metadata
          components = meta[:components]&.any? ? meta[:components] : extra[:components]
          helpers = meta[:helpers]&.any? ? meta[:helpers] : extra[:helpers]
          detail_parts << "ivars: #{extra[:ivars].join(', ')}" if extra[:ivars]&.any?
          detail_parts << "components: #{components.join(', ')}" if components&.any?
          detail_parts << "helpers: #{helpers.join(', ')}" if helpers&.any?
          detail_parts << "stimulus: #{meta[:stimulus].join(', ')}" if meta[:stimulus]&.any?
          detail_parts << "turbo: #{extra[:turbo].join(', ')}" if extra[:turbo]&.any?
        else
          # ERB/Haml/Slim views: existing behavior
          detail_parts << "renders: #{meta[:partials].join(', ')}" if meta[:partials]&.any?
          detail_parts << "stimulus: #{meta[:stimulus].join(', ')}" if meta[:stimulus]&.any?
          detail_parts << "ivars: #{extra[:ivars].join(', ')}" if extra[:ivars]&.any?
          detail_parts << "turbo: #{extra[:turbo].join(', ')}" if extra[:turbo]&.any?
        end

        phlex_tag = meta[:phlex] ? " [phlex]" : ""
        details = detail_parts.any? ? "#{detail_parts.join(' | ')}" : ""
        lines << "- **#{name}** (#{meta[:lines]} lines#{phlex_tag})#{details}"
      end
      ctrl_partials.sort.each do |name, meta|
        fields = meta[:fields]&.any? ? " fields: #{meta[:fields].join(', ')}" : ""
        helpers = meta[:helpers]&.any? ? " helpers: #{meta[:helpers].join(', ')}" : ""
        locals = extract_partial_locals(name, templates)
        locals_str = locals&.any? ? " **locals:** #{locals.join(', ')}" : ""
        lines << "- #{name} (#{meta[:lines]} lines)#{fields}#{helpers}#{locals_str}"
      end
      lines << ""
    end

    # Hydrate: inject schema hints for models inferred from view instance variables
    if RailsAiContext.configuration.hydration_enabled && controller
      all_ivars = []
      templates.each do |path, _meta|
        content = read_view_content(path)
        content.scan(/@(\w+)/).flatten.each { |v| all_ivars << v }
      end
      all_ivars.uniq!
      hydration = Hydrators::ViewHydrator.call(all_ivars, context: cached_context)
      hydration_text = Hydrators::HydrationFormatter.format(hydration)
      lines << hydration_text << "" unless hydration_text.empty?
    end

    text_response(lines.join("\n"))

  when "full"
    if controller
      lines = [ "# Views: #{controller}/", "" ]
      # Combine all content first for cross-template Tailwind compression
      all_content = []
      templates.sort.each do |name, _meta|
        all_content << [ name, strip_svg(read_view_content(name)) ]
      end
      partials.sort.each do |name, _meta|
        all_content << [ name, strip_svg(read_view_content(name)) ]
      end
      # Compress repeated Tailwind classes across all templates
      combined = all_content.map { |name, c| "## #{name}\n```erb\n#{c}\n```\n" }.join("\n")
      combined = compress_tailwind(combined)
      lines << combined
      text_response(lines.join("\n"))
    else
      # List available controllers when no controller specified
      all_dirs = (templates.keys + partials.keys).map { |k| k.split("/").first }.uniq.sort
      lines = [ "# Views — Full Detail", "", "_Specify a controller to see template content:_", "" ]
      all_dirs.each do |ctrl|
        count = templates.count { |k, _| k.start_with?("#{ctrl}/") } +
                partials.count { |k, _| k.start_with?("#{ctrl}/") }
        lines << "- `controller:\"#{ctrl}\"` (#{count} files)"
      end
      lines << "" << "_Or use `path:\"controller/action.html.erb\"` for a specific file._"
      text_response(lines.join("\n"))
    end
  else
    text_response("Unknown detail level: #{detail}. Use summary, standard, or full.")
  end
end