super-slim 3.0.0 → 3.1.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 7c27c1a3bdc54556d0e0418a316838423719f9a0da47bba2be27b4a2812498c7
4
- data.tar.gz: d5a779c6fa56691f985b3a82516769118dcb17a883eacfc6bbbe23b6afb14da0
3
+ metadata.gz: 4e7f0253bc3700761d1b9a6bf57e24b51766356d4e1e761cfe60961d5c612cf9
4
+ data.tar.gz: 82d037bf08dfcf4ddf1ad0a9f0f10a874c29835e1e6b485cb4f8e7a735effcf8
5
5
  SHA512:
6
- metadata.gz: 0d5e8d990ae3886c94cbd198f1ccfbf51722e121cf2529bfc239da0b52b6639aaf9dec2609396eef4ab43f938d9d15d0f1913085c79b23704c8373e17bac4269
7
- data.tar.gz: e7eef329f3c7adef4ba9b7f53e697a35e8aec0501c72304517c590ade320641555ec7167cf6f0ff1fa8f693fe22b45bb99da3a69e6808afcc13cdfa630a5123f
6
+ metadata.gz: 00fb7c76fae6fe6d7c53e5f56dc8650d90b0b88f9c1776810fd22128e86a07299abf45185de83d8f3cfc8c6f8ae92a8d00d037520b4c180f508d6f4d6c856a9e
7
+ data.tar.gz: cc96f26b0a002aec9005bb54ce6703c77b7ce291128e1f67668a29f8e31391929802eca7cbc4ad22adb2d41a0c492eca3a457dedbf14c564c377d53a01c70d19
data/CHANGELOG.md CHANGED
@@ -2,6 +2,26 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [3.1.0] — 2026-11-06
6
+
7
+ A Bootstrap 5 preset for the linter, Ruby code that continues after an open bracket, and a faster formatter.
8
+
9
+ **New**
10
+ - `preset: bootstrap5` on DeprecatedClasses and DeprecatedAttributes: the Bootstrap 4 classes and component data
11
+ attributes Bootstrap 5.3 renamed, breakpoints included (`text-md-right`). The rule's own entries go over it, and
12
+ `~` drops one of the preset.
13
+ - A `(`, `[` or `{` that ends a line of code (`-`, `=`, `tag =`) continues it until the bracket closes, one argument
14
+ per line; Slim refused these lines.
15
+
16
+ **Faster**
17
+ - `super-slim format` takes 3.5 s instead of 4.6 s on 7,500 templates at 120 columns.
18
+
19
+ **Fixed**
20
+ - `super-slim format` no longer refuses a trailing comma or call parentheses, and no longer takes `link_to(a) + b`
21
+ for `link_to (a) + b`.
22
+ - In DeprecatedClasses, the longest prefix wins: `badge-promo-*` over `badge-*`.
23
+ - An empty `classes:` or `attributes:` no longer crashes the linter, and an unknown preset exits 64 with its name.
24
+
5
25
  ## [3.0.0] — 2026-11-05
6
26
 
7
27
  SuperSlim is published as super-slim, the name of its command.
@@ -49,14 +69,14 @@ Two fixes to `super-slim`: braces around wrapped attributes, and `--help`.
49
69
 
50
70
  ## [2.0.0] — 2026-11-05
51
71
 
52
- SlimX becomes SuperSlim, sheds what a Rails app doesn't need, and `super-slim fmt` wraps long lines.
72
+ The gem takes the name SuperSlim, sheds what a Rails app doesn't need, and `super-slim fmt` wraps long lines.
53
73
 
54
74
  **Breaking**
55
75
  - The gem is renamed: `super_slim` in the Gemfile, the `SuperSlim` module, the `super-slim lint|fmt` command,
56
76
  `.super-slim.yml` and `plugins: [super_slim]` for RuboCop. Compiled templates name their variables
57
- `_super_slim1` instead of `_slimx1`.
58
- - No more Tilt adapter: `require "slimx/tilt"` has no replacement. Rails and `SuperSlim.compile` are unchanged.
59
- - No more strict mode (`SlimX.strict`, `strict: true`): run `super-slim fmt --check` in CI instead.
77
+ `_super_slim1`, after the new name.
78
+ - No more Tilt adapter: its `require` has no replacement. Rails and `SuperSlim.compile` are unchanged.
79
+ - No more strict mode (`strict: true`): run `super-slim fmt --check` in CI instead.
60
80
  - No more custom shortcuts: only `#id` and `.class`.
61
81
  - Only `doctype 5`, `doctype html` and `doctype xml` remain; HTML 4 and XHTML doctypes, such as
62
82
  `doctype transitional`, raise `Invalid doctype`.
@@ -69,10 +89,10 @@ SlimX becomes SuperSlim, sheds what a Rails app doesn't need, and `super-slim fm
69
89
 
70
90
  ## [1.1.0] — 2026-11-04
71
91
 
72
- A RuboCop plugin that lints the Ruby inside templates with SlimX's own parser, and templates compiled up to 10% faster.
92
+ A RuboCop plugin that lints the Ruby inside templates with SuperSlim's own parser, and templates compiled up to 10% faster.
73
93
 
74
94
  **New**
75
- - A RuboCop plugin (`plugins: [slimx]`) lints the Ruby of templates: `-` and `=` lines, code attributes, splats,
95
+ - A RuboCop plugin (`plugins: [super-slim]`) lints the Ruby of templates: `-` and `=` lines, code attributes, splats,
76
96
  `#{}` interpolations and `ruby:` blocks. Offenses point at their line and column in the `.slim` file, and
77
97
  autocorrection writes back into it. It replaces rubocop-slim, and with it slimi and Temple; unlike slimi, it
78
98
  also reads the output of a tag with whitespace markers and attributes (`span> title="x" = name`).
@@ -82,7 +102,7 @@ A RuboCop plugin that lints the Ruby inside templates with SlimX's own parser, a
82
102
  public templates, Ruby 3.3 and 4.0). Rendering is unchanged.
83
103
 
84
104
  **Fixed**
85
- - `slimx lint` reports the offenses of one line in the same order on every Ruby version.
105
+ - `super-slim lint` reports the offenses of one line in the same order on every Ruby version.
86
106
 
87
107
  ## [1.0.0] — 2026-11-04
88
108
 
@@ -91,12 +111,12 @@ renders what Slim 5 renders with `format: :html, sort_attrs: false`, byte for by
91
111
  `.atom`) render as XML.
92
112
 
93
113
  **New**
94
- - Rails through a railtie, Tilt through `require "slimx/tilt"`, and `SlimX.compile` for plain Ruby.
114
+ - Rails through a railtie, Tilt through a `require`, and `SuperSlim.compile` for plain Ruby.
95
115
  - Every `-` and `=` stays on its template line, so backtraces point at the right one.
96
- - `slimx fmt`, which refuses any change to the compiled Ruby, and strict mode (`SlimX.strict`), which
116
+ - `super-slim fmt`, which refuses any change to the compiled Ruby, and strict mode, which
97
117
  refuses unformatted templates at compile time.
98
- - `slimx lint` with 29 rules from slim-lint, haml-lint, erb_lint, Herb and eslint-plugin-jsx-a11y,
99
- configured in `.slimx.yml`.
118
+ - `super-slim lint` with 29 rules from slim-lint, haml-lint, erb_lint, Herb and eslint-plugin-jsx-a11y,
119
+ configured in `.super-slim.yml`.
100
120
  - `tailwind_classes`, off by default: class shortcuts read Tailwind class names.
101
121
 
102
122
  **Left out**
@@ -108,11 +128,12 @@ renders what Slim 5 renders with `format: :html, sort_attrs: false`, byte for by
108
128
  - Ruby 3.3 or later, every Ruby still maintained, Rails 8.0 or 8.1 for the railtie, and strscan 3.1.1 or later,
109
129
  newer than the one Ruby 3.3 ships.
110
130
 
111
- [Unreleased]: https://github.com/levups/super-slim/compare/v3.0.0...HEAD
131
+ [Unreleased]: https://github.com/levups/super-slim/compare/v3.1.0...HEAD
132
+ [3.1.0]: https://github.com/levups/super-slim/compare/v3.0.0...v3.1.0
112
133
  [3.0.0]: https://github.com/levups/super-slim/compare/v2.2.0...v3.0.0
113
134
  [2.2.0]: https://github.com/levups/super-slim/compare/v2.1.0...v2.2.0
114
135
  [2.1.0]: https://github.com/levups/super-slim/compare/v2.0.1...v2.1.0
115
136
  [2.0.1]: https://github.com/levups/super-slim/compare/v2.0.0...v2.0.1
116
137
  [2.0.0]: https://github.com/levups/super-slim/compare/v1.1.0...v2.0.0
