Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature request: create a Color from a hex string #9

Open
jamesarosen opened this issue Dec 7, 2018 · 2 comments
Open

Feature request: create a Color from a hex string #9

jamesarosen opened this issue Dec 7, 2018 · 2 comments

Comments

@jamesarosen
Copy link

I'm trying to build an eyeglass module that defines colors in JavaScript and exports them to Sass.

If I return sass.types.String('#abcdef'), then I can use it fine in places like

background-color: my-color();

but this fails:

box-shadow: 0 0 0 1px rgba(my-color(), 1)

with

argument `$color` of `rgba($color, $alpha)` must be a color

But changing that to sass.types.Color('#abcdef') blows up with

error in C function my-color: Only argument should be an integer.

The tests for this library construct a sass.types.Color with four decimal arguments:

sass.types.Color(30, 127, 0, 1.0)

I don't see anything like sassUtils.hexToColor('#abcdef'), though it would certainly be useful.

Possibly related to #7

@jamesarosen
Copy link
Author

This seems to work:

function hexToRGB(hex) {
  if (!/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)) throw new Error(`Invalid hex: ${hex}`)

  let c = hex.substring(1).split('')
  if (c.length == 3) {
    c = [c[0], c[0], c[1], c[1], c[2], c[2]]
  }
  c = `0x${c.join('')}`
  return [(c >> 16) & 255, (c >> 8) & 255, c & 255]
}

return sass.types.Color(...hexToRGB('#abcdef'), 1)

@BuonOmo
Copy link

BuonOmo commented Jan 9, 2019

You could even simplify the last two lines of your function using:

function hexToRGBA(hex) {
  if (!/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)) throw new Error(`Invalid hex: ${hex}`)

  let c = hex.substring(1).split('')
  if (c.length == 3) {
    c = [c[0], c[0], c[1], c[1], c[2], c[2]]
  }
  c = `0xff${c.join('')}`
  return Number(c)
}

return sass.types.Color(hexToRGBA(hex))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants