super-slim 3.1.1 → 3.2.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: 8a3894df5f66ffe80daaf131669b5457659e414579256020b670719ec7bddf8b
4
- data.tar.gz: 696bb115aa3776422a79dcde2f31984f35690ccf08af50cf43c9655c8cc2fc08
3
+ metadata.gz: 4f7d1e689786582fc22547722bf3b3ef03847b976163b3560c48a9ab06e8178e
4
+ data.tar.gz: 7b422a5d70567feef50061078f19bceb966fb7d6363c9fc48040fae004335f34
5
5
  SHA512:
6
- metadata.gz: ee4af8fa3325f7dcbea6a271776987caef9817a97a2e579ad38f01b4fc054a2c4e98ef04b03a10f8ca8efefd8415f8fc37431381aebe6facf8474c03b4eca2e5
7
- data.tar.gz: 33e7e5274420e92acfe0c824ee5f710dd544c466f3e6ae2be22b386949d6d3917d607d8a4787ab2c6a639308002f1165c02ca4b3ead9be2e3eaf69328c311986
6
+ metadata.gz: e5578534152295f0f13694febb4b5f54fa2c6b72a3e9ce0852f0ea45cbbe200f782bf51d6eb1ec19f3f798d9117351e62d3b2fdd9096d9e4cb016c12da51f198
7
+ data.tar.gz: dcef262dc4ff56c2e908d9a57e55b77818370fe2057685e4084b31e1f1d056e9bf66108487000e2f5ecec4f5a00a0027c4127c311e611cc0f7aa5718a0f5a413
data/CHANGELOG.md CHANGED
@@ -2,6 +2,31 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [3.2.0] — 2026-11-06
6
+
7
+ One layout per line and per tag in `super-slim format`, cache digests that follow Slim partials, and a faster lint.
8
+
9
+ **New**
10
+ - With `max_line_length`, `super-slim format` gives each line one layout: Ruby code spread over several lines is
11
+ joined back when it fits, and a longer call spreads its arguments one per line between parentheses, each followed
12
+ by a comma. Code spread by hand stays as it is when this layout would pass the limit.
13
+ - A tag's attributes stand without delimiters when they fit on its line, and one per line inside
14
+ `attribute_delimiters` when they don't. A literal `id` or `class` becomes a shortcut, a repeated class shortcut
15
+ goes, and attributes follow one order, from `id` and `class` to `aria-*` and `role`. The formatter takes attribute
16
+ values to have no side effects.
17
+
18
+ **Faster**
19
+ - `super-slim lint` is 11 to 22% faster, and finding templates from an app's root skips `node_modules` and `tmp`:
20
+ twice as fast.
21
+
22
+ **Fixed**
23
+ - The digest of a `cache` block in a Slim view now follows the partials it renders, as in ERB: a changed partial
24
+ no longer serves a stale fragment. A partial whose name is computed needs `/# Template Dependency: path`. Each
25
+ such fragment is rebuilt once after the upgrade, and Rails 8.0 processes without eager loading now load Prism
26
+ with Action View.
27
+ - The RuboCop plugin's autocorrect works on templates with CRLF line endings, and `super-slim format` keeps the
28
+ spaces a line renders.
29
+
5
30
  ## [3.1.1] — 2026-11-06
6
31
 
7
32
  Two ways for data to inject markup closed, hostile templates read in linear time, and Prism kept out of rendering.
@@ -147,7 +172,8 @@ renders what Slim 5 renders with `format: :html, sort_attrs: false`, byte for by
147
172
  - 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,
148
173
  newer than the one Ruby 3.3 ships.
149
174
 
150
- [Unreleased]: https://github.com/levups/super-slim/compare/v3.1.1...HEAD
175
+ [Unreleased]: https://github.com/levups/super-slim/compare/v3.2.0...HEAD
176
+ [3.2.0]: https://github.com/levups/super-slim/compare/v3.1.1...v3.2.0
151
177
  [3.1.1]: https://github.com/levups/super-slim/compare/v3.1.0...v3.1.1
152
178
  [3.1.0]: https://github.com/levups/super-slim/compare/v3.0.0...v3.1.0
153
179
  [3.0.0]: https://github.com/levups/super-slim/compare/v2.2.0...v3.0.0
data/README.md CHANGED
@@ -42,8 +42,9 @@ SuperSlim replaces it.
42
42
  gem "super-slim"
43
43
  ```
44
44
 
45
- Rails then renders every `.slim` view with SuperSlim. There is nothing to configure. Rails itself is optional, and
46
- SuperSlim is tested on Rails 8.0 and later.
45
+ Rails then renders every `.slim` view with SuperSlim, and the digest of a `cache` block changes when a partial it
46
+ renders changes. A partial whose name is computed needs a `/# Template Dependency: orders/line` comment, as in ERB.
47
+ There is nothing to configure. Rails itself is optional, and SuperSlim is tested on Rails 8.0 and later.
47
48
 
48
49
  Without Rails, `SuperSlim.compile` turns a template into Ruby code, which you evaluate where the template's
49
50
  variables and methods are defined:
@@ -92,7 +93,8 @@ Templates for XML formats (`.xml`, `.rss`, `.atom`) render as XML automatically,
92
93
  ## Formatter
93
94
 
94
95
  `super-slim format` rewrites templates in one layout: two spaces per level, a space after `-` and `=`, no `div`
95
- where a `.class` or `#id` is enough, no trailing whitespace, single blank lines and a final newline. This template:
96
+ where a `.class` or `#id` is enough, no trailing whitespace unless it renders, single blank lines and a final
97
+ newline. This template:
96
98
 
97
99
  ```slim
98
100
  div.card
@@ -136,8 +138,28 @@ format:
136
138
  attribute_delimiters: "()" # or "[]" or "{}"
137
139
  ```
138
140
 
