Skip to content

Instantly share code, notes, and snippets.

@basarat
Created October 11, 2016 21:46
Show Gist options
  • Save basarat/4304a7036a5cc94dfb5ecceabe7cc4c5 to your computer and use it in GitHub Desktop.
Save basarat/4304a7036a5cc94dfb5ecceabe7cc4c5 to your computer and use it in GitHub Desktop.
import { StyleSheet, css } from 'aphrodite';
/** Just for autocomplete convinience */
export interface CSSProperties extends React.CSSProperties {
':hover'?: React.CSSProperties;
':active'?: React.CSSProperties;
}
/**
* Takes CSSProperties and return a generated className you can use on your component
*/
export function style(...objects: CSSProperties[]): string;
export function style(name: string, ...objects: CSSProperties[]): string;
export function style(_name: any, ...objects: any[]): string {
const name = typeof _name === 'string' ? _name : 'anonymous';
const object = extend(...(typeof _name === 'string' ? objects : [_name, ...objects]));
const className = css(StyleSheet.create({[name]:object})[name]);
return className;
}
/**
* Merges various styles into a single style object.
* Note: if two objects have the same property the last one wins
*/
export function extend(...objects: CSSProperties[]): CSSProperties{
/** The final result we will return */
const result: CSSProperties = {};
for (const object of objects) {
for (const key in object) {
if (
// Some psuedo state or media query
(key.indexOf(':') === 0 || key.indexOf('@media') === 0 || key.indexOf('animation') === 0)
// And we already have something for this key
&& result[key]
) {
// Then extend in the final result
result[key] = extend(result[key], object);
}
// Otherwise just copy to output
else {
result[key] = object[key];
}
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment