Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow additional handlers for special selectors to be added. #95

Merged
merged 1 commit into from
Oct 21, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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]);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line wouldn't do anything, right? It's only the return value of this that would contain the extension?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah yes, that is correct. I'm not sure how to indicate that. module.exports =? const {StyleSheet, css} =?

```

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.
Copy link
Collaborator

@jlfwong jlfwong Oct 12, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hrm, I'm not sure I'd say it's non deterministic -- I think this falls into what compilers typically refer to as "undefined behavior", right? So we can say that it's undefined behavior whether the divs will be red or blue.

Given this precise code listed here, the result will be deterministic, no?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes that is correct. "Undefined behaviour" sounds better.


# 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