Class: Unmagic::Color

Inherits:
Object
  • Object
show all
Includes:
Harmony
Defined in:
lib/unmagic/color.rb,
lib/unmagic/color/hsl.rb,
lib/unmagic/color/rgb.rb,
lib/unmagic/color/oklch.rb,
lib/unmagic/color/harmony.rb,
lib/unmagic/color/rgb/hex.rb,
lib/unmagic/color/version.rb,
lib/unmagic/color/gradient.rb,
lib/unmagic/color/rgb/ansi.rb,
lib/unmagic/color/rgb/named.rb,
lib/unmagic/color/console/card.rb,
lib/unmagic/color/console/help.rb,
lib/unmagic/color/gradient/base.rb,
lib/unmagic/color/gradient/stop.rb,
lib/unmagic/color/units/degrees.rb,
lib/unmagic/color/console/banner.rb,
lib/unmagic/color/gradient/bitmap.rb,
lib/unmagic/color/units/direction.rb,
lib/unmagic/color/console/highlighter.rb,
lib/unmagic/color/hsl/gradient/linear.rb,
lib/unmagic/color/rgb/gradient/linear.rb,
lib/unmagic/color/string/hash_function.rb,
lib/unmagic/color/oklch/gradient/linear.rb

Overview

Base class for working with colors in different color spaces.

## Understanding Colors

A color is simply a way to describe what we see. Just like you can describe a location using different coordinate systems (street address, latitude/longitude, etc.), you can describe colors using different “color spaces.”

This library supports three main color spaces:

  • RGB: Describes colors as a mix of Red, Green, and Blue light (like your screen)

  • HSL: Describes colors using Hue (color wheel position), Saturation (intensity), and Lightness (brightness)

  • OKLCH: A modern color space that matches how humans perceive color differences

## Basic Usage

Parse a color from a string:

color = Unmagic::Color.parse("#FF5733")
color = Unmagic::Color["rgb(255, 87, 51)"]
color = Unmagic::Color.parse("hsl(9, 100%, 60%)")

Convert between color spaces:

rgb = Unmagic::Color.parse("#FF5733")
hsl = rgb.to_hsl
oklch = rgb.to_oklch

Manipulate colors:

lighter = color.lighten(0.2)
darker = color.darken(0.1)
mixed = color.blend(other_color, 0.5)

Direct Known Subclasses

HSL, OKLCH, RGB

Defined Under Namespace

Modules: Console, Gradient, Harmony, Units Classes: Alpha, Chroma, Component, Error, HSL, Hue, Lightness, OKLCH, ParseError, RGB, Saturation, String

Constant Summary collapse

DATA_PATH =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

Path to the data directory containing color databases.

File.join(__dir__, "..", "..", "data")
Red =

Type alias for red component

Component
Green =

Type alias for green component

Component
Blue =

Type alias for blue component

Component
VERSION =

Current version of the Unmagic::Color gem

"0.3"

Constants included from Harmony

Harmony::SCALE_CHROMA_CURVE, Harmony::SCALE_LIGHTNESS_DEFAULT, Harmony::SCALE_LIGHTNESS_SHAPE

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Harmony

#analogous, #complementary, #monochromatic, #scale, #shades, #split_complementary, #tetradic_rectangle, #tetradic_square, #tints, #tones, #triadic

Class Method Details

.[](value) ⇒ RGB, ...

Parse a color string using bracket notation.

This is a convenient alias for parse.

Examples:

Unmagic::Color["#FF5733"]
Unmagic::Color["hsl(9, 100%, 60%)"]

Parameters:

Returns:

  • (RGB, HSL, OKLCH)

    A color object in the appropriate color space

Raises:



135
136
137
# File 'lib/unmagic/color.rb', line 135

def [](value)
  parse(value)
end

.parse(input) ⇒ RGB, ...

Parse a color string into the appropriate color space object.

This method automatically detects the format and returns the correct color type. Supported formats include hex colors, RGB, HSL, OKLCH, and named colors.

Examples:

Parse a hex color

Unmagic::Color.parse("#FF5733")

Parse an RGB color

Unmagic::Color.parse("rgb(255, 87, 51)")

Parse an HSL color

Unmagic::Color.parse("hsl(9, 100%, 60%)")

Parse an OKLCH color

Unmagic::Color.parse("oklch(0.65 0.15 30)")

Parse a named color

Unmagic::Color.parse("goldenrod")

Pass through an existing color

color = Unmagic::Color.parse("#FF5733")
Unmagic::Color.parse(color)

Parameters:

  • input (String, Color)

    The color string to parse, or an existing Color object

Returns:

  • (RGB, HSL, OKLCH)

    A color object in the appropriate color space

Raises:

  • (ParseError)

    If the input is nil, empty, or in an unrecognized format



101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/unmagic/color.rb', line 101

def parse(input)
  return input if input.is_a?(self)
  raise ParseError, "Can't pass nil as a color" if input.nil?

  input = input.strip
  raise ParseError, "Can't parse empty string" if input == ""

  # Try hex or RGB format
  if input.start_with?("#") || input.match?(/\A[0-9A-Fa-f]{3,6}\z/) || input.start_with?("rgb")
    RGB.parse(input)
  elsif input.start_with?("hsl")
    HSL.parse(input)
  elsif input.start_with?("oklch")
    OKLCH.parse(input)
  elsif input.match?(/\A\d+(?:;\d+)*\z/) && RGB::ANSI.valid?(input)
    RGB::ANSI.parse(input)
  elsif RGB::Named.valid?(input)
    RGB::Named.parse(input)
  else
    raise ParseError, "Unknown color #{input.inspect}"
  end
