-
-
Save kaspermeyer/922f94de98d6a2e7eb912cc52a45309f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Kasper, how would someone go about implement this with a button on the Trix editor?