twitter-bootstrap-rails 5.5.0 → 5.6.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.
Files changed (36) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +64 -0
  3. data/README.md +115 -4
  4. data/lib/generators/bootstrap/agent/agent_generator.rb +17 -0
  5. data/lib/generators/bootstrap/agent/templates/guide.md.erb +34 -2
  6. data/lib/generators/bootstrap/bootstrap5_markup.rb +22 -0
  7. data/lib/generators/bootstrap/cdn/cdn_generator.rb +32 -2
  8. data/lib/generators/bootstrap/cdn_tags.rb +11 -0
  9. data/lib/generators/bootstrap/doctor/doctor_generator.rb +12 -2
  10. data/lib/generators/bootstrap/install/install_generator.rb +77 -21
  11. data/lib/generators/bootstrap/layout/layout_generator.rb +15 -0
  12. data/lib/generators/bootstrap/layout/templates/layout.html.erb +4 -1
  13. data/lib/generators/bootstrap/layout/templates/layout.html.haml +4 -1
  14. data/lib/generators/bootstrap/layout/templates/layout.html.slim +4 -1
  15. data/lib/generators/bootstrap/nes/nes_generator.rb +101 -0
  16. data/lib/generators/bootstrap/snippets/snippet_base.rb +4 -0
  17. data/lib/generators/bootstrap/stimulus/stimulus_generator.rb +49 -0
  18. data/lib/generators/bootstrap/stimulus/templates/bootstrap_controller.js.tt +67 -0
  19. data/lib/generators/bootstrap/themed/themed_generator.rb +4 -0
  20. data/lib/twitter/bootstrap/rails/config.rb +17 -4
  21. data/lib/twitter/bootstrap/rails/doctor.rb +161 -11
  22. data/lib/twitter/bootstrap/rails/v6_migration.rb +156 -0
  23. data/lib/twitter/bootstrap/rails/version.rb +33 -1
  24. data/spec/lib/generators/agent_generator_spec.rb +9 -0
  25. data/spec/lib/generators/cdn_generator_spec.rb +31 -0
  26. data/spec/lib/generators/doctor_generator_spec.rb +108 -0
  27. data/spec/lib/generators/install_generator_spec.rb +51 -1
  28. data/spec/lib/generators/layout_generator_spec.rb +24 -0
  29. data/spec/lib/generators/nes_generator_spec.rb +164 -0
  30. data/spec/lib/generators/no_hardcoded_versions_spec.rb +3 -1
  31. data/spec/lib/generators/stimulus_generator_spec.rb +65 -0
  32. data/spec/lib/twitter_bootstrap_rails/v6_migration_spec.rb +98 -0
  33. data/spec/support/generator_spec_helper.rb +2 -0
  34. data/vendor/assets/javascripts/twitter/bootstrap/bootstrap.esm.min.js +7 -0
  35. data/vendor/assets/javascripts/twitter/bootstrap/popper.esm.js +15 -0
  36. metadata +31 -10
@@ -2,11 +2,13 @@ require 'rails/generators'
2
2
  require 'twitter/bootstrap/rails/version'
3
3
  require 'twitter/bootstrap/rails/config'
4
4
  require 'generators/bootstrap/cdn_tags'
5
+ require 'generators/bootstrap/bootstrap5_markup'
5
6
 
6
7
  module Bootstrap
7
8
  module Generators
8
9
  class LayoutGenerator < ::Rails::Generators::Base
9
10
  include CdnTags
11
+ include Bootstrap5Markup
10
12
 
11
13
  source_root File.expand_path("../templates", __FILE__)
12
14
  desc "This generator generates a Bootstrap #{Twitter::Bootstrap::Rails::BOOTSTRAP_VERSION} layout file with navigation."
@@ -29,6 +31,7 @@ module Bootstrap
29
31
  end
30
32
 
31
33
  def generate_layout
34
+ warn_if_nes
32
35
  app = ::Rails.application
33
36
  @app_name = app.class.to_s.split("::").first
34
37
  ext = app.config.generators.options[:rails][:template_engine] || :erb
@@ -43,6 +46,18 @@ module Bootstrap
43
46
  Twitter::Bootstrap::Rails.cdn?
44
47
  end
45
48
 
49
+ # Rails 7+ apps load their own JavaScript (Turbo, Stimulus) through the
50
+ # importmap. A layout without these tags silently drops all of it.
51
+ def importmap_app?
52
+ File.exist?(File.join(destination_root, "config/importmap.rb"))
53
+ end
54
+
55
+ # In importmap mode Bootstrap's JavaScript is imported from application.js,
56
+ # so the layout links no script of its own for it.
57
+ def bootstrap_script?
58
+ cdn? || !Twitter::Bootstrap::Rails.importmap?
59
+ end
60
+
46
61
  def separate_popper?
