Merge pull request #261 from erquhart/master

Add widgetsFor helper - fixes #236
This commit is contained in:
David Calavera 2017-03-11 10:35:45 -08:00 committed by GitHub
commit 8ffe6730fa
3 changed files with 145 additions and 13 deletions

View File

@ -37,9 +37,10 @@ Registers a template for a collection.
**React Component Props:**
* collection: The name of the collection which this preview component will be used for.
* react_component: A React component that renders the collection data. Three props will be passed to your component during render:
* react_component: A React component that renders the collection data. Four props will be passed to your component during render:
* entry: Immutable collection containing the entry data.
* widgetFor: Returns the appropriate widget preview component for a given field.
* [widgetsFor](#lists-and-objects): Returns an array of objects with widgets and associated field data. For use with list and object type entries.
* getAsset: Returns the correct filePath or in-memory preview for uploaded images.
**Example:**
@ -63,6 +64,95 @@ CMS.registerPreviewTemplate("posts", PostPreview);
</script>
```
### Lists and Objects
The API for accessing the individual fields of list and object type entries is similar to the API
for accessing fields in standard entries, but there are a few key differences. Access to these
nested fields is facilitated through the `widgetsFor` function, which is passed to the preview
template component during render.
**Note**: as is often the case with the Netlify CMS API, arrays and objects are created with
Immutable.js. If some of the methods that we use are unfamiliar, such as `getIn`, check out
[their docs](https://facebook.github.io/immutable-js/docs/#/) to get a better understanding.
**List Example:**
```html
<script>
var AuthorsPreview = createClass({
// For list fields, the widgetFor function returns an array of objects
// which you can map over in your template. If our field is a list of
// authors containing two entries, with fields `name` and `description`,
// the return value of `widgetsFor` would look like this:
//
// [{
// data: { name: 'Mathias', description: 'Co-Founder'},
// widgets: { name: (<WidgetComponent>), description: (WidgetComponent>)}
// },
// {
// data: { name: 'Chris', description: 'Co-Founder'},
// widgets: { name: (<WidgetComponent>), description: (WidgetComponent>)}
// }]
//
// Templating would look something like this:
render: function() {
return h('div', {},
// This is a static header that would only be rendered once for the entire list
h('h1', {}, 'Authors'),
// Here we provide a simple mapping function that will be applied to each
// object in the array of authors
this.props.widgetsFor('authors').map(function(author, index) {
return h('div', {key: index},
h('hr', {}),
h('strong', {}, author.getIn(['data', 'name'])),
author.getIn(['widgets', 'description'])
);
})
);
}
});
CMS.registerPreviewTemplate("authors", AuthorsPreview);
</script>
```
**Object Example:**
```html
<script>
var GeneralPreview = createClass({
// Object fields are simpler than lists - instead of `widgetsFor` returning
// an array of objects, it returns a single object. Accessing the shape of
// that object is the same as the shape of objects returned for list fields:
//
// {
// data: { front_limit: 0, author: 'Chris' },
// widgets: { front_limit: (<WidgetComponent>), author: (WidgetComponent>)}
// }
render: function() {
var entry = this.props.entry;
var title = entry.getIn(['data', 'site_title']);
var posts = entry.getIn(['data', 'posts']);
return h('div', {},
h('h1', {}, title),
h('dl', {},
h('dt', {}, 'Posts on Frontpage'),
h('dd', {}, this.props.widgetsFor('posts').getIn(['widgets', 'front_limit']) || 0),
h('dt', {}, 'Default Author'),
h('dd', {}, this.props.widgetsFor('posts').getIn(['data', 'author']) || 'None'),
)
);
}
});
CMS.registerPreviewTemplate("general", GeneralPreview);
</script>
```
### Accessing Metadata
Preview Components also receive an additional prop: `fieldsMetaData`. It contains aditional information (besides the plain plain textual value of each field) that can be useful for preview purposes.

View File

@ -98,10 +98,10 @@
h('h1', {}, title),
h('dl', {},
h('dt', {}, 'Posts on Frontpage'),
h('dd', {}, posts && posts.get('front_limit') || '0'),
h('dd', {}, this.props.widgetsFor('posts').getIn(['widgets', 'front_limit']) || 0),
h('dt', {}, 'Default Author'),
h('dd', {}, posts && posts.get('author') || 'None'),
h('dd', {}, this.props.widgetsFor('posts').getIn(['data', 'author']) || 'None'),
h('dt', {}, 'Default Thumbnail'),
h('dd', {}, thumb && h('img', {src: this.props.getAsset(thumb).toString()}))
@ -110,8 +110,24 @@
}
});
var AuthorsPreview = createClass({
render: function() {
return h('div', {},
h('h1', {}, 'Authors'),
this.props.widgetsFor('authors').map(function(author, index) {
return h('div', {key: index},
h('hr', {}),
h('strong', {}, author.getIn(['data', 'name'])),
author.getIn(['widgets', 'description'])
);
})
);
}
});
CMS.registerPreviewTemplate("posts", PostPreview);
CMS.registerPreviewTemplate("general", GeneralPreview);
CMS.registerPreviewTemplate("authors", AuthorsPreview);
CMS.registerPreviewStyle("/example.css");
CMS.registerEditorComponent({
id: "youtube",

View File

@ -1,5 +1,6 @@
import React, { PropTypes } from 'react';
import ReactDOM from 'react-dom';
import { List, Map } from 'immutable';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { ScrollSyncPane } from '../ScrollSync';
import registry from '../../lib/registry';
@ -15,6 +16,18 @@ export default class PreviewPane extends React.Component {
this.renderPreview();
}
getWidget = (field, value, props) => {
const { fieldsMetaData, getAsset } = props;
const widget = resolveWidget(field.get('widget'));
return React.createElement(widget.preview, {
field,
key: field.get('name'),
value: value && Map.isMap(value) ? value.get(field.get('name')) : value,
metadata: fieldsMetaData && fieldsMetaData.get(field.get('name')),
getAsset,
});
};
inferedFields = {};
inferFields() {
@ -29,24 +42,35 @@ export default class PreviewPane extends React.Component {
}
widgetFor = (name) => {
const { fields, entry, fieldsMetaData, getAsset } = this.props;
const { fields, entry } = this.props;
const field = fields.find(f => f.get('name') === name);
let value = entry.getIn(['data', field.get('name')]);
const metadata = fieldsMetaData.get(field.get('name'));
const labelledWidgets = ['string', 'text', 'number'];
if (Object.keys(this.inferedFields).indexOf(name) !== -1) {
value = this.inferedFields[name].defaultPreview(value);
} else if (value && labelledWidgets.indexOf(field.get('widget')) !== -1 && value.toString().length < 50) {
value = <div><strong>{field.get('label')}:</strong> {value}</div>;
}
if (!value) return null;
const widget = resolveWidget(field.get('widget'));
return React.createElement(widget.preview, {
key: field.get('name'),
value,
field,
metadata,
getAsset,
return value ? this.getWidget(field, value, this.props) : null;
};
widgetsFor = (name) => {
const { fields, entry } = this.props;
const field = fields.find(f => f.get('name') === name);
const nestedFields = field && field.get('fields');
const value = entry.getIn(['data', field.get('name')]);
if (List.isList(value)) {
return value.map((val, index) => {
const widgets = nestedFields && Map(nestedFields.map((f, i) => [f.get('name'), <div key={i}>{this.getWidget(f, val, this.props)}</div>]));
return Map({ data: val, widgets });
});
}
return Map({
data: value,
widgets: nestedFields && Map(nestedFields.map(f => [f.get('name'), this.getWidget(f, value, this.props)])),
});
};
@ -80,7 +104,9 @@ export default class PreviewPane extends React.Component {
const previewProps = {
...this.props,
widgetFor: this.widgetFor,
widgetsFor: this.widgetsFor,
};
// We need to use this API in order to pass context to the iframe
ReactDOM.unstable_renderSubtreeIntoContainer(
this,