Class: SyntaxTree::Tailwindcss::Sorter

Inherits:
Object
  • Object
show all
Defined in:
lib/syntax_tree/tailwindcss/sorter.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(classes_in_order) ⇒ Sorter

Returns a new instance of Sorter.



6
7
8
# File 'lib/syntax_tree/tailwindcss/sorter.rb', line 6

def initialize(classes_in_order)
  @classes_order = classes_in_order.to_enum.with_index.to_h
end

Class Method Details

.load!Object



35
36
37
38
39
# File 'lib/syntax_tree/tailwindcss/sorter.rb', line 35

def load!
  tailwind_output = File.read(tailwind_output_path)
  classes = parse_tailwind_output(tailwind_output)
  new(classes)
end

.load_cachedObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/syntax_tree/tailwindcss/sorter.rb', line 19

def load_cached
  return new(SyntaxTree::Tailwindcss.custom_order) if SyntaxTree::Tailwindcss.custom_order

  mtime = File.mtime(tailwind_output_path)
  return @cached_sorter if @cached_mtime == mtime

  @cached_sorter = load!
  @cached_mtime = mtime
  @cached_sorter
rescue Errno::ENOENT
  warn do
    "Couldn't find TailwindCSS output (#{tailwind_output_path}). Classes won't be sorted."
  end
  new([])
end

.parse_tailwind_output(output) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
# File 'lib/syntax_tree/tailwindcss/sorter.rb', line 51

def parse_tailwind_output(output)
  # We could use a real CSS parser, but that'd be slow and we only need to know valid classes
  output
    .gsub(%r{/\*.+?\*/}, "")
    .gsub(/\\(.)/) { "-ESCAPED-#{Regexp.last_match[1].ord}-" }
    .scan(/(?<=\.)[^0-9][^. {:>),\[]*/)
    .uniq
    .join(" ")
    .gsub(/-ESCAPED-(\d+)-/) { Regexp.last_match[1].to_i.chr(Encoding::UTF_8) }
    .split
end

.tailwind_output_pathObject



41
42
43
44
45
46
47
48
49
# File 'lib/syntax_tree/tailwindcss/sorter.rb', line 41

def tailwind_output_path
  if SyntaxTree::Tailwindcss.output_path
    SyntaxTree::Tailwindcss.output_path
  elsif ENV["TAILWIND_OUTPUT_PATH"]
    ENV["TAILWIND_OUTPUT_PATH"]
  else
    "app/assets/builds/application.css"
  end
end

Instance Method Details

#sort(classes) ⇒ Object



10
11
12
# File 'lib/syntax_tree/tailwindcss/sorter.rb', line 10

def sort(classes)
  classes.uniq.sort_by { |cls| @classes_order[cls] || -1 }
end

#sort_order(cls) ⇒ Object



14
15
16
# File 'lib/syntax_tree/tailwindcss/sorter.rb', line 14

def sort_order(cls)
  @classes_order[cls] || -1
end