Skip to content

Commit

Permalink
Allow additional handlers for special selectors to be added.
Browse files Browse the repository at this point in the history
Summary: This adds the ability for users of Aphrodite to add extensions
which support other special selectors. This should let people add
extensions to write global styles or many other not-terribly-well-supported
use cases until we have better solutions.

This adds docs on how to use the extensions, and adds a bunch of jsdocs
to make things clear in the code.

Test Plan:
 - `npm run test`
  • Loading branch information
xymostech committed Oct 21, 2016
1 parent 05f3f0c commit 6eaf4f5
Show file tree
Hide file tree
Showing 8 changed files with 451 additions and 151 deletions.
89 changes: 89 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,95 @@ then we end up with the opposite effect, with `foo` overriding `bar`! The way to
}
```
## Advanced: Extensions
Extra features can be added to Aphrodite using extensions.
To add extensions to Aphrodite, call `StyleSheet.extend` with the extensions
you are adding. The result will be an object containing the usual exports of
Aphrodite (`css`, `StyleSheet`, etc.) which will have your extensions included.
For example:
```js
// my-aphrodite.js
import {StyleSheet} from "aphrodite";

export default StyleSheet.extend([extension1, extension2]);

// styled.js
import {StyleSheet, css} from "my-aphrodite.js";

const styles = StyleSheet.create({
...
});
```
**Note**: Using extensions may cause Aphrodite's styles to not work properly.
Plain Aphrodite, when used properly, ensures that the correct styles will
always be applied to elements. Due to CSS specificity rules, extensions might
allow you to generate styles that conflict with each other, causing incorrect
styles to be shown. See the global extension below to see what could go wrong.
### Creating extensions
Currently, there is only one kind of extension available: selector handlers.
These kinds of extensions let you look at the selectors that someone specifies
and generate new selectors based on them. They are used to handle pseudo-styles
and media queries inside of Aphrodite. See the
[`defaultSelectorHandlers` docs](src/generate.js?L8) for information about how
to create a selector handler function.
To use your extension, create an object containing a key of the kind of
extension that you created, and pass that into `StyleSheet.extend()`:
```js
const mySelectorHandler = ...;

const myExtension = {selectorHandler: mySelectorHandler};

StyleSheet.extend([myExtension]);
```
As an example, you could write an extension which generates global styles like
```js
const globalSelectorHandler = (selector, _, generateSubtreeStyles) => {
if (selector[0] !== "*") {
return null;
}

return generateSubtreeStyles(selector.slice(1));
};

const globalExtension = {selectorHandler: globalSelectorHandler};
```
This might cause problems when two places try to generate styles for the same
global selector however! For example, after
```
const styles = StyleSheet.create({
globals: {
'*div': {
color: 'red',
},
}
});

const styles2 = StyleSheet.create({
globals: {
'*div': {
color: 'blue',
},
},
});

css(styles.globals);
css(styles2.globals);
```
It isn't determinate whether divs will be red or blue.
# Tools
- [Aphrodite output tool](https://output.jsbin.com/qoseye) - Paste what you pass to `StyleSheet.create` and see the generated CSS
Expand Down
125 changes: 125 additions & 0 deletions src/exports.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import {mapObj, hashObject} from './util';
import {
injectAndGetClassName,
reset, startBuffering, flushToString,
addRenderedClassNames, getRenderedClassNames,
} from './inject';

const StyleSheet = {
create(sheetDefinition) {
return mapObj(sheetDefinition, ([key, val]) => {
return [key, {
// TODO(emily): Make a 'production' mode which doesn't prepend
// the class name here, to make the generated CSS smaller.
_name: `${key}_${hashObject(val)}`,
_definition: val
}];
});
},

rehydrate(renderedClassNames=[]) {
addRenderedClassNames(renderedClassNames);
},
};

/**
* Utilities for using Aphrodite server-side.
*/
const StyleSheetServer = {
renderStatic(renderFunc) {
reset();
startBuffering();
const html = renderFunc();
const cssContent = flushToString();

return {
html: html,
css: {
content: cssContent,
renderedClassNames: getRenderedClassNames(),
},
};
},
};

/**
* Utilities for using Aphrodite in tests.
*
* Not meant to be used in production.
*/
const StyleSheetTestUtils = {
/**
* Prevent styles from being injected into the DOM.
*
* This is useful in situations where you'd like to test rendering UI
* components which use Aphrodite without any of the side-effects of
* Aphrodite happening. Particularly useful for testing the output of
* components when you have no DOM, e.g. testing in Node without a fake DOM.
*
* Should be paired with a subsequent call to
* clearBufferAndResumeStyleInjection.
*/
suppressStyleInjection() {
reset();
startBuffering();
},

/**
* Opposite method of preventStyleInject.
*/
clearBufferAndResumeStyleInjection() {
reset();
},
};

/**
* Generate the Aphrodite API exports, with given `selectorHandlers` and
* `useImportant` state.
*/
const makeExports = (useImportant, selectorHandlers) => {
return {
StyleSheet: {
...StyleSheet,

/**
* Returns a version of the exports of Aphrodite (i.e. an object
* with `css` and `StyleSheet` properties) which have some
* extensions included.
*
* @param {Array.<Object>} extensions: An array of extensions to
* add to this instance of Aphrodite. Each object should have a
* single property on it, defining which kind of extension to
* add.
* @param {SelectorHandler} [extensions[].selectorHandler]: A
* selector handler extension. See `defaultSelectorHandlers` in
* generate.js.
*
* @returns {Object} An object containing the exports of the new
* instance of Aphrodite.
*/
extend(extensions) {
const extensionSelectorHandlers = extensions
// Pull out extensions with a selectorHandler property
.map(extension => extension.selectorHandler)
// Remove nulls (i.e. extensions without a selectorHandler
// property).
.filter(handler => handler);

return makeExports(
useImportant,
selectorHandlers.concat(extensionSelectorHandlers)
);
},
},

StyleSheetServer,
StyleSheetTestUtils,

css(...styleDefinitions) {
return injectAndGetClassName(
useImportant, styleDefinitions, selectorHandlers);
},
};
};

module.exports = makeExports;
Loading

0 comments on commit 6eaf4f5

Please sign in to comment.