Skip to content

Commit

Permalink
Merge pull request openSUSE#16641 from danidoni/move-color-helpers-to…
Browse files Browse the repository at this point in the history
…-its-own-file

Move color helpers to its own file
  • Loading branch information
danidoni authored Aug 6, 2024
2 parents d177994 + 33512bd commit 6220d35
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 22 deletions.
22 changes: 22 additions & 0 deletions src/api/app/helpers/webui/color_helper.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
module Webui::ColorHelper
# Calculates a text color that will contrast well with the given color
def contrast_text(color)
red_component = color[1..2].to_i(16)
green_component = color[3..4].to_i(16)
blue_component = color[5..6].to_i(16)

red = relative_luminance(red_component / 255.0)
green = relative_luminance(green_component / 255.0)
blue = relative_luminance(blue_component / 255.0)

# https://www.w3.org/TR/WCAG20/#contrast-ratiodef
((0.2126 * red) + (0.7152 * green) + (0.0722 * blue)) > 0.179 ? 'black' : 'white'
end

# https://www.w3.org/TR/WCAG20/#relativeluminancedef
def relative_luminance(color)
return color / 12.92 if color <= 0.03928

((color + 0.055) / 1.055)**2.4
end
end
22 changes: 0 additions & 22 deletions src/api/app/helpers/webui/webui_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -342,28 +342,6 @@ def contact_link
url = ::Configuration.contact_url || "mailto:#{::Configuration.admin_email}"
link_to(name, url)
end

# Calculates a text color that will contrast well with the given color
def contrast_text(color)
blue_component = color % 0x100
color_without_blue = ((color - blue_component) / 0x100)
green_component = color_without_blue % 0x100
red_component = ((color_without_blue - green_component) / 0x100)

red = relative_luminance(red_component / 255.0)
green = relative_luminance(green_component / 255.0)
blue = relative_luminance(blue_component / 255.0)

# https://www.w3.org/TR/WCAG20/#contrast-ratiodef
((0.2126 * red) + (0.7152 * green) + (0.0722 * blue)) > 0.179 ? 'black' : 'white'
end

# https://www.w3.org/TR/WCAG20/#relativeluminancedef
def relative_luminance(color)
return color / 12.92 if color <= 0.03928

((color + 0.055) / 1.055)**2.4
end
end

# rubocop:enable Metrics/ModuleLength
15 changes: 15 additions & 0 deletions src/api/spec/helpers/webui/color_helper_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
RSpec.describe Webui::ColorHelper do
describe '#contrast_text' do
context 'when passing a light color' do
it 'returns a black text' do
expect(contrast_text('#ffffff')).to eql('black')
end
end

context 'when passing a dark color' do
it 'returns a white text' do
expect(contrast_text('#000000')).to eql('white')
end
end
end
end

0 comments on commit 6220d35

Please sign in to comment.