117
- [1.1.0]: https://github.com/next-gen-gems/slimx/compare/v1.0.0...v1.1.0
118
- [1.0.0]: https://github.com/next-gen-gems/slimx/releases/tag/v1.0.0
138
+ [1.1.0]: https://github.com/levups/super-slim/compare/v1.0.0...v1.1.0
139
+ [1.0.0]: https://github.com/levups/super-slim/releases/tag/v1.0.0
data/README.md CHANGED
@@ -30,6 +30,26 @@ markers, `|` and `'` text, inline HTML, `/` and `/!` comments, `-` control code,
30
30
  templates), and the `ruby:`, `javascript:`, `css:` and `markdown:` (through
31
31
  [Markly](https://github.com/ioquatix/markly)) embedded engines.
32
32
 
33
+ ## Ruby code over several lines
34
+
35
+ Slim continues a line of Ruby code after a comma or a backslash. SuperSlim also continues it after a `(`, `[` or `{`
36
+ that ends the line, until that bracket closes, so calls, arrays and hashes can open on one line and close on their
37
+ own:
38
+
39
+ ```slim
40
+ = render ProductCardComponent.new(
41
+ product:,
42
+ variant: :compact,
43
+ )
44
+ - columns = %w[
45
+ name
46
+ price
47
+ ]
48
+ ```
49
+
50
+ Slim refuses these lines, so no template that works with Slim changes. A bracket opened mid-line, as in
51
+ `- items.each { |item|`, still leaves the lines below it as children.
52
+
33
53
  ## Tailwind class names
34
54
 
35
55
  Slim cuts `.rounded-b-[3px]` at the bracket, and refuses `.lg:[&:nth-child(3)]:hover:underline`. Turn on
@@ -84,11 +104,13 @@ One parser serves the compiler, the formatter and the linter, so all three read
84
104
  `super-slim format [--check] [PATH…]` (or `fmt`) rewrites templates in their canonical layout: two spaces per level, `- code`,
85
105
  `= output` and `p = output` spacing, no redundant `div`, no trailing whitespace, single blank lines, one final
86
106
  newline. Text blocks move as a whole, so the whitespace they render stays put — and before writing anything,
87
- the formatter compiles both versions and refuses if the Ruby differs. Formatting cannot change a page.
107
+ the formatter compiles both versions and refuses unless Prism reads the same Ruby in both, positions aside: line
108
+ breaks, spaces, a trailing comma or the parentheses of a call may differ, nothing else. Formatting cannot change a
109
+ page.
88
110
 
89
111
  With `format: max_line_length: 120` in `.super-slim.yml`, `format` also wraps longer lines: a tag's attributes one
90
112
  per line inside `attribute_delimiters` (`"()"` by default, `"[]"` or `"{}"`), then the arguments of its Ruby code after each comma, four spaces deep when the line opens a block. It keeps a wrap only
91
- when the compiled Ruby differs by whitespace alone, and leaves lines already spread over several lines alone.
113
+ when Prism reads the same compiled Ruby, and leaves lines already spread over several lines alone.
92
114
 
93
115
  `super-slim lint [PATH…]` reads `.super-slim.yml` and checks, with about a third of the CPU time slim-lint takes:
94
116
 
@@ -100,7 +122,7 @@ when the compiled Ruby differs by whitespace alone, and leaves lines already spr
100
122
  | StrictLocals (partials declare `/# locals:`) | Rails 7.1 strict locals | off |
101
123
  | DuplicateId, ImageAlt, IframeTitle, AnchorHref, NestedLinks, PositiveTabindex, BooleanAttributeValue, AriaRole, AriaAttribute | Herb, eslint-plugin-jsx-a11y | on |
102
124
  | ButtonType, InlineStyles | eslint-plugin-react, haml-lint | off |
103
- | DeprecatedClasses (`classes: {old: new}`, `old-*: new-*` for a prefix), DeprecatedAttributes (`attributes: {old: new}`) | erb_lint | on, empty |
125
+ | DeprecatedClasses (`classes: {old: new}`, `old-*: new-*` for a prefix), DeprecatedAttributes (`attributes: {old: new}`), both with `preset: bootstrap5` | erb_lint | on, empty |
104
126
  | UnescapedOutput (`==`, `html_safe`, `raw`, `#{{}}`) | Brakeman, erb_lint | off |
105
127
  | EmbeddedEngines (`forbidden_engines: [javascript, css]`) | slim-lint | off |
106
128
  | HardcodedText (text to translate) | erb_lint | off |
@@ -115,9 +137,12 @@ linters:
115
137
  ButtonType:
116
138
  enabled: true
117
139
  DeprecatedClasses:
140
+ preset: bootstrap5 # Bootstrap 4 classes Bootstrap 5.3 renamed or dropped
118
141
  classes:
119
- text-muted: text-body-secondary
120
- ml-*: ms-*
142
+ media: ~ # drops an entry of the preset
143
+ legacy-*: modern-*
144
+ DeprecatedAttributes:
145
+ preset: bootstrap5 # data-toggle becomes data-bs-toggle, and so on
121
146
  InlineStyles:
122
147
  enabled: true
123
148
  exclude: ["app/views/*_mailer/**/*"]
@@ -126,6 +151,11 @@ linters:
126
151
  include: ["app/views/shop/**/*.slim"]
127
152
  ```
128
153
 
154
+ `preset: bootstrap5` lists the Bootstrap 4 classes and data attributes Bootstrap 5.3 renamed, breakpoints included
155
+ (`text-md-right`). Its data attributes are only those of Bootstrap's components (`data-toggle`, `data-target`…):
156
+ generic ones like `data-content` or `data-delay` go in `attributes:` if your app needs them, and `~` drops an entry of
157
+ the preset your own JavaScript reads.
158
+
129
159
  Every rule takes `include:` and `exclude:`, lists of globs matched against paths relative to `.super-slim.yml`
130
160
  (`**/` spans directories).
131
161
 
@@ -213,5 +243,5 @@ with the version's notes and the `.gem`.
213
243
 
214
244
  ## License
215
245
 
216
- MIT, by Level UP Solutions, part of [Next Gen Gems](https://github.com/next-gen-gems). The parser follows the
246
+ MIT, by [Level UP Solutions](https://github.com/levups). The parser follows the
217
247
  grammar and parsing algorithm of [Slim](https://github.com/slim-template/slim), by the Slim Team (MIT).
@@ -36,7 +36,11 @@ module SuperSlim
36
36
  private
37
37
 
38
38
  def lint(paths, configuration)
39
- linter = Linter.new(configuration.fetch("linters", {}))
39
+ begin
40
+ linter = Linter.new(configuration.fetch("linters", {}))
41
+ rescue Error => exception
42
+ return warn(exception.message) || EX_USAGE
43
+ end
40
44
  offenses = Parallel.map(templates(paths)) { |path| linter.call(path, File.read(path)) }.flatten
41
45
  offenses.each { |offense| puts "#{offense.path}:#{offense.lineno}: [#{offense.rule}] #{offense.message}" }
42
46
  offenses.empty? ? 0 : 1
@@ -1,7 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "ripper"
4
-
5
3
  module SuperSlim
6
4
  class Formatter
7
5
  # Breaks the lines of a formatted template longer than max_line_length: a tag's attributes one per line
@@ -10,10 +8,9 @@ module SuperSlim
10
8
  class LineWrapper
11
9
  CODE_LINE = /\A *(?:-|==?[<>]*) /
12
10
  TAG_OUTPUT = /\G\s*==?['<>]*\s*/
13
- OPENINGS = %i[on_lparen on_lbracket on_lbrace on_tlambeg on_embexpr_beg].freeze
14
- CLOSINGS = %i[on_rparen on_rbracket on_rbrace on_embexpr_end].freeze
15
11
  CONTINUATION_KINDS = %i[continuation text text_blank].freeze
16
- MODIFIERS = %w[if unless while until rescue].freeze
12
+ BLOCK_OPENINGS = %i[KEYWORD_DO KEYWORD_DO_LOOP].freeze
13
+ MODIFIERS = %i[KEYWORD_IF_MODIFIER KEYWORD_UNLESS_MODIFIER KEYWORD_WHILE_MODIFIER KEYWORD_UNTIL_MODIFIER KEYWORD_RESCUE_MODIFIER].freeze
17
14
 
18
15
  # Templates attach ( and [ to their tag but set { apart, as a Ruby block: 6,097 public templates agree.
19
16
  OPENING_BY_ATTRIBUTE_DELIMITERS = {"()" => "(", "[]" => "[", "{}" => " {"}.freeze
@@ -109,19 +106,17 @@ module SuperSlim
109
106
  def argument_breaks(code)
110
107
  depth = 0
111
108
  offsets = []
112
- Ripper.lex(code).each do |(_, column), type, token|
113
- case type
114
- when :on_heredoc_beg then return []
115
- when :on_kw
116
- break if token == "do"
117
- # RuboCop refuses a modifier that ends a statement spread over several lines (Style/MultilineIfModifier).
118
- return [] if depth.zero? && MODIFIERS.include?(token)
119
- when :on_op
120
- # `a, b = …` assigns several variables: its commas separate no arguments.
121
- return [] if depth.zero? && token == "=" && !offsets.empty?
122
- when :on_comma then offsets << column + 1 if depth.zero?
123
- when *OPENINGS then depth += 1
124
- when *CLOSINGS then depth -= 1
109
+ Prism.lex(code).value.each do |(token, _state)|
110
+ case token.type
111
+ when :COMMA then offsets << token.location.end_offset if depth.zero?
112
+ when :HEREDOC_START then return []
113
+ # `a, b = …` assigns several variables: its commas separate no arguments.
114
+ when :EQUAL then return [] if depth.zero? && !offsets.empty?
115
+ when *BLOCK_OPENINGS then break
116
+ # RuboCop refuses a modifier that ends a statement spread over several lines (Style/MultilineIfModifier).
117
+ when *MODIFIERS then return [] if depth.zero?
118
+ when *Parser::OPENING_BRACKETS then depth += 1
119
+ when *Parser::CLOSING_BRACKETS then depth -= 1
125
120
  end
126
121
  end
127
122
  offsets
@@ -5,13 +5,15 @@ require_relative "formatter/line_wrapper"
5
5
  module SuperSlim
6
6
  # Rewrites a template in its canonical layout. Text blocks shift as a whole, so the whitespace they render is
7
7
  # kept; and the formatted template must compile to the same Ruby as the original, or nothing is rewritten.
8
- # With max_line_length, longer lines are then wrapped, but only if the Ruby differs by nothing but whitespace.
8
+ # With max_line_length, longer lines are then wrapped, but only if Prism reads the same Ruby, positions aside.
9
9
  class Formatter
10
10
  INDENT_WIDTH = 2
11
11
  CONTROL = /\A-\s*/
12
12
  OUTPUT = /\A(==?)([<>]*)\s*/
13
13
  TAG_OUTPUT = /\A\s*(==?)(['<>]*)\s*/
14
14
  REDUNDANT_DIV = /\Adiv(?=[.#][\p{Word}-])/
15
+ NEWLINE_FLAG = defined?(Prism::NodeFlags::NEWLINE) ? Prism::NodeFlags::NEWLINE : 0
16
+ FIELDS_BY_NODE_CLASS = {}
15
17
 
16
18
  def self.call(source, **)
17
19
  new(**).call(source)
@@ -24,7 +26,8 @@ module SuperSlim
24
26
 
25
27
  def call(source)
26
28
  formatted = layout(source)
27
- unless formatted == source || compiled(formatted) == compiled(source)
29
+ formatted_ruby = compiled_ruby(formatted) unless formatted == source
30
+ if formatted_ruby && !same_ruby?(compiled_ruby(source), formatted_ruby)
28
31
  raise UnsafeFormattingError, "Formatting would change how this template renders"
29
32
  end
30
33
  return formatted unless @line_wrapper
@@ -32,8 +35,7 @@ module SuperSlim
32
35
  wrapped = @line_wrapper.call(formatted)
33
36
  return formatted if wrapped == formatted
34
37
 
35
- wrapped_tokens = ruby_tokens(wrapped)
36
- (wrapped_tokens && wrapped_tokens == ruby_tokens(formatted)) ? wrapped : formatted
38
+ same_ruby?(formatted_ruby || compiled_ruby(formatted), compiled_ruby(wrapped)) ? wrapped : formatted
37
39
  end
38
40
 
39
41
  private
@@ -99,27 +101,52 @@ module SuperSlim
99
101
  line.sub(/\A[ \t]*/) { _1.gsub(Parser::TAB, "\\1#{" " * Parser::TAB_SIZE}") }
100
102
  end
101
103
 
102
- def compiled(source)
103
- SuperSlim.compile(source, tailwind_classes: @tailwind_classes, format: :xml).gsub(/(?:\s*[;\n]\s*)+/, ";")
104
+ # Prism's tree of the compiled Ruby, or the error that stops it.
105
+ def compiled_ruby(source)
106
+ code = SuperSlim.compile(source, tailwind_classes: @tailwind_classes, format: :xml)
107
+ # Rails runs a template inside a method, where `yield` is valid.
108
+ parsed = Prism.parse("def template\n#{code}\nend")
109
+ parsed.success? ? parsed : code.gsub(/(?:\s*[;\n]\s*)+/, ";")
104
110
  rescue Error => exception
105
111
  exception.message
106
112
  end
107
113
 
108
- # Whitespace aside, wrapping only turns spaces into newlines that Ruby ignores after a comma, and newlines
109
- # that end statements into semicolons.
110
- def ruby_tokens(source)
111
- code = SuperSlim.compile(source, tailwind_classes: @tailwind_classes, format: :xml)
112
- tokens = Ripper.lex(code).flat_map do |_, type, token|
113
- case type
114
- when :on_sp, :on_ignored_nl then []
115
- when :on_nl, :on_semicolon then [";"]
116
- when :on_comment then [token.strip, ";"]
117
- else [token]
118
- end
114
+ # Positions aside: line breaks, spaces, a trailing comma and the parentheses of a call change nothing, a
115
+ # different value or operator does.
116
+ def same_ruby?(ruby, other_ruby)
117
+ return ruby == other_ruby if ruby.is_a?(String) || other_ruby.is_a?(String)
118
+
119
+ same_node?(ruby.value, other_ruby.value) && comment_texts(ruby) == comment_texts(other_ruby)
120
+ end
121
+
122
+ def same_node?(node, other_node)
123
+ return false unless node.instance_of?(other_node.class)
124
+
125
+ field_names, flags = node_fields(node)
126
+ return false if flags && (node.send(:flags) & ~NEWLINE_FLAG) != (other_node.send(:flags) & ~NEWLINE_FLAG)
127
+
128
+ field_names.all? { |name| same_field?(node.public_send(name), other_node.public_send(name)) }
129
+ end
130
+
131
+ def same_field?(value, other_value)
132
+ case value
133
+ when Prism::Node then other_value.is_a?(Prism::Node) && same_node?(value, other_value)
134
+ when Array then other_value.is_a?(Array) && value.size == other_value.size && value.each_index.all? { same_field?(value[_1], other_value[_1]) }
135
+ else value == other_value
119
136
  end
120
- tokens.chunk_while { |previous, token| previous == ";" && token == ";" }.map(&:first)
121
- rescue Error
122
- nil
137
+ end
138
+
139
+ # Prism 0.19 (Ruby 3.3) has no reflection API: the field names come from the first node of each class. Prism
140
+ # 1.x keeps flags out of deconstruct_keys, and counts in them whether a node starts a line.
141
+ def node_fields(node)
142
+ FIELDS_BY_NODE_CLASS[node.class] ||= [
143
+ node.deconstruct_keys(nil).keys.reject { |key| key == :node_id || key == :flags || key == :location || key.end_with?("_loc") },
144
+ node.respond_to?(:flags, true)
145
+ ]
146
+ end
147
+
148
+ def comment_texts(ruby)
149
+ ruby.comments.map { |comment| comment.location.slice.strip }
123
150
  end
124
151
  end
125
152
  end
@@ -0,0 +1,72 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SuperSlim
4
+ class Linter
5
+ # Bootstrap 4 classes and data attributes that Bootstrap 5.3 renamed, keyed by rule then by option.
6
+ PRESETS = {
7
+ "bootstrap5" => {
8
+ "DeprecatedClasses" => {
9
+ classes: {
10
+ "badge-pill" => "rounded-pill",
11
+ "badge-*" => "text-bg-*",
12
+ "border-left*" => "border-start*",
13
+ "border-right*" => "border-end*",
14
+ "btn-block" => "w-100",
15
+ "card-deck" => "row",
16
+ "close" => "btn-close",
17
+ "custom-checkbox" => "form-check",
18
+ "custom-control" => "form-check",
19
+ "custom-control-inline" => "form-check-inline",
20
+ "custom-control-input" => "form-check-input",
21
+ "custom-control-label" => "form-check-label",
22
+ "custom-file" => "form-control",
23
+ "custom-radio" => "form-check",
24
+ "custom-range" => "form-range",
25
+ "custom-select" => "form-select",
26
+ "custom-select-lg" => "form-select-lg",
27
+ "custom-select-sm" => "form-select-sm",
28
+ "custom-switch" => "form-switch",
29
+ "embed-responsive" => "ratio",
30
+ "embed-responsive-1by1" => "ratio-1x1",
31
+ "embed-responsive-4by3" => "ratio-4x3",
32
+ "embed-responsive-16by9" => "ratio-16x9",
33
+ "embed-responsive-21by9" => "ratio-21x9",
34
+ "font-italic" => "fst-italic",
35
+ "font-weight-*" => "fw-*",
36
+ "form-control-file" => "form-control",
37
+ "form-group" => "mb-3",
38
+ "form-inline" => "d-flex",
39
+ "form-row" => "row",
40
+ "jumbotron" => "p-5",
41
+ "media" => "d-flex",
42
+ "media-body" => "flex-grow-1",
43
+ "ml-*" => "ms-*",
44
+ "mr-*" => "me-*",
45
+ "no-gutters" => "g-0",
46
+ "pl-*" => "ps-*",
47
+ "pr-*" => "pe-*",
48
+ "pre-scrollable" => "overflow-y-scroll",
49
+ "rounded-left*" => "rounded-start*",
50
+ "rounded-lg" => "rounded-3",
51
+ "rounded-right*" => "rounded-end*",
52
+ "rounded-sm" => "rounded-1",
53
+ "sr-only" => "visually-hidden",
54
+ "sr-only-focusable" => "visually-hidden-focusable",
55
+ "text-monospace" => "font-monospace",
56
+ "text-muted" => "text-body-secondary",
57
+ "thead-dark" => "table-dark",
58
+ "thead-light" => "table-light",
59
+ **%w[float text dropdown-menu].product(["", "-sm", "-md", "-lg", "-xl"]).flat_map do |utility, breakpoint|
60
+ [["#{utility}#{breakpoint}-left", "#{utility}#{breakpoint}-start"], ["#{utility}#{breakpoint}-right", "#{utility}#{breakpoint}-end"]]
61
+ end.to_h
62
+ }.freeze
63
+ },
64
+ "DeprecatedAttributes" => {
65
+ # Generic names Bootstrap also renamed (`data-content`, `data-delay`, `data-template`…) stay out: apps read them too.
66
+ attributes: %w[backdrop boundary dismiss interval keyboard parent pause placement ride slide slide-to spy target
67
+ toggle trigger wrap].to_h { ["data-#{_1}", "data-bs-#{_1}"] }.freeze
68
+ }
69
+ }.freeze
70
+ }.freeze
71
+ end
72
+ end
@@ -402,13 +402,14 @@ module SuperSlim
402
402
  # A key ending in `*` matches every class with that prefix, and carries the rest over: `ml-*: ms-*`.
403
403
  def initialize(options)
404
404
  super
405
- prefixed, exact = options[:classes].partition { |deprecated,| deprecated.end_with?("*") }
405
+ prefixed, exact = Hash(options[:classes]).partition { |deprecated,| deprecated.end_with?("*") }
406
406
  @replacement_by_class = exact.to_h
407
- @prefixed_replacements = prefixed.map { |deprecated, replacement| [deprecated.delete_suffix("*"), replacement] }
407
+ # The longest prefix wins: `badge-light-*` over `badge-*`.
408
+ @prefixed_replacements = prefixed.map { |deprecated, replacement| [deprecated.delete_suffix("*"), replacement] }.sort_by { -_1.first.size }
408
409
  end
409
410
 
410
411
  def offenses(document, _source)
411
- return [] if options[:classes].empty?
412
+ return [] if @replacement_by_class.empty? && @prefixed_replacements.empty?
412
413
 
413
414
  enum_for(:each_tag, document).flat_map do |tag,|
414
415
  literal_attributes(tag, "class").flat_map { literal_value(_1).split }.filter_map do |css_class|
@@ -432,15 +433,19 @@ module SuperSlim
432
433
  class DeprecatedAttributes < Rule
433
434
  DEFAULTS = {enabled: true, attributes: {}}.freeze
434
435
 
436
+ def initialize(options)
437
+ super
438
+ @replacement_by_attribute = Hash(options[:attributes])
439
+ end
440
+
435
441
  def offenses(document, _source)
436
- replacement_by_attribute = options[:attributes]
437
- return [] if replacement_by_attribute.empty?
442
+ return [] if @replacement_by_attribute.empty?
438
443
 
439
444
  enum_for(:each_tag, document).flat_map do |tag,|
440
445
  attribute_names(tag).filter_map do |name|
441
- next unless replacement_by_attribute.key?(name)
446
+ next unless (replacement = @replacement_by_attribute[name])
442
447
 
443
- offense(document, document.line_of(tag), "`#{name}` is deprecated: use `#{replacement_by_attribute[name]}`")
448
+ offense(document, document.line_of(tag), "`#{name}` is deprecated: use `#{replacement}`")
444
449
  end
445
450
  end
446
451
  end
@@ -58,6 +58,7 @@ module SuperSlim
58
58
  @root = File.join(File.expand_path(root), "")
59
59
  @rules = Rules.all.filter_map do |rule_class|
60
60
  options = rule_class::DEFAULTS.merge(options_by_rule_name.fetch(rule_class.rule_name, {}).transform_keys(&:to_sym))
61
+ options = with_preset(rule_class.rule_name, options) if options[:preset]
61
62
  rule_class.new(options) if options[:enabled]
62
63
  end
63
64
  end
@@ -75,7 +76,21 @@ module SuperSlim
75
76
  rescue SyntaxError => exception
76
77
  [Offense.new(path, exception.lineno, "Syntax", exception.error)]
77
78
  end
79
+
80
+ private
81
+
82
+ # The preset's table goes under the rule's own entries, where `~` drops one of the preset.
83
+ def with_preset(rule_name, options)
84
+ preset_options = PRESETS.dig(options[:preset], rule_name)
85
+ unless preset_options
86
+ presets = PRESETS.filter_map { |preset, options_by_rule| preset if options_by_rule.key?(rule_name) }
87
+ raise Error, "#{rule_name}: unknown preset `#{options[:preset]}`, use one of: #{presets.join(", ")}"
88
+ end
89
+
90
+ options.merge(preset_options.to_h { |key, entries| [key, entries.merge(Hash(options[key])).compact] })
91
+ end
78
92
  end
79
93
  end
80
94
 
95
+ require_relative "linter/presets"
81
96
  require_relative "linter/rules"
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "prism"
3
4
  require "strscan"
4
5
 
5
6
  module SuperSlim
@@ -30,6 +31,11 @@ module SuperSlim
30
31
  # At the scanner, the rest of the line is only this character; on a whole line, the line ends with it.
31
32
  LINE_CONTINUATION = /[,\\]\z/
32
33
  BACKSLASH_AT_END = /\\\z/
34
+ OPENING_BRACKET_AT_LINE_END = /[(\[{]$/
35
+ OPENING_BRACKETS = %i[PARENTHESIS_LEFT PARENTHESIS_LEFT_PARENTHESES BRACKET_LEFT BRACKET_LEFT_ARRAY BRACE_LEFT LAMBDA_BEGIN EMBEXPR_BEGIN].freeze
36
+ CLOSING_BRACKETS = %i[PARENTHESIS_RIGHT BRACKET_RIGHT BRACE_RIGHT EMBEXPR_END].freeze
37
+ PERCENT_LISTS = %i[PERCENT_LOWER_W PERCENT_UPPER_W PERCENT_LOWER_I PERCENT_UPPER_I].freeze
38
+ LINE_ENDS = %i[NEWLINE IGNORED_NEWLINE EOF COMMENT].freeze
33
39
  WHITESPACE_MARKERS = /[<>']*/
34
40
  TEXT_LINE_INDICATOR = /([|'])([<>]{1,2}(?: |\z)| ?)/
35
41
  HTML_COMMENT = /\/!( ?)/
@@ -359,7 +365,7 @@ module SuperSlim
359
365
  first = source_offset + @scanner.rest[/\A\s*/].size if @outline
360
366
  broken_line = @scanner.rest
361
367
  broken_line.strip!
362
- while broken_line.match?(LINE_CONTINUATION)
368
+ while broken_line.match?(LINE_CONTINUATION) || (broken_line.match?(OPENING_BRACKET_AT_LINE_END) && bracket_open_at_line_end?(broken_line))
363
369
  expect_next_line
364
370
  broken_line << "\n" << @scanner.string
365
371
  end
@@ -367,6 +373,25 @@ module SuperSlim
367
373
  broken_line
368
374
  end
369
375
 
376
+ # A bracket that ends its line and is still open continues the code on the next lines, until it closes. A
377
+ # bracket opened mid-line, as in `items.each { |item|`, doesn't: Slim reads the lines below it as children.
378
+ def bracket_open_at_line_end?(code)
379
+ tokens = Prism.lex(code).value
380
+ open_brackets = []
381
+ tokens.each_with_index do |(token, _state), index|
382
+ type = token.type
383
+ if OPENING_BRACKETS.include?(type) || PERCENT_LISTS.include?(type)
384
+ following = tokens[index + 1]&.first
385
+ # In %w[ and %i[, the line break after the bracket is a word separator.
386
+ at_line_end = LINE_ENDS.include?(following&.type) || (following&.type == :WORDS_SEP && following.value.start_with?("\n"))
387
+ open_brackets << [type, at_line_end]
388
+ elsif CLOSING_BRACKETS.include?(type) || (type == :STRING_END && PERCENT_LISTS.include?(open_brackets.last&.first))
389
+ open_brackets.pop
390
+ end
391
+ end
392
+ open_brackets.any? { |(_type, at_line_end)| at_line_end }
393
+ end
394
+
370
395
  def parse_tag(tag)
371
396
  tag_lineno = @lineno
372
397
  tag = Shortcuts::DEFAULT_TAG if Shortcuts::ATTRIBUTE_BY_SHORTCUT.key?(tag)
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module SuperSlim
4
- VERSION = "3.0.0"
4
+ VERSION = "3.1.0"
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: super-slim
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.0.0
4
+ version: 3.1.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Level UP Solutions
@@ -46,6 +46,7 @@ files:
46
46
  - lib/super_slim/formatter.rb
47
47
  - lib/super_slim/formatter/line_wrapper.rb
48
48
  - lib/super_slim/linter.rb
49
+ - lib/super_slim/linter/presets.rb
49
50
  - lib/super_slim/linter/rules.rb
50
51
  - lib/super_slim/parallel.rb
51
52
  - lib/super_slim/parser.rb
@@ -79,7 +80,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
79
80
  - !ruby/object:Gem::Version
80
81
  version: '0'
81
82
  requirements: []
82
- rubygems_version: 4.0.24
83
+ rubygems_version: 4.0.20
83
84
  specification_version: 4
84
85
  summary: 'Slim templates, rewritten: faster to compile and render, with a formatter
85
86
  and a linter'