47
62
  options[:'separate-popper'] && cdn?
48
63
  end
@@ -11,6 +11,9 @@
11
11
  <% else -%>
12
12
 
13
13
  <%%= stylesheet_link_tag <%= stylesheet_arguments %>, :media => "all" %>
14
+ <% end -%>
15
+ <% if importmap_app? -%>
16
+ <%%= javascript_importmap_tags %>
14
17
  <% end -%>
15
18
  </head>
16
19
  <body>
@@ -40,7 +43,7 @@
40
43
 
41
44
  <% if cdn? -%>
42
45
  <%= indent_tags(script_tags, " ") %>
43
- <% else -%>
46
+ <% elsif bootstrap_script? -%>
44
47
  <%%= javascript_include_tag <%= javascript_arguments %> %>
45
48
  <% end -%>
46
49
  </body>
@@ -10,6 +10,9 @@
10
10
  <% else -%>
11
11
  = stylesheet_link_tag <%= stylesheet_arguments %>, :media => "all"
12
12
  <% end -%>
13
+ <% if importmap_app? -%>
14
+ = javascript_importmap_tags
15
+ <% end -%>
13
16
 
14
17
  %body
15
18
  %nav.navbar.navbar-expand-lg.navbar-dark.bg-primary
@@ -30,6 +33,6 @@
30
33
 
31
34
  <% if cdn? -%>
32
35
  <%= indent_tags(script_tags, " ") %>
33
- <% else -%>
36
+ <% elsif bootstrap_script? -%>
34
37
  = javascript_include_tag <%= javascript_arguments %>
35
38
  <% end -%>
@@ -10,6 +10,9 @@ html lang="en"
10
10
  <% else -%>
11
11
  = stylesheet_link_tag <%= stylesheet_arguments %>, :media => "all"
12
12
  <% end -%>
13
+ <% if importmap_app? -%>
14
+ = javascript_importmap_tags
15
+ <% end -%>
13
16
 
14
17
  body
15
18
  nav.navbar.navbar-expand-lg.navbar-dark.bg-primary
@@ -30,6 +33,6 @@ html lang="en"
30
33
 
31
34
  <% if cdn? -%>
32
35
  <%= slim_tags(script_tags, " ") %>
33
- <% else -%>
36
+ <% elsif bootstrap_script? -%>
34
37
  = javascript_include_tag <%= javascript_arguments %>
35
38
  <% end -%>
