icons.rake 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. # frozen_string_literal: true
  2. def download_material_icon(icon, weight: 400, filled: false, size: 20)
  3. url_template = Addressable::Template.new('https://fonts.gstatic.com/s/i/short-term/release/materialsymbolsoutlined/{icon}/{axes}/{size}px.svg')
  4. variant = filled ? '-fill' : ''
  5. axes = []
  6. axes << "wght#{weight}" if weight != 400
  7. axes << 'fill1' if filled
  8. axes = axes.join('-').presence || 'default'
  9. url = url_template.expand(icon: icon, axes: axes, size: size).to_s
  10. path = Rails.root.join('app', 'javascript', 'material-icons', "#{weight}-#{size}px", "#{icon}#{variant}.svg")
  11. FileUtils.mkdir_p(File.dirname(path))
  12. File.write(path, HTTP.get(url).to_s)
  13. end
  14. def find_used_icons
  15. icons_by_weight_and_size = {}
  16. Dir[Rails.root.join('app', 'javascript', '**', '*.*s*')].map do |path|
  17. File.open(path, 'r') do |file|
  18. pattern = %r{\Aimport .* from 'mastodon/../material-icons/(?<weight>[0-9]+)-(?<size>[0-9]+)px/(?<icon>[^-]*)(?<fill>-fill)?.svg';}
  19. file.each_line do |line|
  20. match = pattern.match(line)
  21. next if match.blank?
  22. weight = match['weight'].to_i
  23. size = match['size'].to_i
  24. icons_by_weight_and_size[weight] ||= {}
  25. icons_by_weight_and_size[weight][size] ||= Set.new
  26. icons_by_weight_and_size[weight][size] << match['icon']
  27. end
  28. end
  29. end
  30. icons_by_weight_and_size
  31. end
  32. namespace :icons do
  33. desc 'Download used Material Symbols icons'
  34. task download: :environment do
  35. find_used_icons.each do |weight, icons_by_size|
  36. icons_by_size.each do |size, icons|
  37. icons.each do |icon|
  38. download_material_icon(icon, weight: weight, size: size)
  39. download_material_icon(icon, weight: weight, size: size, filled: true)
  40. end
  41. end
  42. end
  43. end
  44. end