139
- The formatter then puts a long tag's attributes one per line inside those delimiters, and breaks the arguments
140
- of long Ruby calls after their commas. Lines you already split over several lines stay as they are.
141
+ The formatter then gives each line one layout, whatever its author chose. Ruby code spread over several lines is
142
+ joined back when it fits. A longer line spreads the arguments of its call, or the elements of its array or hash, one
143
+ per line between brackets that close on a line of their own, each followed by a comma:
144
+
145
+ ```slim
146
+ = render Card.new(
147
+ title: post.title,
148
+ body: post.body,
149
+ )
150
+ ```
151
+
152
+ A call whose only argument is a call spreads that one, as `Card.new` above. Arguments go four spaces deep and the
153
+ closing bracket two, two more when the line opens a block. Code spread by hand stays as it is when this layout
154
+ would leave a line longer than the limit, and arguments to `new` go in parentheses.
155
+
156
+ A tag's attributes stand without delimiters when they fit on its line, and one per line inside the delimiters when
157
+ they don't, unless its shortcuts alone pass the limit. A literal `id` or `class` becomes a shortcut, a class shortcut
158
+ named twice goes, and the other attributes follow one order: `id`, `class`, what the element is (`type`, `name`,
159
+ `href`, `src`, `value`, `for`, `action`, `method`), the rest, `data-controller`, `data-action` and targets, other
160
+ `data-*`, then `aria-*` and `role`. Delimiters stay around a boolean attribute and before text that would read as
161
+ an attribute, and a tag with a `*splat` keeps its order. The formatter takes attribute values to have no side
162
+ effects: reordering two Ruby values changes the order they run in.
141
163
 
142
164
  ## Linter
143
165
 
@@ -83,13 +83,22 @@ module SuperSlim
83
83
  paths.flat_map do |path|
84
84
  next [path] unless File.directory?(path)
85
85
 
86
- Dir.glob("**/*.slim", base: path).filter_map do |template|
86
+ templates_in(path).filter_map do |template|
87
87
  template_path = File.join(path, template)
88
88
  template_path if !template.match?(SKIPPED_DIRECTORIES) && File.lstat(template_path).file?
89
89
  end
90
90
  end.sort
91
91
  end
92
92
 
93
+ # A glob of the whole directory would walk the skipped directories too, node_modules first of all.
94
+ def templates_in(directory)
95
+ subdirectories = Dir.children(directory).select do |name|
96
+ !name.start_with?(".") && !"#{name}/".match?(SKIPPED_DIRECTORIES) && File.lstat(File.join(directory, name)).directory?
97
+ end
98
+ Dir.glob("*.slim", base: directory) +
99
+ subdirectories.flat_map { |name| Dir.glob("**/*.slim", base: File.join(directory, name)).map { |template| File.join(name, template) } }
100
+ end
101
+
93
102
  # Written beside the template then renamed over it, so that a full disk or a kill cannot leave it cut short.
94
103
  def replace(path, content)
95
104
  Tempfile.create([".super-slim-", ".tmp"], File.dirname(path)) do |file|
