From 9dca9f912ad667a2d77be52e68c2b08bda8b9a43 Mon Sep 17 00:00:00 2001 From: Shawn Erquhart Date: Mon, 6 Mar 2017 12:27:41 -0500 Subject: [PATCH] add widgetsFor helper This allows individual widgets to be accessed from preview templates that handle lists --- example/index.html | 16 +++++++++++++++ src/components/PreviewPane/PreviewPane.js | 25 +++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/example/index.html b/example/index.html index 73c98009..6737c292 100644 --- a/example/index.html +++ b/example/index.html @@ -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", diff --git a/src/components/PreviewPane/PreviewPane.js b/src/components/PreviewPane/PreviewPane.js index 07903ab1..04cf3c93 100644 --- a/src/components/PreviewPane/PreviewPane.js +++ b/src/components/PreviewPane/PreviewPane.js @@ -1,5 +1,6 @@ import React, { PropTypes } from 'react'; import ReactDOM from 'react-dom'; +import { Map } from 'immutable'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { ScrollSyncPane } from '../ScrollSync'; import registry from '../../lib/registry'; @@ -50,6 +51,28 @@ export default class PreviewPane extends React.Component { }); }; + widgetsFor = (name) => { + const { fields, entry, getAsset } = this.props; + const field = fields && fields.find(f => f.get('name') === name); + const nestedFields = field && field.get('fields'); + const values = entry.getIn(['data', field.get('name')]); + + const widgetFor = (field, value) => { + const widget = resolveWidget(field.get('widget')); + return (
{React.createElement(widget.preview, { + key: field.get('name'), + value: value && value.get(field.get('name')), + field, + getAsset, + })}
); + }; + + return values ? values.map((value, index) => { + const widgets = nestedFields && Map(nestedFields.map(f => [f.get('name'), widgetFor(f, value)])); + return Map({ data: value, widgets }); + }) : null; + }; + handleIframeRef = (ref) => { if (ref) { registry.getPreviewStyles().forEach((style) => { @@ -80,7 +103,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,