Skip to content

Instantly share code, notes, and snippets.

@bockoblur
Last active February 28, 2019 14:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bockoblur/7530ddaaa92320f688aa4ede97024e32 to your computer and use it in GitHub Desktop.
Save bockoblur/7530ddaaa92320f688aa4ede97024e32 to your computer and use it in GitHub Desktop.
Ionic 4 : Add new predefined colors (and enumerate them)
// make sure you include tinycolor library from npm
// npm install tinycolor2
const ionPrefix = ".ion-color-";
//
// example usage
//
// addIonColor("myColor", "#123456");
//
// adds 'myColor' to predefined Ionic colors, so that it can be used like
// <ion-button color="myColor">Button Text</ion-button>
//
function addIonColor(name, baseColor){
const namePattern = /^[a-zA-Z][\-_0-9A-Za-z]+$/;
if(!namePattern.test(name)){
throw new Error(`Invalid color name: ${name}`);
return;
}
let color = new tinycolor(baseColor);
if ( !color.isValid() ) {
throw new Error(`Invalid color value: ${baseColor}`)
return;
}
let hex = color.toString('hex6');
let rgb = color.toRgb();
let contrast = tinycolor( color.isLight() ? "#222222" : "#EEEEEE" );
let contrastRgb = contrast.toRgb();
let css =
`${ionPrefix+name} {
--ion-color-base: ${hex};
--ion-color-base-rgb: ${rgb.r},${rgb.g},${rgb.b};
--ion-color-contrast: ${contrast.toString('hex6')};
--ion-color-contrast-rgb: ${contrastRgb.r},${contrastRgb.g},${contrastRgb.b};
--ion-color-shade: ${color.darken().toString('hex6')};
--ion-color-tint: ${color.lighten().toString('hex6')};
}
`
//console.log(css) ;
let docStyle = document.createElement('style');
docStyle.type = 'text/css';
docStyle.innerHTML = css;
document.getElementsByTagName('head')[0].appendChild(docStyle);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment