chore(lint): cleanup unused variables in code (#1563)

This commit is contained in:
Caleb 2018-08-07 09:53:31 -06:00 committed by Shawn Erquhart
parent d0e4435258
commit 88f7dca328
52 changed files with 61 additions and 199 deletions

View File

@ -160,7 +160,7 @@ export default class Bitbucket {
const sem = semaphore(MAX_CONCURRENT_DOWNLOADS); const sem = semaphore(MAX_CONCURRENT_DOWNLOADS);
const promises = []; const promises = [];
files.forEach((file) => { files.forEach((file) => {
promises.push(new Promise((resolve, reject) => ( promises.push(new Promise(resolve => (
sem.take(() => this.api.readFile(file.path, file.id).then((data) => { sem.take(() => this.api.readFile(file.path, file.id).then((data) => {
resolve({ file, data }); resolve({ file, data });
sem.leave(); sem.leave();

View File

@ -98,7 +98,7 @@ export default class API {
cache: "no-store", cache: "no-store",
}) })
.then(response => response.object) .then(response => response.object)
.catch((error) => { .catch(() => {
// Meta ref doesn't exist // Meta ref doesn't exist
const readme = { const readme = {
raw: "# Netlify CMS\n\nThis tree is used by the Netlify CMS to store metadata information for specific files and branches.", raw: "# Netlify CMS\n\nThis tree is used by the Netlify CMS to store metadata information for specific files and branches.",
@ -127,7 +127,7 @@ export default class API {
}; };
return this.uploadBlob(fileTree[`${ key }.json`]) return this.uploadBlob(fileTree[`${ key }.json`])
.then(item => this.updateTree(branchData.sha, "/", fileTree)) .then(() => this.updateTree(branchData.sha, "/", fileTree))
.then(changeTree => this.commit(`Updating “${ key }” metadata`, changeTree)) .then(changeTree => this.commit(`Updating “${ key }” metadata`, changeTree))
.then(response => this.patchRef("meta", "_netlify_cms", response.sha)) .then(response => this.patchRef("meta", "_netlify_cms", response.sha))
.then(() => { .then(() => {
@ -150,7 +150,7 @@ export default class API {
cache: "no-store", cache: "no-store",
}) })
.then(response => JSON.parse(response)) .then(response => JSON.parse(response))
.catch(error => console.log("%c %s does not have metadata", "line-height: 30px;text-align: center;font-weight: bold", key)); .catch(() => console.log("%c %s does not have metadata", "line-height: 30px;text-align: center;font-weight: bold", key));
}); });
} }
@ -217,7 +217,7 @@ export default class API {
isUnpublishedEntryModification(path, branch) { isUnpublishedEntryModification(path, branch) {
return this.readFile(path, null, branch) return this.readFile(path, null, branch)
.then(data => true) .then(() => true)
.catch((err) => { .catch((err) => {
if (err.message && err.message === "Not Found") { if (err.message && err.message === "Not Found") {
return false; return false;
@ -338,7 +338,7 @@ export default class API {
.then(branchData => this.updateTree(branchData.commit.sha, "/", fileTree)) .then(branchData => this.updateTree(branchData.commit.sha, "/", fileTree))
.then(changeTree => this.commit(options.commitMessage, changeTree)) .then(changeTree => this.commit(options.commitMessage, changeTree))
.then(commitResponse => this.createBranch(branchName, commitResponse.sha)) .then(commitResponse => this.createBranch(branchName, commitResponse.sha))
.then(branchResponse => this.createPR(options.commitMessage, branchName)) .then(() => this.createPR(options.commitMessage, branchName))
.then(pr => { .then(pr => {
prResponse = pr; prResponse = pr;
return this.user(); return this.user();
@ -466,7 +466,7 @@ export default class API {
* changing only the parent SHA and tree for each, but retaining all other * changing only the parent SHA and tree for each, but retaining all other
* info, such as the author/committer data. * info, such as the author/committer data.
*/ */
const newHeadPromise = commits.reduce((lastCommitPromise, commit, idx) => { const newHeadPromise = commits.reduce((lastCommitPromise, commit) => {
return lastCommitPromise.then(newParent => { return lastCommitPromise.then(newParent => {
/** /**
* Normalize commit data to ensure it's not nested in `commit.commit`. * Normalize commit data to ensure it's not nested in `commit.commit`.
@ -563,7 +563,7 @@ export default class API {
const contentKey = slug; const contentKey = slug;
const branchName = this.generateBranchName(contentKey); const branchName = this.generateBranchName(contentKey);
return this.retrieveMetadata(contentKey) return this.retrieveMetadata(contentKey)
.then(metadata => this.closePR(metadata.pr, metadata.objects)) .then(metadata => this.closePR(metadata.pr))
.then(() => this.deleteBranch(branchName)) .then(() => this.deleteBranch(branchName))
// If the PR doesn't exist, then this has already been deleted - // If the PR doesn't exist, then this has already been deleted -
// deletion should be idempotent, so we can consider this a // deletion should be idempotent, so we can consider this a
@ -579,7 +579,6 @@ export default class API {
publishUnpublishedEntry(collection, slug) { publishUnpublishedEntry(collection, slug) {
const contentKey = slug; const contentKey = slug;
const branchName = this.generateBranchName(contentKey); const branchName = this.generateBranchName(contentKey);
let prNumber;
return this.retrieveMetadata(contentKey) return this.retrieveMetadata(contentKey)
.then(metadata => this.mergePR(metadata.pr, metadata.objects)) .then(metadata => this.mergePR(metadata.pr, metadata.objects))
.then(() => this.deleteBranch(branchName)); .then(() => this.deleteBranch(branchName));
@ -601,7 +600,7 @@ export default class API {
}); });
} }
deleteRef(type, name, sha) { deleteRef(type, name) {
return this.request(`${ this.repoURL }/git/refs/${ type }/${ encodeURIComponent(name) }`, { return this.request(`${ this.repoURL }/git/refs/${ type }/${ encodeURIComponent(name) }`, {
method: 'DELETE', method: 'DELETE',
}); });
@ -639,8 +638,7 @@ export default class API {
}); });
} }
closePR(pullrequest, objects) { closePR(pullrequest) {
const headSha = pullrequest.head;
const prNumber = pullrequest.number; const prNumber = pullrequest.number;
console.log("%c Deleting PR", "line-height: 30px;text-align: center;font-weight: bold"); console.log("%c Deleting PR", "line-height: 30px;text-align: center;font-weight: bold");
return this.request(`${ this.repoURL }/pulls/${ prNumber }`, { return this.request(`${ this.repoURL }/pulls/${ prNumber }`, {

View File

@ -83,7 +83,7 @@ export default class GitHub {
const sem = semaphore(MAX_CONCURRENT_DOWNLOADS); const sem = semaphore(MAX_CONCURRENT_DOWNLOADS);
const promises = []; const promises = [];
files.forEach((file) => { files.forEach((file) => {
promises.push(new Promise((resolve, reject) => ( promises.push(new Promise(resolve => (
sem.take(() => this.api.readFile(file.path, file.sha).then((data) => { sem.take(() => this.api.readFile(file.path, file.sha).then((data) => {
resolve({ file, data }); resolve({ file, data });
sem.leave(); sem.leave();
@ -123,9 +123,9 @@ export default class GitHub {
async persistMedia(mediaFile, options = {}) { async persistMedia(mediaFile, options = {}) {
try { try {
const response = await this.api.persistFiles(null, [mediaFile], options); await this.api.persistFiles(null, [mediaFile], options);
const { sha, value, size, path, fileObj } = mediaFile; const { sha, value, path, fileObj } = mediaFile;
const url = URL.createObjectURL(fileObj); const url = URL.createObjectURL(fileObj);
return { id: sha, name: value, size: fileObj.size, url, path: trimStart(path, '/') }; return { id: sha, name: value, size: fileObj.size, url, path: trimStart(path, '/') };
} }
@ -144,7 +144,7 @@ export default class GitHub {
const sem = semaphore(MAX_CONCURRENT_DOWNLOADS); const sem = semaphore(MAX_CONCURRENT_DOWNLOADS);
const promises = []; const promises = [];
branches.map((branch) => { branches.map((branch) => {
promises.push(new Promise((resolve, reject) => { promises.push(new Promise(resolve => {
const slug = branch.ref.split("refs/heads/cms/").pop(); const slug = branch.ref.split("refs/heads/cms/").pop();
return sem.take(() => this.api.readUnpublishedBranchFile(slug).then((data) => { return sem.take(() => this.api.readUnpublishedBranchFile(slug).then((data) => {
if (data === null || data === undefined) { if (data === null || data === undefined) {
@ -161,7 +161,7 @@ export default class GitHub {
}); });
sem.leave(); sem.leave();
} }
}).catch((err) => { }).catch(() => {
sem.leave(); sem.leave();
resolve(null); resolve(null);
})); }));

View File

@ -51,7 +51,7 @@ export default class API {
user = () => this.requestJSON("/user"); user = () => this.requestJSON("/user");
WRITE_ACCESS = 30; WRITE_ACCESS = 30;
hasWriteAccess = user => this.requestJSON(this.repoURL).then(({ permissions }) => { hasWriteAccess = () => this.requestJSON(this.repoURL).then(({ permissions }) => {
const { project_access, group_access } = permissions; const { project_access, group_access } = permissions;
if (project_access && (project_access.access_level >= this.WRITE_ACCESS)) { if (project_access && (project_access.access_level >= this.WRITE_ACCESS)) {
return true; return true;

View File

@ -99,7 +99,7 @@ export default class GitLab {
const sem = semaphore(MAX_CONCURRENT_DOWNLOADS); const sem = semaphore(MAX_CONCURRENT_DOWNLOADS);
const promises = []; const promises = [];
files.forEach((file) => { files.forEach((file) => {
promises.push(new Promise((resolve, reject) => ( promises.push(new Promise(resolve => (
sem.take(() => this.api.readFile(file.path, file.id).then((data) => { sem.take(() => this.api.readFile(file.path, file.id).then((data) => {
resolve({ file, data }); resolve({ file, data });
sem.leave(); sem.leave();

View File

@ -207,7 +207,7 @@ export default class TestRepo {
return Promise.resolve(normalizedAsset); return Promise.resolve(normalizedAsset);
} }
deleteFile(path, commitMessage) { deleteFile(path) {
const assetIndex = this.assets.findIndex(asset => asset.path === path); const assetIndex = this.assets.findIndex(asset => asset.path === path);
if (assetIndex > -1) { if (assetIndex > -1) {
this.assets.splice(assetIndex, 1); this.assets.splice(assetIndex, 1);

View File

@ -51,7 +51,6 @@ function validateCollection(collection) {
format, format,
extension, extension,
frontmatter_delimiter: delimiter, frontmatter_delimiter: delimiter,
fields,
} = collection.toJS(); } = collection.toJS();
if (!folder && !files) { if (!folder && !files) {

View File

@ -189,6 +189,7 @@ function unpublishedEntryPublishError(collection, slug, transactionID) {
} }
function unpublishedEntryDeleteRequest(collection, slug, transactionID) { function unpublishedEntryDeleteRequest(collection, slug, transactionID) {
// The reducer doesn't handle this action -- it is for `optimist`.
return { return {
type: UNPUBLISHED_ENTRY_DELETE_REQUEST, type: UNPUBLISHED_ENTRY_DELETE_REQUEST,
payload: { collection, slug }, payload: { collection, slug },
@ -205,6 +206,7 @@ function unpublishedEntryDeleted(collection, slug, transactionID) {
} }
function unpublishedEntryDeleteError(collection, slug, transactionID) { function unpublishedEntryDeleteError(collection, slug, transactionID) {
// The reducer doesn't handle this action -- it is for `optimist`.
return { return {
type: UNPUBLISHED_ENTRY_DELETE_FAILURE, type: UNPUBLISHED_ENTRY_DELETE_FAILURE,
payload: { collection, slug }, payload: { collection, slug },

View File

@ -360,7 +360,6 @@ class Backend {
description: entryDraft.getIn(["entry", "data", "description"], "No Description!"), description: entryDraft.getIn(["entry", "data", "description"], "No Description!"),
}; };
const entryData = entryDraft.getIn(["entry", "data"]).toJS();
let entryObj; let entryObj;
if (newEntry) { if (newEntry) {
if (!selectAllowNewEntries(collection)) { if (!selectAllowNewEntries(collection)) {

View File

@ -167,7 +167,7 @@ class App extends React.Component {
} }
} }
function mapStateToProps(state, ownProps) { function mapStateToProps(state) {
const { auth, config, collections, globalUI } = state; const { auth, config, collections, globalUI } = state;
const user = auth && auth.get('user'); const user = auth && auth.get('user');
const isFetching = globalUI.get('isFetching'); const isFetching = globalUI.get('isFetching');

View File

@ -110,15 +110,12 @@ export default class Header extends React.Component {
const { const {
user, user,
collections, collections,
toggleDrawer,
onLogoutClick, onLogoutClick,
openMediaLibrary, openMediaLibrary,
hasWorkflow, hasWorkflow,
displayUrl, displayUrl,
} = this.props; } = this.props;
const avatarUrl = user.get('avatar_url');
return ( return (
<AppHeaderContainer> <AppHeaderContainer>
<AppHeader> <AppHeader>

View File

@ -8,8 +8,6 @@ const Entries = ({
collections, collections,
entries, entries,
publicFolder, publicFolder,
page,
onPaginate,
isFetching, isFetching,
viewStyle, viewStyle,
cursor, cursor,

View File

@ -53,7 +53,7 @@ class EntriesSearch extends React.Component {
}; };
render () { render () {
const { collections, entries, publicFolder, page, isFetching } = this.props; const { collections, entries, publicFolder, isFetching } = this.props;
return ( return (
<Entries <Entries
cursor={this.getCursor()} cursor={this.getCursor()}
@ -61,8 +61,6 @@ class EntriesSearch extends React.Component {
collections={collections} collections={collections}
entries={entries} entries={entries}
publicFolder={publicFolder} publicFolder={publicFolder}
page={page}
onPaginate={this.handleLoadMore}
isFetching={isFetching} isFetching={isFetching}
/> />
); );

View File

@ -66,9 +66,7 @@ class Editor extends React.Component {
componentDidMount() { componentDidMount() {
const { const {
entry,
newEntry, newEntry,
entryDraft,
collection, collection,
slug, slug,
loadEntry, loadEntry,
@ -179,12 +177,12 @@ class Editor extends React.Component {
return; return;
} }
const newStatus = status.get(newStatusName); const newStatus = status.get(newStatusName);
this.props.updateUnpublishedEntryStatus(collection.get('name'), slug, currentStatus, newStatus); updateUnpublishedEntryStatus(collection.get('name'), slug, currentStatus, newStatus);
} }
handlePersistEntry = async (opts = {}) => { handlePersistEntry = async (opts = {}) => {
const { createNew = false } = opts; const { createNew = false } = opts;
const { persistEntry, collection, entryDraft, newEntry, currentStatus, hasWorkflow, loadEntry, slug, createEmptyDraft } = this.props; const { persistEntry, collection, currentStatus, hasWorkflow, loadEntry, slug, createEmptyDraft } = this.props;
await persistEntry(collection) await persistEntry(collection)
@ -299,7 +297,6 @@ class Editor extends React.Component {
onChangeStatus={this.handleChangeStatus} onChangeStatus={this.handleChangeStatus}
onPublish={this.handlePublishEntry} onPublish={this.handlePublishEntry}
showDelete={this.props.showDelete} showDelete={this.props.showDelete}
enableSave={entryDraft.get('hasChanged')}
user={user} user={user}
hasChanged={hasChanged} hasChanged={hasChanged}
displayUrl={displayUrl} displayUrl={displayUrl}
@ -315,7 +312,7 @@ class Editor extends React.Component {
} }
function mapStateToProps(state, ownProps) { function mapStateToProps(state, ownProps) {
const { collections, entryDraft, mediaLibrary, auth, config, entries } = state; const { collections, entryDraft, auth, config, entries } = state;
const slug = ownProps.match.params.slug; const slug = ownProps.match.params.slug;
const collection = collections.get(ownProps.match.params.name); const collection = collections.get(ownProps.match.params.name);
const collectionName = collection.get('name'); const collectionName = collection.get('name');

View File

@ -195,7 +195,7 @@ class EditorControl extends React.Component {
} }
} }
const mapStateToProps = (state, ownProps) => ({ const mapStateToProps = state => ({
mediaPaths: state.mediaLibrary.get('controlMedia'), mediaPaths: state.mediaLibrary.get('controlMedia'),
boundGetAsset: getAsset.bind(null, state), boundGetAsset: getAsset.bind(null, state),
isFetching: state.search.get('isFetching'), isFetching: state.search.get('isFetching'),

View File

@ -154,7 +154,6 @@ class EditorInterface extends Component {
fieldsErrors, fieldsErrors,
getAsset, getAsset,
onChange, onChange,
enableSave,
showDelete, showDelete,
onDelete, onDelete,
onDeleteUnpublishedChanges, onDeleteUnpublishedChanges,
@ -230,7 +229,6 @@ class EditorInterface extends Component {
showDelete={showDelete} showDelete={showDelete}
onPublish={onPublish} onPublish={onPublish}
onPublishAndNew={() => this.handleOnPublish({ createNew: true })} onPublishAndNew={() => this.handleOnPublish({ createNew: true })}
enableSave={enableSave}
user={user} user={user}
hasChanged={hasChanged} hasChanged={hasChanged}
displayUrl={displayUrl} displayUrl={displayUrl}
@ -278,7 +276,6 @@ EditorInterface.propTypes = {
onChange: PropTypes.func.isRequired, onChange: PropTypes.func.isRequired,
onValidate: PropTypes.func.isRequired, onValidate: PropTypes.func.isRequired,
onPersist: PropTypes.func.isRequired, onPersist: PropTypes.func.isRequired,
enableSave: PropTypes.bool.isRequired,
showDelete: PropTypes.bool.isRequired, showDelete: PropTypes.bool.isRequired,
onDelete: PropTypes.func.isRequired, onDelete: PropTypes.func.isRequired,
onDeleteUnpublishedChanges: PropTypes.func.isRequired, onDeleteUnpublishedChanges: PropTypes.func.isRequired,

View File

@ -116,7 +116,7 @@ export default class PreviewPane extends React.Component {
const value = entry.getIn(['data', field.get('name')]); const value = entry.getIn(['data', field.get('name')]);
if (List.isList(value)) { if (List.isList(value)) {
return value.map((val, index) => { return value.map(val => {
const widgets = nestedFields && Map(nestedFields.map((f, i) => [f.get('name'), <div key={i}>{this.getWidget(f, val, this.props)}</div>])); 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: val, widgets });
}); });

View File

@ -16,7 +16,6 @@ import {
} from 'netlify-cms-ui-default'; } from 'netlify-cms-ui-default';
import { status } from 'Constants/publishModes'; import { status } from 'Constants/publishModes';
import SettingsDropdown from 'UI/SettingsDropdown'; import SettingsDropdown from 'UI/SettingsDropdown';
import { stripProtocol } from 'Lib/urlHelper';
const styles = { const styles = {
buttonMargin: css` buttonMargin: css`
@ -262,8 +261,6 @@ export default class EditorToolbar extends React.Component {
renderWorkflowPublishControls = () => { renderWorkflowPublishControls = () => {
const { const {
collection, collection,
onPersist,
onPersistAndNew,
isUpdatingStatus, isUpdatingStatus,
isPublishing, isPublishing,
onChangeStatus, onChangeStatus,
@ -323,22 +320,13 @@ export default class EditorToolbar extends React.Component {
render() { render() {
const { const {
isPersisting,
onPersist,
onPersistAndNew,
enableSave,
showDelete,
onDelete,
user, user,
hasChanged, hasChanged,
displayUrl, displayUrl,
collection, collection,
hasWorkflow, hasWorkflow,
hasUnpublishedChanges,
onLogoutClick, onLogoutClick,
} = this.props; } = this.props;
const disabled = !enableSave || isPersisting;
const avatarUrl = user.get('avatar_url');
return ( return (
<ToolbarContainer> <ToolbarContainer>

View File

@ -219,7 +219,6 @@ class MediaLibrary extends React.Component {
isPersisting, isPersisting,
isDeleting, isDeleting,
hasNextPage, hasNextPage,
page,
isPaginating, isPaginating,
privateUpload, privateUpload,
} = this.props; } = this.props;
@ -236,7 +235,6 @@ class MediaLibrary extends React.Component {
isPersisting={isPersisting} isPersisting={isPersisting}
isDeleting={isDeleting} isDeleting={isDeleting}
hasNextPage={hasNextPage} hasNextPage={hasNextPage}
page={page}
isPaginating={isPaginating} isPaginating={isPaginating}
privateUpload={privateUpload} privateUpload={privateUpload}
query={this.state.query} query={this.state.query}

View File

@ -37,7 +37,7 @@ const MediaLibraryCardGrid = ({
<CardGridContainer innerRef={setScrollContainerRef}> <CardGridContainer innerRef={setScrollContainerRef}>
<CardGrid> <CardGrid>
{ {
mediaItems.map((file, idx) => mediaItems.map(file =>
<MediaLibraryCard <MediaLibraryCard
key={file.key} key={file.key}
isSelected={isSelectedFile(file)} isSelected={isSelectedFile(file)}

View File

@ -2,7 +2,6 @@ import React from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import styled from 'react-emotion'; import styled from 'react-emotion';
import { isEmpty } from 'lodash'; import { isEmpty } from 'lodash';
import Waypoint from 'react-waypoint';
import { Modal } from 'UI'; import { Modal } from 'UI';
import MediaLibrarySearch from './MediaLibrarySearch'; import MediaLibrarySearch from './MediaLibrarySearch';
import MediaLibraryHeader from './MediaLibraryHeader'; import MediaLibraryHeader from './MediaLibraryHeader';
@ -77,7 +76,6 @@ const MediaLibraryModal = ({
isPersisting, isPersisting,
isDeleting, isDeleting,
hasNextPage, hasNextPage,
page,
isPaginating, isPaginating,
privateUpload, privateUpload,
query, query,
@ -180,7 +178,6 @@ MediaLibraryModal.propTypes = {
isPersisting: PropTypes.bool, isPersisting: PropTypes.bool,
isDeleting: PropTypes.bool, isDeleting: PropTypes.bool,
hasNextPage: PropTypes.bool, hasNextPage: PropTypes.bool,
page: PropTypes.number,
isPaginating: PropTypes.bool, isPaginating: PropTypes.bool,
privateUpload: PropTypes.bool, privateUpload: PropTypes.bool,
query: PropTypes.string, query: PropTypes.string,

View File

@ -11,12 +11,12 @@ export const DragSource = ({ namespace, ...props }) => {
const DragComponent = ReactDNDDragSource( const DragComponent = ReactDNDDragSource(
namespace, namespace,
{ {
beginDrag({ children, isDragging, connectDragComponent, ...ownProps }) { beginDrag({ children, isDragging, connectDragComponent, ...ownProps }) { // eslint-disable-line no-unused-vars
// We return the rest of the props as the ID of the element being dragged. // We return the rest of the props as the ID of the element being dragged.
return ownProps; return ownProps;
}, },
}, },
(connect, monitor) => ({ connect => ({
connectDragComponent: connect.dragSource(), connectDragComponent: connect.dragSource(),
}), }),
)( )(

View File

@ -98,7 +98,6 @@ const WorkflowCardContainer = styled.div`
const WorkflowCard = ({ const WorkflowCard = ({
collectionName, collectionName,
title, title,
author,
authorLastChange, authorLastChange,
body, body,
isModification, isModification,

View File

@ -159,8 +159,6 @@ Please drag the card to the "Ready" column to enable publishing.`
<div> <div>
{ {
entries.map((entry) => { entries.map((entry) => {
// Look for an "author" field. Fallback to username on backend implementation;
const author = entry.getIn(['data', 'author'], entry.getIn(['metaData', 'user']));
const timestamp = moment(entry.getIn(['metaData', 'timeStamp'])).format('MMMM D'); const timestamp = moment(entry.getIn(['metaData', 'timeStamp'])).format('MMMM D');
const editLink = `collections/${ entry.getIn(['metaData', 'collection']) }/entries/${ entry.get('slug') }`; const editLink = `collections/${ entry.getIn(['metaData', 'collection']) }/entries/${ entry.get('slug') }`;
const slug = entry.get('slug'); const slug = entry.get('slug');
@ -181,7 +179,6 @@ Please drag the card to the "Ready" column to enable publishing.`
<WorkflowCard <WorkflowCard
collectionName={collection} collectionName={collection}
title={entry.getIn(['data', 'title'])} title={entry.getIn(['data', 'title'])}
author={author}
authorLastChange={entry.getIn(['metaData', 'user'])} authorLastChange={entry.getIn(['metaData', 'user'])}
body={entry.getIn(['data', 'body'])} body={entry.getIn(['data', 'body'])}
isModification={isModification} isModification={isModification}

View File

@ -14,9 +14,7 @@ import {
UNPUBLISHED_ENTRY_PUBLISH_REQUEST, UNPUBLISHED_ENTRY_PUBLISH_REQUEST,
UNPUBLISHED_ENTRY_PUBLISH_SUCCESS, UNPUBLISHED_ENTRY_PUBLISH_SUCCESS,
UNPUBLISHED_ENTRY_PUBLISH_FAILURE, UNPUBLISHED_ENTRY_PUBLISH_FAILURE,
UNPUBLISHED_ENTRY_DELETE_REQUEST,
UNPUBLISHED_ENTRY_DELETE_SUCCESS, UNPUBLISHED_ENTRY_DELETE_SUCCESS,
UNPUBLISHED_ENTRY_DELETE_FAILURE,
} from 'Actions/editorialWorkflow'; } from 'Actions/editorialWorkflow';
import { CONFIG_SUCCESS } from 'Actions/config'; import { CONFIG_SUCCESS } from 'Actions/config';

View File

@ -57,7 +57,7 @@ const mediaLibrary = (state = Map({ isVisible: false, controlMedia: Map() }), ac
map.set('isPaginating', action.payload.page > 1); map.set('isPaginating', action.payload.page > 1);
}); });
case MEDIA_LOAD_SUCCESS: { case MEDIA_LOAD_SUCCESS: {
const { files = [], page, canPaginate, dynamicSearch, dynamicSearchQuery, privateUpload } = action.payload; const { files = [], page, canPaginate, dynamicSearch, dynamicSearchQuery } = action.payload;
if (privateUploadChanged) { if (privateUploadChanged) {
return state; return state;

View File

@ -30,7 +30,7 @@ AssetProxy.prototype.toString = function () {
}; };
AssetProxy.prototype.toBase64 = function () { AssetProxy.prototype.toBase64 = function () {
return new Promise((resolve, reject) => { return new Promise(resolve => {
const fr = new FileReader(); const fr = new FileReader();
fr.onload = (readerEvt) => { fr.onload = (readerEvt) => {
const binaryString = readerEvt.target.result; const binaryString = readerEvt.target.result;
@ -50,7 +50,7 @@ export function createAssetProxy(value, fileObj, uploaded = false, privateUpload
response => ( response => (
new AssetProxy(response.asset.url.replace(/^(https?):/, ''), null, true, response.asset) new AssetProxy(response.asset.url.replace(/^(https?):/, ''), null, true, response.asset)
), ),
error => new AssetProxy(value, fileObj, false) () => new AssetProxy(value, fileObj, false)
); );
} else if (privateUpload) { } else if (privateUpload) {
throw new Error('The Private Upload option is only avaible for Asset Store Integration'); throw new Error('The Private Upload option is only avaible for Asset Store Integration');

View File

@ -1,11 +1,8 @@
import PropTypes from 'prop-types'; import { Record, fromJS } from 'immutable';
import { Component, Children } from 'react';
import { List, Record, fromJS } from 'immutable';
import { isFunction } from 'lodash'; import { isFunction } from 'lodash';
const plugins = { editor: List() };
const catchesNothing = /.^/; const catchesNothing = /.^/;
/* eslint-disable no-unused-vars */
const EditorComponent = Record({ const EditorComponent = Record({
id: null, id: null,
label: 'unnamed component', label: 'unnamed component',
@ -16,25 +13,7 @@ const EditorComponent = Record({
toBlock(attributes) { return 'Plugin'; }, toBlock(attributes) { return 'Plugin'; },
toPreview(attributes) { return 'Plugin'; }, toPreview(attributes) { return 'Plugin'; },
}); });
/* eslint-enable */
class Plugin extends Component {
static propTypes = {
children: PropTypes.element.isRequired,
};
static childContextTypes = {
plugins: PropTypes.object,
};
getChildContext() {
return { plugins };
}
render() {
return Children.only(this.props.children);
}
}
export default function createEditorComponent(config) { export default function createEditorComponent(config) {
const configObj = new EditorComponent({ const configObj = new EditorComponent({

View File

@ -1,8 +1,7 @@
const path = require('path'); const path = require('path');
const webpack = require('webpack'); const webpack = require('webpack');
const pkg = require('./package.json'); const pkg = require('./package.json');
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin'); const { getConfig, rules } = require('../../scripts/webpack.js');
const { getConfig, rules, plugins } = require('../../scripts/webpack.js');
const isProduction = process.env.NODE_ENV === 'production'; const isProduction = process.env.NODE_ENV === 'production';
@ -16,7 +15,7 @@ module.exports = {
rules: [ rules: [
...Object.entries(rules) ...Object.entries(rules)
.filter(([ key ]) => key !== 'js') .filter(([ key ]) => key !== 'js')
.map(([ _, rule ]) => rule()), .map(([ , rule ]) => rule()),
{ {
test: /\.js$/, test: /\.js$/,
exclude: /node_modules/, exclude: /node_modules/,

View File

@ -96,7 +96,7 @@ export default class Cursor {
return [this.store.get("data").delete("wrapped_cursor_data"), this.updateStore("data", data => data.get("wrapped_cursor_data"))]; return [this.store.get("data").delete("wrapped_cursor_data"), this.updateStore("data", data => data.get("wrapped_cursor_data"))];
} }
clearData() { clearData() {
return this.updateStore("data", data => Map()); return this.updateStore("data", () => Map());
} }
setMeta(meta) { setMeta(meta) {

View File

@ -2,7 +2,7 @@ import zipObject from 'lodash/zipObject';
export const filterPromises = (arr, filter) => export const filterPromises = (arr, filter) =>
Promise.all(arr.map(entry => filter(entry))) Promise.all(arr.map(entry => filter(entry)))
.then(bits => arr.filter(entry => bits.shift())); .then(bits => arr.filter(() => bits.shift()));
export const resolvePromiseProperties = (obj) => { export const resolvePromiseProperties = (obj) => {
// Get the keys which represent promises // Get the keys which represent promises

View File

@ -50,7 +50,7 @@ const sizes = {
large: '32px', large: '32px',
}; };
const Icon = ({ type, direction, size = 'medium', width, height, className }) => ( const Icon = ({ type, direction, size = 'medium', className }) => (
<IconWrapper <IconWrapper
className={className} className={className}
dangerouslySetInnerHTML={{ __html: icons[type].image }} dangerouslySetInnerHTML={{ __html: icons[type].image }}

View File

@ -102,7 +102,7 @@ export class Loader extends React.Component {
}; };
render() { render() {
const { active, className } = this.props; const { className } = this.props;
return <div className={className}>{this.renderChild()}</div>; return <div className={className}>{this.renderChild()}</div>;
} }
} }

View File

@ -39,7 +39,6 @@ const ToggleBackground = styled.span`
const Toggle = ({ const Toggle = ({
active, active,
onChange, onChange,
renderBackground,
onFocus, onFocus,
onBlur, onBlur,
className, className,

View File

@ -81,7 +81,7 @@ export default class DateControl extends React.Component {
}; };
render() { render() {
const { includeTime, value, classNameWrapper, setActiveStyle, setInactiveStyle } = this.props; const { includeTime, value, classNameWrapper, setActiveStyle } = this.props;
return ( return (
<DateTime <DateTime
timeFormat={!!includeTime} timeFormat={!!includeTime}

View File

@ -117,7 +117,7 @@ export default function withFileControl({ forImage } = {}) {
}; };
renderFileName = () => { renderFileName = () => {
const { value, classNameWrapper } = this.props; const { value } = this.props;
const size = MAX_DISPLAY_LENGTH; const size = MAX_DISPLAY_LENGTH;
if (!value || value.length <= size) { if (!value || value.length <= size) {
return value; return value;

View File

@ -202,7 +202,7 @@ export default class ListControl extends React.Component {
} }
onSortEnd = ({ oldIndex, newIndex }) => { onSortEnd = ({ oldIndex, newIndex }) => {
const { value, onChange } = this.props; const { value } = this.props;
const { itemsCollapsed } = this.state; const { itemsCollapsed } = this.state;
// Update value // Update value
@ -219,11 +219,6 @@ export default class ListControl extends React.Component {
renderItem = (item, index) => { renderItem = (item, index) => {
const { const {
field, field,
getAsset,
mediaPaths,
onOpenMediaLibrary,
onAddAsset,
onRemoveInsertedMedia,
classNameWrapper, classNameWrapper,
editorControl, editorControl,
resolveWidget, resolveWidget,

View File

@ -77,7 +77,7 @@ export default class Shortcode extends React.Component {
} }
} }
renderControl = (shortcodeData, field, index) => { renderControl = (shortcodeData, field) => {
if (field.get('widget') === 'hidden') return null; if (field.get('widget') === 'hidden') return null;
const value = shortcodeData.get(field.get('name')); const value = shortcodeData.get(field.get('name'));
const key = `field-${ field.get('name') }`; const key = `field-${ field.get('name') }`;
@ -92,7 +92,7 @@ export default class Shortcode extends React.Component {
}; };
render() { render() {
const { attributes, node, editor } = this.props; const { attributes, node } = this.props;
const { collapsed } = this.state; const { collapsed } = this.state;
const pluginId = node.data.get('shortcode'); const pluginId = node.data.get('shortcode');
const shortcodeData = Map(this.props.node.data.get('shortcodeData')); const shortcodeData = Map(this.props.node.data.get('shortcodeData'));

View File

@ -64,13 +64,6 @@ export default class Toolbar extends React.Component {
disabled: PropTypes.bool, disabled: PropTypes.bool,
}; };
constructor(props) {
super(props);
this.state = {
activePlugin: null,
};
}
isHidden = button => { isHidden = button => {
const { buttons } = this.props; const { buttons } = this.props;
return List.isList(buttons) ? !buttons.includes(button) : false; return List.isList(buttons) ? !buttons.includes(button) : false;
@ -87,14 +80,10 @@ export default class Toolbar extends React.Component {
onToggleMode, onToggleMode,
rawMode, rawMode,
plugins, plugins,
onAddAsset,
getAsset,
disabled, disabled,
onSubmit, onSubmit,
} = this.props; } = this.props;
const { activePlugin } = this.state;
return ( return (
<ToolbarContainer> <ToolbarContainer>
<div> <div>

View File

@ -76,7 +76,7 @@ export default class Editor extends React.Component {
handleBlockClick = (event, type) => { handleBlockClick = (event, type) => {
event.preventDefault(); event.preventDefault();
let { value } = this.state; let { value } = this.state;
const { document: doc, selection } = value; const { document: doc } = value;
const { unwrapList, wrapInList } = EditListConfigured.changes; const { unwrapList, wrapInList } = EditListConfigured.changes;
let change = value.change(); let change = value.change();
@ -178,9 +178,8 @@ export default class Editor extends React.Component {
handleDocumentChange = debounce(change => { handleDocumentChange = debounce(change => {
const { onChange, getEditorComponents } = this.props; const { onChange } = this.props;
const raw = change.value.document.toJSON(); const raw = change.value.document.toJSON();
const plugins = getEditorComponents();
const markdown = slateToMarkdown(raw); const markdown = slateToMarkdown(raw);
onChange(markdown); onChange(markdown);
}, 150); }, 150);

View File

@ -1,51 +1,7 @@
import React from 'react';
import { fromJS } from 'immutable';
import { markdownToSlate } from '../../serializers'; import { markdownToSlate } from '../../serializers';
const parser = markdownToSlate; const parser = markdownToSlate;
// Temporary plugins test
const testPlugins = fromJS([
{
label: 'Image',
id: 'image',
fromBlock: match => match && {
image: match[2],
alt: match[1],
},
toBlock: data => `![${ data.alt }](${ data.image })`,
toPreview: data => <img src={data.image} alt={data.alt} />, // eslint-disable-line react/display-name
pattern: /^!\[([^\]]+)]\(([^)]+)\)$/,
fields: [{
label: 'Image',
name: 'image',
widget: 'image',
}, {
label: 'Alt Text',
name: 'alt',
}],
},
{
id: "youtube",
label: "Youtube",
fields: [{name: 'id', label: 'Youtube Video ID'}],
pattern: /^{{<\s?youtube (\S+)\s?>}}/,
fromBlock: function(match) {
return {
id: match[1]
};
},
toBlock: function(obj) {
return '{{< youtube ' + obj.id + ' >}}';
},
toPreview: function(obj) {
return (
'<img src="http://img.youtube.com/vi/' + obj.id + '/maxresdefault.jpg" alt="Youtube Video"/>'
);
}
},
]);
describe("Compile markdown to Slate Raw AST", () => { describe("Compile markdown to Slate Raw AST", () => {
it("should compile simple markdown", () => { it("should compile simple markdown", () => {
const value = ` const value = `

View File

@ -20,7 +20,7 @@ function onKeyDown(event, change) {
* If the selected block is the first block in the document, create the * If the selected block is the first block in the document, create the
* new block above it. If not, create the new block below it. * new block above it. If not, create the new block below it.
*/ */
const { document: doc, range, anchorBlock, focusBlock } = change.value; const { document: doc, anchorBlock, focusBlock } = change.value;
const singleBlockSelected = anchorBlock === focusBlock; const singleBlockSelected = anchorBlock === focusBlock;
if (!singleBlockSelected || !focusBlock.isVoid) return; if (!singleBlockSelected || !focusBlock.isVoid) return;
@ -45,7 +45,7 @@ function onKeyDown(event, change) {
[ '`', 'code' ], [ '`', 'code' ],
]; ];
const [ markKey, markName ] = marks.find(([ key ]) => isHotkey(`mod+${key}`, event)) || []; const [ , markName ] = marks.find(([ key ]) => isHotkey(`mod+${key}`, event)) || [];
if (markName) { if (markName) {
event.preventDefault(); event.preventDefault();

View File

@ -14,7 +14,7 @@ export function joinPatternSegments(patterns) {
* each in a non-capturing group and interposing alternation characters (|) so * each in a non-capturing group and interposing alternation characters (|) so
* that each expression is executed separately. * that each expression is executed separately.
*/ */
export function combinePatterns(patterns, flags = '') { export function combinePatterns(patterns) {
return patterns.map(p => `(?:${p.source})`).join('|'); return patterns.map(p => `(?:${p.source})`).join('|');
} }

View File

@ -16,7 +16,6 @@ export default function remarkAllowHtmlEntities() {
var tokenizer; var tokenizer;
var name; var name;
var min; var min;
var now;
/* istanbul ignore if - never used (yet) */ /* istanbul ignore if - never used (yet) */
if (silent) { if (silent) {

View File

@ -92,7 +92,7 @@ function transform(node) {
* they were text is a bit of a necessary hack. * they were text is a bit of a necessary hack.
*/ */
function combineTextAndInline(nodes) { function combineTextAndInline(nodes) {
return nodes.reduce((acc, node, idx, nodes) => { return nodes.reduce((acc, node) => {
const prevNode = last(acc); const prevNode = last(acc);
const prevNodeLeaves = get(prevNode, 'leaves'); const prevNodeLeaves = get(prevNode, 'leaves');
const data = node.data || {}; const data = node.data || {};
@ -158,19 +158,6 @@ function processCodeMark(markTypes) {
return { filteredMarkTypes, textNodeType }; return { filteredMarkTypes, textNodeType };
} }
/**
* Wraps a text node in one or more mark nodes by placing the text node in an
* array and using that as the `children` value of a mark node. The resulting
* mark node is then placed in an array and used as the child of a mark node for
* the next mark type in `markTypes`. This continues for each member of
* `markTypes`. If `markTypes` is empty, the original text node is returned.
*/
function wrapTextWithMarks(textNode, markTypes) {
const wrapTextWithMark = (childNode, markType) => u(markType, [childNode]);
return markTypes.reduce(wrapTextWithMark, textNode);
}
/** /**
* Converts a Slate Raw text node to an MDAST text node. * Converts a Slate Raw text node to an MDAST text node.
* *

View File

@ -51,13 +51,11 @@ export default class ObjectControl extends Component {
} }
controlFor(field, key) { controlFor(field, key) {
const { value, onChangeObject, editorControl: EditorControl, resolveWidget } = this.props; const { value, onChangeObject, editorControl: EditorControl } = this.props;
if (field.get('widget') === 'hidden') { if (field.get('widget') === 'hidden') {
return null; return null;
} }
const widgetName = field.get('widget') || 'string';
const widget = resolveWidget(widgetName);
const fieldName = field.get('name'); const fieldName = field.get('name');
const fieldValue = value && Map.isMap(value) ? value.get(fieldName) : value; const fieldValue = value && Map.isMap(value) ? value.get(fieldName) : value;

View File

@ -23,7 +23,7 @@ export default class TextControl extends React.Component {
* state. Always updating this particular widget should generally be low cost, * state. Always updating this particular widget should generally be low cost,
* but this should be optimized in the future. * but this should be optimized in the future.
*/ */
shouldComponentUpdate(nextProps) { shouldComponentUpdate() {
return true; return true;
} }

View File

@ -14,7 +14,7 @@ const baseConfig = {
plugins: [ plugins: [
...Object.entries(plugins) ...Object.entries(plugins)
.filter(([ key ]) => key !== 'friendlyErrors') .filter(([ key ]) => key !== 'friendlyErrors')
.map(([ _, plugin ]) => plugin()), .map(([ , plugin ]) => plugin()),
new webpack.DefinePlugin({ new webpack.DefinePlugin({
NETLIFY_CMS_VERSION: JSON.stringify(`${pkg.version}${isProduction ? '' : '-dev'}`), NETLIFY_CMS_VERSION: JSON.stringify(`${pkg.version}${isProduction ? '' : '-dev'}`),
NETLIFY_CMS_CORE_VERSION: null, NETLIFY_CMS_CORE_VERSION: null,

View File

@ -22,7 +22,7 @@ class Header extends Component {
window.removeEventListener('scroll', this.handleScroll); window.removeEventListener('scroll', this.handleScroll);
} }
handleScroll = event => { handleScroll = () => {
const currentWindowPos = const currentWindowPos =
document.documentElement.scrollTop || document.body.scrollTop; document.documentElement.scrollTop || document.body.scrollTop;

View File

@ -6,7 +6,7 @@ class VideoEmbed extends Component {
state = { state = {
toggled: false toggled: false
}; };
toggleVideo = event => { toggleVideo = () => {
this.setState({ this.setState({
toggled: true toggled: true
}); });

View File

@ -1,4 +1,4 @@
import React, { Component } from 'react'; import React from 'react';
import Helmet from 'react-helmet'; import Helmet from 'react-helmet';
import Markdown from 'react-markdown'; import Markdown from 'react-markdown';

View File

@ -1,4 +1,4 @@
import React, { Component, Fragment } from 'react'; import React, { Fragment } from 'react';
import moment from 'moment'; import moment from 'moment';
import Markdownify from '../components/markdownify'; import Markdownify from '../components/markdownify';