end

Instance Method Details

#blend(other, amount = 0.5) ⇒ Color

Blend this color with another color.

Creates a new color by mixing this color with another. The amount parameter controls how much of the other color to mix in.

Examples:

Mix two colors equally

red = Unmagic::Color.parse("#FF0000")
blue = Unmagic::Color.parse("#0000FF")
red.blend(blue, 0.5)

Add a hint of another color

base = Unmagic::Color.parse("#336699")
base.blend(Unmagic::Color.parse("#FF0000"), 0.1)

Parameters:

  • other (Color)

    The color to blend with

  • amount (Float) (defaults to: 0.5)

    How much of the other color to use (0.0 to 1.0)

Returns:

  • (Color)

    A new color that is a blend of the two colors

Raises:

  • (NotImplementedError)


437
438
439
# File 'lib/unmagic/color.rb', line 437

def blend(other, amount = 0.5)
  raise NotImplementedError
end

#dark?Boolean

Check if this is a dark color.

A color is considered dark if its luminance is 0.5 or less. This is the opposite of #light?.

Returns:

  • (Boolean)

    true if the color is dark, false otherwise



493
494
495
# File 'lib/unmagic/color.rb', line 493

def dark?
  !light?
end

#darken(amount = 0.1) ⇒ Color

Create a darker version of this color.

Returns a new color that is darker than the original. The exact implementation depends on the color space.

Examples:

Make a color 10% darker

bright = Unmagic::Color.parse("#FF9966")
bright.darken(0.1)

Parameters:

  • amount (Float) (defaults to: 0.1)

    How much to darken (0.0 to 1.0)

Returns:

  • (Color)

    A new, darker color

Raises:

  • (NotImplementedError)


467
468
469
# File 'lib/unmagic/color.rb', line 467

def darken(amount = 0.1)
  raise NotImplementedError
end

#light?Boolean

Check if this is a light color.

A color is considered light if its luminance is greater than 0.5. This is useful for determining whether to use dark or light text on a colored background.

Examples:

Choose text color based on background

bg = Unmagic::Color.parse("#FFFF00")  # Yellow
text_color = bg.light? ? "#000000" : "#FFFFFF"
# => "#000000"

Returns:

  • (Boolean)

    true if the color is light, false otherwise



483
484
485
# File 'lib/unmagic/color.rb', line 483

def light?
  luminance > 0.5
end

#lighten(amount = 0.1) ⇒ Color

Create a lighter version of this color.

Returns a new color that is lighter than the original. The exact implementation depends on the color space.

Examples:

Make a color 20% lighter

dark = Unmagic::Color.parse("#336699")
dark.lighten(0.2)

Parameters:

  • amount (Float) (defaults to: 0.1)

    How much to lighten (0.0 to 1.0)

Returns:

  • (Color)

    A new, lighter color

Raises:

  • (NotImplementedError)


452
453
454
# File 'lib/unmagic/color.rb', line 452

def lighten(amount = 0.1)
  raise NotImplementedError
end

#luminanceFloat

Calculate the perceptual luminance of this color.

Luminance represents how bright the color appears to the human eye, accounting for the fact that we perceive green as brighter than red, and red as brighter than blue.

Returns:

  • (Float)

    The luminance value from 0.0 (black) to 1.0 (white)

Raises:

  • (NotImplementedError)


416
417
418
# File 'lib/unmagic/color.rb', line 416

def luminance
  raise NotImplementedError
end

#to_ansi(layer: :foreground) ⇒ String

Convert this color to an ANSI SGR color code.

Returns an ANSI Select Graphic Rendition (SGR) parameter string that can be used in terminal output. The returned string does not include the escape sequence prefix (x1b[) or the trailing ‘m’.

Examples:

Output red text

color = Unmagic::Color.parse("red")
puts "\x1b[#{color.to_ansi}mHello\x1b[0m"

Set background color

color = Unmagic::Color.parse("#336699")
puts "\x1b[#{color.to_ansi(layer: :background)}mText\x1b[0m"

Parameters:

  • layer (Symbol) (defaults to: :foreground)

    Whether to generate foreground (:foreground) or background (:background) code

Returns:

  • (String)

    ANSI SGR code like “31” or “38;2;255;0;0”

Raises:

  • (NotImplementedError)


405
406
407
# File 'lib/unmagic/color.rb', line 405

def to_ansi(layer: :foreground)
  raise NotImplementedError
end

#to_hslHSL

Convert this color to HSL color space.

HSL represents colors using Hue (0-360°), Saturation (0-100%), and Lightness (0-100%).

Returns:

  • (HSL)

    The color in HSL color space

Raises:

  • (NotImplementedError)


375
376
377
# File 'lib/unmagic/color.rb', line 375

def to_hsl
  raise NotImplementedError
end

#to_oklchOKLCH

Convert this color to OKLCH color space.

OKLCH is a perceptually uniform color space that better matches how humans perceive color differences.

Returns:

  • (OKLCH)

    The color in OKLCH color space

Raises:

  • (NotImplementedError)


385
386
387
# File 'lib/unmagic/color.rb', line 385

def to_oklch
  raise NotImplementedError
end

#to_rgbRGB

Convert this color to RGB color space.

RGB represents colors as a combination of Red, Green, and Blue light, with each component ranging from 0-255.

Returns:

  • (RGB)

    The color in RGB color space

Raises:

  • (NotImplementedError)


365
366
367
# File 'lib/unmagic/color.rb', line 365

def to_rgb
  raise NotImplementedError
end