critiqs-rails 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/engine"
4
+ require "critiqs/rails/helper"
5
+
6
+ module Critiqs
7
+ module Rails
8
+ # Adds `critiqs_tag` to every view. Its app/assets/javascripts holds
9
+ # critiqs/element.js and critiqs/context.js, which Propshaft and Sprockets
10
+ # both pick up from an engine's app/assets folders; the page loads each
11
+ # with its own <script type="module">, so importmap apps need no pin.
12
+ class Engine < ::Rails::Engine
13
+ initializer "critiqs.helper" do
14
+ ActiveSupport.on_load(:action_view) { include Critiqs::Rails::Helper }
15
+ end
16
+
17
+ # Sprockets compiles only what it is told to; Propshaft serves every file
18
+ # on its load path and has no precompile list.
19
+ initializer "critiqs.assets" do |app|
20
+ precompile = app.config.respond_to?(:assets) ? app.config.assets.precompile : nil
21
+ precompile.push(ELEMENT_ASSET, CONTEXT_ASSET) if precompile.is_a?(Array)
22
+ end
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,95 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Critiqs
4
+ module Rails
5
+ module Helper
6
+ # Adds Critiqs to the page: a <critiqs-app> element carrying the page's
7
+ # route as its data-critiqs-context attribute, the gem's small module
8
+ # that reports that context to the element whenever it changes (Turbo
9
+ # visits and morph refreshes too), and the module that defines the
10
+ # element. Put it once in the layout's <body>.
11
+ #
12
+ # <%= critiqs_tag %>
13
+ # <%= critiqs_tag(project_id: "j1…", backend: "https://…") %>
14
+ #
15
+ # project_id - The Critiqs project. Defaults to ENV["CRITIQS_PROJECT_ID"],
16
+ # read on each render.
17
+ # require_project_id - Show Critiqs only where project_id is set (default true).
18
+ # Where it's blank, the tag renders nothing at all. Pass
19
+ # false to show project setup when there's no ID.
20
+ # backend - A team's own Critiqs backend URL, when not Critiqs Cloud.
21
+ # version - The prototype's version, such as a release or commit,
22
+ # recorded with each message.
23
+ # screen - The screen threads on this page belong to. Defaults to
24
+ # the matched route's pattern, such as "users/:id", with
25
+ # its parameters as view state ("route.id" => "42").
26
+ # Pass false to let Critiqs use the URL path instead.
27
+ # html_options - Other attributes for <critiqs-app>, such as id.
28
+ #
29
+ # Both scripts get the request's CSP nonce when the app configures one;
30
+ # there's no inline script.
31
+ def critiqs_tag(project_id: ENV["CRITIQS_PROJECT_ID"], require_project_id: true, backend: nil, version: nil, screen: nil, **html_options)
32
+ project_id = project_id.presence
33
+ return "".html_safe if require_project_id && project_id.nil?
34
+
35
+ context = critiqs_route_context(screen)
36
+ attributes = html_options.merge(
37
+ "project-id" => project_id,
38
+ "backend" => backend.presence,
39
+ "version" => version.presence,
40
+ "require-project-id" => require_project_id ? "" : nil,
41
+ "data-critiqs-context" => context&.to_json,
42
+ ).compact
43
+ safe_join([
44
+ content_tag("critiqs-app", nil, attributes),
45
+ javascript_include_tag(CONTEXT_ASSET, ELEMENT_ASSET, type: "module", nonce: true),
46
+ ])
47
+ end
48
+
49
+ private
50
+
51
+ # What this page reports: the screen and the route's parameters as view
52
+ # state, following the critiqs package's routeContext. nil without a
53
+ # screen, so Critiqs falls back to the URL path.
54
+ def critiqs_route_context(screen)
55
+ return nil if screen == false
56
+
57
+ matched = respond_to?(:request) ? request : nil
58
+ screen ||= Critiqs::Rails.route_screen(matched&.route_uri_pattern)
59
+ return nil if screen.blank?
60
+
61
+ params = matched ? matched.path_parameters.except(:controller, :action, :format) : {}
62
+ # A repeated parameter (a glob, ":path*") keeps its segments apart, each one's own % escaped.
63
+ repeated = screen.to_s.scan(%r{(?:\A|/):([\w-]+)[*+](?=/|\z)}).flatten
64
+ view_state = params.to_h do |name, value|
65
+ value = value.to_s
66
+ value = value.split("/", -1).map { |segment| segment.gsub("%", "%25") }.join("/") if repeated.include?(name.to_s)
67
+ ["route.#{name}", value]
68
+ end
69
+ { screen: screen, viewState: view_state }
70
+ end
71
+ end
72
+
73
+ # A Rails route pattern in the critiqs package's screen form: "/users/:id(.:format)"
74
+ # becomes "users/:id", an optional parameter "(/:page)" becomes ":page?", a
75
+ # glob "*path" becomes ":path*", and the root route is "/". nil without a
76
+ # pattern, or when the critiqs package's routePath couldn't build the
77
+ # page's path back from the screen, so Critiqs uses the URL path there:
78
+ # another optional part, such as "(/page/:page)" (no screen gives both
79
+ # /posts and /posts/page/2), or a parameter inside a segment, such as
80
+ # "release-:version" (routePath fills in only whole segments).
81
+ def self.route_screen(pattern)
82
+ return nil if pattern.blank?
83
+
84
+ path = pattern.delete_suffix("(.:format)")
85
+ .gsub(%r{\((/?):(\w+)\)}, '\1:\2?')
86
+ .gsub(%r{\((/?)\*(\w+)\)}, '\1*\2')
87
+ .gsub(/\*(\w+)/, ':\1*')
88
+ return nil if path.match?(/[()]/)
89
+ return nil unless path.split("/").all? { |segment| !segment.match?(/[:*]/) || segment.match?(/\A:\w+[?*]?\z/) }
90
+
91
+ path = path.gsub(%r{\A/+|/+\z}, "")
92
+ path.empty? ? "/" : path
93
+ end
94
+ end
95
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Critiqs
6
+ module Rails
7
+ VERSION = JSON.parse(File.read(File.expand_path("../../../package.json", __dir__))).fetch("version")
8
+ end
9
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "critiqs/rails/version"
4
+ require "critiqs/rails/engine"
5
+
6
+ module Critiqs
7
+ module Rails
8
+ # The browser bundle's logical path in the asset pipeline.
9
+ ELEMENT_ASSET = "critiqs/element.js"
10
+ # The gem's own module that reports each page's context to the element.
11
+ CONTEXT_ASSET = "critiqs/context.js"
12
+ end
13
+ end
@@ -0,0 +1,3 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "critiqs/rails"
@@ -0,0 +1,218 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler"
4
+ require "prism"
5
+ require "rails/generators"
6
+
7
+ module Critiqs
8
+ module Generators
9
+ # bin/rails generate critiqs:install
10
+ class InstallGenerator < ::Rails::Generators::Base
11
+ LAYOUT = "app/views/layouts/application.html.erb"
12
+ GEM = "critiqs-rails"
13
+ TAG = "<%= critiqs_tag %>"
14
+ # ERB as Rails's Erubi reads it: a tag runs from <% to the first %>,
15
+ # whatever the Ruby inside says. <%# is a comment and <%% writes <%.
16
+ ERB_TAG = /<%(={1,2}|-|\#|%)?(.*?)[-=]?%>/m
17
+
18
+ desc "Adds <%= critiqs_tag %> to #{LAYOUT}, just before </body>."
19
+
20
+ def add_tag
21
+ if (problem = gem_problem)
22
+ @refused = true
23
+ say_status :skip, "#{problem} Production would fail on pages calling critiqs_tag, so #{LAYOUT} wasn't changed. " \
24
+ "Declare gem \"critiqs-rails\" at the top level of the Gemfile, outside any group or condition, with no platforms or require: false, " \
25
+ "run bundle install, then run this generator again.", :red
26
+ return
27
+ end
28
+ if (view = view_with_tag)
29
+ say_status :identical, "#{view} already has critiqs_tag", :blue
30
+ return
31
+ end
32
+ path = File.join(destination_root, LAYOUT)
33
+ unless File.exist?(path)
34
+ say_status :skip, "#{LAYOUT} not found. Add #{TAG} just before </body> in your layout.", :yellow
35
+ return
36
+ end
37
+ source = File.read(path)
38
+ if source.gsub(ERB_TAG, "").include?("<%")
39
+ say_status :skip, "#{LAYOUT} has an ERB tag (<%) that never closes. Add #{TAG} just before </body>.", :yellow
40
+ return
41
+ end
42
+ tags = erb_tags(source)
43
+ closings = markup_only(source, tags).to_enum(:scan, %r{</body\s*>}i).map { Regexp.last_match.begin(0) }
44
+ unless closings.size == 1
45
+ say_status :skip, "#{LAYOUT} has #{closings.size} </body> tags outside ERB code, comments and scripts. Add #{TAG} just before the right one.", :yellow
46
+ return
47
+ end
48
+ File.binwrite(path, insertion(source, closings.first)) unless options[:pretend]
49
+ say_status :insert, LAYOUT
50
+ end
51
+
52
+ def next_steps
53
+ return if @refused
54
+
55
+ say ""
56
+ say "Critiqs appears where CRITIQS_PROJECT_ID is set to your project's ID, and nowhere else."
57
+ say "Set it in each environment that should show Critiqs, then restart the server."
58
+ end
59
+
60
+ private
61
+
62
+ # Bundler's DSL, also noting where each critiqs-rails declaration is
63
+ # (file and line) and whether an install_if wraps it, which Bundler
64
+ # reduces to whether this computer meets it now.
65
+ class GemfileReader < ::Bundler::Dsl
66
+ attr_reader :declaration
67
+
68
+ def install_if(*)
69
+ @install_ifs = (@install_ifs || 0) + 1
70
+ super
71
+ ensure
72
+ @install_ifs -= 1
73
+ end
74
+
75
+ def gem(name, *args)
76
+ if name == GEM
77
+ options = args.last.is_a?(Hash) ? args.last : {}
78
+ location = caller_locations(1, 1).first
79
+ install_if = (@install_ifs || 0).positive? || options.key?(:install_if) || options.key?("install_if")
80
+ @declaration = { path: location.path, line: location.lineno, install_if: install_if }
81
+ end
82
+ super
83
+ end
84
+ end
85
+
86
+ # Code around a gem declaration that decides whether it runs, or a block
87
+ # Bundler scopes it to; `group` blocks are judged from Bundler's result.
88
+ CONDITIONS = {
89
+ Prism::IfNode => "under an if", Prism::UnlessNode => "under an unless", Prism::CaseNode => "in a case",
90
+ Prism::CaseMatchNode => "in a case", Prism::WhileNode => "in a while", Prism::UntilNode => "in an until",
91
+ Prism::AndNode => "after an and", Prism::OrNode => "after an or", Prism::RescueNode => "in a rescue",
92
+ Prism::DefNode => "inside a method", Prism::LambdaNode => "inside a lambda",
93
+ }.freeze
94
+ UNSCOPED_BLOCKS = %i[source git github path group].freeze
95
+
96
+ # Why the declaration at `path`:`line` might not run in production, read
97
+ # from its file with Prism, or nil.
98
+ def condition_around(path, line)
99
+ result = Prism.parse_file(path)
100
+ where = "#{File.basename(path)}:#{line}"
101
+ return "in code setup can't parse (#{where})" unless result.success?
102
+
103
+ ancestors = declaration_ancestors(result.value, line, [])
104
+ return "in a way setup can't find in #{where}" if ancestors.nil?
105
+
106
+ ancestors.reverse_each do |node|
107
+ condition = CONDITIONS.find { |type, _| node.is_a?(type) }&.last
108
+ condition ||= "inside `#{node.name}`" if node.is_a?(Prism::CallNode) && !UNSCOPED_BLOCKS.include?(node.name)
109
+ return "#{condition} (#{where})" if condition
110
+ end
111
+ nil
112
+ end
113
+
114
+ # The nodes around the `gem "critiqs-rails"` call on `line`, outermost first, or nil.
115
+ def declaration_ancestors(node, line, ancestors)
116
+ if node.is_a?(Prism::CallNode) && node.name == :gem && node.receiver.nil? && node.location.start_line == line &&
117
+ node.arguments&.arguments&.first.then { _1.is_a?(Prism::StringNode) && _1.unescaped == GEM }
118
+ return ancestors
119
+ end
120
+
121
+ ancestors.push(node)
122
+ node.compact_child_nodes.each do |child|
123
+ found = declaration_ancestors(child, line, ancestors)
124
+ return found if found
125
+ end
126
+ ancestors.pop
127
+ nil
128
+ end
129
+
130
+ # The ERB tags in a template.
131
+ def erb_tags(source) = source.to_enum(:scan, ERB_TAG).map { Regexp.last_match }
132
+
133
+ # The first view under app/views (layouts and the partials they render
134
+ # among them) that already calls critiqs_tag outside comments, relative
135
+ # to the app, or nil.
136
+ def view_with_tag
137
+ views = Dir.glob("app/views/**/*.{erb,haml,slim}", base: destination_root).sort
138
+ views.find do |view|
139
+ source = File.read(File.join(destination_root, view))
140
+ if view.end_with?(".erb")
141
+ erb_tags(source).any? { |tag| !["#", "%"].include?(tag[1]) && tag[2].match?(/\bcritiqs_tag\b/) }
142
+ else
143
+ source.each_line.any? { |line| line.match?(/\bcritiqs_tag\b/) && !line.match?(%r{\A\s*(?:-#|/)}) }
144
+ end
145
+ end
146
+ end
147
+
148
+ # Why production might not load critiqs_tag, read from the app's Gemfile
149
+ # the way Bundler reads it, or nil. Production apps usually install
150
+ # without the development and test groups (BUNDLE_WITHOUT), and Rails
151
+ # requires only the default group's gems that don't say require: false.
152
+ def gem_problem
153
+ gemfile = %w[Gemfile gems.rb].map { File.join(destination_root, _1) }.find { File.exist?(_1) }
154
+ return "There's no Gemfile in #{destination_root}." unless gemfile
155
+
156
+ dsl = GemfileReader.new
157
+ dsl.eval_gemfile(gemfile)
158
+ gem = dsl.dependencies.find { _1.name == GEM }
159
+ name = File.basename(gemfile)
160
+ if gem.nil?
161
+ "#{name} doesn't declare critiqs-rails."
162
+ elsif !gem.groups.include?(:default)
163
+ "#{name} declares critiqs-rails only in the #{gem.groups.join(", ")} group#{"s" if gem.groups.size > 1}."
164
+ elsif gem.platforms.any?
165
+ "#{name} declares critiqs-rails only for the #{gem.platforms.join(", ")} platform#{"s" if gem.platforms.size > 1}."
166
+ elsif gem.autorequire == []
167
+ "#{name} declares critiqs-rails with require: false, so Rails doesn't load it."
168
+ elsif !gem.should_include?
169
+ "#{name} installs critiqs-rails only under a condition (install_if or env) this computer doesn't meet."
170
+ elsif gem.env
171
+ "#{name} declares critiqs-rails only where #{gem.env.inspect} is set in the environment (an env block)."
172
+ elsif dsl.declaration&.fetch(:install_if)
173
+ "#{name} installs critiqs-rails only under an install_if condition, which production might not meet."
174
+ elsif dsl.declaration.nil?
175
+ "Setup couldn't tell where #{name} declares critiqs-rails."
176
+ elsif (condition = condition_around(dsl.declaration[:path], dsl.declaration[:line]))
177
+ "#{name} declares critiqs-rails #{condition}, so production might not load it."
178
+ end
179
+ rescue ScriptError, StandardError => e
180
+ "Bundler couldn't read the Gemfile (#{e.message.lines.first.to_s.strip})."
181
+ end
182
+
183
+ # The layout with ERB tags, HTML comments, quoted attribute values and
184
+ # the contents of script, style, textarea and title blanked out, same
185
+ # length and lines, so what's left is the page's markup.
186
+ def markup_only(source, tags)
187
+ markup = source.dup
188
+ tags.each { |tag| markup[tag.begin(0)...tag.end(0)] = blank(tag[0]) }
189
+ markup.gsub(%r{<!--.*?(?:-->|\z)|(<(script|style|textarea|title)\b(?:"[^"]*"|'[^']*'|[^>"'])*>)(.*?)(?=</\2\s*>|\z)|<[a-z][^\s/>]*(?:"[^"]*"|'[^']*'|[^>"'])*>}mi) do
190
+ match = Regexp.last_match
191
+ if match[1] then blank_values(match[1]) + blank(match[3])
192
+ elsif match[0].start_with?("<!--") then blank(match[0])
193
+ else blank_values(match[0])
194
+ end
195
+ end
196
+ end
197
+
198
+ def blank(text) = text.gsub(/[^\r\n]/, " ")
199
+
200
+ def blank_values(tag) = tag.gsub(/"[^"]*"|'[^']*'/) { |value| value[0] + blank(value[1...-1]) + value[0] }
201
+
202
+ # The tag on its own line before the </body> at `at`, indented like the
203
+ # body's other children, or right before it when it shares a line with
204
+ # markup.
205
+ def insertion(source, at)
206
+ line_start = at.zero? ? 0 : (source.rindex("\n", at - 1) || -1) + 1
207
+ indent = source[line_start...at]
208
+ return source.dup.insert(at, TAG) unless indent.match?(/\A[ \t]*\z/)
209
+
210
+ before = source[0...line_start].split(/\r?\n/).reverse.find { |line| !line.strip.empty? }.to_s
211
+ previous = before[/\A[ \t]*/]
212
+ child = previous.length > indent.length ? previous : "#{indent}#{indent.include?("\t") ? "\t" : " "}"
213
+ newline = source.include?("\r\n") ? "\r\n" : "\n"
214
+ "#{source[0...line_start]}#{child}#{TAG}#{newline}#{source[line_start..]}"
215
+ end
216
+ end
217
+ end
218
+ end
data/package.json ADDED
@@ -0,0 +1,14 @@
1
+ {
2
+ "name": "critiqs-rails",
3
+ "private": true,
4
+ "version": "0.4.0",
5
+ "description": "Workspace marker for the critiqs-rails Ruby gem: carries its version in the shared release group and its scripts.",
6
+ "critiqsRelease": {
7
+ "registry": "rubygems"
8
+ },
9
+ "scripts": {
10
+ "test": "bun scripts/gem.ts test",
11
+ "release:build": "bun scripts/gem.ts build",
12
+ "check:consumer": "bun scripts/check-consumer.ts"
13
+ }
14
+ }
metadata ADDED
@@ -0,0 +1,84 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: critiqs-rails
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.4.0
5
+ platform: ruby
6
+ authors:
7
+ - Noah Jung
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: railties
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '7.1'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - ">="
24
+ - !ruby/object:Gem::Version
25
+ version: '7.1'
26
+ - !ruby/object:Gem::Dependency
27
+ name: actionview
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: '7.1'
33
+ type: :runtime
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: '7.1'
40
+ description: Adds Critiqs to a Rails app's pages with one view helper, critiqs_tag,
41
+ and serves Critiqs's browser bundle through the app's asset pipeline (Propshaft
42
+ or Sprockets).
43
+ executables: []
44
+ extensions: []
45
+ extra_rdoc_files: []
46
+ files:
47
+ - LICENSE
48
+ - README.md
49
+ - app/assets/javascripts/critiqs/context.js
50
+ - app/assets/javascripts/critiqs/element.js
51
+ - lib/critiqs-rails.rb
52
+ - lib/critiqs/rails.rb
53
+ - lib/critiqs/rails/engine.rb
54
+ - lib/critiqs/rails/helper.rb
55
+ - lib/critiqs/rails/version.rb
56
+ - lib/generators/critiqs/install/install_generator.rb
57
+ - package.json
58
+ homepage: https://github.com/noahsjung/critiqs/tree/main/packages/rails#readme
59
+ licenses:
60
+ - MIT
61
+ metadata:
62
+ homepage_uri: https://github.com/noahsjung/critiqs/tree/main/packages/rails#readme
63
+ source_code_uri: https://github.com/noahsjung/critiqs/tree/main/packages/rails
64
+ bug_tracker_uri: https://github.com/noahsjung/critiqs/issues
65
+ rubygems_mfa_required: 'true'
66
+ rdoc_options: []
67
+ require_paths:
68
+ - lib
69
+ required_ruby_version: !ruby/object:Gem::Requirement
70
+ requirements:
71
+ - - ">="
72
+ - !ruby/object:Gem::Version
73
+ version: '3.3'
74
+ required_rubygems_version: !ruby/object:Gem::Requirement
75
+ requirements:
76
+ - - ">="
77
+ - !ruby/object:Gem::Version
78
+ version: '0'
79
+ requirements: []
80
+ rubygems_version: 3.6.9
81
+ specification_version: 4
82
+ summary: 'Critiqs for Ruby on Rails apps: comment on an interactive prototype, discuss
83
+ feedback, and find its context.'
84
+ test_files: []