@@ -0,0 +1,130 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SuperSlim
4
+ class Formatter
5
+ # Rewrites the attributes of a tag written on one line: a literal id or class becomes a shortcut, a class named
6
+ # twice goes, and the others follow one order: what the element is, then what it does, then how it reads aloud.
7
+ class AttributeArranger
8
+ # Only plain names: a dot between digits (`py-1.5`), `:` or `/` would read as another class under Tailwind.
9
+ SHORTCUT = /[.#][A-Za-z_-][\w-]*/
10
+ WHOLE_SHORTCUT = /\A#{SHORTCUT}\z/
11
+ LITERAL_ID = /\Aid=(["'])([A-Za-z_][\w-]*)\1\z/
12
+ LITERAL_CLASS = /\Aclass=(["']) *([\w-][\w\- ]*)\1\z/
13
+ TAG_HEAD = /\A([\w:-]*)((?:#{SHORTCUT})*)([<>']*)\z/
14
+ LEADING_SHORTCUTS = /\A( *[\w:-]*)((?:#{SHORTCUT})+)(?=[ =<>'\/]|: |\z)/
15
+ ATTRIBUTE_AT_START = /\A#{Parser::CODE_ATTRIBUTE}/
16
+ RANK_BY_NAME = {
17
+ "id" => 0, "class" => 1, **%w[type name href src value for action method].to_h { [_1, 2] },
18
+ "data-controller" => 4, "data-action" => 5, "role" => 7
19
+ }.freeze
20
+
21
+ def initialize(tailwind_classes:)
22
+ @tailwind_classes = tailwind_classes
23
+ end
24
+
25
+ # Returns the line rearranged and its outline, or the line and its outline as they were when its tag has
26
+ # nothing to rearrange. Without an outline, the line is read alone.
27
+ def call(line, info = nil)
28
+ info ||= line_info(line)
29
+ return [line, info] unless info
30
+
31
+ lists = info.attribute_lists
32
+ return without_duplicate_shortcuts(line, info) if lists.nil?
33
+ return [line, info] unless lists.size == 1
34
+
35
+ indent = line[/\A */]
36
+ first, last, spans = lists.first
37
+ head = line[indent.size...first].rstrip
38
+ # A dynamic tag, `*{tag: name}`, has no head to put shortcuts on.
39
+ return [line, info] if head.empty? || !(head_parts = TAG_HEAD.match(head)) || head_parts[1].end_with?(":")
40
+
41
+ attributes = spans.map { |span_first, span_last| line[span_first...span_last] }
42
+ rest = line[last..]
43
+ # Without delimiters, text that reads as an attribute would become one.
44
+ if Parser::DELIMITERS.key?(line[first])
45
+ return [line, info] if attributes.any? { !_1.include?("=") } || rest.match?(ATTRIBUTE_AT_START)
46
+ end
47
+
48
+ name, shortcuts, markers = head_parts.captures
49
+ shortcuts = shortcuts.scan(SHORTCUT)
50
+ # A splat merges attributes in the order they come.
51
+ unless attributes.any? { _1.start_with?("*") }
52
+ attributes = moved_to_shortcuts(attributes, shortcuts)
53
+ attributes = attributes.sort_by.with_index { |attribute, index| [rank(attribute[/\A"?[^=\s"]+/].delete('"')), index] }
54
+ end
55
+ shortcuts.uniq!
56
+
57
+ name = "" if name == "div" && !shortcuts.empty?
58
+ rest = " #{rest.lstrip}" unless rest.empty? || rest.start_with?(" ")
59
+ arranged = "#{indent}#{name}#{shortcuts.join}#{markers}#{" " unless attributes.empty?}#{attributes.join(" ")}#{rest}"
60
+ outlined(arranged, line, info)
61
+ end
62
+
63
+ private
64
+
65
+ # Appends a literal id or class to the shortcuts and returns the attributes left.
66
+ def moved_to_shortcuts(attributes, shortcuts)
67
+ class_kept = false
68
+ attributes.reject do |attribute|
69
+ if (id = LITERAL_ID.match(attribute)) && shortcuts.none? { _1.start_with?("#") }
70
+ shortcuts << "##{id[2]}"
71
+ elsif !class_kept && (class_shortcuts = literal_class_shortcuts(attribute, shortcuts))
72
+ shortcuts.concat(class_shortcuts)
73
+ else
74
+ # Shortcuts come first among class values: a literal class after this one would move ahead of it.
75
+ class_kept ||= attribute.start_with?("class=")
76
+ false
77
+ end
78
+ end
79
+ end
80
+
81
+ # Nil when a class would be named twice: the check reads a shortcut and a class attribute as two values.
82
+ def literal_class_shortcuts(attribute, shortcuts)
83
+ return unless (classes = LITERAL_CLASS.match(attribute))
84
+
85
+ class_shortcuts = classes[2].split.map { ".#{_1}" }
86
+ class_shortcuts if class_shortcuts.all?(WHOLE_SHORTCUT) && class_shortcuts.uniq == class_shortcuts && !shortcuts.intersect?(class_shortcuts)
87
+ end
88
+
89
+ def without_duplicate_shortcuts(line, info)
90
+ shortcuts = line[LEADING_SHORTCUTS, 2]&.scan(SHORTCUT)
91
+ return [line, info] unless shortcuts && shortcuts.uniq.size < shortcuts.size
92
+
93
+ outlined(line.sub(LEADING_SHORTCUTS) { "#{$1}#{shortcuts.uniq.join}" }, line, info)
94
+ end
95
+
96
+ # The outline of a line read alone, in columns of the indented line; nil when it doesn't parse alone.
97
+ def line_info(line)
98
+ indent = line[/\A */].size
99
+ parser = Parser.new(outline: true, tailwind_classes: @tailwind_classes)
100
+ parser.call(line.lstrip)
101
+ info = parser.outline[1].dup
102
+ info.output_column += indent if info.output_column
103
+ info.attribute_lists = info.attribute_lists&.map do |first, last, spans|
104
+ [first + indent, last + indent, spans.map { |span_first, span_last| [span_first + indent, span_last + indent] }]
105
+ end
106
+ info
107
+ rescue Error
108
+ nil
109
+ end
110
+
111
+ def outlined(arranged, line, info)
112
+ return [line, info] if arranged == line
113
+
114
+ arranged_info = line_info(arranged)
115
+ arranged_info ? [arranged, arranged_info] : [line, info]
116
+ end
117
+
118
+ def rank(name)
119
+ RANK_BY_NAME.fetch(name) do
120
+ case name
121
+ when /\Adata-.+-target\z/ then 5
122
+ when /\Adata-/ then 6
123
+ when /\Aaria-/ then 7
124
+ else 3
125
+ end
126
+ end
127
+ end
128
+ end
129
+ end
130
+ end
@@ -0,0 +1,129 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SuperSlim
4
+ class Formatter
5
+ # Spreads a line of Ruby code over several: the arguments of its call, or the elements of its array or hash,
6
+ # one per line, each followed by a comma, between brackets that close on a line of their own. A call whose only
7
+ # argument is itself a call, an array or a hash spreads that argument instead: `render Card.new(…)`.
8
+ class CodeWrapper
9
+ METHOD_NAME = /\A[a-z_][a-zA-Z0-9_]*[?!]?\z/
10
+ # Rails runs a template inside a method, where `yield` is valid.
11
+ TEMPLATE_METHOD = "def template\n"
12
+ CODE_OFFSET = TEMPLATE_METHOD.bytesize
13
+
14
+ # Returns the lines after the first one's indentation, or nil when the code has nothing to spread.
15
+ def self.call(code, indent, opens_block:)
16
+ new(code, indent, opens_block:).call
17
+ end
18
+
19
+ # `render Card.new title:` reads as if title went to render: arguments to `new` go in parentheses.
20
+ def self.parenthesize_new(code)
21
+ loop do
22
+ statements, _opens_block = parse(code)
23
+ call = statements && new_without_parentheses(statements)
24
+ return code unless call
25
+
26
+ arguments = arguments_of(call)
27
+ name_end = call.message_loc.end_offset - CODE_OFFSET
28
+ arguments_start = arguments.first.location.start_offset - CODE_OFFSET
29
+ arguments_end = end_offset(arguments.last) - CODE_OFFSET
30
+ return code if arguments_end > code.bytesize
31
+
32
+ code = "#{code.byteslice(0, name_end)}(#{code.byteslice(arguments_start...arguments_end)})#{code.byteslice(arguments_end..)}"
33
+ end
34
+ end
35
+
36
+ def self.new_without_parentheses(statements)
37
+ nodes = statements.dup
38
+ while (node = nodes.pop)
39
+ return node if node.is_a?(Prism::CallNode) && node.name == :new && node.opening_loc.nil? && arguments_of(node)
40
+
41
+ nodes.concat(node.child_nodes.compact)
42
+ end
43
+ end
44
+ private_class_method :new_without_parentheses
45
+
46
+ # Returns the statements of the line and whether it opens a block: it then holds its `do` but not its `end`.
47
+ # Their offsets count from CODE_OFFSET.
48
+ def self.parse(code)
49
+ parsed = Prism.parse("#{TEMPLATE_METHOD}#{code}\nend")
50
+ opens_block = !parsed.success?
51
+ parsed = Prism.parse("#{TEMPLATE_METHOD}#{code}\nend\nend") if opens_block
52
+ [parsed.value.statements.body.first.body&.body || [], opens_block] if parsed.success? && parsed.comments.empty?
53
+ end
54
+
55
+ # Positional and keyword arguments, then the block argument; nil when the call takes none.
56
+ def self.arguments_of(call)
57
+ arguments = (call.arguments&.arguments || []).flat_map { |argument| argument.is_a?(Prism::KeywordHashNode) ? argument.elements : [argument] }
58
+ arguments += [call.block] if call.block.is_a?(Prism::BlockArgumentNode)
59
+ arguments unless call.message_loc.nil? || arguments.empty?
60
+ end
61
+
62
+ # 2026-11: Prism 0.19 (Ruby 3.3) ends a call that takes a block argument, and any node around it, before the
63
+ # call's closing parenthesis: `f(&x`.
64
+ def self.end_offset(node)
65
+ closing = node.closing_loc if node.respond_to?(:closing_loc)
66
+ child_ends = node.child_nodes.filter_map { |child| end_offset(child) if child }
67
+ [node.location.end_offset, closing&.end_offset || 0, *child_ends].max
68
+ end
69
+
70
+ # opens_block: whether the line has children, which Slim passes to its call as a block even without `do`.
71
+ def initialize(code, indent, opens_block:)
72
+ @code = code
73
+ @indent = indent
74
+ @opens_block = opens_block
75
+ end
76
+
77
+ def call
78
+ statements, opens_block = self.class.parse(@code)
79
+ return unless statements&.size == 1 && (node = spreadable(statements.first))
80
+
81
+ spread(node, @opens_block || opens_block)
82
+ end
83
+
84
+ private
85
+
86
+ def spreadable(node)
87
+ node = node.value if node.type.end_with?("_write_node") && node.respond_to?(:value)
88
+ case node
89
+ when Prism::CallNode
90
+ items = self.class.arguments_of(node)
91
+ # An operator such as `+` has no parentheses to add, and `list[index] = value` holds value in its arguments.
92
+ return if items.nil? || node.name.end_with?("=") || (node.opening_loc.nil? && !METHOD_NAME.match?(node.name.to_s))
93
+ return spreadable(items.first) if items.size == 1
94
+
95
+ node
96
+ when Prism::ArrayNode, Prism::HashNode
97
+ # `%w[a b]` takes no commas.
98
+ node if ["[", "{"].include?(node.opening) && node.elements.size > 1
99
+ end
100
+ end
101
+
102
+ def spread(node, opens_block)
103
+ items = node.is_a?(Prism::CallNode) ? self.class.arguments_of(node) : node.elements
104
+ # `hint: -> do` ends past the line, with the children of the line.
105
+ return if self.class.end_offset(items.last) > CODE_OFFSET + @code.bytesize
106
+
107
+ closing_indent = @indent + (" " * (opens_block ? 2 * INDENT_WIDTH : INDENT_WIDTH))
108
+ item_indent = closing_indent + (" " * INDENT_WIDTH)
109
+ head, tail =
110
+ if node.opening_loc
111
+ [slice(CODE_OFFSET, node.opening_loc.end_offset), slice(node.closing_loc.start_offset)]
112
+ else
113
+ ["#{slice(CODE_OFFSET, node.message_loc.end_offset)}(", ")#{slice(self.class.end_offset(items.last))}"]
114
+ end
115
+ item_lines = items.map do |item|
116
+ # A comma after `&block` is a syntax error.
117
+ comma = "," unless item.is_a?(Prism::BlockArgumentNode)
118
+ "#{item_indent}#{slice(item.location.start_offset, self.class.end_offset(item))}#{comma}"
119
+ end
120
+ [head, *item_lines, closing_indent + tail]
121
+ end
122
+
123
+ # From offsets in the parsed source, up to the end of the line by default.
124
+ def slice(first, last = CODE_OFFSET + @code.bytesize)
125
+ @code.byteslice((first - CODE_OFFSET)...(last - CODE_OFFSET))
126
+ end
127
+ end
128
+ end
129
+ end
@@ -2,21 +2,15 @@
2
2
 
3
3
  module SuperSlim
4
4
  class Formatter
5
- # Breaks the lines of a formatted template longer than max_line_length: a tag's attributes one per line
6
- # inside attribute_delimiters, then the arguments of its Ruby code after each comma, as Slim reads a line ending
7
- # with a comma as continued on the next one. Lines already spread over several lines are left as they are.
5
+ # Gives each line one layout, whatever its author chose: Ruby code spread over several lines is joined back
6
+ # when it fits in max_line_length, and a longer line is broken: a tag's attributes one per line inside
7
+ # attribute_delimiters, then its Ruby code by CodeWrapper.
8
8
  class LineWrapper
9
9
  CODE_LINE = /\A *(?:-|==?[<>]*) /
10
10
  TAG_OUTPUT = /\G\s*==?['<>]*\s*/
11
11
  CONTINUATION_KINDS = %i[continuation text text_blank].freeze
12
- DO_KEYWORDS = %i[KEYWORD_DO KEYWORD_DO_BLOCK KEYWORD_DO_LAMBDA KEYWORD_DO_LOOP].freeze
13
- MODIFIERS = %i[KEYWORD_IF_MODIFIER KEYWORD_UNLESS_MODIFIER KEYWORD_WHILE_MODIFIER KEYWORD_UNTIL_MODIFIER KEYWORD_RESCUE_MODIFIER].freeze
14
- # Prism 2 splits some tokens by role (BRACE_LEFT_HASH, PARENTHESIS_LEFT_GROUPING): older ones never emit them.
15
- OPENING_BRACKETS = %i[
16
- PARENTHESIS_LEFT PARENTHESIS_LEFT_PARENTHESES PARENTHESIS_LEFT_GROUPING BRACKET_LEFT BRACKET_LEFT_ARRAY
17
- BRACE_LEFT BRACE_LEFT_HASH BRACE_LEFT_ARGUMENT LAMBDA_BEGIN EMBEXPR_BEGIN
18
- ].freeze
19
- CLOSING_BRACKETS = %i[PARENTHESIS_RIGHT BRACKET_RIGHT BRACE_RIGHT EMBEXPR_END].freeze
12
+ CLOSING_BRACKET_AT_START = /\A[)\]}]/
13
+ NEW_WITHOUT_PARENTHESES = /\.new [^\s=]/
20
14
 
21
15
  # Templates attach ( and [ to their tag but set { apart, as a Ruby block: 6,097 public templates agree.
22
16
  OPENING_BY_ATTRIBUTE_DELIMITERS = {"()" => "(", "[]" => "[", "{}" => " {"}.freeze
@@ -29,27 +23,83 @@ module SuperSlim
29
23
  @max_line_length = max_line_length
30
24
  @tailwind_classes = tailwind_classes
31
25
  @closing = attribute_delimiters[1]
26
+ @attribute_arranger = AttributeArranger.new(tailwind_classes:)
32
27
  end
33
28
 
34
29
  def call(source)
35
30
  lines = source.split("\n")
36
- return source if lines.none? { _1.size > @max_line_length }
37
-
38
31
  parser = Parser.new(outline: true, tailwind_classes: @tailwind_classes)
39
32
  parser.call(source)
40
- wrapped = lines.each.with_index(1).flat_map do |line, lineno|
41
- info = parser.outline[lineno]
42
- next [line] unless line.size > @max_line_length && info.kind == :structure && one_line?(parser.outline[lineno + 1], lineno)
43
-
44
- wrap(line, info, children?(parser.outline, lineno))
33
+ outline = parser.outline
34
+ wrapped = []
35
+ lineno = 1
36
+ while lineno <= lines.size
37
+ info = outline[lineno]
38
+ last_lineno = lineno
39
+ last_lineno += 1 while outline[last_lineno + 1]&.owner == lineno && CONTINUATION_KINDS.include?(outline[last_lineno + 1].kind)
40
+ wrapped.concat(layout(lines[(lineno - 1)...last_lineno], info, outline, lineno))
41
+ lineno = last_lineno + 1
45
42
  end
46
43
  "#{wrapped.join("\n")}\n"
47
44
  end
48
45
 
49
46
  private
50
47
 
51
- def one_line?(next_info, lineno)
52
- next_info.nil? || next_info.owner != lineno || !CONTINUATION_KINDS.include?(next_info.kind)
48
+ def layout(lines, info, outline, lineno)
49
+ return lines unless info.kind == :structure
50
+
51
+ line = (lines.size > 1) ? joined_code(lines, info) || joined_attributes(lines, info) : lines.first
52
+ return lines unless line
53
+
54
+ line, arranged_info = @attribute_arranger.call(line, (info if line == lines.first))
55
+ info = arranged_info || info
56
+ line = with_new_parenthesized(line, info)
57
+ return [line] if line.size <= @max_line_length
58
+
59
+ broken = wrap(line, info, children?(outline, lineno))
60
+ return ((lines.size > 1) ? lines : broken) if broken == [line]
61
+
62
+ # Joined back, brackets lose the spaces inside them (`{ a: 1 }` becomes `{a: 1}`), which may now fit.
63
+ rejoined = joined_code(broken, info)
64
+ return [rejoined] if rejoined && rejoined.size <= @max_line_length
65
+
66
+ # Only the outer call is spread: a hash spread inside it by hand would come back longer than the limit.
67
+ return lines if lines.size > 1 && lines.none? { _1.size > @max_line_length } && broken.any? { _1.size > @max_line_length }
68
+
69
+ broken
70
+ end
71
+
72
+ def with_new_parenthesized(line, info)
73
+ return line unless line.match?(NEW_WITHOUT_PARENTHESES) && (start = code_start(line, info.output_column))
74
+
75
+ line[0...start] + CodeWrapper.parenthesize_new(line[start..])
76
+ end
77
+
78
+ # The code of a line continued after a comma, a backslash or an opening bracket, on one line; nil when the
79
+ # continuation lines hold anything else, such as attributes or text.
80
+ def joined_code(lines, info)
81
+ return unless info.text.nil? && code_start(lines.first, info.output_column) && lines.drop(1).none? { _1.strip.empty? }
82
+
83
+ lines.drop(1).reduce(lines.first.rstrip) do |joined, line|
84
+ piece = line.strip
85
+ joined = joined.delete_suffix("\\").rstrip
86
+ if piece.match?(CLOSING_BRACKET_AT_START)
87
+ joined.delete_suffix(",") + piece
88
+ elsif joined.match?(Parser::OPENING_BRACKET_AT_LINE_END)
89
+ joined + piece
90
+ else
91
+ "#{joined} #{piece}"
92
+ end
93
+ end
94
+ end
95
+
96
+ # A tag whose attributes stand one per line inside delimiters, on one line: `p {` `title="A"` `} = text`.
97
+ def joined_attributes(lines, info)
98
+ return unless info.text.nil? && lines.first.lstrip.match?(Shortcuts::TAG_PATTERN) && !code_start(lines.first, info.output_column)
99
+ return unless lines.first.rstrip.match?(Parser::OPENING_BRACKET_AT_LINE_END)
100
+ return unless lines.last.strip.match?(CLOSING_BRACKET_AT_START) && lines[1...-1].none? { _1.strip.empty? }
101
+
102
+ lines.first.rstrip + lines[1...-1].map(&:strip).join(" ") + lines.last.strip
53
103
  end
54
104
 
55
105
  def children?(outline, lineno)
@@ -57,20 +107,24 @@ module SuperSlim
57
107
  next_structure && next_structure.depth > outline[lineno].depth
58
108
  end
59
109
 
60
- def wrap(line, info, children)
110
+ def wrap(line, info, opens_block)
61
111
  indent = line[/\A */]
62
112
  lists = info.attribute_lists
113
+ head = line[0...lists.first.first].rstrip if lists&.size == 1
63
114
  lines, code_start =
64
- if lists&.size == 1 && named_tag?(line[0...lists.first.first].strip)
115
+ # Attributes spread over lines would not bring back under the limit a tag whose shortcuts alone pass it.
116
+ if head && named_tag?(head.strip) && head.size + @opening.size <= @max_line_length
65
117
  wrap_attributes(line, lists.first, indent, info.output_column)
66
118
  else
67
119
  [[line], code_start(line, info.output_column)]
68
120
  end
69
121
  return lines unless code_start && lines.last.size > @max_line_length
70
122
 
71
- # Arguments go two levels deeper than the line when it opens a block, so they stand apart from its children.
72
- argument_indent = indent + (" " * (children ? 2 * INDENT_WIDTH : INDENT_WIDTH))
73
- lines[0...-1] + wrap_arguments(lines.last, code_start, argument_indent)
123
+ last_indent = lines.last[/\A */]
124
+ code_lines = CodeWrapper.call(lines.last[code_start..], last_indent, opens_block:)
125
+ return lines unless code_lines
126
+
127
+ lines[0...-1] + [lines.last[0...code_start] + code_lines.first, *code_lines.drop(1)]
74
128
  end
75
129
 
76
130
  # A dynamic tag, `*{tag: name}` or `li: *{tag: name}`, has no name for its attribute list to follow.
@@ -93,40 +147,6 @@ module SuperSlim
93
147
  match.end(0)
94
148
  end
95
149
  end
96
-
97
- def wrap_arguments(line, code_start, argument_indent)
98
- code = line[code_start..]
99
- offsets = argument_breaks(code)
100
- return [line] if offsets.empty?
101
-
102
- first = 0
103
- first_piece, *pieces = [*offsets, code.bytesize].map do |last|
104
- piece = code.byteslice(first...last).strip
105
- first = last
106
- piece
107
- end
108
- [line[0...code_start] + first_piece, *pieces.map { argument_indent + _1 }]
109
- end
110
-
111
- # Byte offsets right after each comma that separates the arguments of the outermost call, up to its block.
112
- def argument_breaks(code)
113
- depth = 0
114
- offsets = []
115
- Prism.lex(code).value.each do |(token, _state)|
116
- case token.type
117
- when :COMMA then offsets << token.location.end_offset if depth.zero?
118
- when :HEREDOC_START then return []
119
- # `a, b = …` assigns several variables: its commas separate no arguments.
120
- when :EQUAL then return [] if depth.zero? && !offsets.empty?
121
- when *DO_KEYWORDS then break
122
- # RuboCop refuses a modifier that ends a statement spread over several lines (Style/MultilineIfModifier).
123
- when *MODIFIERS then return [] if depth.zero?
124
- when *OPENING_BRACKETS then depth += 1
125
- when *CLOSING_BRACKETS then depth -= 1
126
- end
127
- end
128
- offsets
129
- end
130
150
  end
131
151
  end
132
152
  end
@@ -1,6 +1,8 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "prism"
4
+ require_relative "formatter/attribute_arranger"
5
+ require_relative "formatter/code_wrapper"
4
6
  require_relative "formatter/line_wrapper"
5
7
 
6
8
  module SuperSlim
@@ -112,14 +114,33 @@ module SuperSlim
112
114
  # Prism's tree of the compiled Ruby; that Ruby with its separators folded when Prism can't read it; the error
113
115
  # when the template doesn't compile.
114
116
  def compiled_ruby(source)
115
- code = SuperSlim.compile(source, tailwind_classes: @tailwind_classes, format: :xml)
116
- # Rails runs a template inside a method, where `yield` is valid.
117
- parsed = Prism.parse("def template\n#{code}\nend")
117
+ nodes = Parser.new(tailwind_classes: @tailwind_classes).call(source)
118
+ code = Compiler.new(format: :xml).call(with_attributes_sorted_by_name(nodes))
119
+ parsed = Prism.parse("#{CodeWrapper::TEMPLATE_METHOD}#{code}\nend")
118
120
  parsed.success? ? parsed : code.gsub(/(?:\s*[;\n]\s*)+/, ";")
119
121
  rescue Error => exception
120
122
  exception.message
121
123
  end
122
124
 
125
+ # A tag renders the same whatever the order of its attributes, and with a class shortcut named twice once: both
126
+ # templates get their attributes sorted by name, class values kept in order, before they are compiled. A
127
+ # splat merges attributes in order, so a tag holding one keeps its own.
128
+ def with_attributes_sorted_by_name(nodes)
129
+ nodes.each do |node|
130
+ next unless node.is_a?(Struct)
131
+
132
+ if node.is_a?(AST::Tag) && node.attributes.none?(AST::Splat)
133
+ attributes = node.attributes.uniq { class_shortcut?(_1) ? _1 : _1.__id__ }
134
+ node.attributes = attributes.sort_by.with_index { |attribute, index| [attribute.name, index] }
135
+ end
136
+ node.each { with_attributes_sorted_by_name(_1) if _1.is_a?(Array) }
137
+ end
138
+ end
139
+
140
+ def class_shortcut?(attribute)
141
+ attribute.is_a?(AST::StaticAttribute) && attribute.name == "class"
142
+ end
143
+
123
144
  # Positions aside: line breaks, spaces, a trailing comma and the parentheses of a call change nothing, a
124
145
  # different value or operator does.
125
146
  def same_ruby?(ruby, other_ruby)
@@ -15,7 +15,7 @@ module SuperSlim
15
15
  DEFAULTS = {enabled: true}.freeze
16
16
 
17
17
  def self.rule_name
18
- name.split("::").last
18
+ @rule_name ||= name.split("::").last
19
19
  end
20
20
 
21
21
  GLOB_FLAGS = File::FNM_PATHNAME | File::FNM_EXTGLOB | File::FNM_DOTMATCH
@@ -86,7 +86,9 @@ module SuperSlim
86
86
  document.outline.each_with_index.filter_map do |info, lineno|
87
87
  next unless info&.kind == :structure
88
88
 
89
- indent = document.lines[lineno - 1][/\A */].size
89
+ line = document.lines[lineno - 1]
90
+ indent = 0
91
+ indent += 1 while line.getbyte(indent) == Parser::SPACE_BYTE
90
92
  expected = info.depth * Formatter::INDENT_WIDTH
91
93
  offense(document, lineno, "Indent with #{expected} spaces, not #{indent}") if indent != expected
92
94
  end
@@ -102,11 +104,11 @@ module SuperSlim
102
104
  end
103
105
 
104
106
  class TrailingWhitespace < Rule
105
- # Matches wherever a line may end in whitespace, and a little more (a \r before \n): it only skips files.
106
- ANY_TRAILING_WHITESPACE = /[ \t\r\f\v](?=\r?\n|\z)/
107
-
108
107
  def offenses(document, source)
109
- return [] unless source.match?(ANY_TRAILING_WHITESPACE)
108
+ # Whitespace ending a line is in one of these, as are a few more files (a \r anywhere): they only skip files.
109
+ # A string search is faster than any regexp here.
110
+ return [] unless source.include?(" \n") || source.include?("\t\n") || source.include?("\r") || source.include?("\f") ||
111
+ source.include?("\v") || source.end_with?(" ", "\t")
110
112
 
111
113
  each_line(document).filter_map do |line, lineno|
112
114
  next unless line.match?(/\s\z/)
@@ -142,6 +144,9 @@ module SuperSlim
142
144
 
143
145
  class ControlStatementSpacing < Rule
144
146
  TAG_OUTPUT = /\A(\s*)(==?)(['<>]*)(\s*)(?=\S)/
147
+ # [\s\0]* is what String#lstrip strips.
148
+ UNSPACED_CONTROL = /\A[\s\0]*-(?=\S)/
149
+ UNSPACED_OUTPUT = /\A[\s\0]*((?>==?[<>]*))(?=\S)/
145
150
 
146
151
  def offenses(document, _source)
147
152
  document.outline.each_with_index.filter_map do |info, lineno|
@@ -153,9 +158,9 @@ module SuperSlim
153
158
 
154
159
  offense(document, lineno, "Put a space before and after `#{$2}`") if $1.empty? || $4.empty?
155
160
  elsif info.kind == :structure
156
- case line.lstrip
157
- when /\A-(?=\S)/ then offense(document, lineno, "Put a space after `-`")
158
- when /\A((?>==?[<>]*))(?=\S)/ then offense(document, lineno, "Put a space after `#{$1}`")
161
+ case line
162
+ when UNSPACED_CONTROL then offense(document, lineno, "Put a space after `-`")
163
+ when UNSPACED_OUTPUT then offense(document, lineno, "Put a space after `#{$1}`")
159
164
  end
160
165
  end
161
166
  end
@@ -163,9 +168,12 @@ module SuperSlim
163
168
  end
164
169
 
165
170
  class RedundantDiv < Rule
171
+ # [\s\0]* is what String#lstrip strips.
172
+ REDUNDANT_DIV = /\A[\s\0]*div(?=[.#][\p{Word}-])/
173
+
166
174
  def offenses(document, _source)
167
175
  document.outline.each_with_index.filter_map do |info, lineno|
168
- next unless info&.kind == :structure && document.lines[lineno - 1].lstrip.match?(Formatter::REDUNDANT_DIV)
176
+ next unless info&.kind == :structure && document.lines[lineno - 1].match?(REDUNDANT_DIV)
169
177
 
170
178
  offense(document, lineno, "`div` is implied by the `.class` or `#id` shortcut")
171
179
  end
@@ -574,7 +582,7 @@ module SuperSlim
574
582
  EMOJI_JOINER = /(?<=\p{Extended_Pictographic}|[\u{1F3FB}-\u{1F3FF}]|\uFE0F)\u200D(?=\p{Extended_Pictographic})/
575
583
 
576
584
  def offenses(document, source)
577
- return [] unless source.match?(INVISIBLE)
585
+ return [] if source.ascii_only? || !source.match?(INVISIBLE)
578
586
 
579
587
  each_line(document).filter_map do |line, lineno|
580
588
  line = line.delete_prefix("\uFEFF") if lineno == 1
@@ -114,7 +114,8 @@ module SuperSlim
114
114
  parser = Parser.new(file: path, outline: true)
115
115
  nodes = parser.call(source)
116
116
  visits = Document.visits_of(nodes, parser.line_by_node)
117
- document = Document.new(path:, lines: source.split(/\r?\n/), nodes:, outline: parser.outline, line_by_node: parser.line_by_node,
117
+ lines = source.include?("\r") ? source.split(/\r?\n/) : source.split("\n")
118
+ document = Document.new(path:, lines:, nodes:, outline: parser.outline, line_by_node: parser.line_by_node,
118
119
  visits:, tag_visits: visits.select { |node,| node.is_a?(AST::Tag) })
119
120
  relative_path = File.expand_path(path).delete_prefix(@root)
120
121
  offenses = @rules.select { _1.applies_to?(relative_path) }.flat_map { _1.offenses(document, source) }
@@ -12,7 +12,9 @@ module SuperSlim
12
12
  process_count = [Etc.nprocessors, items.size / minimum_per_process].min
13
13
  return items.map(&block) if process_count < 2 || !Process.respond_to?(:fork)
14
14
 
15
- workers = items.each_slice((items.size.to_f / process_count).ceil).map do |slice|
15
+ # Dealt like cards: neighbouring templates, as heavy as each other, would load one process with all of them.
16
+ slices = Array.new(process_count) { |process_index| items.values_at(*process_index.step(items.size - 1, process_count)) }
17
+ workers = slices.map do |slice|
16
18
  reader, writer = IO.pipe
17
19
  pid = fork do
18
20
  reader.close
@@ -22,9 +24,12 @@ module SuperSlim
22
24
  writer.close
23
25
  [pid, reader]
24
26
  end
25
- results_by_process = workers.map { |pid, reader| receive(pid, reader) }
26
- results_by_process.each { |results| raise results if results.is_a?(Exception) }
27
- results_by_process.flatten(1)
27
+ results_per_process = workers.map { |pid, reader| receive(pid, reader) }
28
+ results_per_process.each { |results| raise results if results.is_a?(Exception) }
29
+ # The first slice is the longest: zip pads the others with nils past the last item.
30
+ results_in_item_order = results_per_process.first.zip(*results_per_process.drop(1))
31
+ results_in_item_order.flatten!(1)
32
+ results_in_item_order.first(items.size)
28
33
  ensure
29
34
  workers&.each do |pid, reader|
30
35
  reader.close unless reader.closed?
@@ -107,7 +107,16 @@ module SuperSlim
107
107
 
108
108
  def line_starts(source, byte_order_mark_size)
109
109
  line_starts = [nil, byte_order_mark_size]
110
- source.each_line { |line| line_starts << line_starts.last + line.size }
110
+ if source.ascii_only?
111
+ line_start = 0
112
+ while (newline_index = source.byteindex("\n", line_start))
113
+ line_start = newline_index + 1
114
+ line_starts << byte_order_mark_size + line_start
115
+ end
116
+ line_starts << byte_order_mark_size + source.bytesize if line_start < source.bytesize
117
+ else
118
+ source.each_line { |line| line_starts << line_starts.last + line.size }
119
+ end
111
120
  line_starts
112
121
  end
113
122
 
@@ -258,7 +267,10 @@ module SuperSlim
258
267
  end
259
268
 
260
269
  def parse_inline_html
261
- record_ruby(:text, source_offset, line_end_offset) if @outline
270
+ if @outline
271
+ @outline[@lineno].text = true
272
+ record_ruby(:text, source_offset, line_end_offset)
273
+ end
262
274
  children = []
263
275
  @stacks.last << located(InlineHtml.new(@scanner.rest, children))
264
276
  nest(children)
@@ -391,7 +403,7 @@ module SuperSlim
391
403
  end
392
404
 
393
405
  def parse_broken_line
394
- first = source_offset + @scanner.rest[/\A\s*/].size if @outline
406
+ first = source_offset + @scanner.match?(WHITESPACE) if @outline
395
407
  broken_line = @scanner.rest
396
408
  broken_line.strip!
397
409
  brackets = RubyBrackets.new(broken_line) if broken_line.match?(OPENING_BRACKET_AT_LINE_END)
@@ -573,6 +585,8 @@ module SuperSlim
573
585
 
574
586
  until depth == 0 && @scanner.peek_byte == quote_byte
575
587
  if @scanner.eos? || @scanner.match?(BACKSLASH_AT_END)
588
+ # Unlike a stripped continuation line, a line read whole keeps its trailing whitespace in the value.
589
+ @outline[@lineno].text = true if @outline && @scanner.eos? && @scanner.string.equal?(@line)
576
590
  value << (@scanner.eos? ? "\n" : " ")
577
591
  @stacks.last << NEWLINE
578
592
  expect_next_line
@@ -5,7 +5,11 @@ module SuperSlim
5
5
  initializer "super_slim.register_template_handler" do
6
6
  ActiveSupport.on_load(:action_view) do
7
7
  require_relative "rails_handler"
8
+ require "action_view/dependency_tracker" # Rails 8.0 does not autoload it
8
9
  ActionView::Template.register_template_handler(:slim, SuperSlim::RailsHandler.new)
10
+ # After the handler: register_tracker looks it up by extension, an unknown one falls back to the Raw handler.
11
+ # Not ERBTracker: since Rails 8.1 it only reads <% %> tags, and finds no render call in Slim.
12
+ ActionView::DependencyTracker.register_tracker(:slim, ActionView::DependencyTracker::RubyTracker)
9
13
  end
10
14
  end
11
15
  end
@@ -45,7 +45,9 @@ module SuperSlim
45
45
 
46
46
  def initialize(processed_source)
47
47
  @processed_source = processed_source
48
- @source = processed_source.raw_source
48
+ # Offsets count in the source buffer, which reads \r\n as \n: counted with the \r, a correction lands one
49
+ # character further for each line above it.
50
+ @source = processed_source.raw_source.gsub("\r\n", "\n")
49
51
  end
50
52
 
51
53
  def call
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module SuperSlim
4
- VERSION = "3.1.1"
4
+ VERSION = "3.2.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.1.1
4
+ version: 3.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Level UP Solutions
@@ -23,10 +23,10 @@ dependencies:
23
23
  - - ">="
24
24
  - !ruby/object:Gem::Version
25
25
  version: 3.1.1
26
- description: 'A Slim template engine rewritten from scratch, without Temple: same
27
- HTML as Slim 5, faster compilation and rendering with fewer allocations, a formatter
28
- that cannot change a page, a linter with HTML and accessibility rules, and a RuboCop
29
- plugin for the Ruby inside templates.'
26
+ description: A Slim template engine written from scratch, without Temple. It renders
27
+ the same HTML as Slim 5, compiles and renders faster with fewer allocations, and
28
+ comes with a formatter that cannot change a page, a linter with HTML and accessibility
29
+ rules, and a RuboCop plugin for the Ruby inside templates.
30
30
  executables:
31
31
  - super-slim
32
32
  extensions: []
@@ -44,6 +44,8 @@ files:
44
44
  - lib/super_slim/cli.rb
45
45
  - lib/super_slim/compiler.rb
46
46
  - lib/super_slim/formatter.rb
47
+ - lib/super_slim/formatter/attribute_arranger.rb
48
+ - lib/super_slim/formatter/code_wrapper.rb
47
49
  - lib/super_slim/formatter/line_wrapper.rb
48
50
  - lib/super_slim/linter.rb
49
51
  - lib/super_slim/linter/presets.rb
@@ -83,6 +85,6 @@ required_rubygems_version: !ruby/object:Gem::Requirement
83
85
  requirements: []
84
86
  rubygems_version: 4.0.20
85
87
  specification_version: 4
86
- summary: 'Slim templates, rewritten: faster to compile and render, with a formatter
87
- and a linter'
88
+ summary: A Slim template engine that compiles and renders faster, with a formatter
89
+ and a linter
88
90
  test_files: []