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 promises = [];
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) => {
resolve({ file, data });
sem.leave();

View File

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

View File

@ -83,7 +83,7 @@ export default class GitHub {
const sem = semaphore(MAX_CONCURRENT_DOWNLOADS);
const promises = [];
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) => {
resolve({ file, data });
sem.leave();
@ -123,9 +123,9 @@ export default class GitHub {
async persistMedia(mediaFile, options = {}) {
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);
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 promises = [];
branches.map((branch) => {
promises.push(new Promise((resolve, reject) => {
promises.push(new Promise(resolve => {
const slug = branch.ref.split("refs/heads/cms/").pop();
return sem.take(() => this.api.readUnpublishedBranchFile(slug).then((data) => {
if (data === null || data === undefined) {
@ -161,7 +161,7 @@ export default class GitHub {
});
sem.leave();
}
}).catch((err) => {
}).catch(() => {
sem.leave();
resolve(null);
}));

View File

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

View File

@ -99,7 +99,7 @@ export default class GitLab {
const sem = semaphore(MAX_CONCURRENT_DOWNLOADS);
const promises = [];
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) => {
resolve({ file, data });
sem.leave();

View File

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

View File

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

View File

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

View File

@ -360,7 +360,6 @@ class Backend {
description: entryDraft.getIn(["entry", "data", "description"], "No Description!"),
};
const entryData = entryDraft.getIn(["entry", "data"]).toJS();
let entryObj;
if (newEntry) {
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 user = auth && auth.get('user');
const isFetching = globalUI.get('isFetching');

View File

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

View File

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

View File

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

View File

@ -66,9 +66,7 @@ class Editor extends React.Component {
componentDidMount() {
const {
entry,
newEntry,
entryDraft,
collection,
slug,
loadEntry,
@ -179,12 +177,12 @@ class Editor extends React.Component {
return;
}
const newStatus = status.get(newStatusName);
this.props.updateUnpublishedEntryStatus(collection.get('name'), slug, currentStatus, newStatus);
updateUnpublishedEntryStatus(collection.get('name'), slug, currentStatus, newStatus);
}
handlePersistEntry = async (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)
@ -299,7 +297,6 @@ class Editor extends React.Component {
onChangeStatus={this.handleChangeStatus}
onPublish={this.handlePublishEntry}
showDelete={this.props.showDelete}
enableSave={entryDraft.get('hasChanged')}
user={user}
hasChanged={hasChanged}
displayUrl={displayUrl}
@ -315,7 +312,7 @@ class Editor extends React.Component {
}
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 collection = collections.get(ownProps.match.params.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'),
boundGetAsset: getAsset.bind(null, state),
isFetching: state.search.get('isFetching'),

View File

@ -154,7 +154,6 @@ class EditorInterface extends Component {
fieldsErrors,
getAsset,
onChange,
enableSave,
showDelete,
onDelete,
onDeleteUnpublishedChanges,
@ -230,7 +229,6 @@ class EditorInterface extends Component {
showDelete={showDelete}
onPublish={onPublish}
onPublishAndNew={() => this.handleOnPublish({ createNew: true })}
enableSave={enableSave}
user={user}
hasChanged={hasChanged}
displayUrl={displayUrl}
@ -278,7 +276,6 @@ EditorInterface.propTypes = {
onChange: PropTypes.func.isRequired,
onValidate: PropTypes.func.isRequired,
onPersist: PropTypes.func.isRequired,
enableSave: PropTypes.bool.isRequired,
showDelete: PropTypes.bool.isRequired,
onDelete: 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')]);
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>]));
return Map({ data: val, widgets });
});

View File

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

View File

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

View File

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

View File

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

View File

@ -11,12 +11,12 @@ export const DragSource = ({ namespace, ...props }) => {
const DragComponent = ReactDNDDragSource(
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.
return ownProps;
},
},
(connect, monitor) => ({
connect => ({
connectDragComponent: connect.dragSource(),
}),
)(

View File

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

View File

@ -159,8 +159,6 @@ Please drag the card to the "Ready" column to enable publishing.`
<div>
{
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 editLink = `collections/${ entry.getIn(['metaData', 'collection']) }/entries/${ entry.get('slug') }`;
const slug = entry.get('slug');
@ -181,7 +179,6 @@ Please drag the card to the "Ready" column to enable publishing.`
<WorkflowCard
collectionName={collection}
title={entry.getIn(['data', 'title'])}
author={author}
authorLastChange={entry.getIn(['metaData', 'user'])}
body={entry.getIn(['data', 'body'])}
isModification={isModification}

View File

@ -14,9 +14,7 @@ import {
UNPUBLISHED_ENTRY_PUBLISH_REQUEST,
UNPUBLISHED_ENTRY_PUBLISH_SUCCESS,
UNPUBLISHED_ENTRY_PUBLISH_FAILURE,
UNPUBLISHED_ENTRY_DELETE_REQUEST,
UNPUBLISHED_ENTRY_DELETE_SUCCESS,
UNPUBLISHED_ENTRY_DELETE_FAILURE,
} from 'Actions/editorialWorkflow';
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);
});
case MEDIA_LOAD_SUCCESS: {
const { files = [], page, canPaginate, dynamicSearch, dynamicSearchQuery, privateUpload } = action.payload;
const { files = [], page, canPaginate, dynamicSearch, dynamicSearchQuery } = action.payload;
if (privateUploadChanged) {
return state;

View File

@ -30,7 +30,7 @@ AssetProxy.prototype.toString = function () {
};
AssetProxy.prototype.toBase64 = function () {
return new Promise((resolve, reject) => {
return new Promise(resolve => {
const fr = new FileReader();
fr.onload = (readerEvt) => {
const binaryString = readerEvt.target.result;
@ -50,7 +50,7 @@ export function createAssetProxy(value, fileObj, uploaded = false, privateUpload
response => (
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) {
throw new Error('The Private Upload option is only avaible for Asset Store Integration');

View File

@ -1,40 +1,19 @@
import PropTypes from 'prop-types';
import { Component, Children } from 'react';
import { List, Record, fromJS } from 'immutable';
import { Record, fromJS } from 'immutable';
import { isFunction } from 'lodash';
const plugins = { editor: List() };
const catchesNothing = /.^/;
/* eslint-disable no-unused-vars */
const EditorComponent = Record({
id: null,
label: 'unnamed component',
icon: 'exclamation-triangle',
fields: [],
pattern: catchesNothing,
fromBlock(match) { return {}; },
fromBlock(match) { return {}; },
toBlock(attributes) { return 'Plugin'; },
toPreview(attributes) { return 'Plugin'; },
});
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);
}
}
/* eslint-enable */
export default function createEditorComponent(config) {
const configObj = new EditorComponent({

View File

@ -1,8 +1,7 @@
const path = require('path');
const webpack = require('webpack');
const pkg = require('./package.json');
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');
const { getConfig, rules, plugins } = require('../../scripts/webpack.js');
const { getConfig, rules } = require('../../scripts/webpack.js');
const isProduction = process.env.NODE_ENV === 'production';
@ -16,7 +15,7 @@ module.exports = {
rules: [
...Object.entries(rules)
.filter(([ key ]) => key !== 'js')
.map(([ _, rule ]) => rule()),
.map(([ , rule ]) => rule()),
{
test: /\.js$/,
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"))];
}
clearData() {
return this.updateStore("data", data => Map());
return this.updateStore("data", () => Map());
}
setMeta(meta) {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -202,7 +202,7 @@ export default class ListControl extends React.Component {
}
onSortEnd = ({ oldIndex, newIndex }) => {
const { value, onChange } = this.props;
const { value } = this.props;
const { itemsCollapsed } = this.state;
// Update value
@ -219,11 +219,6 @@ export default class ListControl extends React.Component {
renderItem = (item, index) => {
const {
field,
getAsset,
mediaPaths,
onOpenMediaLibrary,
onAddAsset,
onRemoveInsertedMedia,
classNameWrapper,
editorControl,
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;
const value = shortcodeData.get(field.get('name'));
const key = `field-${ field.get('name') }`;
@ -92,7 +92,7 @@ export default class Shortcode extends React.Component {
};
render() {
const { attributes, node, editor } = this.props;
const { attributes, node } = this.props;
const { collapsed } = this.state;
const pluginId = node.data.get('shortcode');
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,
};
constructor(props) {
super(props);
this.state = {
activePlugin: null,
};
}
isHidden = button => {
const { buttons } = this.props;
return List.isList(buttons) ? !buttons.includes(button) : false;
@ -87,14 +80,10 @@ export default class Toolbar extends React.Component {
onToggleMode,
rawMode,
plugins,
onAddAsset,
getAsset,
disabled,
onSubmit,
} = this.props;
const { activePlugin } = this.state;
return (
<ToolbarContainer>
<div>

View File

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

View File

@ -1,51 +1,7 @@
import React from 'react';
import { fromJS } from 'immutable';
import { markdownToSlate } from '../../serializers';
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", () => {
it("should compile simple markdown", () => {
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
* 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;
if (!singleBlockSelected || !focusBlock.isVoid) return;
@ -45,7 +45,7 @@ function onKeyDown(event, change) {
[ '`', 'code' ],
];
const [ markKey, markName ] = marks.find(([ key ]) => isHotkey(`mod+${key}`, event)) || [];
const [ , markName ] = marks.find(([ key ]) => isHotkey(`mod+${key}`, event)) || [];
if (markName) {
event.preventDefault();

View File

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

View File

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

View File

@ -92,7 +92,7 @@ function transform(node) {
* they were text is a bit of a necessary hack.
*/
function combineTextAndInline(nodes) {
return nodes.reduce((acc, node, idx, nodes) => {
return nodes.reduce((acc, node) => {
const prevNode = last(acc);
const prevNodeLeaves = get(prevNode, 'leaves');
const data = node.data || {};
@ -158,19 +158,6 @@ function processCodeMark(markTypes) {
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.
*

View File

@ -51,13 +51,11 @@ export default class ObjectControl extends Component {
}
controlFor(field, key) {
const { value, onChangeObject, editorControl: EditorControl, resolveWidget } = this.props;
const { value, onChangeObject, editorControl: EditorControl } = this.props;
if (field.get('widget') === 'hidden') {
return null;
}
const widgetName = field.get('widget') || 'string';
const widget = resolveWidget(widgetName);
const fieldName = field.get('name');
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,
* but this should be optimized in the future.
*/
shouldComponentUpdate(nextProps) {
shouldComponentUpdate() {
return true;
}

View File

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

View File

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

View File

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

View File

@ -1,4 +1,4 @@
import React, { Component } from 'react';
import React from 'react';
import Helmet from 'react-helmet';
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 Markdownify from '../components/markdownify';