sprites.thor 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. class SpritesCLI < Thor
  2. def self.to_s
  3. 'Sprites'
  4. end
  5. def initialize(*args)
  6. require 'docs'
  7. require 'chunky_png'
  8. require 'fileutils'
  9. super
  10. end
  11. desc 'generate [--verbose]', 'Generate the documentation icon spritesheets'
  12. option :verbose, type: :boolean
  13. def generate
  14. icons = get_icons
  15. icons_per_row = Math.sqrt(icons.length).ceil
  16. bg_color = get_sidebar_background
  17. icons.each_with_index do |icon, index|
  18. icon[:row] = (index / icons_per_row).floor
  19. icon[:col] = index - icon[:row] * icons_per_row
  20. icon[:icon_16] = get_icon(icon[:path_16], 16)
  21. icon[:icon_32] = get_icon(icon[:path_32], 32)
  22. icon[:dark_icon_fix] = needs_dark_icon_fix(icon[:icon_32], bg_color)
  23. end
  24. log_details(icons, icons_per_row)
  25. generate_spritesheet(16, icons, 'assets/images/sprites/docs.png') {|icon| icon[:icon_16]}
  26. generate_spritesheet(32, icons, 'assets/images/sprites/docs@2x.png') {|icon| icon[:icon_32]}
  27. save_manifest(icons, icons_per_row, 'assets/images/sprites/docs.json')
  28. end
  29. private
  30. def get_icons
  31. items = Docs.all.map do |doc|
  32. base_path = "public/icons/docs/#{doc.slug}"
  33. {
  34. :type => doc.slug,
  35. :path_16 => "#{base_path}/16.png",
  36. :path_32 => "#{base_path}/16@2x.png"
  37. }
  38. end
  39. # Checking paths against an array of possible paths is faster than 200+ File.exist? calls
  40. files = Dir.glob('public/icons/docs/**/*.png')
  41. items.select {|item| files.include?(item[:path_16]) && files.include?(item[:path_32])}
  42. end
  43. def get_icon(path, max_size)
  44. icon = ChunkyPNG::Image.from_file(path)
  45. # Check if the icon is too big
  46. # If it is, resize the image without changing the aspect ratio
  47. if icon.width > max_size || icon.height > max_size
  48. ratio = icon.width.to_f / icon.height
  49. new_width = (icon.width >= icon.height ? max_size : max_size * ratio).floor
  50. new_height = (icon.width >= icon.height ? max_size / ratio : max_size).floor
  51. logger.warn("Icon #{path} is too big: max size is #{max_size} x #{max_size}, icon is #{icon.width} x #{icon.height}, resizing to #{new_width} x #{new_height}")
  52. icon.resample_nearest_neighbor!(new_width, new_height)
  53. end
  54. icon
  55. end
  56. def get_sidebar_background
  57. # This is a hacky way to get the background color of the sidebar
  58. # Unfortunately, it's not possible to get the value of a SCSS variable from a Thor task
  59. # Because hard-coding the value is even worse, we extract it using some regex
  60. path = 'assets/stylesheets/global/_variables-dark.scss'
  61. regex = /\$sidebarBackground:\s+([^;]+);/
  62. ChunkyPNG::Color.parse(File.read(path)[regex, 1])
  63. end
  64. def needs_dark_icon_fix(icon, bg_color)
  65. # Determine whether the icon needs to be grayscaled if the user has enabled the dark theme
  66. # The logic comes from https://www.w3.org/TR/2008/REC-WCAG20-20081211/#visual-audio-contrast
  67. contrast = icon.pixels.map do |pixel|
  68. get_contrast(bg_color, pixel)
  69. end
  70. contrast.max < 7
  71. end
  72. def get_contrast(base, other)
  73. l1 = get_luminance(base) + 0.05
  74. l2 = get_luminance(other) + 0.05
  75. ratio = l1 / l2
  76. l2 > l1 ? 1 / ratio : ratio
  77. end
  78. def get_luminance(color)
  79. rgba = [
  80. ChunkyPNG::Color.r(color).to_f,
  81. ChunkyPNG::Color.g(color).to_f,
  82. ChunkyPNG::Color.b(color).to_f,
  83. ChunkyPNG::Color.a(color).to_f
  84. ]
  85. rgba.map! do |rgb|
  86. rgb /= 255
  87. rgb < 0.03928 ? rgb / 12.92 : ((rgb + 0.055) / 1.055) ** 2.4
  88. end
  89. 0.2126 * rgba[0] + 0.7152 * rgba[1] + 0.0722 * rgba[2]
  90. end
  91. def generate_spritesheet(size, icons, output_path, &icon_to_img)
  92. logger.info("Generating spritesheet #{output_path} with icons of size #{size} x #{size}")
  93. icons_per_row = Math.sqrt(icons.length).ceil
  94. spritesheet = ChunkyPNG::Image.new(size * icons_per_row, size * icons_per_row)
  95. icons.each do |icon|
  96. img = icon_to_img.call(icon)
  97. # Calculate the base coordinates
  98. base_x = icon[:col] * size
  99. base_y = icon[:row] * size
  100. # Center the icon if it's not a perfect rectangle
  101. x = base_x + ((size - img.width) / 2).floor
  102. y = base_y + ((size - img.height) / 2).floor
  103. spritesheet.compose!(img, x, y)
  104. end
  105. FileUtils.mkdir_p(File.dirname(output_path))
  106. spritesheet.save(output_path)
  107. end
  108. def save_manifest(icons, icons_per_row, path)
  109. logger.info("Saving spritesheet details to #{path}")
  110. FileUtils.mkdir_p(File.dirname(path))
  111. # Only save the details that the scss file needs
  112. manifest_icons = icons.map do |icon|
  113. {
  114. :type => icon[:type],
  115. :row => icon[:row],
  116. :col => icon[:col],
  117. :dark_icon_fix => icon[:dark_icon_fix]
  118. }
  119. end
  120. manifest = {:icons_per_row => icons_per_row, :icons => manifest_icons}
  121. File.open(path, 'w') do |f|
  122. f.write(JSON.generate(manifest))
  123. end
  124. end
  125. def log_details(icons, icons_per_row)
  126. logger.debug("Amount of icons: #{icons.length}")
  127. logger.debug("Icons per row: #{icons_per_row}")
  128. max_type_length = icons.map { |icon| icon[:type].length }.max
  129. border = "+#{'-' * (max_type_length + 2)}+#{'-' * 5}+#{'-' * 8}+#{'-' * 15}+"
  130. logger.debug(border)
  131. logger.debug("| #{'Type'.ljust(max_type_length)} | Row | Column | Dark icon fix |")
  132. logger.debug(border)
  133. icons.each do |icon|
  134. logger.debug("| #{icon[:type].ljust(max_type_length)} | #{icon[:row].to_s.ljust(3)} | #{icon[:col].to_s.ljust(6)} | #{(icon[:dark_icon_fix] ? 'Yes' : 'No').ljust(13)} |")
  135. end
  136. logger.debug(border)
  137. end
  138. def logger
  139. @logger ||= Logger.new($stdout).tap do |logger|
  140. logger.level = options[:verbose] ? Logger::DEBUG : Logger::INFO
  141. logger.formatter = proc { |severity, datetime, progname, msg| "#{msg}\n" }
  142. end
  143. end
  144. end