Skip to content

Instantly share code, notes, and snippets.

@javan
Created March 23, 2018 20:02
Show Gist options
  • Save javan/a8a237f0db7648ba88d66cf9a50fa1f5 to your computer and use it in GitHub Desktop.
Save javan/a8a237f0db7648ba88d66cf9a50fa1f5 to your computer and use it in GitHub Desktop.
getHexColor = (color) ->
return "" unless color
return color if /^#/.test(color)
rgbValues = getRGBValues(color)
hexValues = rgbValues.map(numberToHex)
"#" + hexValues.join("")
numberToHex = (number) ->
"0#{number.toString(16)}".slice(-2).toUpperCase()
getRGBValues = (color) ->
if match = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/i)
[..., r, g, b] = match
else
canvas = document.createElement("canvas")
canvas.height = canvas.width = 1
context = canvas.getContext("2d")
context.fillStyle = color
context.fillRect(0, 0, 1, 1)
{data} = context.getImageData(0, 0, 1, 1)
[r, g, b] = data
[r, g, b].map(Number)
createColorParser = ->
(element) ->
while element and element.tagName isnt "TRIX-EDITOR"
if styleColor = element.style[@styleProperty]
if color = getHexColor(styleColor)
return color
element = element.parentElement
Trix.config.textAttributes.foregroundColor =
inheritable: true
styleProperty: "color"
parser: createColorParser()
Trix.config.textAttributes.backgroundColor =
inheritable: true
styleProperty: "backgroundColor"
parser: createColorParser()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment