sprites.thor 7.0 KB

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