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

Widget fixes #162

Merged
merged 10 commits into from
Nov 17, 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
7 changes: 5 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,10 @@
"git add"
]
},
"files": ["dist/", "README.md"],
"files": [
"dist/",
"README.md"
],
"pre-commit": "lint:staged",
"jest": {
"moduleNameMapper": {
Expand Down Expand Up @@ -127,7 +130,7 @@
"react-datetime": "^2.6.0",
"react-dom": "^15.1.0",
"react-hot-loader": "^3.0.0-beta.2",
"react-immutable-proptypes": "^1.6.0",
"react-immutable-proptypes": "^2.1.0",
"react-lazy-load": "^3.0.3",
"react-portal": "^2.2.1",
"react-pure-render": "^1.0.2",
Expand Down
16 changes: 7 additions & 9 deletions src/components/ControlPanel/ControlPane.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ function isHidden(field) {
export default class ControlPane extends Component {

controlFor(field) {
const { entry, fields, getMedia, onChange, onAddMedia, onRemoveMedia } = this.props;
const { entry, getMedia, onChange, onAddMedia, onRemoveMedia } = this.props;
const widget = resolveWidget(field.get('widget'));
const fieldName = field.get('name');
const value = entry.getIn(['data', fieldName]);
Expand Down Expand Up @@ -41,14 +41,12 @@ export default class ControlPane extends Component {
return (
<div>
{
fields.map(field =>
isHidden(field) ? null : <div
key={field.get('name')}
className={styles.widget}
>
{this.controlFor(field)}
</div>
)
fields.map((field) => {
if (isHidden(field)) {
return null;
}
return <div key={field.get('name')} className={styles.widget}>{this.controlFor(field)}</div>;
})
}
</div>
);
Expand Down
35 changes: 16 additions & 19 deletions src/components/PreviewPane/PreviewPane.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export default class PreviewPane extends React.Component {

widgetFor = (name) => {
const { fields, entry, getMedia } = this.props;
const field = fields.find(field => field.get('name') === name);
const field = fields.find(f => f.get('name') === name);
const widget = resolveWidget(field.get('widget'));
return React.createElement(widget.preview, {
key: field.get('name'),
Expand All @@ -25,6 +25,21 @@ export default class PreviewPane extends React.Component {
});
};

handleIframeRef = (ref) => {
if (ref) {
registry.getPreviewStyles().forEach((style) => {
const linkEl = document.createElement('link');
linkEl.setAttribute('rel', 'stylesheet');
linkEl.setAttribute('href', style);
ref.contentDocument.head.appendChild(linkEl);
});
this.previewEl = document.createElement('div');
this.iframeBody = ref.contentDocument.body;
this.iframeBody.appendChild(this.previewEl);
this.renderPreview();
}
};

renderPreview() {
const { entry, collection } = this.props;
const component = registry.getPreviewTemplate(selectTemplateName(collection, entry.get('slug'))) || Preview;
Expand All @@ -42,21 +57,6 @@ export default class PreviewPane extends React.Component {
, this.previewEl);
}

handleIframeRef = (ref) => {
if (ref) {
registry.getPreviewStyles().forEach((style) => {
const linkEl = document.createElement('link');
linkEl.setAttribute('rel', 'stylesheet');
linkEl.setAttribute('href', style);
ref.contentDocument.head.appendChild(linkEl);
});
this.previewEl = document.createElement('div');
this.iframeBody = ref.contentDocument.body;
this.iframeBody.appendChild(this.previewEl);
this.renderPreview();
}
};

render() {
const { collection } = this.props;
if (!collection) {
Expand All @@ -72,7 +72,4 @@ PreviewPane.propTypes = {
fields: ImmutablePropTypes.list.isRequired,
entry: ImmutablePropTypes.map.isRequired,
getMedia: PropTypes.func.isRequired,
scrollTop: PropTypes.number,
scrollHeight: PropTypes.number,
offsetHeight: PropTypes.number,
};
10 changes: 8 additions & 2 deletions src/components/Widgets.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,12 @@ import MarkdownControl from './Widgets/MarkdownControl';
import MarkdownPreview from './Widgets/MarkdownPreview';
import ImageControl from './Widgets/ImageControl';
import ImagePreview from './Widgets/ImagePreview';
import DateControl from './Widgets/DateControl';
import DatePreview from './Widgets/DatePreview';
import DateTimeControl from './Widgets/DateTimeControl';
import DateTimePreview from './Widgets/DateTimePreview';
import SelectControl from './Widgets/SelectControl';
import SelectPreview from './Widgets/SelectPreview';
import ObjectControl from './Widgets/ObjectControl';
import ObjectPreview from './Widgets/ObjectPreview';

Expand All @@ -24,10 +28,12 @@ registry.registerWidget('number', NumberControl, NumberPreview);
registry.registerWidget('list', ListControl, ListPreview);
registry.registerWidget('markdown', MarkdownControl, MarkdownPreview);
registry.registerWidget('image', ImageControl, ImagePreview);
registry.registerWidget('date', DateControl, DatePreview);
registry.registerWidget('datetime', DateTimeControl, DateTimePreview);
registry.registerWidget('select', SelectControl, SelectPreview);
registry.registerWidget('object', ObjectControl, ObjectPreview);
registry.registerWidget('unknown', UnknownControl, UnknownPreview);

export function resolveWidget(name) {
return registry.getWidget(name) || registry.getWidget('unknown');
export function resolveWidget(name) { // eslint-disable-line
return registry.getWidget(name || 'string') || registry.getWidget('unknown');
}
21 changes: 21 additions & 0 deletions src/components/Widgets/DateControl.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import React, { PropTypes } from 'react';
import DateTime from 'react-datetime';

export default class DateControl extends React.Component {
handleChange = (datetime) => {
this.props.onChange(datetime);
};

render() {
return (<DateTime
timeFormat={false}
value={this.props.value || new Date()}
onChange={this.handleChange}
/>);
}
}

DateControl.propTypes = {
onChange: PropTypes.func.isRequired,
value: PropTypes.object,
Copy link
Contributor Author

Choose a reason for hiding this comment

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

PropTypes.object is not allowed in our linting rules, but i'm not sure there's any better choice for the DateControl or the DateTimeControl.

The problem here is that depending on the formatter the value for a date control can either be a string, a Date or a moment.js object and the control (and preview) component should do the right thing with either of those.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Our linter treats PropTypes.object as an error, but in this case I'm not sure there's a better option.

The DateControl (and preview) should be able to handle either a string, a Date or a moment.js object, since this will vary depending on the formatter (JSON and CSV for example, doesn't have any date concept and will deserialize date fields to a string).

Copy link
Contributor

Choose a reason for hiding this comment

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

There is a propType for that PropType.oneOfType :)

Also, I'd suggest we don't couple with moment.js so tightly. So, I'd say:

PropTypes.oneOfType([
  React.PropTypes.string,
  React.PropTypes.instanceOf(Date)
])

Copy link
Contributor

Choose a reason for hiding this comment

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

Also, in case it is an object with the known shape, there is https://facebook.github.io/react/docs/react-api.html#react.proptypes.shape

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The reason we currently have a tighter coupling with moment is because in general it's so important to have timezone, date formating functions, etc, throughout the CMS that the standard Date model is not enough, and that the YAML formatter uses it as part of the serialization/deserializtion process right now as the only way to know how a date should be formattet in the YAML (for Jekyll for example, it makes a huge different if a date is persisted like 2016-11-01 or 2016-11-01 00:00:00 since once will get deserialized as a Ruby Date object, the other as a Ruby DateTime object and those behave differently).

The Ember prototype uses moment.js for deserialized dates since moment can carry around the format in the object - but I think we've actually broken that functionality in the React version right now...

};
9 changes: 9 additions & 0 deletions src/components/Widgets/DatePreview.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import React, { PropTypes } from 'react';

export default function DatePreview({ value }) {
return <span>{value ? value.toString() : null}</span>;
}

DatePreview.propTypes = {
value: PropTypes.node,
};
41 changes: 34 additions & 7 deletions src/components/Widgets/ListControl.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,22 +13,43 @@ ListItem.propTypes = {
};
ListItem.displayName = 'list-item';

function valueToString(value) {
return value ? value.join(',').replace(/,([^\s]|$)/g, ', $1') : '';
}

const SortableListItem = sortable(ListItem);

export default class ListControl extends Component {
static propTypes = {
onChange: PropTypes.func.isRequired,
value: PropTypes.node,
field: PropTypes.node,
getMedia: PropTypes.func.isRequired,
onAddMedia: PropTypes.func.isRequired,
onRemoveMedia: PropTypes.func.isRequired,
};

constructor(props) {
super(props);
this.state = { itemStates: Map() };
this.state = { itemStates: Map(), value: valueToString(props.value) };
}

handleChange = (e) => {
this.props.onChange(e.target.value.split(',').map(item => item.trim()));
const oldValue = this.state.value;
const newValue = e.target.value;
const listValue = e.target.value.split(',');
if (newValue.match(/,$/) && oldValue.match(/, $/)) {
listValue.pop();
}

this.setState({ value: valueToString(listValue) });
this.props.onChange(listValue);
};

handleCleanup = (e) => {
const listValue = e.target.value.split(',').map(el => el.trim()).filter(el => el);
this.setState({ value: valueToString(listValue) });
this.props.onChange(listValue);
};

handleAdd = (e) => {
Expand Down Expand Up @@ -80,13 +101,13 @@ export default class ListControl extends Component {

renderItem(item, index) {
const { value, field, getMedia, onAddMedia, onRemoveMedia } = this.props;
const { itemStates, draggedItem } = this.state;
const { itemStates } = this.state;
const collapsed = itemStates.getIn([index, 'collapsed']);
const classNames = [styles.item, collapsed ? styles.collapsed : styles.expanded];

return (<SortableListItem
key={index}
updateState={this.handleSort}
updateState={this.handleSort} // eslint-disable-line
items={value ? value.toJS() : []}
draggingIndex={this.state.draggingIndex}
sortId={index}
Expand All @@ -113,20 +134,26 @@ export default class ListControl extends Component {
}

renderListControl() {
const { value, field } = this.props;
const { value } = this.props;
return (<div>
{value && value.map((item, index) => this.renderItem(item, index))}
<div><button className={styles.addButton} onClick={this.handleAdd}>new</button></div>
</div>);
}

render() {
const { value, field } = this.props;
const { field } = this.props;
const { value } = this.state;

if (field.get('fields')) {
return this.renderListControl();
}

return <input type="text" value={value ? value.join(', ') : ''} onChange={this.handleChange} />;
return (<input
type="text"
value={value}
onChange={this.handleChange}
onBlur={this.handleCleanup}
/>);
}
}
25 changes: 0 additions & 25 deletions src/components/Widgets/MarkdownControlElements/RawEditor/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import React, { PropTypes } from 'react';
import { fromJS } from 'immutable';
import MarkupIt from 'markup-it';
import markdownSyntax from 'markup-it/syntaxes/markdown';
import htmlSyntax from 'markup-it/syntaxes/html';
Expand Down Expand Up @@ -65,29 +64,6 @@ function getCleanPaste(e) {
});
}

const buildtInPlugins = [{
label: 'Image',
id: 'image',
fromBlock: match => match && {
image: match[2],
alt: match[1],
},
toBlock: data => `![${ data.alt }](${ data.image })`,
toPreview: (data) => {
return <img src={data.image} alt={data.alt} />;
},
pattern: /^!\[([^\]]+)\]\(([^\)]+)\)$/,
fields: [{
label: 'Image',
name: 'image',
widget: 'image',
}, {
label: 'Alt Text',
name: 'alt',
}],
}];
buildtInPlugins.forEach(plugin => registry.registerEditorComponent(plugin));

export default class RawEditor extends React.Component {
constructor(props) {
super(props);
Expand Down Expand Up @@ -237,7 +213,6 @@ export default class RawEditor extends React.Component {
if (selection.start !== selection.end && !HAS_LINE_BREAK.test(selection.selected)) {
try {
const selectionPosition = this.caretPosition.get(selection.start, selection.end);
console.log('pos: %o', selectionPosition);
this.setState({ showToolbar: true, showBlockMenu: false, selectionPosition });
} catch (e) {
this.setState({ showToolbar: false, showBlockMenu: false });
Expand Down
44 changes: 44 additions & 0 deletions src/components/Widgets/SelectControl.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import React, { PropTypes } from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';

export default class SelectControl extends React.Component {
handleChange = (e) => {
this.props.onChange(e.target.value);
};

render() {
const { field, value } = this.props;
const fieldOptions = field.get('options');

if (!fieldOptions) {
return <div>Error rendering select control for {field.get('name')}: No options</div>;
}

const options = fieldOptions.map((option) => {
if (typeof option === 'string') {
return { label: option, value: option };
}
return option;
});

return (<select value={value || ''} onChange={this.handleChange}>
{options.map((option, idx) => <option key={idx} value={option.value}>
{option.label}
</option>)}
</select>);
}
}

SelectControl.propTypes = {
onChange: PropTypes.func.isRequired,
value: PropTypes.node,
field: ImmutablePropTypes.contains({
options: ImmutablePropTypes.listOf(PropTypes.oneOf([
PropTypes.string,
ImmutablePropTypes.contains({
label: PropTypes.string.isRequired,
value: PropTypes.string.isRequired,
}),
])).isRequired,
}),
};
9 changes: 9 additions & 0 deletions src/components/Widgets/SelectPreview.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import React, { PropTypes } from 'react';

export default function SelectPreview({ value }) {
return <span>{value ? value.toString() : null}</span>;
}

SelectPreview.propTypes = {
value: PropTypes.string,
};
23 changes: 23 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,26 @@ for (const method in registry) {
}
window.createClass = React.createClass;
window.h = React.createElement;

const buildtInPlugins = [{
label: 'Image',
id: 'image',
fromBlock: match => match && {
image: match[2],
alt: match[1],
},
toBlock: data => `![${ data.alt }](${ data.image })`,
toPreview: (data) => {
return <img src={data.image} alt={data.alt} />;
},
pattern: /^!\[([^\]]+)\]\(([^\)]+)\)$/,
fields: [{
label: 'Image',
name: 'image',
widget: 'image',
}, {
label: 'Alt Text',
name: 'alt',
}],
}];
buildtInPlugins.forEach(plugin => registry.registerEditorComponent(plugin));
Loading