@@ -0,0 +1,101 @@
1
+ require 'json'
2
+ require 'rails/generators'
3
+ require 'twitter/bootstrap/rails/version'
4
+
5
+ module Bootstrap
6
+ module Generators
7
+ # Points an npm-based app (jsbundling-rails / cssbundling-rails) at HeroDevs
8
+ # Bootstrap NES 4.6: security-patched Bootstrap 4 for apps that can't move to 5
9
+ # yet. NES is a paid product from a private registry, so nothing is vendored.
10
+ # The access token stays in an environment variable and never touches a file.
11
+ # Never prompts, so agents and CI can run it.
12
+ class NesGenerator < ::Rails::Generators::Base
13
+ NES = Twitter::Bootstrap::Rails::BOOTSTRAP_NES
14
+ PACKAGE_JSON = "package.json".freeze
15
+ NPMRC = ".npmrc".freeze
16
+
17
+ desc "Sets up HeroDevs Bootstrap NES #{NES[:bootstrap_version]} (paid, security-patched Bootstrap 4.6) through npm"
18
+
19
+ class_option :'token-env', :type => :string, :default => NES[:token_env],
20
+ :desc => 'Environment variable that holds the HeroDevs access token'
21
+
22
+ def require_package_json
23
+ return if File.exist?(app_path(PACKAGE_JSON))
24
+
25
+ raise ::Rails::Generators::Error,
26
+ "Bootstrap NES is installed with npm, but #{PACKAGE_JSON} does not exist. Set up jsbundling-rails or " \
27
+ "cssbundling-rails first (`bin/rails javascript:install:esbuild` or `css:install:bootstrap`)."
28
+ end
29
+
30
+ def update_package_json
31
+ json = JSON.parse(File.read(app_path(PACKAGE_JSON)))
32
+ (json["dependencies"] ||= {})["bootstrap"] = alias_spec
33
+ # The override makes packages that depend on bootstrap get NES too.
34
+ (json["overrides"] ||= {})["bootstrap"] = { "." => alias_spec }
35
+
36
+ create_file PACKAGE_JSON, JSON.pretty_generate(json) + "\n", :force => true
37
+ end
38
+
39
+ def update_npmrc
40
+ lines = File.exist?(app_path(NPMRC)) ? File.read(app_path(NPMRC)).lines.map(&:chomp) : []
41
+ lines << scope_line unless lines.any? { |line| line.start_with?("@neverendingsupport:registry=") }
42
+ lines << auth_line unless lines.any? { |line| line.start_with?("#{registry_key}:_authToken=") }
43
+
44
+ create_file NPMRC, lines.join("\n") + "\n", :force => true
45
+ end
46
+
47
+ def add_initializer
48
+ create_file "config/initializers/bootstrap.rb", <<~RUBY, :force => true
49
+ # Bootstrap comes from #{NES[:name]} #{NES[:bootstrap_version]} through npm
50
+ # (package.json and .npmrc). `rails g bootstrap:doctor` checks that setup, and the
51
+ # gem's generators warn that they write Bootstrap 5 markup.
52
+ Twitter::Bootstrap::Rails.asset_mode = :nes
53
+ RUBY
54
+ end
55
+
56
+ def next_steps
57
+ say <<~TEXT
58
+
59
+ #{NES[:name]} #{NES[:bootstrap_version]} is set up in #{PACKAGE_JSON} and #{NPMRC}. Next:
60
+
61
+ 1. Get an access token from HeroDevs (a paid NES subscription; see #{NES[:docs]}).
62
+ 2. Export it where npm runs, locally and in CI: export #{token_env}=...
63
+ #{NPMRC} reads it from that variable, so don't commit the token.
64
+ 3. Run `npm install` (or yarn / bun).
65
+ 4. Bootstrap 4's JavaScript needs jQuery; the bundle includes Popper 1. Import
66
+ jQuery before Bootstrap in your JavaScript entry point.
67
+
68
+ This gem's layout, themed and snippet generators and its view helpers write
69
+ Bootstrap 5 markup, which doesn't work on Bootstrap 4. Run `rails g bootstrap:doctor`
70
+ to check the NES setup, and `rails g bootstrap:agent` so coding agents know.
71
+ TEXT
72
+ end
73
+
74
+ private
75
+
76
+ def alias_spec
77
+ "npm:#{NES[:package]}@#{NES[:version]}"
78
+ end
79
+
80
+ def registry_key
81
+ NES[:registry].sub(%r{\Ahttps?:}, "")
82
+ end
83
+
84
+ def scope_line
85
+ "@neverendingsupport:registry=#{NES[:registry]}"
86
+ end
87
+
88
+ def auth_line
89
+ "#{registry_key}:_authToken=${#{token_env}}"
90
+ end
91
+
92
+ def token_env
93
+ options[:'token-env']
94
+ end
95
+
96
+ def app_path(relative)
97
+ File.join(destination_root, relative)
98
+ end
99
+ end
100
+ end
101
+ end
@@ -2,6 +2,7 @@ require 'json'
2
2
  require 'rails/generators'
3
3
  require 'twitter/bootstrap/rails/version'
4
4
  require 'generators/bootstrap/snippets/snippet_catalog'
5
+ require 'generators/bootstrap/bootstrap5_markup'
5
6
 
6
7
  module Bootstrap
7
8
  module Generators
@@ -9,6 +10,8 @@ module Bootstrap
9
10
  # bootstrap:hero, ...). Each subclass only declares which docs category it
10
11
  # serves; everything else lives here.
11
12
  class SnippetBase < ::Rails::Generators::Base
13
+ include Bootstrap5Markup
14
+
12
15
  ICONS_PARTIAL = 'bootstrap_icons'.freeze
13
16
 
14
17
  argument :requested_variant, :type => :string, :required => false,
@@ -53,6 +56,7 @@ module Bootstrap
53
56
  def copy_snippet
54
57
  return if listing?
55
58
 
59
+ warn_if_nes
56
60
  copy_file "#{category}/#{variant_name}.html.erb", partial_path
57
61
  end
58
62
 
@@ -0,0 +1,49 @@
1
+ require 'rails/generators'
2
+
3
+ module Bootstrap
4
+ module Generators
5
+ # Writes a Stimulus controller that sets up Bootstrap's tooltips and popovers
6
+ # when Turbo renders a page, and closes open components before Turbo caches
7
+ # it, so a cached page doesn't come back with a stuck modal or tooltip.
8
+ class StimulusGenerator < ::Rails::Generators::Base
9
+ CONTROLLERS = "app/javascript/controllers".freeze
10
+ IMPORTMAP = "config/importmap.rb".freeze
11
+
12
+ source_root File.expand_path("../templates", __FILE__)
13
+ desc "Writes a Stimulus controller that keeps Bootstrap's JavaScript working with Turbo"
14
+
15
+ def require_stimulus
16
+ return if File.directory?(File.join(destination_root, CONTROLLERS))
17
+
18
+ raise ::Rails::Generators::Error,
19
+ "#{CONTROLLERS} does not exist. Install Stimulus first (`bundle add stimulus-rails && bin/rails stimulus:install`)."
20
+ end
21
+
22
+ def write_controller
23
+ template "bootstrap_controller.js.tt", "#{CONTROLLERS}/bootstrap_controller.js"
24
+ end
25
+
26
+ def explain
27
+ say %(Add data-controller="bootstrap" to <body> in your layout, so it covers every page.)
28
+ return unless manual_registration?
29
+
30
+ say "Your controllers are registered by hand. Run `bin/rails stimulus:manifest:update`, " \
31
+ "or register BootstrapController in #{CONTROLLERS}/index.js."
32
+ end
33
+
34
+ private
35
+
36
+ # Importmap apps import the ES module build; everything else gets the
37
+ # global that the bundle (vendored or CDN) defines.
38
+ def import_bootstrap?
39
+ path = File.join(destination_root, IMPORTMAP)
40
+ File.exist?(path) && File.read(path).match?(/^\s*pin\s+["']bootstrap["']/)
41
+ end
42
+
43
+ def manual_registration?
44
+ index = File.join(destination_root, CONTROLLERS, "index.js")
45
+ File.exist?(index) && File.read(index).include?("application.register(")
46
+ end
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,67 @@
1
+ import { Controller } from "@hotwired/stimulus"
2
+ <% if import_bootstrap? -%>
3
+ import * as bootstrap from "bootstrap"
4
+ <% end -%>
5
+
6
+ // Generated by twitter-bootstrap-rails (rails g bootstrap:stimulus).
7
+ //
8
+ // Attach it once, to <body>: <body data-controller="bootstrap">
9
+ //
10
+ // Bootstrap's data attributes (data-bs-toggle="modal", "dropdown", "collapse")
11
+ // keep working on their own. Tooltips and popovers are opt-in, so this sets them
12
+ // up on every Turbo render and disposes of them afterwards. Before Turbo caches
13
+ // a page it also closes open modals, offcanvases and dropdowns, so going back
14
+ // doesn't restore a page with a backdrop stuck over it.
15
+ export default class extends Controller {
16
+ connect() {
17
+ this.beforeCache = this.beforeCache.bind(this)
18
+ document.addEventListener("turbo:before-cache", this.beforeCache)
19
+ this.setUp()
20
+ }
21
+
22
+ disconnect() {
23
+ document.removeEventListener("turbo:before-cache", this.beforeCache)
24
+ this.tearDown()
25
+ }
26
+
27
+ setUp() {
28
+ const bs = this.bootstrap
29
+ if (!bs) return
30
+
31
+ this.element.querySelectorAll('[data-bs-toggle="tooltip"]').forEach((el) => bs.Tooltip.getOrCreateInstance(el))
32
+ this.element.querySelectorAll('[data-bs-toggle="popover"]').forEach((el) => bs.Popover.getOrCreateInstance(el))
33
+ }
34
+
35
+ tearDown() {
36
+ const bs = this.bootstrap
37
+ if (!bs) return
38
+
39
+ this.element.querySelectorAll('[data-bs-toggle="tooltip"]').forEach((el) => bs.Tooltip.getInstance(el)?.dispose())
40
+ this.element.querySelectorAll('[data-bs-toggle="popover"]').forEach((el) => bs.Popover.getInstance(el)?.dispose())
41
+ }
42
+
43
+ beforeCache() {
44
+ const bs = this.bootstrap
45
+ if (bs) {
46
+ document.querySelectorAll(".modal.show").forEach((el) => bs.Modal.getInstance(el)?.dispose())
47
+ document.querySelectorAll(".offcanvas.show").forEach((el) => bs.Offcanvas.getInstance(el)?.dispose())
48
+ document.querySelectorAll('[data-bs-toggle="dropdown"]').forEach((el) => bs.Dropdown.getInstance(el)?.hide())
49
+ }
50
+ this.tearDown()
51
+
52
+ // dispose() skips the hide transition, so clear what it would have removed.
53
+ document.querySelectorAll(".modal.show, .offcanvas.show").forEach((el) => el.classList.remove("show"))
54
+ document.querySelectorAll(".modal-backdrop, .offcanvas-backdrop").forEach((el) => el.remove())
55
+ document.body.classList.remove("modal-open")
56
+ document.body.style.removeProperty("overflow")
57
+ document.body.style.removeProperty("padding-right")
58
+ }
59
+
60
+ get bootstrap() {
61
+ <% if import_bootstrap? -%>
62
+ return bootstrap
63
+ <% else -%>
64
+ return window.bootstrap
65
+ <% end -%>
66
+ }
67
+ }
@@ -1,9 +1,12 @@
1
1
  require 'rails/generators'
2
2
  require 'rails/generators/generated_attribute'
3
+ require 'generators/bootstrap/bootstrap5_markup'
3
4
 
4
5
  module Bootstrap
5
6
  module Generators
6
7
  class ThemedGenerator < ::Rails::Generators::Base
8
+ include Bootstrap5Markup
9
+
7
10
  source_root File.expand_path('../templates', __FILE__)
8
11
  argument :controller_path, :type => :string
9
12
  argument :model_name, :type => :string, :required => false
@@ -18,6 +21,7 @@ module Bootstrap
18
21
  end
19
22
 
20
23
  def copy_views
24
+ warn_if_nes
21
25
  generate_views
22
26
  end
23
27
 
@@ -4,10 +4,15 @@ module Twitter
4
4
  module Bootstrap
5
5
  module Rails
6
6
  # How the host app loads Bootstrap's assets. `rails g bootstrap:install cdn`
7
- # writes an initializer setting this to :cdn; `bootstrap:layout` reads it to
8
- # pick its default. Defaults to :static so the layout generator works whether
9
- # or not that initializer exists.
10
- VALID_ASSET_MODES = [:static, :cdn].freeze
7
+ # (or importmap) and `rails g bootstrap:nes` write an initializer setting
8
+ # this; `bootstrap:layout` reads it to pick its default. Defaults to :static
9
+ # so the layout generator works whether or not that initializer exists.
10
+ #
11
+ # :static vendored files, linked through the asset pipeline
12
+ # :cdn jsDelivr tags with Subresource Integrity
13
+ # :importmap vendored stylesheet, ES modules pinned in config/importmap.rb
14
+ # :nes HeroDevs Bootstrap NES 4.6 from its private npm registry
15
+ VALID_ASSET_MODES = [:static, :cdn, :importmap, :nes].freeze
11
16
 
12
17
  @asset_mode = :static
13
18
 
@@ -27,6 +32,14 @@ module Twitter
27
32
  asset_mode == :cdn
28
33
  end
29
34
 
35
+ def importmap?
36
+ asset_mode == :importmap
37
+ end
38
+
39
+ def nes?
40
+ asset_mode == :nes
41
+ end
42
+
30
43
  # Which asset pipeline the host app runs. Propshaft (the Rails 8 default)
31
44
  # has no Sprockets directives: a `//= require` line in a manifest is an
32
45
  # inert comment there, so assets have to be linked explicitly instead.
@@ -1,6 +1,8 @@
1
+ require 'json'
1
2
  require 'twitter/bootstrap/rails/version'
2
3
  require 'twitter/bootstrap/rails/config'
3
4
  require 'twitter/bootstrap/rails/legacy_markup'
5
+ require 'twitter/bootstrap/rails/v6_migration'
4
6
 
5
7
  module Twitter
6
8
  module Bootstrap
@@ -14,24 +16,40 @@ module Twitter
14
16
  SCANNED_EXTENSIONS = %w[.erb .haml .slim .rb].freeze
15
17
  PLACEHOLDER_IMAGES = ["bootstrap-docs.png", "bootstrap-themes.png", "/docs/5.3/assets/", "unsplash-photo-"].freeze
16
18
  SEVERITY = %w[ok warn error].freeze
19
+ IMPORTMAP = "config/importmap.rb".freeze
20
+ APPLICATION_JS = "app/javascript/application.js".freeze
21
+ # What `--v6` scans on top of views and helpers. The gem's own vendored
22
+ # Bootstrap files are skipped: replacing them is the first migration step.
23
+ V6_EXTRA_FILES = "app/{javascript,assets/javascripts,assets/stylesheets}/**/*".freeze
24
+ V6_EXTENSIONS = %w[.js .mjs .ts .css .scss .sass].freeze
25
+ VENDORED_DIR = %r{/twitter/bootstrap/}
17
26
 
18
27
  def initialize(root)
19
28
  @root = root
20
29
  end
21
30
 
22
- def report
23
- checks = [css_check, js_check, version_check, sprite_check, placeholder_check, legacy_check]
24
-
25
- facts.merge(
31
+ # v6: true adds a v6_migration check and list for apps moving to Bootstrap 6.
32
+ def report(v6: false)
33
+ checks = if nes?
34
+ [nes_package_check, nes_registry_check, importmap_tags_check]
35
+ else
36
+ [css_check, js_check, importmap_tags_check, version_check]
37
+ end
38
+ checks += [sprite_check, placeholder_check, legacy_check]
39
+ checks << v6_check if v6
40
+
41
+ result = facts.merge(
26
42
  :status => checks.map { |c| c[:status] }.max_by { |s| SEVERITY.index(s) },
27
43
  :checks => checks,
28
44
  :legacy_markup => legacy_markup
29
45
  )
46
+ v6 ? result.merge(:v6_migration => v6_migration) : result
30
47
  end
31
48
 
32
49
  def facts
33
50
  {
34
- :bootstrap_version => BOOTSTRAP_VERSION,
51
+ :bootstrap_version => nes? ? BOOTSTRAP_NES[:bootstrap_version] : BOOTSTRAP_VERSION,
52
+ :bootstrap_distribution => nes? ? BOOTSTRAP_NES[:name] : "Bootstrap",
35
53
  :gem_version => VERSION,
36
54
  :rails_version => ::Rails.version,
37
55
  :asset_pipeline => pipeline.to_s,
@@ -42,14 +60,19 @@ module Twitter
42
60
 
43
61
  private
44
62
 
63
+ def nes?
64
+ asset_mode == "nes"
65
+ end
66
+
45
67
  def pipeline
46
68
  Twitter::Bootstrap::Rails.asset_pipeline
47
69
  end
48
70
 
49
71
  def asset_mode
50
- initializer = read("config/initializers/bootstrap.rb")
51
- cdn = initializer.match?(/asset_mode\s*=\s*:cdn/) || layouts.match?(%r{cdn\.jsdelivr\.net/npm/bootstrap@})
52
- cdn ? "cdn" : "static"
72
+ @asset_mode ||= begin
73
+ recorded = read("config/initializers/bootstrap.rb")[/asset_mode\s*=\s*:(\w+)/, 1]
74
+ recorded || (layouts.match?(%r{cdn\.jsdelivr\.net/npm/bootstrap@}) ? "cdn" : "static")
75
+ end
53
76
  end
54
77
 
55
78
  def template_engine
@@ -68,6 +91,8 @@ module Twitter
68
91
  end
69
92
 
70
93
  def js_check
94
+ return importmap_js_check if asset_mode == "importmap"
95
+
71
96
  asset_check("bootstrap_js", "JavaScript",
72
97
  :cdn => %r{bootstrap@[\d.]+/dist/js/bootstrap},
73
98
  :vendored_name => "twitter/bootstrap/bootstrap.bundle.min",
@@ -96,6 +121,96 @@ module Twitter
96
121
  "or link it from your own layout (`rails g bootstrap:cdn` prints the tags).")
97
122
  end
98
123
 
124
+ def importmap_js_check
125
+ pinned = read(IMPORTMAP).match?(/^\s*pin\s+["']bootstrap["']/)
126
+ unless pinned
127
+ return check("bootstrap_js", "error", "#{IMPORTMAP} does not pin \"bootstrap\", so `import \"bootstrap\"` fails in the browser.",
128
+ "Run `rails g bootstrap:install importmap`.")
129
+ end
130
+
131
+ vendored = read(IMPORTMAP)[/^\s*pin\s+["']bootstrap["']\s*,\s*to:\s*["']([^"']+)["']/, 1]
132
+ if vendored && !vendored.start_with?("http") && !exist?(File.join("vendor/javascript", vendored))
133
+ return check("bootstrap_js", "error", "#{IMPORTMAP} pins bootstrap to vendor/javascript/#{vendored}, which does not exist.",
134
+ "Run `rails g bootstrap:install importmap`.")
135
+ end
136
+
137
+ unless javascript_sources.match?(/^\s*import\s+(?:\*\s+as\s+\w+\s+from\s+|\{[^}]*\}\s+from\s+)?["']bootstrap["']/)
138
+ return check("bootstrap_js", "error", "Bootstrap is pinned, but nothing in app/javascript imports it, so it never runs.",
139
+ "Add `import \"bootstrap\"` to #{APPLICATION_JS}.")
140
+ end
141
+
142
+ check("bootstrap_js", "ok", "Bootstrap JavaScript is pinned in the importmap and imported.")
143
+ end
144
+
145
+ def nes_package_check
146
+ json = package_json
147
+ spec = json.dig("dependencies", "bootstrap").to_s
148
+ prefix = "npm:#{BOOTSTRAP_NES[:package]}@"
149
+
150
+ unless spec.start_with?(prefix)
151
+ return check("nes_package", "error",
152
+ "This app is set to NES mode, but package.json's bootstrap dependency is #{spec.empty? ? 'missing' : spec.inspect}, not the NES package.",
153
+ "Run `rails g bootstrap:nes`.")
154
+ end
155
+
156
+ version = spec.delete_prefix(prefix)
157
+ if version != BOOTSTRAP_NES[:version]
158
+ return check("nes_package", "warn",
159
+ "package.json uses #{BOOTSTRAP_NES[:name]} #{version}; the latest this gem knows is #{BOOTSTRAP_NES[:version]}.",
160
+ "Run `rails g bootstrap:nes`, then `npm install`.")
161
+ end
162
+
163
+ unless json.dig("overrides", "bootstrap")
164
+ return check("nes_package", "warn", "package.json has no override for bootstrap, so a dependency could still pull in an unpatched Bootstrap.",
165
+ "Run `rails g bootstrap:nes`.")
166
+ end
167
+
168
+ check("nes_package", "ok", "package.json uses #{BOOTSTRAP_NES[:name]} #{version}, with an override.")
169
+ end
170
+
171
+ def nes_registry_check
172
+ npmrc = read(".npmrc")
173
+ registry = BOOTSTRAP_NES[:registry]
174
+ unless npmrc.include?("@neverendingsupport:registry=#{registry}")
175
+ return check("nes_registry", "error", ".npmrc doesn't point @neverendingsupport at #{registry}, so npm can't find the NES package.",
176
+ "Run `rails g bootstrap:nes`.")
177
+ end
178
+
179
+ auth = npmrc[/^#{Regexp.escape(registry.sub(/\Ahttps?:/, ''))}:_authToken=(.*)$/, 1]
180
+ if auth.nil?
181
+ return check("nes_registry", "error", ".npmrc has no access token line for the NES registry.",
182
+ "Run `rails g bootstrap:nes`, then export #{BOOTSTRAP_NES[:token_env]}.")
183
+ end
184
+
185
+ unless auth.strip.match?(/\A\$\{\w+\}\z/)
186
+ # Never echo the value: it is a credential.
187
+ return check("nes_registry", "warn", ".npmrc contains the NES access token itself, which leaks it if the file is committed.",
188
+ "Replace it with ${#{BOOTSTRAP_NES[:token_env]}} and set that environment variable instead.")
189
+ end
190
+
191
+ check("nes_registry", "ok", ".npmrc reads the NES access token from #{auth.strip}.")
192
+ end
193
+
194
+ def package_json
195
+ JSON.parse(read("package.json"))
196
+ rescue JSON::ParserError
197
+ {}
198
+ end
199
+
200
+ def importmap_tags_check
201
+ return check("importmap_tags", "ok", "The app does not use importmap.") unless exist?(IMPORTMAP)
202
+ return check("importmap_tags", "ok", "A layout loads the importmap.") if layouts.include?("javascript_importmap_tags")
203
+
204
+ check("importmap_tags", "warn",
205
+ "#{IMPORTMAP} exists, but no layout calls javascript_importmap_tags, so the app's own JavaScript " \
206
+ "(Turbo, Stimulus, an imported Bootstrap) never loads.",
207
+ "Add <%= javascript_importmap_tags %> to the <head> of your layout, or re-run `rails g bootstrap:layout`.")
208
+ end
209
+
210
+ def javascript_sources
211
+ relative_files("app/javascript/**/*", %w[.js .mjs]).map { |file| read(file) }.join("\n")
212
+ end
213
+
99
214
  def linked_through_pipeline?(source)
100
215
  propshaft_link = layouts.include?(source[:vendored_name])
101
216
  sprockets_link = layouts.match?(source[:layout_tag]) && read(source[:manifest]).match?(source[:manifest_entry])
@@ -112,7 +227,7 @@ module Twitter
112
227
  end
113
228
 
114
229
  def version_check
115
- found = layouts.scan(/bootstrap@(\d+\.\d+\.\d+)/).flatten
230
+ found = layouts.scan(/bootstrap@(\d+\.\d+\.\d+(?:-[\w.]+)?)/).flatten
116
231
  [VENDORED_CSS, VENDORED_JS].each do |file|
117
232
  found.concat(read(file)[0, 400].to_s.scan(/Bootstrap\s+v(\d+\.\d+\.\d+)/).flatten)
118
233
  end
@@ -120,6 +235,12 @@ module Twitter
120
235
 
121
236
  return check("bootstrap_version", "ok", "No Bootstrap version other than #{BOOTSTRAP_VERSION} found.") if stale.empty?
122
237
 
238
+ if stale.any? { |version| version.start_with?("6.") }
239
+ return check("bootstrap_version", "warn",
240
+ "Found Bootstrap #{stale.join(', ')}. This gem ships #{BOOTSTRAP_VERSION}, and its generators and helpers write Bootstrap 5 markup.",
241
+ "Run `rails g bootstrap:doctor --v6` for the Bootstrap 5 markup to migrate.")
242
+ end
243
+
123
244
  check("bootstrap_version", "warn",
124
245
  "Found Bootstrap #{stale.join(', ')}, but this gem ships #{BOOTSTRAP_VERSION}.",
125
246
  "Run `rails g bootstrap:install static --force` or update the CDN tags with `rails g bootstrap:cdn`.")
@@ -156,6 +277,11 @@ module Twitter
156
277
  end
157
278
 
158
279
  def legacy_check
280
+ if nes?
281
+ return check("legacy_markup", "ok",
282
+ "Skipped: this app runs Bootstrap #{BOOTSTRAP_NES[:bootstrap_version]} (NES), where Bootstrap 4 markup is correct.")
283
+ end
284
+
159
285
  count = legacy_markup.size
160
286
  return check("legacy_markup", "ok", "No older Bootstrap markup found.") if count.zero?
161
287
 
@@ -164,11 +290,35 @@ module Twitter
164
290
  end
165
291
 
166
292
  def legacy_markup
293
+ return [] if nes?
294
+
167
295
  @legacy_markup ||= scanned_files.flat_map do |file|
168
296
  LegacyMarkup.scan(read(file), File.extname(file)).map { |finding| { :file => file }.merge(finding) }
169
297
  end
170
298
  end
171
299
 
300
+ def v6_check
301
+ count = v6_migration.size
302
+ return check("v6_migration", "ok", "Nothing found that changes in Bootstrap 6.") if count.zero?
303
+
304
+ check("v6_migration", "warn",
305
+ "#{count} use(s) of Bootstrap 5 markup, Sass or JavaScript that change in Bootstrap 6, listed in v6_migration. " \
306
+ "This gem still ships Bootstrap #{BOOTSTRAP_VERSION}, so only change them as part of moving the app to Bootstrap 6.",
307
+ "Install the upstream migration skill (`#{V6Migration::SKILL_COMMAND}`) and follow it, " \
308
+ "or read #{V6Migration::GUIDE_URL}. Switch the Bootstrap assets first.")
309
+ end
310
+
311
+ def v6_migration
312
+ @v6_migration ||= v6_files.flat_map do |file|
313
+ V6Migration.scan(read(file), File.extname(file)).map { |finding| { :file => file }.merge(finding) }
314
+ end
315
+ end
316
+
317
+ def v6_files
318
+ extra = relative_files(V6_EXTRA_FILES, V6_EXTENSIONS).reject { |file| file.match?(VENDORED_DIR) }
319
+ (scanned_files + extra).uniq.sort
320
+ end
321
+
172
322
  def check(id, status, message, fix = nil)
173
323
  result = { :id => id, :status => status, :message => message }
174
324
  result[:fix] = fix if fix
@@ -187,9 +337,9 @@ module Twitter
187
337
  relative_files("app/{views,helpers,components}/**/*")
188
338
  end
189
339
 
190
- def relative_files(pattern)
340
+ def relative_files(pattern, extensions = SCANNED_EXTENSIONS)
191
341
  Dir[File.join(@root, pattern)]
192
- .select { |file| File.file?(file) && SCANNED_EXTENSIONS.include?(File.extname(file)) }
342
+ .select { |file| File.file?(file) && extensions.include?(File.extname(file)) }
193
343
  .map { |file| file.delete_prefix("#{@root}/") }
194
344
  .sort
195
345
  end