From 3b2e0b773d4c11ed368a6290ef88bb5d796b1f9b Mon Sep 17 00:00:00 2001 From: Manuel Trezza <5673677+mtrezza@users.noreply.github.com> Date: Mon, 3 Jul 2023 02:45:49 +0200 Subject: [PATCH 1/6] Update .eslintrc.json --- .eslintrc.json | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/.eslintrc.json b/.eslintrc.json index 805abf68f8..158152efd3 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -1,23 +1,36 @@ { "root": true, + "extends": "eslint:recommended", "env": { "es6": true, "node": true, "browser": true }, "parser": "@babel/eslint-parser", - "extends": "eslint:recommended", + "plugins": [ + "react" + ], "parserOptions": { - "sourceType": "module" + "ecmaVersion": 6, + "sourceType": "module", + "requireConfigFile": false }, - "plugins": ["react"], "rules": { + "indent": ["error", 2, { "SwitchCase": 1 }], + "linebreak-style": ["error", "unix"], + "no-trailing-spaces": 2, + "eol-last": 2, + "space-in-parens": ["error", "never"], + "no-multiple-empty-lines": 1, + "prefer-const": "error", + "space-infix-ops": "error", + "no-useless-escape": "off", + "require-atomic-updates": "off", "react/jsx-uses-vars": 1, "react/jsx-uses-react": 1, "react/react-in-jsx-scope": 1, "no-console": 0, "no-case-declarations": 0, - "quotes": ["error", "single"], - "eol-last": ["error", "always"] + "quotes": ["error", "single"] } } From 013d3db9d6b1d623cce9ffc3a4e8e2d99f9f15fe Mon Sep 17 00:00:00 2001 From: Manuel Trezza <5673677+mtrezza@users.noreply.github.com> Date: Mon, 3 Jul 2023 02:49:19 +0200 Subject: [PATCH 2/6] Update package.json --- package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/package.json b/package.json index 3a936eae2c..53e35271a4 100644 --- a/package.json +++ b/package.json @@ -123,6 +123,7 @@ "build": "webpack --node-env=production --config webpack/production.config.js && webpack --config webpack/PIG.config.js", "test": "jest", "lint": "eslint . --ignore-path .gitignore --cache", + "lint:fix": "eslint . --fix --cache ./", "generate": "node scripts/generate.js", "prepare": "webpack --config webpack/publish.config.js --progress", "start": "node ./Parse-Dashboard/index.js", From 31385032ac31ccb5fcacdf624718f06a72451011 Mon Sep 17 00:00:00 2001 From: Manuel Trezza <5673677+mtrezza@users.noreply.github.com> Date: Mon, 3 Jul 2023 02:56:39 +0200 Subject: [PATCH 3/6] fix lint --- .eslintignore | 3 + Parse-Dashboard/Authentication.js | 26 +- Parse-Dashboard/CLI/mfa.js | 4 +- Parse-Dashboard/app.js | 22 +- Parse-Dashboard/server.js | 22 +- ci/nodeEngineCheck.js | 2 +- package.json | 2 +- release.config.js | 2 +- scripts/generate.js | 16 +- src/components/ACLEditor/ACLEditor.react.js | 18 +- src/components/AppBadge/AppBadge.react.js | 2 +- .../Autocomplete/Autocomplete.react.js | 12 +- .../BrowserCell/BrowserCell.react.js | 64 +- .../BrowserFilter/BrowserFilter.react.js | 24 +- .../BrowserFilter/FilterRow.react.js | 152 ++-- .../BrowserMenu/BrowserMenu.react.js | 4 +- src/components/BrowserMenu/MenuItem.react.js | 4 +- src/components/BrowserMenu/Separator.react.js | 2 +- src/components/BrowserRow/BrowserRow.react.js | 10 +- src/components/Button/Button.react.js | 6 +- src/components/CSRFInput/CSRFInput.react.js | 2 +- src/components/Calendar/Calendar.react.js | 18 +- .../CascadingView/CascadingView.example.js | 2 +- .../CascadingView/CascadingView.react.js | 8 +- .../CategoryList/CategoryList.react.js | 12 +- src/components/Chart/Chart.react.js | 44 +- src/components/Chart/Shape.react.js | 4 +- src/components/Checkbox/Checkbox.react.js | 4 +- src/components/Chip/Chip.react.js | 22 +- .../ChromeDatePicker.react.js | 4 +- .../ChromeDropdown/ChromeDropdown.react.js | 8 +- .../CodeSnippet/CodeSnippet.example.js | 4 +- .../CodeSnippet/CodeSnippet.react.js | 6 +- .../ColumnConfigurationItem.react.js | 2 +- .../ColumnsConfiguration.react.js | 2 +- .../ContextMenu/ContextMenu.react.js | 40 +- .../CreditCardInput/CreditCardInput.react.js | 2 +- .../DataBrowserHeader.example.js | 2 +- .../DataBrowserHeader.react.js | 4 +- .../DataBrowserHeaderBar.react.js | 14 +- src/components/DatePicker/DatePicker.react.js | 4 +- src/components/DateRange/DateRange.react.js | 8 +- .../DateTimeEditor/DateTimeEditor.react.js | 4 +- .../DateTimeEntry/DateTimeEntry.react.js | 12 +- .../DateTimeInput/DateTimeInput.react.js | 6 +- .../DateTimePicker/DateTimePicker.react.js | 44 +- .../DonutChart/DonutChart.example.js | 2 +- src/components/DonutChart/DonutChart.react.js | 12 +- .../DragHandle/DragHandle.example.js | 10 +- src/components/Dropdown/Dropdown.react.js | 6 +- src/components/Dropdown/Option.react.js | 2 +- src/components/EmptyState/EmptyState.react.js | 28 +- .../ExpirationDateInput.react.js | 12 +- .../ExplorerActiveChartButton.react.js | 8 +- .../ExplorerMenuButton.example.js | 2 +- .../ExplorerMenuButton.react.js | 6 +- .../ExplorerQueryComposer.react.js | 78 +-- .../ExplorerQueryPicker.example.js | 2 +- .../ExplorerQueryPicker.react.js | 2 +- src/components/Field/Field.react.js | 4 +- src/components/Fieldset/Fieldset.react.js | 2 +- src/components/FileEditor/FileEditor.react.js | 6 +- src/components/FileInput/FileInput.react.js | 8 +- src/components/FileTree/FileTree.react.js | 16 +- src/components/Filter/Filter.react.js | 20 +- src/components/FlowFooter/FlowFooter.react.js | 2 +- src/components/FlowView/FlowView.react.js | 32 +- src/components/FormButton/FormButton.react.js | 4 +- src/components/FormModal/FormModal.react.js | 6 +- src/components/FormNote/FormNote.react.js | 2 +- src/components/FormTable/FormTable.react.js | 4 +- .../GeoPointEditor/GeoPointEditor.react.js | 4 +- .../GeoPointInput/GeoPointInput.react.js | 2 +- src/components/Icon/Icon.react.js | 4 +- .../IntervalInput/IntervalInput.react.js | 12 +- .../JsonPrinter/JsonPrinter.example.js | 2 +- .../JsonPrinter/JsonPrinter.react.js | 2 +- src/components/Label/Label.react.js | 4 +- .../LiveReload/LiveReload.example.js | 10 +- src/components/LiveReload/LiveReload.react.js | 100 +-- src/components/Loader/Loader.react.js | 8 +- .../LoaderContainer.example.js | 6 +- src/components/LogView/LogView.example.js | 6 +- src/components/LogView/LogView.react.js | 2 +- src/components/LogView/LogViewEntry.react.js | 16 +- src/components/LoginRow/LoginRow.react.js | 2 +- src/components/Markdown/Markdown.example.js | 2 +- src/components/Markdown/Markdown.react.js | 8 +- src/components/Modal/Modal.react.js | 10 +- src/components/MoneyInput/MoneyInput.react.js | 2 +- .../MultiSelect/MultiSelect.react.js | 62 +- .../MultiSelect/MultiSelectOption.react.js | 20 +- .../NumberEditor/NumberEditor.react.js | 4 +- .../PasswordStrength.react.js | 2 +- .../PermissionsDialog.example.js | 2 +- .../PermissionsDialog.react.js | 204 +++--- src/components/Pill/Pill.react.js | 2 +- .../PlatformCard/PlatformCard.example.js | 34 +- .../PlatformCard/PlatformCard.react.js | 2 +- src/components/Popover/Popover.react.js | 2 +- .../ProtectedFieldsDialog.example.js | 52 +- .../ProtectedFieldsDialog.react.js | 56 +- .../InstallationCondition.react.js | 20 +- .../PushAudienceDialog.react.js | 44 +- .../PushAudiencesBaseRow.react.js | 4 +- .../PushAudiencesOption.example.js | 24 +- .../PushAudiencesOption.react.js | 4 +- .../PushAudiencesSelector.example.js | 6 +- .../PushAudiencesSelector.react.js | 2 +- src/components/PushCerts/CertsTable.react.js | 6 +- src/components/PushCerts/PushCerts.react.js | 2 +- .../PushExperimentDropdown.react.js | 12 +- .../PushOpenRate/PushOpenRate.example.js | 32 +- .../PushOpenRate/PushOpenRate.react.js | 20 +- .../PushPreview/PushPreview.react.js | 16 +- .../PushPreview/VisiblePreview.react.js | 4 +- .../RadioButton/RadioButton.example.js | 2 +- .../RadioButton/RadioButton.react.js | 2 +- src/components/Range/Range.example.js | 2 +- src/components/Range/Range.react.js | 10 +- src/components/ReleaseInfo/ReleaseInfo.js | 2 +- .../SaveButton/SaveButton.example.js | 2 +- src/components/SaveButton/SaveButton.react.js | 6 +- src/components/ScrollHint/ScrollHint.react.js | 38 +- .../SegmentSelect/SegmentSelect.react.js | 2 +- src/components/Sidebar/Sidebar.react.js | 8 +- .../Sidebar/SidebarSection.react.js | 4 +- .../Sidebar/SidebarSubItem.react.js | 2 +- .../SliderWrap/SliderWrap.example.js | 4 +- src/components/SliderWrap/SliderWrap.react.js | 6 +- .../SlowQueriesFilter.react.js | 10 +- .../StatusIndicator/StatusIndicator.react.js | 2 +- .../StringEditor/StringEditor.react.js | 4 +- .../SuggestionsList/SuggestionsList.react.js | 60 +- src/components/Table/TableHeader.react.js | 4 +- src/components/TextInput/TextInput.example.js | 2 +- src/components/TextInput/TextInput.react.js | 2 +- src/components/TimeInput/TimeInput.react.js | 6 +- src/components/Toggle/Toggle.react.js | 6 +- src/components/Toolbar/Toolbar.react.js | 2 +- src/components/Tooltip/Tooltip.example.js | 8 +- src/components/Tooltip/Tooltip.react.js | 2 +- .../TrackVisibility.example.js | 6 +- .../Account/AccountLinkField.react.js | 16 +- .../Account/AccountOverview.react.js | 28 +- src/dashboard/AccountView.react.js | 2 +- .../Analytics/Explorer/Explorer.react.js | 78 +-- .../Analytics/Overview/Overview.react.js | 22 +- .../Performance/Performance.react.js | 26 +- .../Analytics/Retention/Retention.react.js | 52 +- .../SlowQueries/SlowQueries.react.js | 26 +- src/dashboard/AppData.react.js | 2 +- src/dashboard/AppSelector.react.js | 8 +- src/dashboard/Apps/AppsIndex.react.js | 34 +- src/dashboard/Dashboard.js | 10 +- src/dashboard/DashboardView.react.js | 14 +- .../Data/ApiConsole/GraphQLConsole.react.js | 20 +- .../Data/ApiConsole/RestConsole.react.js | 18 +- src/dashboard/Data/ApiConsole/generateCurl.js | 10 +- src/dashboard/Data/ApiConsole/request.js | 2 +- .../Data/Browser/AddColumnDialog.react.js | 4 +- .../Browser/AttachSelectedRowsDialog.react.js | 86 +-- src/dashboard/Data/Browser/Browser.react.js | 82 +-- .../Data/Browser/BrowserTable.react.js | 18 +- .../Data/Browser/BrowserToolbar.react.js | 48 +- .../Browser/CloneSelectedRowsDialog.react.js | 2 +- .../Data/Browser/CreateClassDialog.react.js | 24 +- .../Data/Browser/DataBrowser.react.js | 16 +- .../Data/Browser/DeleteRowsDialog.react.js | 2 +- .../Data/Browser/EditRowDialog.react.js | 58 +- src/dashboard/Data/Browser/Editor.react.js | 16 +- .../Data/Browser/ExportDialog.react.js | 2 +- .../Browser/ExportSelectedRowsDialog.react.js | 10 +- .../Data/Browser/Notification.react.js | 4 +- .../Data/Browser/ObjectPickerDialog.react.js | 46 +- .../Data/Browser/PointerKeyDialog.react.js | 6 +- .../Data/Browser/RemoveColumnDialog.react.js | 4 +- .../Data/Browser/SchemaOverview.react.js | 6 +- .../Data/Browser/SecureFieldsDialog.react.js | 12 +- .../Data/Browser/SecurityDialog.react.js | 12 +- .../Data/CloudCode/CloudCode.react.js | 12 +- src/dashboard/Data/Config/Config.react.js | 18 +- .../Data/Config/ConfigDialog.react.js | 18 +- .../Config/DeleteParameterDialog.react.js | 2 +- src/dashboard/Data/Jobs/JobEdit.react.js | 10 +- src/dashboard/Data/Jobs/Jobs.react.js | 12 +- src/dashboard/Data/Jobs/JobsData.react.js | 2 +- src/dashboard/Data/Jobs/JobsForm.react.js | 8 +- src/dashboard/Data/Jobs/RunNowButton.react.js | 2 +- src/dashboard/Data/Logs/Logs.react.js | 6 +- .../Data/Migration/Migration.react.js | 38 +- .../Data/Migration/MigrationStep.react.js | 6 +- .../Data/Playground/Playground.react.js | 4 +- src/dashboard/Data/Webhooks/Webhooks.react.js | 88 +-- src/dashboard/Push/PushAudiencesData.react.js | 18 +- .../Push/PushAudiencesIndex.react.js | 20 +- .../Push/PushAudiencesIndexRow.react.js | 4 +- .../Push/PushComposerHelper.react.js | 22 +- src/dashboard/Push/PushDetails.react.js | 210 +++--- src/dashboard/Push/PushIndex.react.js | 76 +- src/dashboard/Push/PushNew.react.js | 104 +-- src/dashboard/Settings/AppleCerts.react.js | 2 +- src/dashboard/Settings/Collaborators.react.js | 8 +- .../DashboardSettings.react.js | 4 +- .../Settings/GeneralSettings.react.js | 224 +++--- .../Settings/HostingSettings.react.js | 662 +++++++++--------- src/dashboard/Settings/PushSettings.react.js | 54 +- .../Settings/SecuritySettings.react.js | 6 +- src/dashboard/Settings/SettingsData.react.js | 4 +- src/dashboard/Settings/UsersSettings.react.js | 630 ++++++++--------- src/dashboard/SidebarBuilder.js | 4 +- src/dashboard/TableView.react.js | 14 +- src/lib/AJAX.js | 12 +- src/lib/AccountManager.js | 22 +- src/lib/AppsManager.js | 18 +- src/lib/CSRFManager.js | 2 +- src/lib/Charting.js | 18 +- src/lib/ClassPreferences.js | 4 +- src/lib/ColumnPreferences.js | 34 +- src/lib/DateUtils.js | 10 +- src/lib/Email.js | 26 +- src/lib/Filters.js | 8 +- src/lib/ParseApp.js | 196 +++--- src/lib/Position.js | 4 +- src/lib/PropTypes.js | 2 +- src/lib/PushUtils.js | 64 +- src/lib/StringEscaping.js | 6 +- src/lib/encodeFormData.js | 4 +- src/lib/englishOrdinalIndicator.js | 2 +- src/lib/getSiteDomain.js | 2 +- src/lib/howLongAgo.js | 2 +- src/lib/isInsidePopover.js | 16 +- src/lib/keyMirror.js | 2 +- src/lib/passwordStrength.js | 8 +- src/lib/prettyNumber.js | 6 +- src/lib/queryFromFilters.js | 6 +- src/lib/renderFlowFooterChanges.js | 30 +- src/lib/setDifference.js | 2 +- src/lib/stores/AnalyticsQueryStore.js | 18 +- src/lib/stores/ConfigStore.js | 4 +- src/lib/stores/JobsStore.js | 10 +- src/lib/stores/PushAudiencesStore.js | 30 +- src/lib/stores/SchemaStore.js | 16 +- src/lib/stores/StateManager.js | 4 +- src/lib/stores/StoreManager.js | 16 +- src/lib/stores/WebhookStore.js | 12 +- src/lib/stringList.js | 2 +- src/lib/subscribeTo.js | 4 +- src/lib/tests/Authentication.test.js | 26 +- src/lib/tests/ColumnPreferences.test.js | 2 +- src/lib/tests/DateUtils.test.js | 8 +- src/lib/tests/e2e.js | 36 +- src/lib/validateEmailFormat.js | 2 +- src/lib/validateNumeric.js | 2 +- src/login/Login.js | 42 +- src/parse-interface-guide/ComponentsMap.js | 138 ++-- src/parse-interface-guide/PIG.react.js | 8 +- src/parse-interface-guide/PropsTable.react.js | 12 +- src/parse-interface-guide/routes.js | 10 +- webpack/plugins/svg-prep.js | 2 +- 260 files changed, 3015 insertions(+), 3012 deletions(-) create mode 100644 .eslintignore diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 0000000000..962a806609 --- /dev/null +++ b/.eslintignore @@ -0,0 +1,3 @@ +bundles/ +PIG/bundles/ +Parse-Dashboard/public/bundles/ diff --git a/Parse-Dashboard/Authentication.js b/Parse-Dashboard/Authentication.js index 53f2b05b17..962692d2d8 100644 --- a/Parse-Dashboard/Authentication.js +++ b/Parse-Dashboard/Authentication.js @@ -67,16 +67,16 @@ function initialize(app, options) { app.post('/login', csrf(), - (req,res,next) => { - let redirect = 'apps'; - if (req.body.redirect) { - redirect = req.body.redirect.charAt(0) === '/' ? req.body.redirect.substring(1) : req.body.redirect - } - return passport.authenticate('local', { - successRedirect: `${self.mountPath}${redirect}`, - failureRedirect: `${self.mountPath}login${req.body.redirect ? `?redirect=${req.body.redirect}` : ''}`, - failureFlash : true - })(req, res, next) + (req,res,next) => { + let redirect = 'apps'; + if (req.body.redirect) { + redirect = req.body.redirect.charAt(0) === '/' ? req.body.redirect.substring(1) : req.body.redirect + } + return passport.authenticate('local', { + successRedirect: `${self.mountPath}${redirect}`, + failureRedirect: `${self.mountPath}login${req.body.redirect ? `?redirect=${req.body.redirect}` : ''}`, + failureFlash : true + })(req, res, next) }, ); @@ -100,13 +100,13 @@ function authenticate(userToTest, usernameOnly) { let otpValid = true; //they provided auth - let isAuthenticated = userToTest && + const isAuthenticated = userToTest && //there are configured users this.validUsers && //the provided auth matches one of the users this.validUsers.find(user => { let isAuthenticated = false; - let usernameMatches = userToTest.name == user.user; + const usernameMatches = userToTest.name == user.user; if (usernameMatches && user.mfa && !usernameOnly) { if (!userToTest.otpCode) { otpMissingLength = user.mfaDigits || 6; @@ -126,7 +126,7 @@ function authenticate(userToTest, usernameOnly) { } } } - let passwordMatches = this.useEncryptedPasswords && !usernameOnly ? bcrypt.compareSync(userToTest.pass, user.pass) : userToTest.pass == user.pass; + const passwordMatches = this.useEncryptedPasswords && !usernameOnly ? bcrypt.compareSync(userToTest.pass, user.pass) : userToTest.pass == user.pass; if (usernameMatches && (usernameOnly || passwordMatches)) { isAuthenticated = true; matchingUsername = user.user; diff --git a/Parse-Dashboard/CLI/mfa.js b/Parse-Dashboard/CLI/mfa.js index 3f26a73a98..feab6433a8 100644 --- a/Parse-Dashboard/CLI/mfa.js +++ b/Parse-Dashboard/CLI/mfa.js @@ -129,7 +129,7 @@ const showInstructions = ({ app, username, passwordCopied, encrypt, config }) => `\n${getOrder()}. Make sure that "useEncryptedPasswords" is set to "true" in your dashboard configuration.` + '\n You chose to generate an encrypted password for this user.' + '\n Any existing users with non-encrypted passwords will require newly created, encrypted passwords.' - ); + ); } console.log( '\n------------------------------------------------------------------------------\n' @@ -198,7 +198,7 @@ module.exports = { } ]); const { algorithm, digits, period } = await getAlgorithm(); - const secret =generateSecret({ app, username, algorithm, digits, period }); + const secret = generateSecret({ app, username, algorithm, digits, period }); Object.assign(config, secret.config); showQR(secret.config.url); } diff --git a/Parse-Dashboard/app.js b/Parse-Dashboard/app.js index 2b4c73fca0..eaa5133849 100644 --- a/Parse-Dashboard/app.js +++ b/Parse-Dashboard/app.js @@ -38,16 +38,16 @@ function checkIfIconsExistForApps(apps, iconsFolder) { fs.stat(path, function(err) { if (err) { - if ('ENOENT' == err.code) {// file does not exist - console.warn('Icon with file name: ' + iconName +' couldn\'t be found in icons folder!'); - } else { - console.log( - 'An error occurd while checking for icons, please check permission!'); - } + if ('ENOENT' == err.code) {// file does not exist + console.warn('Icon with file name: ' + iconName + ' couldn\'t be found in icons folder!'); + } else { + console.log( + 'An error occurd while checking for icons, please check permission!'); + } } else { - //every thing was ok so for example you can read it and send it to client + //every thing was ok so for example you can read it and send it to client } - } ); + }); } } @@ -81,8 +81,8 @@ module.exports = function(config, options) { // Serve the configuration. app.get('/parse-dashboard-config.json', function(req, res) { - let apps = config.apps.map((app) => Object.assign({}, app)); // make a copy - let response = { + const apps = config.apps.map((app) => Object.assign({}, app)); // make a copy + const response = { apps: apps, newFeaturesInLatestVersion: newFeaturesInLatestVersion, }; @@ -213,7 +213,7 @@ module.exports = function(config, options) { } return res.redirect(`${mountPath}login`); } - if (users && req.user && req.user.matchingUsername ) { + if (users && req.user && req.user.matchingUsername) { res.append('username', req.user.matchingUsername); } res.send(` diff --git a/Parse-Dashboard/server.js b/Parse-Dashboard/server.js index 76ac4bc398..a9f5dc275c 100644 --- a/Parse-Dashboard/server.js +++ b/Parse-Dashboard/server.js @@ -27,18 +27,18 @@ module.exports = (options) => { process.exit(-1); } - let explicitConfigFileProvided = !!options.config; + const explicitConfigFileProvided = !!options.config; let configFile = null; let configFromCLI = null; - let configServerURL = options.serverURL || process.env.PARSE_DASHBOARD_SERVER_URL; - let configGraphQLServerURL = options.graphQLServerURL || process.env.PARSE_DASHBOARD_GRAPHQL_SERVER_URL; - let configMasterKey = options.masterKey || process.env.PARSE_DASHBOARD_MASTER_KEY; - let configAppId = options.appId || process.env.PARSE_DASHBOARD_APP_ID; - let configAppName = options.appName || process.env.PARSE_DASHBOARD_APP_NAME; - let configUserId = options.userId || process.env.PARSE_DASHBOARD_USER_ID; - let configUserPassword = options.userPassword || process.env.PARSE_DASHBOARD_USER_PASSWORD; - let configSSLKey = options.sslKey || process.env.PARSE_DASHBOARD_SSL_KEY; - let configSSLCert = options.sslCert || process.env.PARSE_DASHBOARD_SSL_CERT; + const configServerURL = options.serverURL || process.env.PARSE_DASHBOARD_SERVER_URL; + const configGraphQLServerURL = options.graphQLServerURL || process.env.PARSE_DASHBOARD_GRAPHQL_SERVER_URL; + const configMasterKey = options.masterKey || process.env.PARSE_DASHBOARD_MASTER_KEY; + const configAppId = options.appId || process.env.PARSE_DASHBOARD_APP_ID; + const configAppName = options.appName || process.env.PARSE_DASHBOARD_APP_NAME; + const configUserId = options.userId || process.env.PARSE_DASHBOARD_USER_ID; + const configUserPassword = options.userPassword || process.env.PARSE_DASHBOARD_USER_PASSWORD; + const configSSLKey = options.sslKey || process.env.PARSE_DASHBOARD_SSL_KEY; + const configSSLCert = options.sslCert || process.env.PARSE_DASHBOARD_SSL_CERT; function handleSIGs(server) { const signals = { @@ -146,7 +146,7 @@ module.exports = (options) => { if (allowInsecureHTTP || trustProxy || dev) app.enable('trust proxy'); config.data.trustProxy = trustProxy; - let dashboardOptions = { allowInsecureHTTP, cookieSessionSecret, dev, cookieSessionMaxAge }; + const dashboardOptions = { allowInsecureHTTP, cookieSessionSecret, dev, cookieSessionMaxAge }; app.use(mountPath, parseDashboard(config.data, dashboardOptions)); let server; if(!configSSLKey || !configSSLCert){ diff --git a/ci/nodeEngineCheck.js b/ci/nodeEngineCheck.js index 2b71a02d47..9af1544237 100644 --- a/ci/nodeEngineCheck.js +++ b/ci/nodeEngineCheck.js @@ -46,7 +46,7 @@ class NodeEngineCheck { const dirents = await fs.readdir(basePath, { withFileTypes: true }); const validFiles = dirents.filter(d => d.name.toLowerCase() == 'package.json').map(d => path.join(basePath, d.name)); files.push(...validFiles); - + // For each directory entry for (const dirent of dirents) { if (dirent.isDirectory()) { diff --git a/package.json b/package.json index 53e35271a4..8b9da55c61 100644 --- a/package.json +++ b/package.json @@ -123,7 +123,7 @@ "build": "webpack --node-env=production --config webpack/production.config.js && webpack --config webpack/PIG.config.js", "test": "jest", "lint": "eslint . --ignore-path .gitignore --cache", - "lint:fix": "eslint . --fix --cache ./", + "lint:fix": "DEBUG=eslint:cli-engine eslint --fix --cache ./", "generate": "node scripts/generate.js", "prepare": "webpack --config webpack/publish.config.js --progress", "start": "node ./Parse-Dashboard/index.js", diff --git a/release.config.js b/release.config.js index 9858e3ce9f..082f461781 100644 --- a/release.config.js +++ b/release.config.js @@ -116,7 +116,7 @@ async function readFile(filePath) { function getReleaseComment() { const url = repositoryUrl + '/releases/tag/${nextRelease.gitTag}'; - let comment = '🎉 This change has been released in version [${nextRelease.version}](' + url + ')'; + const comment = '🎉 This change has been released in version [${nextRelease.version}](' + url + ')'; return comment; } diff --git a/scripts/generate.js b/scripts/generate.js index 36070e8728..3fbc000d95 100644 --- a/scripts/generate.js +++ b/scripts/generate.js @@ -17,7 +17,7 @@ const pigDir = path.join(__dirname, '..', 'src','parse-interface-guide'); const testDir = path.join(__dirname, '..', 'src','lib', 'tests'); function padding(length) { - let space = []; + const space = []; for (let i = 0; i < length; i++) { space[i] = ' '; } @@ -26,7 +26,7 @@ function padding(length) { function generateReact(name) { return ( -`/* + `/* * Copyright (c) 2016-present, Parse, LLC * All rights reserved. * @@ -49,7 +49,7 @@ ${name}.propTypes = { function generateExample(name) { return ( -`/* + `/* * Copyright (c) 2016-present, Parse, LLC * All rights reserved. * @@ -57,7 +57,7 @@ function generateExample(name) { * the root directory of this source tree. */ import React${padding(name.length - 5)} from 'react'; -import ${name}${padding(5 - name.length)} f`+ 'rom' +` 'components/${name}/${name}.react'; +import ${name}${padding(5 - name.length)} f` + 'rom' + ` 'components/${name}/${name}.react'; export const component = ${name}; @@ -74,7 +74,7 @@ export const demos = [ function generateTest(name) { return ( -`/* + `/* * Copyright (c) 2016-present, Parse, LLC * All rights reserved. * @@ -109,18 +109,18 @@ function updateComponentMap(name) { } let spaces = ''; - for (let i = 0; i Promise.resolve([]) }; - let user = text.substring(5); + const user = text.substring(5); entry = user; userQuery = new Parse.Query.or( new Parse.Query(Parse.User).equalTo('username', user), @@ -39,7 +39,7 @@ function validateEntry(text, returnInvalid = true) { userQuery = { find: () => Promise.resolve([]) }; - let role = text.substring(5); + const role = text.substring(5); entry = role; roleQuery = new Parse.Query.or( new Parse.Query(Parse.Role).equalTo('name', role), @@ -79,9 +79,9 @@ function toPerms(acl) { if (!acl) { return { read: { '*': true }, write: { '*': true } }; } - let json = acl.toJSON(); - let perms = { read: {}, write: {} }; - for (let key in json) { + const json = acl.toJSON(); + const perms = { read: {}, write: {} }; + for (const key in json) { if (json[key].read) { perms.read[key] = true; } @@ -93,13 +93,13 @@ function toPerms(acl) { } function toACL(perms) { - let acl = {}; - for (let key in perms.read) { + const acl = {}; + for (const key in perms.read) { if (perms.read[key]) { acl[key] = { read: true }; } } - for (let key in perms.write) { + for (const key in perms.write) { if (perms.write[key]) { if (acl[key]) { acl[key].write = true; @@ -111,7 +111,7 @@ function toACL(perms) { return new Parse.ACL(acl); } -let ACLEditor = ({ value, onCommit }) => ( +const ACLEditor = ({ value, onCommit }) => ( ( +const AppBadge = ({ production }) => ( {production ? 'PROD' : 'DEV'} diff --git a/src/components/Autocomplete/Autocomplete.react.js b/src/components/Autocomplete/Autocomplete.react.js index 6e0647baae..c1c977ead4 100644 --- a/src/components/Autocomplete/Autocomplete.react.js +++ b/src/components/Autocomplete/Autocomplete.react.js @@ -73,7 +73,7 @@ export default class Autocomplete extends Component { getPosition() { const node = this.fieldRef.current; - let newPosition = this.props.fixed + const newPosition = this.props.fixed ? Position.inWindow(node) : Position.inDocument(node); @@ -97,9 +97,9 @@ export default class Autocomplete extends Component { const filteredSuggestions = buildSuggestions ? buildSuggestions(userInput) : suggestions.filter( - suggestion => - suggestion.toLowerCase().indexOf(userInput.toLowerCase()) > -1 - ); + suggestion => + suggestion.toLowerCase().indexOf(userInput.toLowerCase()) > -1 + ); return filteredSuggestions; } @@ -249,8 +249,8 @@ export default class Autocomplete extends Component { // Enter const { userInput } = this.state; - if (e.keyCode === 13) { - if (userInput && userInput.length > 0) { + if (e.keyCode === 13) { + if (userInput && userInput.length > 0) { this.props.onSubmit(userInput); } } else if (e.keyCode === 9) { diff --git a/src/components/BrowserCell/BrowserCell.react.js b/src/components/BrowserCell/BrowserCell.react.js index 9d16b142b4..d87c858c88 100644 --- a/src/components/BrowserCell/BrowserCell.react.js +++ b/src/components/BrowserCell/BrowserCell.react.js @@ -35,9 +35,9 @@ export default class BrowserCell extends Component { renderCellContent() { let content = this.props.value; - let isNewRow = this.props.row < 0; + const isNewRow = this.props.row < 0; this.copyableValue = content; - let classes = [styles.cell, baseStyles.unselectable]; + const classes = [styles.cell, baseStyles.unselectable]; if (this.props.hidden) { content = this.props.value !== undefined || !isNewRow ? '(hidden)' : this.props.isRequired ? '(required)' : '(undefined)'; classes.push(styles.empty); @@ -58,22 +58,22 @@ export default class BrowserCell extends Component { } else if (this.props.type === 'Pointer') { const defaultPointerKey = ColumnPreferences.getPointerDefaultKey(this.props.appId, this.props.value.className); let dataValue = this.props.value.id; - if( defaultPointerKey !== 'objectId' ) { + if(defaultPointerKey !== 'objectId') { dataValue = this.props.value.get(defaultPointerKey); - if ( dataValue && typeof dataValue === 'object' ){ - if ( dataValue instanceof Date ) { + if (dataValue && typeof dataValue === 'object'){ + if (dataValue instanceof Date) { dataValue = dataValue.toLocaleString(); } else { - if ( !this.props.value.id ) { + if (!this.props.value.id) { dataValue = this.props.value.id; } else { dataValue = '(undefined)'; } } } - if ( !dataValue ) { - if ( this.props.value.id ) { + if (!dataValue) { + if (this.props.value.id) { dataValue = this.props.value.id; } else { dataValue = '(undefined)'; @@ -96,22 +96,22 @@ export default class BrowserCell extends Component { this.copyableValue = this.props.value.id; } else if (this.props.type === 'Array') { - if ( this.props.value[0] && typeof this.props.value[0] === 'object' && this.props.value[0].__type === 'Pointer' && typeof this.props.onPointerClick === 'function' ) { + if (this.props.value[0] && typeof this.props.value[0] === 'object' && this.props.value[0].__type === 'Pointer' && typeof this.props.onPointerClick === 'function') { const array = []; - this.props.value.map( (v, i) => { - if ( typeof v !== 'object' || v.__type !== 'Pointer' ) { + this.props.value.map((v, i) => { + if (typeof v !== 'object' || v.__type !== 'Pointer') { throw new Error('Invalid type found in pointer array'); } const object = new Parse.Object(v.className); object.id = v.objectId; array.push( - - ); + + ); }); this.copyableValue = content =
    - { array.map( a =>
  • {a}
  • ) } + { array.map(a =>
  • {a}
  • ) }
- if ( array.length > 1 ) { + if (array.length > 1) { classes.push(styles.hasMore); } } @@ -135,8 +135,8 @@ export default class BrowserCell extends Component { content = ; this.copyableValue = fileName; } else if (this.props.type === 'ACL') { - let pieces = []; - let json = this.props.value.toJSON(); + const pieces = []; + const json = this.props.value.toJSON(); if (Object.prototype.hasOwnProperty.call(json, '*')) { if (json['*'].read && json['*'].write) { pieces.push('Public Read + Write'); @@ -146,7 +146,7 @@ export default class BrowserCell extends Component { pieces.push('Public Write'); } } - for (let role in json) { + for (const role in json) { if (role !== '*') { pieces.push(role); } @@ -165,8 +165,8 @@ export default class BrowserCell extends Component { this.props.setRelation(this.props.value)} value='View relation' followClick={true} shrinkablePill /> ) : ( - 'Relation' - ); + 'Relation' + ); this.copyableValue = undefined; } this.onContextMenu = this.onContextMenu.bind(this); @@ -179,7 +179,7 @@ export default class BrowserCell extends Component { } componentDidUpdate(prevProps) { - if ( this.props.value !== prevProps.value ) { + if (this.props.value !== prevProps.value) { this.renderCellContent(); this.props.value?._previousSave ?.then(() => this.renderCellContent()) @@ -253,7 +253,7 @@ export default class BrowserCell extends Component { } getContextMenuOptions(constraints) { - let { onEditSelectedRow, readonly } = this.props; + const { onEditSelectedRow, readonly } = this.props; const contextMenuOptions = []; const setFilterContextMenuOption = this.getSetFilterContextMenuOption(constraints); @@ -268,7 +268,7 @@ export default class BrowserCell extends Component { !readonly && onEditSelectedRow && contextMenuOptions.push({ text: 'Edit row', callback: () => { - let { objectId, onEditSelectedRow } = this.props; + const { objectId, onEditSelectedRow } = this.props; onEditSelectedRow(true, objectId); } }); @@ -277,7 +277,7 @@ export default class BrowserCell extends Component { onEditSelectedRow && contextMenuOptions.push({ text: 'Open pointer in new tab', callback: () => { - let { value, onPointerCmdClick } = this.props; + const { value, onPointerCmdClick } = this.props; onPointerCmdClick(value); } }); @@ -333,8 +333,8 @@ export default class BrowserCell extends Component { copyableValue.length < 30 ? copyableValue : `${copyableValue.substr(0, 20)}...${copyableValue.substr( - copyableValue.length - 7 - )}`; + copyableValue.length - 7 + )}`; const text = `${this.props.field} ${definition.name}${ definition.comparable ? ' ' + value : '' }`; @@ -430,11 +430,11 @@ export default class BrowserCell extends Component { //#endregion render() { - let { type, value, hidden, width, current, onSelect, onEditChange, setCopyableValue, onPointerCmdClick, row, col, field, onEditSelectedRow, isRequired, markRequiredFieldRow } = this.props; + const { type, value, hidden, width, current, onSelect, onEditChange, setCopyableValue, onPointerCmdClick, row, col, field, onEditSelectedRow, isRequired, markRequiredFieldRow } = this.props; - let classes = [...this.state.classes]; + const classes = [...this.state.classes]; - if ( current ) { + if (current) { classes.push(styles.current); } if (markRequiredFieldRow === row && isRequired && value == null) { @@ -491,9 +491,9 @@ export default class BrowserCell extends Component { } }}} onContextMenu={this.onContextMenu.bind(this)} - > - {this.state.content} - {extras} + > + {this.state.content} + {extras} } } diff --git a/src/components/BrowserFilter/BrowserFilter.react.js b/src/components/BrowserFilter/BrowserFilter.react.js index 30e8f7f2b5..fef20a66e9 100644 --- a/src/components/BrowserFilter/BrowserFilter.react.js +++ b/src/components/BrowserFilter/BrowserFilter.react.js @@ -46,8 +46,8 @@ export default class BrowserFilter extends React.Component { toggle() { let filters = this.props.filters; if (this.props.filters.size === 0) { - let available = Filters.availableFilters(this.props.schema, null, this.state.blacklistedFilters); - let field = Object.keys(available)[0]; + const available = Filters.availableFilters(this.props.schema, null, this.state.blacklistedFilters); + const field = Object.keys(available)[0]; filters = new List([new Map({ field: field, constraint: available[field][0] })]); } this.setState((prevState) => ({ @@ -61,8 +61,8 @@ export default class BrowserFilter extends React.Component { } addRow() { - let available = Filters.availableFilters(this.props.schema, this.state.filters, this.state.blacklistedFilters); - let field = Object.keys(available)[0]; + const available = Filters.availableFilters(this.props.schema, this.state.filters, this.state.blacklistedFilters); + const field = Object.keys(available)[0]; this.setState(({ filters }) => ({ filters: filters.push( new Map({ field: field, constraint: available[field][0] }) @@ -76,7 +76,7 @@ export default class BrowserFilter extends React.Component { } apply() { - let formatted = this.state.filters.map((filter) => { + const formatted = this.state.filters.map((filter) => { // TODO: type is unused? /*let type = this.props.schema[filter.get('field')].type; if (Filters.Constraints[filter.get('constraint')].hasOwnProperty('field')) { @@ -85,7 +85,7 @@ export default class BrowserFilter extends React.Component { // since we are preserving previous compareTo value // remove compareTo for constraints which are not comparable - let isComparable = Filters.Constraints[filter.get('constraint')].comparable; + const isComparable = Filters.Constraints[filter.get('constraint')].comparable; if (!isComparable) { return filter.delete('compareTo'); } @@ -95,8 +95,8 @@ export default class BrowserFilter extends React.Component { } save() { - let formatted = this.state.filters.map((filter) => { - let isComparable = Filters.Constraints[filter.get('constraint')].comparable; + const formatted = this.state.filters.map((filter) => { + const isComparable = Filters.Constraints[filter.get('constraint')].comparable; if (!isComparable) { return filter.delete('compareTo'); } @@ -108,18 +108,18 @@ export default class BrowserFilter extends React.Component { render() { let popover = null; - let buttonStyle = [styles.entry]; + const buttonStyle = [styles.entry]; const node = this.wrapRef.current; if (this.state.open) { - let position = Position.inDocument(node); - let popoverStyle = [styles.popover]; + const position = Position.inDocument(node); + const popoverStyle = [styles.popover]; buttonStyle.push(styles.title); if (this.props.filters.size) { popoverStyle.push(styles.active); } - let available = Filters.availableFilters(this.props.schema, this.state.filters); + const available = Filters.availableFilters(this.props.schema, this.state.filters); popover = (
this.props.setCurrent(null)} id={POPOVER_CONTENT_ID}> diff --git a/src/components/BrowserFilter/FilterRow.react.js b/src/components/BrowserFilter/FilterRow.react.js index eed8c281b2..dc1a28366e 100644 --- a/src/components/BrowserFilter/FilterRow.react.js +++ b/src/components/BrowserFilter/FilterRow.react.js @@ -16,8 +16,8 @@ import React, { useCallback } from 'react'; import styles from 'components/BrowserFilter/BrowserFilter.scss'; import validateNumeric from 'lib/validateNumeric'; -let constraintLookup = {}; -for (let c in Constraints) { +const constraintLookup = {}; +for (const c in Constraints) { constraintLookup[Constraints[c].name] = c; } @@ -34,7 +34,7 @@ function compareValue(info, value, onChangeCompareTo, onKeyDown, active, parentC type='text' value={value.objectId || ''} onChange={(e) => { - let obj = new Parse.Object(info.targetClass); + const obj = new Parse.Object(info.targetClass); obj.id = e.target.value; onChangeCompareTo(obj.toPointer()); }} @@ -57,7 +57,7 @@ function compareValue(info, value, onChangeCompareTo, onKeyDown, active, parentC onChangeCompareTo(val); }} onKeyDown={onKeyDown} - /> + /> ); case 'Date': return ( @@ -72,81 +72,81 @@ function compareValue(info, value, onChangeCompareTo, onKeyDown, active, parentC } } -let FilterRow = ({ - fields, - constraints, - compareInfo, - currentField, - currentConstraint, - compareTo, - onChangeField, - onChangeConstraint, - onChangeCompareTo, - onKeyDown, - onDeleteRow, - active, - parentContentId, - editMode - }) => { +const FilterRow = ({ + fields, + constraints, + compareInfo, + currentField, + currentConstraint, + compareTo, + onChangeField, + onChangeConstraint, + onChangeCompareTo, + onKeyDown, + onDeleteRow, + active, + parentContentId, + editMode +}) => { - let setFocus = useCallback((input) => { - if (input !== null && editMode) { - input.focus(); - } - }, []) + const setFocus = useCallback((input) => { + if (input !== null && editMode) { + input.focus(); + } + }, []) - const buildSuggestions = (input) => { - const regex = new RegExp(input.split('').join('.*?'), 'i'); - return fields.filter(f => regex.test(f)); - }; + const buildSuggestions = (input) => { + const regex = new RegExp(input.split('').join('.*?'), 'i'); + return fields.filter(f => regex.test(f)); + }; - return ( -
- ''} - /> - Constraints[c].name)} - onChange={(c) => onChangeConstraint(constraintLookup[c], compareTo)} /> - {compareValue(compareInfo, compareTo, onChangeCompareTo, onKeyDown, active, parentContentId, setFocus)} - -
- ); + return ( +
+ ''} + /> + Constraints[c].name)} + onChange={(c) => onChangeConstraint(constraintLookup[c], compareTo)} /> + {compareValue(compareInfo, compareTo, onChangeCompareTo, onKeyDown, active, parentContentId, setFocus)} + +
+ ); } export default React.memo(FilterRow); diff --git a/src/components/BrowserMenu/BrowserMenu.react.js b/src/components/BrowserMenu/BrowserMenu.react.js index 5939920667..d875aeb981 100644 --- a/src/components/BrowserMenu/BrowserMenu.react.js +++ b/src/components/BrowserMenu/BrowserMenu.react.js @@ -23,8 +23,8 @@ export default class BrowserMenu extends React.Component { render() { let menu = null; if (this.state.open) { - let position = Position.inDocument(this.wrapRef.current); - let titleStyle = [styles.title]; + const position = Position.inDocument(this.wrapRef.current); + const titleStyle = [styles.title]; if (this.props.active) { titleStyle.push(styles.active); } diff --git a/src/components/BrowserMenu/MenuItem.react.js b/src/components/BrowserMenu/MenuItem.react.js index 27b1df6f9f..ce27f0c888 100644 --- a/src/components/BrowserMenu/MenuItem.react.js +++ b/src/components/BrowserMenu/MenuItem.react.js @@ -8,8 +8,8 @@ import React from 'react'; import styles from 'components/BrowserMenu/BrowserMenu.scss'; -let MenuItem = ({ text, disabled, active, greenActive, onClick }) => { - let classes = [styles.item]; +const MenuItem = ({ text, disabled, active, greenActive, onClick }) => { + const classes = [styles.item]; if (disabled) { classes.push(styles.disabled); } diff --git a/src/components/BrowserMenu/Separator.react.js b/src/components/BrowserMenu/Separator.react.js index 655e8daf85..34989f46d9 100644 --- a/src/components/BrowserMenu/Separator.react.js +++ b/src/components/BrowserMenu/Separator.react.js @@ -8,6 +8,6 @@ import React from 'react'; import styles from 'components/BrowserMenu/BrowserMenu.scss'; -let Separator = () =>
; +const Separator = () =>
; export default Separator; diff --git a/src/components/BrowserRow/BrowserRow.react.js b/src/components/BrowserRow/BrowserRow.react.js index 7a6c99a74e..1ff56c559b 100644 --- a/src/components/BrowserRow/BrowserRow.react.js +++ b/src/components/BrowserRow/BrowserRow.react.js @@ -20,7 +20,7 @@ export default class BrowserRow extends Component { render() { const { className, columns, currentCol, isUnique, obj, onPointerClick, onPointerCmdClick, order, readOnlyFields, row, rowWidth, selection, selectRow, setCopyableValue, setCurrent, setEditing, setRelation, onEditSelectedRow, setContextMenu, onFilterChange, markRequiredFieldRow } = this.props; - let attributes = obj.attributes; + const attributes = obj.attributes; let requiredCols = []; Object.entries(columns).reduce((acc, cur) => { if (cur[1].required) { @@ -44,10 +44,10 @@ export default class BrowserRow extends Component { {order.map(({ name, width, visible }, j) => { if (!visible) return null; - let type = columns[name].type; + const type = columns[name].type; let attr = obj; if (!isUnique) { - attr = attributes[name]; + attr = attributes[name]; if (name === 'objectId') { attr = obj.id; } else if (name === 'ACL' && className === '_User' && !attr) { @@ -71,7 +71,7 @@ export default class BrowserRow extends Component { hidden = true; } } - let isRequired = requiredCols.includes(name); + const isRequired = requiredCols.includes(name); return ( + /> ); })}
diff --git a/src/components/Button/Button.react.js b/src/components/Button/Button.react.js index 80baeb6e4e..592cfb172e 100644 --- a/src/components/Button/Button.react.js +++ b/src/components/Button/Button.react.js @@ -12,9 +12,9 @@ import styles from 'components/Button/Button.scss'; const noop = () => {}; -let Button = (props) => { +const Button = (props) => { const hasOnClick = props.onClick && !props.disabled; - let classes = [styles.button, baseStyles.unselectable]; + const classes = [styles.button, baseStyles.unselectable]; // if a button is disabled, that overrides any color selection if (props.disabled) { classes.push(styles.disabled); @@ -33,7 +33,7 @@ let Button = (props) => { classes.push(styles.progress); } } - let clickHandler = hasOnClick ? props.onClick : noop; + const clickHandler = hasOnClick ? props.onClick : noop; let styleOverride = null; if (props.width) { styleOverride = { width: props.width, minWidth: props.width, ...props.additionalStyles }; diff --git a/src/components/CSRFInput/CSRFInput.react.js b/src/components/CSRFInput/CSRFInput.react.js index ff5f9e316e..70c4fb2832 100644 --- a/src/components/CSRFInput/CSRFInput.react.js +++ b/src/components/CSRFInput/CSRFInput.react.js @@ -10,7 +10,7 @@ import React from 'react'; // An invisible component that embeds a hidden input // containing the CSRF token into a form -let CSRFInput = () => ( +const CSRFInput = () => (
diff --git a/src/components/Calendar/Calendar.react.js b/src/components/Calendar/Calendar.react.js index 9ae8f8315c..2fcf291fa1 100644 --- a/src/components/Calendar/Calendar.react.js +++ b/src/components/Calendar/Calendar.react.js @@ -20,7 +20,7 @@ import styles from 'components/Calendar/Calendar.scss'; export default class Calendar extends React.Component { constructor(props) { super(); - let now = props.value || new Date(); + const now = props.value || new Date(); this.state = { currentMonth: new Date(now[getDateMethod(props.local, 'getFullYear')](), now[getDateMethod(props.local, 'getMonth')](), 1) }; @@ -65,21 +65,21 @@ export default class Calendar extends React.Component { } renderDays() { - let isValueMonth = ( + const isValueMonth = ( this.props.value && this.props.value[getDateMethod(this.props.local, 'getFullYear')]() === this.state.currentMonth.getFullYear() && this.props.value[getDateMethod(this.props.local, 'getMonth')]() === this.state.currentMonth.getMonth() ); - let offset = this.state.currentMonth.getDay(); - let days = daysInMonth(this.state.currentMonth); - let labels = []; + const offset = this.state.currentMonth.getDay(); + const days = daysInMonth(this.state.currentMonth); + const labels = []; for (let i = 0; i < offset; i++) { labels.push(); } for (let i = 1; i <= days; i++) { - let isSelected = isValueMonth && (this.props.value[getDateMethod(this.props.local, 'getDate')]() === i); - let className = isSelected ? styles.selected : ''; - let onChange = this.props.onChange.bind( + const isSelected = isValueMonth && (this.props.value[getDateMethod(this.props.local, 'getDate')]() === i); + const className = isSelected ? styles.selected : ''; + const onChange = this.props.onChange.bind( null, this.props.local ? new Date(this.state.currentMonth.getFullYear(), this.state.currentMonth.getMonth(), i) : @@ -89,7 +89,7 @@ export default class Calendar extends React.Component { ); } - let classes = [styles.days]; + const classes = [styles.days]; if (isValueMonth && this.props.shadeBefore) { classes.push(styles.shadeBefore); } diff --git a/src/components/CascadingView/CascadingView.example.js b/src/components/CascadingView/CascadingView.example.js index fe96c2b224..4d1e99482f 100644 --- a/src/components/CascadingView/CascadingView.example.js +++ b/src/components/CascadingView/CascadingView.example.js @@ -27,7 +27,7 @@ export const demos = [ }, { render: () => { - let contents = []; + const contents = []; for (let i = 0; i < 4; ++i) { contents.push(
; - let childrenContainer = this.state.expanded ? (
+ const childrenContainer = this.state.expanded ? (
{children}
) : null; - let classes = [styles.contentContainer]; + const classes = [styles.contentContainer]; if (className) { classes.push(className); } diff --git a/src/components/CategoryList/CategoryList.react.js b/src/components/CategoryList/CategoryList.react.js index afce681dfe..7949648f7f 100644 --- a/src/components/CategoryList/CategoryList.react.js +++ b/src/components/CategoryList/CategoryList.react.js @@ -23,7 +23,7 @@ export default class CategoryList extends React.Component { } componentDidMount() { - let listWrapper = this.listWrapperRef.current; + const listWrapper = this.listWrapperRef.current; if (listWrapper) { this.highlight = document.createElement('div'); this.highlight.className = styles.highlight; @@ -46,8 +46,8 @@ export default class CategoryList extends React.Component { if (this.highlight) { let height = 0; for (let i = 0; i < this.props.categories.length; i++) { - let c = this.props.categories[i]; - let id = c.id || c.name; + const c = this.props.categories[i]; + const id = c.id || c.name; if (id === this.props.current) { if (this.state.openClasses.includes(id)) { const query = new URLSearchParams(this.props.params); @@ -98,11 +98,11 @@ export default class CategoryList extends React.Component { return (
{this.props.categories.map((c) => { - let id = c.id || c.name; + const id = c.id || c.name; if (c.type === 'separator') { return
; } - let count = c.count; + const count = c.count; let className = id === this.props.current ? styles.active : ''; let selectedFilter = null; if (this.state.openClasses.includes(id) && id === this.props.current) { @@ -119,7 +119,7 @@ export default class CategoryList extends React.Component { } } } - let link = generatePath(this.context, (this.props.linkPrefix || '') + (c.link || id)); + const link = generatePath(this.context, (this.props.linkPrefix || '') + (c.link || id)); return (
diff --git a/src/components/Chart/Chart.react.js b/src/components/Chart/Chart.react.js index ea555273da..beb8e6c685 100644 --- a/src/components/Chart/Chart.react.js +++ b/src/components/Chart/Chart.react.js @@ -25,7 +25,7 @@ function sortPoints(a, b) { } function formatDate(date) { - let str = DateUtils.getMonth(date.getMonth()) + ' ' + date.getDate(); + const str = DateUtils.getMonth(date.getMonth()) + ' ' + date.getDate(); if (date.getUTCHours() === 0 && date.getUTCMinutes() === 0 && date.getUTCSeconds() === 0) { return str; } @@ -59,17 +59,17 @@ export default class Chart extends React.Component { } render() { - let { width, height, data } = this.props; - let plotting = {}; + const { width, height, data } = this.props; + const plotting = {}; let minX = Infinity; let maxX = -Infinity; let maxY = -Infinity; - let chartWidth = width - MARGIN_LEFT - MARGIN_RIGHT; - let chartHeight = height - MARGIN_TOP - MARGIN_BOTTOM; + const chartWidth = width - MARGIN_LEFT - MARGIN_RIGHT; + const chartHeight = height - MARGIN_TOP - MARGIN_BOTTOM; - for (let key in data) { - let ordered = data[key].points.map(([x, y]) => [x, y]).sort(sortPoints); + for (const key in data) { + const ordered = data[key].points.map(([x, y]) => [x, y]).sort(sortPoints); for (let i = 0; i < ordered.length; i++) { if (ordered[i][0] < minX) { minX = ordered[i][0]; @@ -83,14 +83,14 @@ export default class Chart extends React.Component { } plotting[key] = { data: ordered, index: data[key].index }; } - let timeBuckets = Charting.timeAxisBuckets(minX, maxX); - let valueBuckets = Charting.valueAxisBuckets(maxY || 10); - let groups = []; - for (let key in plotting) { - let color = data[key].color; - let index = data[key].index || 0; - let points = Charting.getDataPoints(chartWidth, chartHeight, timeBuckets, valueBuckets, plotting[key].data); - let path = p.join(' ')).join(' L')} style={{ stroke: color, fill: 'none', strokeWidth: 2 }} />; + const timeBuckets = Charting.timeAxisBuckets(minX, maxX); + const valueBuckets = Charting.valueAxisBuckets(maxY || 10); + const groups = []; + for (const key in plotting) { + const color = data[key].color; + const index = data[key].index || 0; + const points = Charting.getDataPoints(chartWidth, chartHeight, timeBuckets, valueBuckets, plotting[key].data); + const path = p.join(' ')).join(' L')} style={{ stroke: color, fill: 'none', strokeWidth: 2 }} />; groups.push( {path} @@ -106,11 +106,11 @@ export default class Chart extends React.Component { ); } - let labels = valueBuckets.slice(1, valueBuckets.length - 1); - let labelHeights = labels.map((label) => chartHeight * (1 - label / valueBuckets[valueBuckets.length - 1])); - let tickPoints = timeBuckets.map((t) => chartWidth * (t - timeBuckets[0]) / (timeBuckets[timeBuckets.length - 1] - timeBuckets[0])); + const labels = valueBuckets.slice(1, valueBuckets.length - 1); + const labelHeights = labels.map((label) => chartHeight * (1 - label / valueBuckets[valueBuckets.length - 1])); + const tickPoints = timeBuckets.map((t) => chartWidth * (t - timeBuckets[0]) / (timeBuckets[timeBuckets.length - 1] - timeBuckets[0])); let last = null; - let tickLabels = timeBuckets.map((t, i) => { + const tickLabels = timeBuckets.map((t, i) => { let text = ''; if (timeBuckets.length > 20 && i % 2 === 0) { return ''; @@ -128,11 +128,11 @@ export default class Chart extends React.Component { }); let popup = null; if (this.state.hoverValue !== null) { - let style = { + const style = { color: this.state.hoverColor, borderColor: this.state.hoverColor, }; - let classes = [styles.popup]; + const classes = [styles.popup]; if (this.state.hoverPosition.x < 200) { classes.push(styles.popupRight); } else { @@ -182,7 +182,7 @@ Chart.propTypes = { 'The height of the chart.' ), data: PropTypes.object.isRequired.describe( - 'The data to graph. It is a map of data names to objects containing two keys: ' + + 'The data to graph. It is a map of data names to objects containing two keys: ' + '"color," the color to use for the lines, and "points," an array of tuples containing time-value data.' ), formatter: PropTypes.func.describe( diff --git a/src/components/Chart/Shape.react.js b/src/components/Chart/Shape.react.js index 7490470630..233305b6de 100644 --- a/src/components/Chart/Shape.react.js +++ b/src/components/Chart/Shape.react.js @@ -12,8 +12,8 @@ function joinPoints(points) { return points.map((p) => p.join(',')).join(' '); } -let Shape = ({ x, y, fill, index }) => { - let style = { fill: fill, stroke: 'white', strokeWidth: 2 }; +const Shape = ({ x, y, fill, index }) => { + const style = { fill: fill, stroke: 'white', strokeWidth: 2 }; switch (index % 7) { case 0: return ; diff --git a/src/components/Checkbox/Checkbox.react.js b/src/components/Checkbox/Checkbox.react.js index 8ca96fe600..399ce30a75 100644 --- a/src/components/Checkbox/Checkbox.react.js +++ b/src/components/Checkbox/Checkbox.react.js @@ -9,8 +9,8 @@ import Icon from 'components/Icon/Icon.react'; import React from 'react'; import styles from 'components/Checkbox/Checkbox.scss'; -let Checkbox = ({ label, checked, indeterminate, onChange }) => { - let classes = [styles.input]; +const Checkbox = ({ label, checked, indeterminate, onChange }) => { + const classes = [styles.input]; if (checked) { classes.push(styles.checked); } else if (indeterminate) { diff --git a/src/components/Chip/Chip.react.js b/src/components/Chip/Chip.react.js index c737699cf9..e1dc23abaa 100644 --- a/src/components/Chip/Chip.react.js +++ b/src/components/Chip/Chip.react.js @@ -10,25 +10,25 @@ import styles from 'components/Chip/Chip.scss'; import PropTypes from 'lib/PropTypes' import Icon from 'components/Icon/Icon.react' -let Chip = ({ value, onClose }) => ( +const Chip = ({ value, onClose }) => (
{value}
{ - try{ - e.stopPropagation(); - e.nativeEvent.stopPropagation(); - } catch(e){ - console.error(e); - } - - onClose(value); + try{ + e.stopPropagation(); + e.nativeEvent.stopPropagation(); + } catch(e){ + console.error(e); } + + onClose(value); + } }> - + />
diff --git a/src/components/ChromeDatePicker/ChromeDatePicker.react.js b/src/components/ChromeDatePicker/ChromeDatePicker.react.js index a607b2f4b1..dd7244af6e 100644 --- a/src/components/ChromeDatePicker/ChromeDatePicker.react.js +++ b/src/components/ChromeDatePicker/ChromeDatePicker.react.js @@ -34,7 +34,7 @@ export default class ChromeDatePicker extends React.Component { if (this.state.open) { return { open: false }; } - let pos = Position.inWindow(this.wrapRef.current); + const pos = Position.inWindow(this.wrapRef.current); if (this.props.align === Directions.RIGHT) { pos.x += this.wrapRef.current.clientWidth; } @@ -60,7 +60,7 @@ export default class ChromeDatePicker extends React.Component { let popover = null; let content = null; if (this.state.open) { - let classes = [styles.open]; + const classes = [styles.open]; if (this.props.align === Directions.RIGHT) { classes.push(styles.right); } diff --git a/src/components/ChromeDropdown/ChromeDropdown.react.js b/src/components/ChromeDropdown/ChromeDropdown.react.js index d83c8f411f..9786f94ceb 100644 --- a/src/components/ChromeDropdown/ChromeDropdown.react.js +++ b/src/components/ChromeDropdown/ChromeDropdown.react.js @@ -51,8 +51,8 @@ export default class ChromeDropdown extends React.Component { render() { let widthStyle = { width: parseFloat(this.props.width || 140) }; - let styles = this.styles; - let color = this.props.color || 'purple'; + const styles = this.styles; + const color = this.props.color || 'purple'; let label = this.props.value; if (this.keyValueMap) { @@ -69,8 +69,8 @@ export default class ChromeDropdown extends React.Component { ); if (this.state.open) { - let position = Position.inWindow(this.dropdownRef.current); - let measuredWidth = parseFloat(this.dropdownRef.current.offsetWidth); + const position = Position.inWindow(this.dropdownRef.current); + const measuredWidth = parseFloat(this.dropdownRef.current.offsetWidth); widthStyle = { width: measuredWidth }; content = ( this.setState({ open: false })}> diff --git a/src/components/CodeSnippet/CodeSnippet.example.js b/src/components/CodeSnippet/CodeSnippet.example.js index 699be4da7a..1cadfe2c4a 100644 --- a/src/components/CodeSnippet/CodeSnippet.example.js +++ b/src/components/CodeSnippet/CodeSnippet.example.js @@ -13,7 +13,7 @@ export const component = CodeSnippet; export const demos = [ { render() { - let source = `// Some comment here + const source = `// Some comment here Parse.Cloud.define('hello', function(req, resp) { let someVariable = "
"; let otherVariable = "
"; @@ -27,7 +27,7 @@ Parse.Cloud.define('hello', function(req, resp) { { name: 'Print JSON', render() { - let obj = { + const obj = { this: 'is awesome', awesome: true }; diff --git a/src/components/CodeSnippet/CodeSnippet.react.js b/src/components/CodeSnippet/CodeSnippet.react.js index 85b57bbe89..5827e94fab 100644 --- a/src/components/CodeSnippet/CodeSnippet.react.js +++ b/src/components/CodeSnippet/CodeSnippet.react.js @@ -31,12 +31,12 @@ export default class CodeSnippet extends React.Component { } render() { - let { fullPage = true, lineNumbers = true } = this.props; - let classes = ['language-' + this.props.language]; + const { fullPage = true, lineNumbers = true } = this.props; + const classes = ['language-' + this.props.language]; if (lineNumbers) { classes.push('line-numbers'); } - let pageStyle = fullPage ? { minHeight: 'calc(100vh - 96px)'} : {}; + const pageStyle = fullPage ? { minHeight: 'calc(100vh - 96px)'} : {}; return (
         {this.props.source}
diff --git a/src/components/ColumnsConfiguration/ColumnConfigurationItem.react.js b/src/components/ColumnsConfiguration/ColumnConfigurationItem.react.js
index 279beb1926..7cd7426033 100644
--- a/src/components/ColumnsConfiguration/ColumnConfigurationItem.react.js
+++ b/src/components/ColumnsConfiguration/ColumnConfigurationItem.react.js
@@ -9,7 +9,7 @@ const DND_TYPE = 'ColumnConfigurationItem';
 export default ({ name, handleColumnDragDrop, index, onChangeVisible, visible }) => {
   const [ { isDragging}, drag ] = useDrag({
     item: { type: DND_TYPE, index },
-		collect: monitor => ({ isDragging: !!monitor.isDragging() })
+    collect: monitor => ({ isDragging: !!monitor.isDragging() })
   });
 
   const [ { canDrop, isOver }, drop ] = useDrop({
diff --git a/src/components/ColumnsConfiguration/ColumnsConfiguration.react.js b/src/components/ColumnsConfiguration/ColumnsConfiguration.react.js
index 45c9389087..e3bb3a0856 100644
--- a/src/components/ColumnsConfiguration/ColumnsConfiguration.react.js
+++ b/src/components/ColumnsConfiguration/ColumnsConfiguration.react.js
@@ -38,7 +38,7 @@ export default class ColumnsConfiguration extends React.Component {
 
   showAll() {
     let shouldReload = false;
-    let updatedOrder = this.props.order.map(field => {
+    const updatedOrder = this.props.order.map(field => {
       if (!shouldReload && !field.cached) {
         shouldReload = true;
       }
diff --git a/src/components/ContextMenu/ContextMenu.react.js b/src/components/ContextMenu/ContextMenu.react.js
index 611e1e0a99..f68aad8d8d 100644
--- a/src/components/ContextMenu/ContextMenu.react.js
+++ b/src/components/ContextMenu/ContextMenu.react.js
@@ -54,37 +54,37 @@ const MenuSection = ({ level, items, path, setPath, hide }) => {
     {items.map((item, index) => {
       if (item.items) {
         return (
-            
  • { - const newPath = path.slice(0, level + 1); - newPath.push(index); - setPath(newPath); - }} - > - {item.text} -
  • - ); - } - return (
  • { - item.callback && item.callback(); - hide(); + className={styles.item} + onMouseEnter={() => { + const newPath = path.slice(0, level + 1); + newPath.push(index); + setPath(newPath); }} > {item.text} - {item.subtext && - {item.subtext}}
  • ); + } + return ( +
  • { + item.callback && item.callback(); + hide(); + }} + > + {item.text} + {item.subtext && - {item.subtext}} +
  • + ); })} ); } -let ContextMenu = ({ x, y, items }) => { +const ContextMenu = ({ x, y, items }) => { const [path, setPath] = useState([0]); const [visible, setVisible] = useState(true); diff --git a/src/components/CreditCardInput/CreditCardInput.react.js b/src/components/CreditCardInput/CreditCardInput.react.js index c9eeb524cb..532fb8908c 100644 --- a/src/components/CreditCardInput/CreditCardInput.react.js +++ b/src/components/CreditCardInput/CreditCardInput.react.js @@ -44,7 +44,7 @@ class CreditCardInput extends React.Component { } }} onChange={e => { - let newValue = e.target.value; + const newValue = e.target.value; if (VALID_REGEX.test(newValue)) { onChange(newValue.replace(/\s/g, '')); this.setState({cursorPosition: e.target.selectionStart}); diff --git a/src/components/DataBrowserHeader/DataBrowserHeader.example.js b/src/components/DataBrowserHeader/DataBrowserHeader.example.js index 83d9e2a05c..df2360bb33 100644 --- a/src/components/DataBrowserHeader/DataBrowserHeader.example.js +++ b/src/components/DataBrowserHeader/DataBrowserHeader.example.js @@ -12,7 +12,7 @@ import { DndProvider } from 'react-dnd' export const component = DataBrowserHeader; -let lightBg = { background: 'rgba(224,224,234,0.10)' }; +const lightBg = { background: 'rgba(224,224,234,0.10)' }; class HeadersDemo extends React.Component { render() { diff --git a/src/components/DataBrowserHeader/DataBrowserHeader.react.js b/src/components/DataBrowserHeader/DataBrowserHeader.react.js index 2e17b297d5..92e0bd7317 100644 --- a/src/components/DataBrowserHeader/DataBrowserHeader.react.js +++ b/src/components/DataBrowserHeader/DataBrowserHeader.react.js @@ -54,8 +54,8 @@ const dataBrowserHeaderSource = { })) class DataBrowserHeader extends React.Component { render() { - let { connectDragSource, connectDropTarget, name, type, targetClass, order, style, isDragging, isOver } = this.props; - let classes = [styles.header, baseStyles.unselectable]; + const { connectDragSource, connectDropTarget, name, type, targetClass, order, style, isDragging, isOver } = this.props; + const classes = [styles.header, baseStyles.unselectable]; if (order) { classes.push(styles[order]); } diff --git a/src/components/DataBrowserHeaderBar/DataBrowserHeaderBar.react.js b/src/components/DataBrowserHeaderBar/DataBrowserHeaderBar.react.js index d021924386..15ebbe2dcc 100644 --- a/src/components/DataBrowserHeaderBar/DataBrowserHeaderBar.react.js +++ b/src/components/DataBrowserHeaderBar/DataBrowserHeaderBar.react.js @@ -14,22 +14,22 @@ import { DndProvider } from 'react-dnd' export default class DataBrowserHeaderBar extends React.Component { render() { - let { headers, onResize, selectAll, onAddColumn, updateOrdering, readonly, preventSchemaEdits, selected, isDataLoaded } = this.props; - let elements = [ + const { headers, onResize, selectAll, onAddColumn, updateOrdering, readonly, preventSchemaEdits, selected, isDataLoaded } = this.props; + const elements = [
    {readonly ? null : selectAll(e.target.checked)} /> + type='checkbox' + checked={selected} + onChange={(e) => selectAll(e.target.checked)} /> }
    ]; headers.forEach(({ width, name, type, targetClass, order, visible, preventSort }, i) => { if (!visible) return; - let wrapStyle = { width }; + const wrapStyle = { width }; if (i % 2) { wrapStyle.background = '#726F85'; } else { @@ -66,7 +66,7 @@ export default class DataBrowserHeaderBar extends React.Component { }); if (onAddColumn) { - let finalStyle = {}; + const finalStyle = {}; if (headers.length % 2) { finalStyle.background = 'rgba(224,224,234,0.10)'; } diff --git a/src/components/DatePicker/DatePicker.react.js b/src/components/DatePicker/DatePicker.react.js index 6ae363adf9..341e4b160b 100644 --- a/src/components/DatePicker/DatePicker.react.js +++ b/src/components/DatePicker/DatePicker.react.js @@ -45,7 +45,7 @@ export default class DatePicker extends React.Component { render() { let popover = null; if (this.state.open) { - let width = this.inputRef.current.clientWidth; + const width = this.inputRef.current.clientWidth; popover = ( @@ -69,7 +69,7 @@ export default class DatePicker extends React.Component {
    ); } - + return (
    {content} diff --git a/src/components/DateRange/DateRange.react.js b/src/components/DateRange/DateRange.react.js index 555b7eb6c8..0920025a86 100644 --- a/src/components/DateRange/DateRange.react.js +++ b/src/components/DateRange/DateRange.react.js @@ -23,7 +23,7 @@ export default class DateRange extends React.Component { constructor(props) { super(); - let val = props.value || {}; + const val = props.value || {}; this.state = { open: false, @@ -40,7 +40,7 @@ export default class DateRange extends React.Component { if (this.state.open) { return { open: false }; } - let pos = Position.inWindow(this.wrapRef.current); + const pos = Position.inWindow(this.wrapRef.current); if (this.props.align === Directions.RIGHT) { pos.x += this.wrapRef.current.clientWidth; } @@ -84,11 +84,11 @@ export default class DateRange extends React.Component { let popover = null; let content = null; if (this.state.open) { - let classes = [styles.open]; + const classes = [styles.open]; if (this.props.align === Directions.RIGHT) { classes.push(styles.right); } - let renderShade = ( + const renderShade = ( this.state.start.getFullYear() < this.state.end.getFullYear() || this.state.start.getMonth() !== this.state.end.getMonth() ); diff --git a/src/components/DateTimeEditor/DateTimeEditor.react.js b/src/components/DateTimeEditor/DateTimeEditor.react.js index f2af5dc61c..a67f2bea79 100644 --- a/src/components/DateTimeEditor/DateTimeEditor.react.js +++ b/src/components/DateTimeEditor/DateTimeEditor.react.js @@ -66,14 +66,14 @@ export default class DateTimeEditor extends React.Component { if (this.state.text === this.props.value.toISOString()) { return; } - let date = new Date(this.state.text); + const date = new Date(this.state.text); if (isNaN(date.getTime())) { this.setState({ value: this.props.value, text: this.props.value.toISOString() }); } else { if (this.state.text.endsWith('Z')) { this.setState({ value: date }); } else { - let utc = new Date(Date.UTC( + const utc = new Date(Date.UTC( date.getFullYear(), date.getMonth(), date.getDate(), diff --git a/src/components/DateTimeEntry/DateTimeEntry.react.js b/src/components/DateTimeEntry/DateTimeEntry.react.js index 2da49d5f62..dd89ded159 100644 --- a/src/components/DateTimeEntry/DateTimeEntry.react.js +++ b/src/components/DateTimeEntry/DateTimeEntry.react.js @@ -39,10 +39,10 @@ export default class DateTimeEntry extends React.Component { } open() { - let node = this.rootRef.current; - let pos = Position.inDocument(node); + const node = this.rootRef.current; + const pos = Position.inDocument(node); pos.y += node.clientHeight; - let height = 230 + node.clientWidth * 0.14; + const height = 230 + node.clientWidth * 0.14; if (window.innerHeight - pos.y - height < 40) { pos.y = window.innerHeight - height - 40; } @@ -67,11 +67,11 @@ export default class DateTimeEntry extends React.Component { if (this.state.value === this.props.value.toISOString()) { return; } - let date = new Date(this.state.value); + const date = new Date(this.state.value); if (isNaN(date.getTime())) { this.setState({ value: this.props.value.toISOString() }); } else if (!this.state.value.toLowerCase().endsWith('z')) { - let utc = new Date(Date.UTC( + const utc = new Date(Date.UTC( date.getFullYear(), date.getMonth(), date.getDate(), @@ -103,7 +103,7 @@ export default class DateTimeEntry extends React.Component { ); } - + return (
    ); } - + return (
    {content} diff --git a/src/components/DateTimePicker/DateTimePicker.react.js b/src/components/DateTimePicker/DateTimePicker.react.js index a4fdabe5b2..f3cfaa0ccb 100644 --- a/src/components/DateTimePicker/DateTimePicker.react.js +++ b/src/components/DateTimePicker/DateTimePicker.react.js @@ -15,7 +15,7 @@ import styles from 'components/DateTimePicker/Date export default class DateTimePicker extends React.Component { constructor(props) { super(); - let timeRef = props.value || hoursFrom(new Date(), 1); + const timeRef = props.value || hoursFrom(new Date(), 1); this.state = { hours: String(timeRef[getDateMethod(props.local, 'getHours')]()), minutes: (timeRef[getDateMethod(props.local, 'getMinutes')]() < 10 ? '0' : '') + String(timeRef[getDateMethod(props.local, 'getMinutes')]()), @@ -23,7 +23,7 @@ export default class DateTimePicker extends React.Component { } componentWillReceiveProps(props) { - let timeRef = props.value || hoursFrom(new Date(), 1); + const timeRef = props.value || hoursFrom(new Date(), 1); this.setState({ hours: String(timeRef[getDateMethod(props.local, 'getHours')]()), minutes: (timeRef[getDateMethod(props.local, 'getMinutes')]() < 10 ? '0' : '') + String(timeRef[getDateMethod(props.local, 'getMinutes')]()), @@ -31,7 +31,7 @@ export default class DateTimePicker extends React.Component { } changeHours(e) { - let hoursString = e.target.value; + const hoursString = e.target.value; if (hoursString === '') { return this.setState({ hours: '' }); } @@ -49,7 +49,7 @@ export default class DateTimePicker extends React.Component { } changeMinutes(e) { - let minutesString = e.target.value; + const minutesString = e.target.value; if (minutesString === '') { return this.setState({ minutes: '' }); } @@ -67,21 +67,21 @@ export default class DateTimePicker extends React.Component { } commitTime() { - let dateRef = this.props.value || new Date(); - let newDate = this.props.local ? new Date( + const dateRef = this.props.value || new Date(); + const newDate = this.props.local ? new Date( dateRef.getFullYear(), dateRef.getMonth(), dateRef.getDate(), parseInt(this.state.hours, 10), parseInt(this.state.minutes, 10) ) : - new Date(Date.UTC( - dateRef.getUTCFullYear(), - dateRef.getUTCMonth(), - dateRef.getUTCDate(), - parseInt(this.state.hours, 10), - parseInt(this.state.minutes, 10) - )); + new Date(Date.UTC( + dateRef.getUTCFullYear(), + dateRef.getUTCMonth(), + dateRef.getUTCDate(), + parseInt(this.state.hours, 10), + parseInt(this.state.minutes, 10) + )); this.props.onChange(newDate); if (this.props.close) { this.props.close(); @@ -92,21 +92,21 @@ export default class DateTimePicker extends React.Component { return (
    e.stopPropagation()} > { - let timeRef = this.props.value || hoursFrom(new Date(), 1); - let newDate = this.props.local ? new Date( + const timeRef = this.props.value || hoursFrom(new Date(), 1); + const newDate = this.props.local ? new Date( newValue.getFullYear(), newValue.getMonth(), newValue.getDate(), timeRef.getHours(), timeRef.getMinutes() ) : - new Date(Date.UTC( - newValue.getUTCFullYear(), - newValue.getUTCMonth(), - newValue.getUTCDate(), - timeRef.getUTCHours(), - timeRef.getUTCMinutes() - )); + new Date(Date.UTC( + newValue.getUTCFullYear(), + newValue.getUTCMonth(), + newValue.getUTCDate(), + timeRef.getUTCHours(), + timeRef.getUTCMinutes() + )); this.props.onChange(newDate); }} />
    diff --git a/src/components/DonutChart/DonutChart.example.js b/src/components/DonutChart/DonutChart.example.js index 3f2e2ea9ea..f8f31f73a4 100644 --- a/src/components/DonutChart/DonutChart.example.js +++ b/src/components/DonutChart/DonutChart.example.js @@ -24,7 +24,7 @@ export const demos = [ label='Installations' /> ) }, { - name: 'Progress Bar with DonutChart', + name: 'Progress Bar with DonutChart', render: () => ( { - let centerX = diameter / 2; - let centerY = centerX; - let radius = centerX * 0.9; +const DonutChart = ({ segments = [], diameter = 200, label = '', isMonochrome = false, printPercentage = false }) => { + const centerX = diameter / 2; + const centerY = centerX; + const radius = centerX * 0.9; let lastX = centerX; let lastY = centerY - radius; @@ -36,9 +36,9 @@ let DonutChart = ({ segments=[], diameter=200, label='', isMonochrome=false, pri sum += segments[i]; } - let paths = []; + const paths = []; for (let i = 0; i < segments.length; ++i) { - let arc = segments[i] / sum * 2 * Math.PI; + const arc = segments[i] / sum * 2 * Math.PI; let angle = alpha - Math.min(arc, Math.PI); let endX = radius * Math.cos(angle) + centerX; let endY = -radius * Math.sin(angle) + centerY; diff --git a/src/components/DragHandle/DragHandle.example.js b/src/components/DragHandle/DragHandle.example.js index cb0571f2b6..16cb4af9c7 100644 --- a/src/components/DragHandle/DragHandle.example.js +++ b/src/components/DragHandle/DragHandle.example.js @@ -22,14 +22,14 @@ class DragDemo extends React.Component { handleDrag(dx, dy) { this.setState(({ x, y }) => { - let newX = Math.max(0, Math.min(x + dx, 480)); - let newY = Math.max(0, Math.min(y + dy, 480)); + const newX = Math.max(0, Math.min(x + dx, 480)); + const newY = Math.max(0, Math.min(y + dy, 480)); return { x: newX, y: newY }; }); } render() { - let style = { + const style = { width: 20, height: 20, background: '#5298fc', @@ -53,8 +53,8 @@ class DragDemo extends React.Component { } } -let lightBg = { background: 'rgba(224,224,234,0.10)' }; -let handleStyle = { +const lightBg = { background: 'rgba(224,224,234,0.10)' }; +const handleStyle = { position: 'relative', display: 'inline-block', width: 4, diff --git a/src/components/Dropdown/Dropdown.react.js b/src/components/Dropdown/Dropdown.react.js index 3f444767f9..daa59fed04 100644 --- a/src/components/Dropdown/Dropdown.react.js +++ b/src/components/Dropdown/Dropdown.react.js @@ -60,8 +60,8 @@ export default class Dropdown extends React.Component { render() { let popover = null; if (this.state.open && !this.props.disabled) { - let width = this.dropdownRef.current.clientWidth; - let popoverChildren = ( + const width = this.dropdownRef.current.clientWidth; + const popoverChildren = (
    {React.Children.map(this.props.children, c => ( @@ -95,7 +95,7 @@ export default class Dropdown extends React.Component { float: 'left' }; } - let dropdownClasses = [styles.dropdown]; + const dropdownClasses = [styles.dropdown]; if (this.props.disabled) { dropdownClasses.push(styles.disabled); } diff --git a/src/components/Dropdown/Option.react.js b/src/components/Dropdown/Option.react.js index d9726537d2..4995b2d4d5 100644 --- a/src/components/Dropdown/Option.react.js +++ b/src/components/Dropdown/Option.react.js @@ -8,6 +8,6 @@ import React from 'react'; import styles from 'components/Dropdown/Dropdown.scss'; -let Option = props =>
    ; +const Option = props =>
    ; export default Option; diff --git a/src/components/EmptyState/EmptyState.react.js b/src/components/EmptyState/EmptyState.react.js index 22be2eb529..a97686ea2d 100644 --- a/src/components/EmptyState/EmptyState.react.js +++ b/src/components/EmptyState/EmptyState.react.js @@ -13,7 +13,7 @@ import styles from 'components/EmptyState/EmptyState.scss'; import stylesButton from 'components/Button/Button.scss'; import baseStyles from 'stylesheets/base.scss'; -let ctaButton = (cta, action) => { +const ctaButton = (cta, action) => { if (cta) { if (action.constructor === String) { return ( @@ -23,11 +23,11 @@ let ctaButton = (cta, action) => { ); } else { return ( -
    ); -let { ...otherPropTypes } = Button.propTypes; +const { ...otherPropTypes } = Button.propTypes; FormButton.propTypes = otherPropTypes; export default FormButton; diff --git a/src/components/FormModal/FormModal.react.js b/src/components/FormModal/FormModal.react.js index eb375e6545..cc05ce0676 100644 --- a/src/components/FormModal/FormModal.react.js +++ b/src/components/FormModal/FormModal.react.js @@ -20,7 +20,7 @@ export default class FormModal extends React.Component { } render() { - let { + const { children, open, submitText = 'Confirm', @@ -33,7 +33,7 @@ export default class FormModal extends React.Component { showErrors = true, ...modalProps } = this.props; - let showModal = open || this.state.inProgress; + const showModal = open || this.state.inProgress; if (!modalProps.type) { if (this.state.errorMessage.length > 0) { modalProps.type = Modal.Types.DANGER; @@ -81,7 +81,7 @@ export default class FormModal extends React.Component { } } -let { ...forwardedModalProps} = Modal.propTypes; +const { ...forwardedModalProps} = Modal.propTypes; FormModal.propTypes = { ...forwardedModalProps, children: PropTypes.node.describe('The form elements to be rendered in the modal.'), diff --git a/src/components/FormNote/FormNote.react.js b/src/components/FormNote/FormNote.react.js index d1c2879a74..3c19b5dea5 100644 --- a/src/components/FormNote/FormNote.react.js +++ b/src/components/FormNote/FormNote.react.js @@ -11,7 +11,7 @@ import React from 'react'; import SliderWrap from 'components/SliderWrap/SliderWrap.react'; import styles from 'components/FormNote/FormNote.scss'; -let FormNote = ({ show, children, color, ...other }) => ( +const FormNote = ({ show, children, color, ...other }) => (
    {children}
    diff --git a/src/components/FormTable/FormTable.react.js b/src/components/FormTable/FormTable.react.js index 35cf9cf6d5..a4803137b3 100644 --- a/src/components/FormTable/FormTable.react.js +++ b/src/components/FormTable/FormTable.react.js @@ -9,7 +9,7 @@ import PropTypes from 'lib/PropTypes'; import React from 'react'; import styles from 'components/FormTable/FormTable.scss'; -let Row = ({ +const Row = ({ title, notes = [], color = 'blue', @@ -33,7 +33,7 @@ let Row = ({ ); }; -let FormTable = ({ items, keyWidth = '70px' }) => ( +const FormTable = ({ items, keyWidth = '70px' }) => (
    {items.map((item, index) => )}
    diff --git a/src/components/GeoPointEditor/GeoPointEditor.react.js b/src/components/GeoPointEditor/GeoPointEditor.react.js index f29e1713b1..cc62f2f1f5 100644 --- a/src/components/GeoPointEditor/GeoPointEditor.react.js +++ b/src/components/GeoPointEditor/GeoPointEditor.react.js @@ -102,8 +102,8 @@ export default class GeoPointEditor extends React.Component { } render() { - let onChange = (target, e) => { - let value = e.target.value; + const onChange = (target, e) => { + const value = e.target.value; if (!validateNumeric(value)) { const regex = /[[("' ]?(?[0-9.]+)["' ]?,["' ]?(?[0-9.]+)["' )\]]?/; diff --git a/src/components/GeoPointInput/GeoPointInput.react.js b/src/components/GeoPointInput/GeoPointInput.react.js index c80484519b..8b9a6a146e 100644 --- a/src/components/GeoPointInput/GeoPointInput.react.js +++ b/src/components/GeoPointInput/GeoPointInput.react.js @@ -32,7 +32,7 @@ export default class GeoPointInput extends React.Component { } render() { - let value = this.props.value || { latitude: '0.0', longitude: '0.0' }; + const value = this.props.value || { latitude: '0.0', longitude: '0.0' }; return (
    diff --git a/src/components/Icon/Icon.react.js b/src/components/Icon/Icon.react.js index e32e65eabb..510b8b24a3 100644 --- a/src/components/Icon/Icon.react.js +++ b/src/components/Icon/Icon.react.js @@ -8,8 +8,8 @@ import PropTypes from 'lib/PropTypes'; import React from 'react'; -let Icon = ({ name, fill, width, height }) => { - let props = { +const Icon = ({ name, fill, width, height }) => { + const props = { width: width, height: height }; diff --git a/src/components/IntervalInput/IntervalInput.react.js b/src/components/IntervalInput/IntervalInput.react.js index 97afccbe7b..93159bd67b 100644 --- a/src/components/IntervalInput/IntervalInput.react.js +++ b/src/components/IntervalInput/IntervalInput.react.js @@ -10,15 +10,15 @@ import Option from 'components/Dropdown/Option.react'; import PropTypes from 'lib/PropTypes'; import React from 'react'; -let IntervalInput = ({ count, unit, onChange }) => { - let counts = []; - let max = (unit === 'hour') ? 23 : 59; +const IntervalInput = ({ count, unit, onChange }) => { + const counts = []; + const max = (unit === 'hour') ? 23 : 59; for (let i = 1; i <= max; i++) { - counts.push(); + counts.push(); } - let countChange = (newCount) => onChange(parseInt(newCount, 10), unit); - let unitChange = (newUnit) => { + const countChange = (newCount) => onChange(parseInt(newCount, 10), unit); + const unitChange = (newUnit) => { if (newUnit === 'minute') { return onChange(count, newUnit); } else { diff --git a/src/components/JsonPrinter/JsonPrinter.example.js b/src/components/JsonPrinter/JsonPrinter.example.js index 449ad2978d..0443d16606 100644 --- a/src/components/JsonPrinter/JsonPrinter.example.js +++ b/src/components/JsonPrinter/JsonPrinter.example.js @@ -11,7 +11,7 @@ import React from 'react'; export const component = JsonPrinter; -let json = { +const json = { results: [ { name: 'Apples', diff --git a/src/components/JsonPrinter/JsonPrinter.react.js b/src/components/JsonPrinter/JsonPrinter.react.js index fddf5a75c3..23f036ddd7 100644 --- a/src/components/JsonPrinter/JsonPrinter.react.js +++ b/src/components/JsonPrinter/JsonPrinter.react.js @@ -9,7 +9,7 @@ import CodeSnippet from 'components/CodeSnippet/CodeSnippet.react'; import PropTypes from 'lib/PropTypes'; import React from 'react'; -let JsonPrinter = ({ object }) => ( +const JsonPrinter = ({ object }) => ( { - let padding = (props.padding || 20) + 'px'; +const Label = (props) => { + const padding = (props.padding || 20) + 'px'; return (
    Promise.resolve(Math.random())} - render={num => {num}} - refreshIntervalMillis={100} - initialData={0}/>, + source={() => Promise.resolve(Math.random())} + render={num => {num}} + refreshIntervalMillis={100} + initialData={0}/>, }, - ]; +]; diff --git a/src/components/LiveReload/LiveReload.react.js b/src/components/LiveReload/LiveReload.react.js index 2497760ac3..ae3f2d5b01 100644 --- a/src/components/LiveReload/LiveReload.react.js +++ b/src/components/LiveReload/LiveReload.react.js @@ -16,66 +16,66 @@ export default class LiveReload extends React.Component { this.timer = null; this.refreshIntervalMillis = props.refreshIntervalMillis || 1000; this.state = { - currentData: props.initialData, - }; + currentData: props.initialData, + }; } fetchNewData() { - clearTimeout(this.timer); - let promise = null; - let xhr = null; - if (typeof(this.props.source) === 'function') { - let obj = this.props.source(); - if (obj.promise && obj.xhr) { - promise = obj.promise; - xhr = obj.xhr; - } else { - promise = obj; - } - } else { - let obj = abortableGet(this.props.source); - promise = obj.promise; - xhr = obj.xhr; - } - this.abortXHR = () => { - if (xhr) { - xhr.abort(); - } - clearTimeout(this.timer); - } - promise.then(data => { - this.setState({currentData: data}); - }).finally(() => { - if (this.shouldContinueReloading) { - this.timer = setTimeout(this.fetchNewData.bind(this), this.refreshIntervalMillis); - } - }); - return promise; - } + clearTimeout(this.timer); + let promise = null; + let xhr = null; + if (typeof(this.props.source) === 'function') { + const obj = this.props.source(); + if (obj.promise && obj.xhr) { + promise = obj.promise; + xhr = obj.xhr; + } else { + promise = obj; + } + } else { + const obj = abortableGet(this.props.source); + promise = obj.promise; + xhr = obj.xhr; + } + this.abortXHR = () => { + if (xhr) { + xhr.abort(); + } + clearTimeout(this.timer); + } + promise.then(data => { + this.setState({currentData: data}); + }).finally(() => { + if (this.shouldContinueReloading) { + this.timer = setTimeout(this.fetchNewData.bind(this), this.refreshIntervalMillis); + } + }); + return promise; + } componentWillMount() { - this.shouldContinueReloading = true; - if (!this.state.currentData) { - this.fetchNewData(); - } else { - this.timer = setTimeout(this.fetchNewData.bind(this), this.refreshIntervalMillis); - } - } + this.shouldContinueReloading = true; + if (!this.state.currentData) { + this.fetchNewData(); + } else { + this.timer = setTimeout(this.fetchNewData.bind(this), this.refreshIntervalMillis); + } + } - componentWillUnmount() { - this.abortXHR(); - this.shouldContinueReloading = false; - clearTimeout(this.timer); - } + componentWillUnmount() { + this.abortXHR(); + this.shouldContinueReloading = false; + clearTimeout(this.timer); + } render() { - return this.props.render(this.state.currentData); + return this.props.render(this.state.currentData); } } LiveReload.propTypes = { - refreshIntervalMillis: PropTypes.number.describe('How often to refresh the data, in milliseconds. Defaults to 1s.'), - source: PropTypes.oneOfType([PropTypes.string, PropTypes.func]).isRequired.describe('Either a URL to fetch updates from, or a function that returns a promise that fetches update, or a function that returns { promise, xhr }.'), - render: PropTypes.func.isRequired.describe('Receives the data from the URL or promise and returns the component to be rendered.'), - initialData: PropTypes.any.describe('Initial data to seed the component before any request has been made. If this is not passed, then your render function must be prepared to handle being called with "undefined" instead of data. Passing this will also cause the first load to happen after refreshIntervalMillis, while not passing it will cause it the first load to happen immediately.'), + refreshIntervalMillis: PropTypes.number.describe('How often to refresh the data, in milliseconds. Defaults to 1s.'), + source: PropTypes.oneOfType([PropTypes.string, PropTypes.func]).isRequired.describe('Either a URL to fetch updates from, or a function that returns a promise that fetches update, or a function that returns { promise, xhr }.'), + render: PropTypes.func.isRequired.describe('Receives the data from the URL or promise and returns the component to be rendered.'), + initialData: PropTypes.any.describe('Initial data to seed the component before any request has been made. If this is not passed, then your render function must be prepared to handle being called with "undefined" instead of data. Passing this will also cause the first load to happen after refreshIntervalMillis, while not passing it will cause it the first load to happen immediately.'), } diff --git a/src/components/Loader/Loader.react.js b/src/components/Loader/Loader.react.js index 277972f68f..7907d31ca7 100644 --- a/src/components/Loader/Loader.react.js +++ b/src/components/Loader/Loader.react.js @@ -26,7 +26,7 @@ function getRadius(t) { function getPosition(t) { if (t < POINTS.A) { - let multiplier = LENGTH / SMALL_RADIUS; + const multiplier = LENGTH / SMALL_RADIUS; return { x: SMALL_RADIUS + SMALL_RADIUS * Math.cos(t * multiplier + Math.PI / 2), y: 2 * LARGE_RADIUS + SMALL_RADIUS - SMALL_RADIUS * Math.sin(t * multiplier + Math.PI / 2) @@ -37,8 +37,8 @@ function getPosition(t) { y: LENGTH * (POINTS.A - t) + 2 * LARGE_RADIUS + SMALL_RADIUS }; } else if (t < POINTS.C) { - let t2 = t - POINTS.B; - let multiplier = LENGTH / LARGE_RADIUS; + const t2 = t - POINTS.B; + const multiplier = LENGTH / LARGE_RADIUS; return { x: 2 * SMALL_RADIUS + LARGE_RADIUS - LARGE_RADIUS * Math.cos(t2 * multiplier), y: LARGE_RADIUS - LARGE_RADIUS * Math.sin(t2 * multiplier) @@ -73,7 +73,7 @@ export default class Loader extends React.Component { if (!this.mounted) { return; } - let delta = new Date() - this.mountTime; + const delta = new Date() - this.mountTime; let t = (delta / DURATION) % 1; let pos = getPosition(t); let style = this.dot0Ref.current.style; diff --git a/src/components/LoaderContainer/LoaderContainer.example.js b/src/components/LoaderContainer/LoaderContainer.example.js index 2d1a111855..013902b781 100644 --- a/src/components/LoaderContainer/LoaderContainer.example.js +++ b/src/components/LoaderContainer/LoaderContainer.example.js @@ -28,7 +28,7 @@ class PushAudiencesSelectorDemo extends React.Component { } } -let mockData = [ +const mockData = [ { objectId: '1', name: 'Everyone', @@ -41,13 +41,13 @@ let mockData = [ count: 148, createdAt: new Date(1444757195683) }, - { + { objectId: '3', name: 'Completed Checkout <30 days', count: 148, createdAt: new Date(1444757195683) }, - { + { objectId: '4', name: 'New Users', count: 148, diff --git a/src/components/LogView/LogView.example.js b/src/components/LogView/LogView.example.js index 8125b57835..17fc2362b5 100644 --- a/src/components/LogView/LogView.example.js +++ b/src/components/LogView/LogView.example.js @@ -14,7 +14,7 @@ export const component = LogView; export const demos = [ { render() { - let text1 = `I2015-09-30T00:25:26.950Z]Deployed v1 with triggers: + const text1 = `I2015-09-30T00:25:26.950Z]Deployed v1 with triggers: Item: before_save after_save @@ -26,11 +26,11 @@ export const demos = [ anotherFunction WillError`; - let text2 = `I2015-09-30T00:35:42.336Z]v2 before_save triggered for Item: + const text2 = `I2015-09-30T00:35:42.336Z]v2 before_save triggered for Item: Input: {"original":null,"update":{"name":"i"}} Result: Update changed to {"name":"i","count":12}`; - let text3 = `I2015-10-06T22:39:11.029Z]v4 Ran cloud function doSomething with: + const text3 = `I2015-10-06T22:39:11.029Z]v4 Ran cloud function doSomething with: Input: {} Result: {}`; diff --git a/src/components/LogView/LogView.react.js b/src/components/LogView/LogView.react.js index f50a9cbc69..86727be183 100644 --- a/src/components/LogView/LogView.react.js +++ b/src/components/LogView/LogView.react.js @@ -8,7 +8,7 @@ import React from 'react'; import styles from 'components/LogView/LogView.scss'; -let LogView = (props) => { +const LogView = (props) => { return (
      {props.children} diff --git a/src/components/LogView/LogViewEntry.react.js b/src/components/LogView/LogViewEntry.react.js index c434f2ec84..3a8980f228 100644 --- a/src/components/LogView/LogViewEntry.react.js +++ b/src/components/LogView/LogViewEntry.react.js @@ -20,11 +20,11 @@ const TIMESTAMP_REGEX = [ '(\\])' // Any Single Character 2 ].join(''); -let isError = (str) => str[0] === 'E'; +const isError = (str) => str[0] === 'E'; -let getLogEntryInfo = (str) => { - let re = getTimestampRegex(); - let timeStampStr = str.match(re) ? str.match(re)[0] : ''; +const getLogEntryInfo = (str) => { + const re = getTimestampRegex(); + const timeStampStr = str.match(re) ? str.match(re)[0] : ''; return { time: timeStampStr, content: str.replace(timeStampStr,''), @@ -33,14 +33,14 @@ let getLogEntryInfo = (str) => { } //example timestamp: 'I2015-09-30T00:36:45.522Z]' -let getTimestampRegex = () => new RegExp(TIMESTAMP_REGEX,['i']); +const getTimestampRegex = () => new RegExp(TIMESTAMP_REGEX,['i']); -let LogViewEntry = ({ +const LogViewEntry = ({ text = '', timestamp, }) => { - let logEntryInfo = getLogEntryInfo(text); - let classes = [styles.entry, logEntryInfo.error ? styles.error: '']; + const logEntryInfo = getLogEntryInfo(text); + const classes = [styles.entry, logEntryInfo.error ? styles.error : '']; return (
    1. {/* handle the timestamp format used by both Parse Server and Parse.com */} diff --git a/src/components/LoginRow/LoginRow.react.js b/src/components/LoginRow/LoginRow.react.js index 69215b29d1..355d1f4c74 100644 --- a/src/components/LoginRow/LoginRow.react.js +++ b/src/components/LoginRow/LoginRow.react.js @@ -8,7 +8,7 @@ import React from 'react'; import styles from 'components/LoginRow/LoginRow.scss'; -let LoginRow = ({ label, input, extra }) => ( +const LoginRow = ({ label, input, extra }) => (
    }> + Disable legacy session tokens to make your app more secure. If enabled, all requests with legacy tokens will error. Learn more} + />} + input={} + /> + We’ll automatically delete revocable sessions that have not made an API request in the last year.} + />} + input={} + /> + When a user changes or resets their password, we’ll
    automatically delete all Session objects associated with this user.} + />} + input={} + /> + - let userAuthenticationFields =
    - } - input={} - /> - } - input={} - /> - } - input={} - /> -
    + const userAuthenticationFields =
    + } + input={} + /> + } + input={} + /> + } + input={} + /> +
    - let socialLoginFields =
    - } - input={ { - setField('allowFacebookAuthentication', enabled); - if (!enabled) { - setField('facebookAppID', ''); - setField('facebookAppSecret', ''); - } - }} - value={fields.allowFacebookAuthentication} - />} - /> - {fields.allowFacebookAuthentication ? } - input={[ - , - , - ]} - /> : null} - {fields.facebookAppIDList.length > 0 ? } - input={ ({ - title: 'App #' + (index + 1).toString(), - color: 'green', - onDelete: () => { - let newFacebookAppIDList = fields.facebookAppIDList.slice(); - newFacebookAppIDList.splice(index, 1); + const socialLoginFields =
    + } + input={ { + setField('allowFacebookAuthentication', enabled); + if (!enabled) { + setField('facebookAppID', ''); + setField('facebookAppSecret', ''); + } + }} + value={fields.allowFacebookAuthentication} + />} + /> + {fields.allowFacebookAuthentication ? } + input={[ + , + , + ]} + /> : null} + {fields.facebookAppIDList.length > 0 ? } + input={ ({ + title: 'App #' + (index + 1).toString(), + color: 'green', + onDelete: () => { + const newFacebookAppIDList = fields.facebookAppIDList.slice(); + newFacebookAppIDList.splice(index, 1); - let newFacebookAppSecretList = fields.facebookAppSecretList.slice(); - newFacebookAppSecretList.splice(index, 1); + const newFacebookAppSecretList = fields.facebookAppSecretList.slice(); + newFacebookAppSecretList.splice(index, 1); - //TODO(drewgross): handle errors, display progress, etc. - this.context.setConnectedFacebookApps(newFacebookAppIDList, newFacebookAppSecretList).then(() => { - this.forceUpdate(); - }); - }, - notes: [ - { - key: 'App ID', - value: fields.facebookAppIDList[index], - }, - { - key: 'App Secret', - value: fields.facebookAppSecretList[index], - } - ], - }))} - />} - /> : null} - } - input={ { - setField('allowTwitterAuthentication', enabled); - if (!enabled) { - setField('twitterConsumerKey', ''); - } - }} - value={fields.allowTwitterAuthentication} - />} /> - {fields.allowTwitterAuthentication ? } - input={ - }/> : null} - {fields.twitterConsumerKeysList.length > 0 ? } - input={ ({ - title: 'App #' + (index + 1).toString(), - color: 'green', - onDelete: () => { - let twitterConsumerKeyList = fields.twitterConsumerKeysList.slice(); - twitterConsumerKeyList.splice(index, 1); + //TODO(drewgross): handle errors, display progress, etc. + this.context.setConnectedFacebookApps(newFacebookAppIDList, newFacebookAppSecretList).then(() => { + this.forceUpdate(); + }); + }, + notes: [ + { + key: 'App ID', + value: fields.facebookAppIDList[index], + }, + { + key: 'App Secret', + value: fields.facebookAppSecretList[index], + } + ], + }))} + />} + /> : null} + } + input={ { + setField('allowTwitterAuthentication', enabled); + if (!enabled) { + setField('twitterConsumerKey', ''); + } + }} + value={fields.allowTwitterAuthentication} + />} /> + {fields.allowTwitterAuthentication ? } + input={ + }/> : null} + {fields.twitterConsumerKeysList.length > 0 ? } + input={ ({ + title: 'App #' + (index + 1).toString(), + color: 'green', + onDelete: () => { + const twitterConsumerKeyList = fields.twitterConsumerKeysList.slice(); + twitterConsumerKeyList.splice(index, 1); - //TODO(drewgross): handle errors, display progress, etc. - this.context.setConnectedTwitterApps(twitterConsumerKeyList).then(() => { - this.forceUpdate(); - }); - }, - notes: [ - { - key: 'Consumer Key', - value: fields.twitterConsumerKeysList[index], - }, - ], - }))} - />} - /> : null} -
    + //TODO(drewgross): handle errors, display progress, etc. + this.context.setConnectedTwitterApps(twitterConsumerKeyList).then(() => { + this.forceUpdate(); + }); + }, + notes: [ + { + key: 'Consumer Key', + value: fields.twitterConsumerKeysList[index], + }, + ], + }))} + />} + /> : null} +
    - return
    - {userSessionsFields} - {userAuthenticationFields} - {socialLoginFields} - {toolbar} -
    ; - } + return
    + {userSessionsFields} + {userAuthenticationFields} + {socialLoginFields} + {toolbar} +
    ; + } - return renderFlowFooterChanges(changes, initialFields, userFieldOptions)} - onSubmit={({ changes, setField }) => { - let promiseList = []; - if (changes.requireRevocableSessions !== undefined) { - promiseList.push(this.context.setRequireRevocableSessions(changes.requireRevocableSessions)); - } - if (changes.expireInactiveSessions !== undefined) { - promiseList.push(this.context.setExpireInactiveSessions(changes.expireInactiveSessions)); - } - if (changes.revokeSessionOnPasswordChange !== undefined) { - promiseList.push(this.context.setRevokeSessionOnPasswordChange(changes.revokeSessionOnPasswordChange)); - } - if (changes.enableNewMethodsByDefault !== undefined) { - promiseList.push(this.context.setEnableNewMethodsByDefault(changes.enableNewMethodsByDefault)); - } - if (changes.allowUsernameAndPassword !== undefined) { - promiseList.push(this.context.setAllowUsernameAndPassword(changes.allowUsernameAndPassword)); - } - if (changes.allowAnonymousUsers !== undefined) { - promiseList.push(this.context.setAllowAnonymousUsers(changes.allowAnonymousUsers)); - } - if (changes.allowFacebookAuthentication !== undefined) { - promiseList.push(this.context.setAllowFacebookAuth(changes.allowFacebookAuthentication)); - } - if (changes.allowCustomAuthentication !== undefined) { - promiseList.push(this.context.setAllowCustomAuthentication(changes.allowCustomAuthentication)); - } - if (changes.facebookAppID !== undefined && changes.facebookAppSecret !== undefined) { - let fbAppPromise = this.context.addConnectedFacebookApp(changes.facebookAppID, changes.facebookAppSecret); - fbAppPromise.then(() => { - setField('facebookAppID', ''); - setField('facebookAppSecret', ''); - }) - promiseList.push(fbAppPromise); - } - if (changes.twitterConsumerKey !== undefined) { - let twitterAppPromise = this.context.addConnectedTwitterApp(changes.twitterConsumerKey); - twitterAppPromise.then(() => { - setField('twitterConsumerKey', ''); - }); - promiseList.push(twitterAppPromise); - } - if (changes.allowTwitterAuthentication !== undefined) { - promiseList.push(this.context.setAllowTwitterAuth(changes.allowTwitterAuthentication)); - } + return renderFlowFooterChanges(changes, initialFields, userFieldOptions)} + onSubmit={({ changes, setField }) => { + const promiseList = []; + if (changes.requireRevocableSessions !== undefined) { + promiseList.push(this.context.setRequireRevocableSessions(changes.requireRevocableSessions)); + } + if (changes.expireInactiveSessions !== undefined) { + promiseList.push(this.context.setExpireInactiveSessions(changes.expireInactiveSessions)); + } + if (changes.revokeSessionOnPasswordChange !== undefined) { + promiseList.push(this.context.setRevokeSessionOnPasswordChange(changes.revokeSessionOnPasswordChange)); + } + if (changes.enableNewMethodsByDefault !== undefined) { + promiseList.push(this.context.setEnableNewMethodsByDefault(changes.enableNewMethodsByDefault)); + } + if (changes.allowUsernameAndPassword !== undefined) { + promiseList.push(this.context.setAllowUsernameAndPassword(changes.allowUsernameAndPassword)); + } + if (changes.allowAnonymousUsers !== undefined) { + promiseList.push(this.context.setAllowAnonymousUsers(changes.allowAnonymousUsers)); + } + if (changes.allowFacebookAuthentication !== undefined) { + promiseList.push(this.context.setAllowFacebookAuth(changes.allowFacebookAuthentication)); + } + if (changes.allowCustomAuthentication !== undefined) { + promiseList.push(this.context.setAllowCustomAuthentication(changes.allowCustomAuthentication)); + } + if (changes.facebookAppID !== undefined && changes.facebookAppSecret !== undefined) { + const fbAppPromise = this.context.addConnectedFacebookApp(changes.facebookAppID, changes.facebookAppSecret); + fbAppPromise.then(() => { + setField('facebookAppID', ''); + setField('facebookAppSecret', ''); + }) + promiseList.push(fbAppPromise); + } + if (changes.twitterConsumerKey !== undefined) { + const twitterAppPromise = this.context.addConnectedTwitterApp(changes.twitterConsumerKey); + twitterAppPromise.then(() => { + setField('twitterConsumerKey', ''); + }); + promiseList.push(twitterAppPromise); + } + if (changes.allowTwitterAuthentication !== undefined) { + promiseList.push(this.context.setAllowTwitterAuth(changes.allowTwitterAuthentication)); + } - return Promise.all(promiseList).then(() => { + return Promise.all(promiseList).then(() => { this.forceUpdate(); //Need to forceUpdate to see changes applied to source ParseApp - }).catch(errors => { - return Promise.reject({ error: unique(pluck(errors, 'error')).join(' ') }); - }); - }} - />; + }).catch(errors => { + return Promise.reject({ error: unique(pluck(errors, 'error')).join(' ') }); + }); + }} + />; } } const userFieldOptions = { - requireRevocableSessions: { - friendlyName: 'require revocable sessions', - type: 'boolean', - }, - expireInactiveSessions: { - friendlyName: 'expire inactive sessions', - type: 'boolean', - }, - revokeSessionOnPasswordChange: { - friendlyName: 'revoke session on password change', - type: 'boolean', - }, - enableNewMethodsByDefault: { - friendlyName: 'new authentication methods by default', - type: 'boolean', - }, - allowUsernameAndPassword: { - friendlyName: 'user name and password login', - type: 'boolean', - }, - allowAnonymousUsers: { - friendlyName: 'annonymous users', - type: 'boolean', - }, - allowFacebookAuthentication: { - friendlyName: 'Facebook authentication', - type: 'boolean', - }, - facebookAppID: { - friendlyName: 'Facebook app ID', - type: 'addition', - }, - facebookAppSecret: { - friendlyName: 'Facebook app secret', - type: 'addition', - }, - allowTwitterAuthentication: { - friendlyName: 'Twitter authentication', - type: 'boolean', - }, - twitterConsumerKey: { - friendlyName: 'Twitter Consumer Key', - type: 'addition', - }, - allowCustomAuthentication: { - friendlyName: 'custom authentication', - type: 'boolean', - }, + requireRevocableSessions: { + friendlyName: 'require revocable sessions', + type: 'boolean', + }, + expireInactiveSessions: { + friendlyName: 'expire inactive sessions', + type: 'boolean', + }, + revokeSessionOnPasswordChange: { + friendlyName: 'revoke session on password change', + type: 'boolean', + }, + enableNewMethodsByDefault: { + friendlyName: 'new authentication methods by default', + type: 'boolean', + }, + allowUsernameAndPassword: { + friendlyName: 'user name and password login', + type: 'boolean', + }, + allowAnonymousUsers: { + friendlyName: 'annonymous users', + type: 'boolean', + }, + allowFacebookAuthentication: { + friendlyName: 'Facebook authentication', + type: 'boolean', + }, + facebookAppID: { + friendlyName: 'Facebook app ID', + type: 'addition', + }, + facebookAppSecret: { + friendlyName: 'Facebook app secret', + type: 'addition', + }, + allowTwitterAuthentication: { + friendlyName: 'Twitter authentication', + type: 'boolean', + }, + twitterConsumerKey: { + friendlyName: 'Twitter Consumer Key', + type: 'addition', + }, + allowCustomAuthentication: { + friendlyName: 'custom authentication', + type: 'boolean', + }, }; diff --git a/src/dashboard/SidebarBuilder.js b/src/dashboard/SidebarBuilder.js index 6af38979af..c548f5f3a8 100644 --- a/src/dashboard/SidebarBuilder.js +++ b/src/dashboard/SidebarBuilder.js @@ -8,7 +8,7 @@ import React from 'react'; import Sidebar from 'components/Sidebar/Sidebar.react'; -let accountSidebarSections = [ +const accountSidebarSections = [ { name: 'Your Apps', icon: 'blank-app-outline', @@ -21,7 +21,7 @@ let accountSidebarSections = [ ]; export function buildAccountSidebar(options) { - let { + const { section, subsection } = options; diff --git a/src/dashboard/TableView.react.js b/src/dashboard/TableView.react.js index 679912835a..63337acd84 100644 --- a/src/dashboard/TableView.react.js +++ b/src/dashboard/TableView.react.js @@ -12,8 +12,8 @@ import styles from 'dashboard/TableView.scss'; export default class TableView extends DashboardView { columnWidths(keys) { - let equalWidth = 100 / keys.length + '%'; - let widths = {}; + const equalWidth = 100 / keys.length + '%'; + const widths = {}; // leave the last key undefined, so it fills the remaining space for (let i = 0; i < keys.length - 1; i++) { widths[keys[i]] = equalWidth; @@ -26,9 +26,9 @@ export default class TableView extends DashboardView { } renderContent() { - let toolbar = this.renderToolbar(); - let data = this.tableData(); - let footer = this.renderFooter(); + const toolbar = this.renderToolbar(); + const data = this.tableData(); + const footer = this.renderFooter(); let content = null; let headers = null; if (data !== undefined) { @@ -52,8 +52,8 @@ export default class TableView extends DashboardView { } } } - let extras = this.renderExtras ? this.renderExtras() : null; - let loading = this.state ? this.state.loading : false; + const extras = this.renderExtras ? this.renderExtras() : null; + const loading = this.state ? this.state.loading : false; return (
    diff --git a/src/lib/AJAX.js b/src/lib/AJAX.js index 74824324ce..14b99d3b65 100644 --- a/src/lib/AJAX.js +++ b/src/lib/AJAX.js @@ -12,7 +12,7 @@ let basePath = ''; export function setBasePath(newBasePath) { basePath = newBasePath || ''; if (basePath.endsWith('/')) { - basePath = basePath.slice(0, basePath.length-1); + basePath = basePath.slice(0, basePath.length - 1); } } @@ -24,7 +24,7 @@ export function request(method, url, body, abortable = false, withCredentials = && !url.startsWith(basePath + '/')) { url = basePath + url; } - let xhr = new XMLHttpRequest(); + const xhr = new XMLHttpRequest(); xhr.open(method, url, true); if (method === 'POST' || method === 'PUT' || method === 'DELETE') { xhr.setRequestHeader('X-CSRF-Token', CSRFManager.getToken()); @@ -35,7 +35,7 @@ export function request(method, url, body, abortable = false, withCredentials = xhr.withCredentials = withCredentials; let resolve; let reject; - let p = new Promise((res, rej) => { + const p = new Promise((res, rej) => { resolve = res; reject = rej; }); @@ -80,7 +80,7 @@ export function request(method, url, body, abortable = false, withCredentials = p.reject(this.responseText) return; } - let message = json.message || json.error || json.notice || 'Request Error'; + const message = json.message || json.error || json.notice || 'Request Error'; p.reject({ success: false, message: message, @@ -107,8 +107,8 @@ export function request(method, url, body, abortable = false, withCredentials = 'application/x-www-form-urlencoded; charset=UTF-8' ); // Encode it as a url parameter string - let formData = []; - for (let k in body) { + const formData = []; + for (const k in body) { formData.push(encodeFormData(k, body[k])); } xhr.send(formData.join('&')); diff --git a/src/lib/AccountManager.js b/src/lib/AccountManager.js index 04695f7556..1c3db8c3ca 100644 --- a/src/lib/AccountManager.js +++ b/src/lib/AccountManager.js @@ -9,11 +9,11 @@ import { abortableGet, put, post, del } from 'lib/AJAX'; import { unescape } from 'lib/StringEscaping'; let currentUser = null; -let xhrMap = {}; +const xhrMap = {}; -let AccountManager = { +const AccountManager = { init() { - let accountData = document.getElementById('accountData'); + const accountData = document.getElementById('accountData'); if (!accountData) { return; } @@ -28,7 +28,7 @@ let AccountManager = { }, resetPasswordAndEmailAndName(currentPassword, newPassword, newEmail, newName) { - let path = '/account'; + const path = '/account'; return put(path, { confirm_password: currentPassword, 'user[password]':newPassword, @@ -38,10 +38,10 @@ let AccountManager = { }, createAccountKey(keyName) { - let path = '/account/keys'; - let promise = post(path, {name: keyName}); + const path = '/account/keys'; + const promise = post(path, {name: keyName}); promise.then(newKey => { - let hiddenKey = {...newKey, token: '\u2022\u2022' + newKey.token.substr(newKey.token.length - 4)}; + const hiddenKey = {...newKey, token: '\u2022\u2022' + newKey.token.substr(newKey.token.length - 4)}; //TODO: save the account key better. This currently only works because everywhere that uses // the account keys happens to rerender after the account keys change anyway. currentUser.account_keys.unshift(hiddenKey); @@ -50,8 +50,8 @@ let AccountManager = { }, deleteAccountKeyById(id) { - let path = '/account/keys/' + id.toString(); - let promise = del(path); + const path = '/account/keys/' + id.toString(); + const promise = del(path); promise.then(() => { //TODO: delete the account key better. This currently only works because everywhere that uses @@ -62,8 +62,8 @@ let AccountManager = { }, fetchLinkedAccounts(xhrKey) { - let path = '/account/linked_accounts'; - let {xhr, promise} = abortableGet(path); + const path = '/account/linked_accounts'; + const {xhr, promise} = abortableGet(path); xhrMap[xhrKey] = xhr; promise.then((result) => { this.linkedAccounts = result; diff --git a/src/lib/AppsManager.js b/src/lib/AppsManager.js index e3d58c589f..5e70282413 100644 --- a/src/lib/AppsManager.js +++ b/src/lib/AppsManager.js @@ -8,7 +8,7 @@ import ParseApp from 'lib/ParseApp'; import { post, del } from 'lib/AJAX'; -let appsStore = []; +const appsStore = []; const AppsManager = { addApp(raw) { @@ -23,7 +23,7 @@ const AppsManager = { }, findAppBySlugOrName(slugOrName) { - let apps = this.apps(); + const apps = this.apps(); for (let i = apps.length; i--;) { if (apps[i].slug === slugOrName || apps[i].name === slugOrName) { return apps[i]; @@ -33,14 +33,14 @@ const AppsManager = { }, create(name, connectionURL) { - let payload = { + const payload = { parse_app: { name } }; if (connectionURL) { payload.parse_app.connectionString = connectionURL; } return post('/apps', payload).then((response) => { - let newApp = new ParseApp(response.app); + const newApp = new ParseApp(response.app); appsStore.push(newApp); return newApp; }); @@ -77,7 +77,7 @@ const AppsManager = { // indicating which parts of the app to clone. cloneApp(slug, name, options) { //Clone nothing by default - let optionsForRuby = { + const optionsForRuby = { cloud_code: false, background_jobs: false, config: false, @@ -90,8 +90,8 @@ const AppsManager = { optionsForRuby[option] = true; } }); - let path = '/apps/' + slug + '/clone_app'; - let request = post(path, { + const path = '/apps/' + slug + '/clone_app'; + const request = post(path, { app_name: name, options: optionsForRuby, }); @@ -105,7 +105,7 @@ const AppsManager = { }, transferApp(slug, newOwner, password) { - let payload = { + const payload = { new_owner_email: newOwner, } if (password) { @@ -114,7 +114,7 @@ const AppsManager = { payload.password_confirm_transfer = password; } - let promise = post('/apps/' + slug + '/transfer', payload); + const promise = post('/apps/' + slug + '/transfer', payload); promise.then(() => { //TODO modify appsStore to reflect transfer }); diff --git a/src/lib/CSRFManager.js b/src/lib/CSRFManager.js index fcb0c3813d..bcbf22a732 100644 --- a/src/lib/CSRFManager.js +++ b/src/lib/CSRFManager.js @@ -11,7 +11,7 @@ let currentToken = null; export function getToken() { if (!currentToken) { - let tokenScript = document.getElementById('csrf'); + const tokenScript = document.getElementById('csrf'); if (tokenScript) { currentToken = JSON.parse(unescape(tokenScript.innerHTML)); } diff --git a/src/lib/Charting.js b/src/lib/Charting.js index 18b8773361..c9b74072f0 100644 --- a/src/lib/Charting.js +++ b/src/lib/Charting.js @@ -10,11 +10,11 @@ const DAY = HOUR * 24; // Determines the points marked on the x-axis of a chart export function timeAxisBuckets(minRaw, maxRaw) { - let min = new Date(minRaw); - let max = new Date(maxRaw); + const min = new Date(minRaw); + const max = new Date(maxRaw); if (max - min <= DAY * 2) { - let buckets = []; + const buckets = []; let bucket = new Date(Date.UTC(min.getUTCFullYear(), min.getUTCMonth(), min.getUTCDate(), min.getUTCHours())); while (bucket < max) { buckets.push(bucket); @@ -25,7 +25,7 @@ export function timeAxisBuckets(minRaw, maxRaw) { } if (max - min <= DAY * 60) { - let buckets = []; + const buckets = []; let bucket = new Date(Date.UTC(min.getUTCFullYear(), min.getUTCMonth(), min.getUTCDate())); while (bucket < max) { buckets.push(bucket); @@ -37,7 +37,7 @@ export function timeAxisBuckets(minRaw, maxRaw) { return buckets; } - let buckets = []; + const buckets = []; let bucket = new Date(Date.UTC(min.getUTCFullYear(), min.getUTCMonth())); while (bucket < max) { buckets.push(bucket); @@ -59,8 +59,8 @@ export function valueAxisBuckets(max) { if (max / Math.pow(10, magnitude) < 1.5) { magnitude--; } - let skip = Math.pow(10, magnitude); - let buckets = []; + const skip = Math.pow(10, magnitude); + const buckets = []; let bucket = 0; while (bucket <= max) { buckets.push(bucket); @@ -72,8 +72,8 @@ export function valueAxisBuckets(max) { // Determines the x,y points on the chart for each data point export function getDataPoints(chartWidth, chartHeight, timeBuckets, valueBuckets, dataPoints) { - let xLength = timeBuckets[timeBuckets.length - 1] - timeBuckets[0]; - let yLength = valueBuckets[valueBuckets.length - 1] - valueBuckets[0]; + const xLength = timeBuckets[timeBuckets.length - 1] - timeBuckets[0]; + const yLength = valueBuckets[valueBuckets.length - 1] - valueBuckets[0]; return dataPoints.map(([x, y]) => { return [chartWidth * (x - timeBuckets[0]) / xLength, chartHeight - (chartHeight * y / yLength)]; }); diff --git a/src/lib/ClassPreferences.js b/src/lib/ClassPreferences.js index b36b1a5a7b..620767fd6a 100644 --- a/src/lib/ClassPreferences.js +++ b/src/lib/ClassPreferences.js @@ -1,5 +1,5 @@ const VERSION = 1; // In case we ever need to invalidate these -let cache = {}; +const cache = {}; export function updatePreferences(prefs, appId, className) { try { localStorage.setItem(path(appId, className), JSON.stringify(prefs)); @@ -27,7 +27,7 @@ export function getPreferences(appId, className) { return null; } try { - let prefs = JSON.parse(entry); + const prefs = JSON.parse(entry); cache[appId] = cache[appId] || {}; cache[appId][className] = prefs; return prefs; diff --git a/src/lib/ColumnPreferences.js b/src/lib/ColumnPreferences.js index 78619dbe18..e17e45a75b 100644 --- a/src/lib/ColumnPreferences.js +++ b/src/lib/ColumnPreferences.js @@ -9,7 +9,7 @@ const VERSION = 'v1'; // In case we ever need to invalidate these const DEFAULT_WIDTH = 150; const COLUMN_SORT = '__columnClassesSort'; // Used for storing classes sort field const DEFAULT_COLUMN_SORT = '-createdAt'; // Default column sorting -let cache = {}; +const cache = {}; export function updatePreferences(prefs, appId, className) { try { @@ -36,7 +36,7 @@ export function getPreferences(appId, className) { return null; } try { - let prefs = JSON.parse(entry); + const prefs = JSON.parse(entry); cache[appId] = cache[appId] || {}; cache[appId][className] = prefs; return prefs; @@ -63,8 +63,8 @@ export function getAllPreferences(appId) { } export function getColumnSort(sortBy, appId, className) { - let cachedSort = getPreferences(appId, COLUMN_SORT) || [ { name: className, value: DEFAULT_COLUMN_SORT } ]; - let ordering = [].concat(cachedSort); + const cachedSort = getPreferences(appId, COLUMN_SORT) || [ { name: className, value: DEFAULT_COLUMN_SORT } ]; + const ordering = [].concat(cachedSort); let updated = false; let missing = true; let currentSort = sortBy ? sortBy : DEFAULT_COLUMN_SORT; @@ -115,14 +115,14 @@ export function getOrder(cols, appId, className, defaultPrefs) { } }); } - let order = [].concat(prefs); - let seen = {}; + const order = [].concat(prefs); + const seen = {}; for (let i = 0; i < order.length; i++) { seen[order[i].name] = true; } - let requested = {}; + const requested = {}; let updated = false; - for (let name in cols) { + for (const name in cols) { requested[name] = true; if (!seen[name]) { order.push({ name: name, width: DEFAULT_WIDTH, visible: !defaultPrefs, required: cols[name]['required'], cached: !defaultPrefs }); @@ -130,7 +130,7 @@ export function getOrder(cols, appId, className, defaultPrefs) { updated = true; } } - let filtered = []; + const filtered = []; for (let i = 0; i < order.length; i++) { const { name, visible, required, cached } = order[i]; @@ -166,26 +166,26 @@ export function getOrder(cols, appId, className, defaultPrefs) { } export function updateCachedColumns(appId, className) { - let prefs = getPreferences(appId, className); - let order = [].concat(prefs); + const prefs = getPreferences(appId, className); + const order = [].concat(prefs); - for (let col of order) { - let { visible } = col; + for (const col of order) { + const { visible } = col; col.cached = visible; } updatePreferences(order, appId, className); return order; } -export function setPointerDefaultKey( appId, className, name ) { +export function setPointerDefaultKey(appId, className, name) { localStorage.setItem(pointerKeyPath(appId, className), name); // remove old pointer key. localStorage.removeItem(className); } -export function getPointerDefaultKey( appId, className ) { +export function getPointerDefaultKey(appId, className) { let pointerKey = localStorage.getItem(pointerKeyPath(appId, className)); - if ( !pointerKey ) { + if (!pointerKey) { // old pointer key. pointerKey = localStorage.getItem(className) || 'objectId'; } @@ -196,6 +196,6 @@ function path(appId, className) { return `ParseDashboard:${VERSION}:${appId}:${className}`; } -function pointerKeyPath( appId, className ) { +function pointerKeyPath(appId, className) { return `ParseDashboard:${VERSION}:${appId}:${className}::defaultPointerKey`; } diff --git a/src/lib/DateUtils.js b/src/lib/DateUtils.js index 0e405551ff..c4c49ddea8 100644 --- a/src/lib/DateUtils.js +++ b/src/lib/DateUtils.js @@ -75,8 +75,8 @@ export function prevMonth(date) { } export function daysInMonth(date) { - let next = nextMonth(date); - let lastDay = new Date(next.getFullYear(), next.getMonth(), next.getDate() - 1); + const next = nextMonth(date); + const lastDay = new Date(next.getFullYear(), next.getMonth(), next.getDate() - 1); return lastDay.getDate(); } @@ -114,12 +114,12 @@ export function dateStringUTC(date) { let full = String(date.getUTCDate()) + ' ' + shortMonth(date.getUTCMonth()) + ' ' + String(date.getUTCFullYear()) + ' at '; - let time = { + const time = { hours: String(date.getUTCHours()), minutes: String(date.getUTCMinutes()), seconds: String(date.getUTCSeconds()) }; - for (let k in time) { + for (const k in time) { if (time[k].length < 2) { time[k] = '0' + time[k]; } @@ -142,7 +142,7 @@ export function yearMonthDayFormatter(date) { } export function yearMonthDayTimeFormatter(date, timeZone) { - let options = {year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: 'numeric', hour12: false}; + const options = {year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: 'numeric', hour12: false}; if (timeZone) { options.timeZoneName = 'short'; } diff --git a/src/lib/Email.js b/src/lib/Email.js index c3b7cd1fbc..5fa5e58b82 100644 --- a/src/lib/Email.js +++ b/src/lib/Email.js @@ -48,10 +48,10 @@ const domains = [ const domainMap = {}; for (let i = domains.length; i--;) { - let levels = domains[i].split('.'); - let secondLevel = levels.shift(); - let tld = levels.join('.'); - let pairs = domainMap[secondLevel]; + const levels = domains[i].split('.'); + const secondLevel = levels.shift(); + const tld = levels.join('.'); + const pairs = domainMap[secondLevel]; if (!pairs) { domainMap[secondLevel] = [tld]; } else { @@ -70,9 +70,9 @@ export function dist(a, b) { return a.length; } - let vectors = []; + const vectors = []; for (let i = 0; i <= a.length; i++) { - let row = []; + const row = []; for (let j = 0; j <= b.length; j++) { row[j] = 0; } @@ -107,16 +107,16 @@ export const emailRegex = /^([^@<>\s]+)@([^@<>\s]{2,}\.[^@<>\s]{2,})$/; // If we think there's a typo, return a string suggesting a correction // Return null if we have no suggestion export function suggestion(email, checkTLD) { - let match = email.match(emailRegex); + const match = email.match(emailRegex); if (!match) { return null; } - let emailDomain = match[2].toLowerCase(); - let emailSecondLevel = emailDomain.split('.').shift(); + const emailDomain = match[2].toLowerCase(); + const emailSecondLevel = emailDomain.split('.').shift(); let closestDistance = Infinity; let closestDomain = ''; - let secondLevelDomains = Object.keys(domainMap); + const secondLevelDomains = Object.keys(domainMap); let i; let d; for (i = secondLevelDomains.length; i--;) { @@ -132,12 +132,12 @@ export function suggestion(email, checkTLD) { if (closestDistance > 3 || (!checkTLD && closestDistance === 0)) { return null; } - let selectedDomain = closestDomain; + const selectedDomain = closestDomain; closestDistance = Infinity; - let tlds = domainMap[selectedDomain]; + const tlds = domainMap[selectedDomain]; for (i = tlds.length; i--;) { - let joined = selectedDomain + '.' + tlds[i]; + const joined = selectedDomain + '.' + tlds[i]; d = dist(emailDomain, joined); if (d < closestDistance) { closestDistance = d; diff --git a/src/lib/Filters.js b/src/lib/Filters.js index c53e41a008..cd68ce0c53 100644 --- a/src/lib/Filters.js +++ b/src/lib/Filters.js @@ -211,7 +211,7 @@ export const DefaultComparisons = { // blacklist is an optional array of constraints to ignore export function availableFilters(schema, currentFilters, blacklist) { blacklist = blacklist || []; - let disabled = {}; + const disabled = {}; if (currentFilters) { currentFilters.forEach((filter) => { if (!Constraints[filter.get('constraint')].composable) { @@ -219,12 +219,12 @@ export function availableFilters(schema, currentFilters, blacklist) { } }); } - let available = {}; - for (let col in schema) { + const available = {}; + for (const col in schema) { if (disabled[col]) { continue; } - let type = schema[col].type; + const type = schema[col].type; if (!FieldConstraints[type]) { continue; } diff --git a/src/lib/ParseApp.js b/src/lib/ParseApp.js index 9b84a50fe7..17c2130de1 100644 --- a/src/lib/ParseApp.js +++ b/src/lib/ParseApp.js @@ -11,11 +11,11 @@ import Parse from 'parse'; import { updatePreferences, getPreferences } from 'lib/ClassPreferences'; function setEnablePushSource(setting, enable) { - let path = `/apps/${this.slug}/update_push_notifications`; - let attr = `parse_app[${setting}]`; - let body = {}; + const path = `/apps/${this.slug}/update_push_notifications`; + const attr = `parse_app[${setting}]`; + const body = {}; body[attr] = enable ? 'true' : 'false'; - let promise = AJAX.put(path, body); + const promise = AJAX.put(path, body); promise.then(() => { this.settings.fields.fields[setting] = enable; }); @@ -54,7 +54,7 @@ export default class ParseApp { this.applicationId = appId; this.slug = appNameForURL || appName; if (!this.slug && dashboardURL) { - let pieces = dashboardURL.split('/'); + const pieces = dashboardURL.split('/'); this.slug = pieces[pieces.length - 1]; } this.clientKey = clientKey; @@ -68,8 +68,8 @@ export default class ParseApp { this.serverURL = serverURL; this.serverInfo = serverInfo; this.icon = iconName; - this.primaryBackgroundColor=primaryBackgroundColor; - this.secondaryBackgroundColor=secondaryBackgroundColor; + this.primaryBackgroundColor = primaryBackgroundColor; + this.secondaryBackgroundColor = secondaryBackgroundColor; this.supportedPushLocales = supportedPushLocales ? supportedPushLocales : []; this.preventSchemaEdits = preventSchemaEdits || false; this.graphQLServerURL = graphQLServerURL; @@ -136,7 +136,7 @@ export default class ParseApp { * since - only fetch lines since this Date */ getLogs(level, since) { - let path = 'scriptlog?level=' + encodeURIComponent(level.toLowerCase()) + '&n=100' + (since?'&startDate=' + encodeURIComponent(since.getTime()):''); + const path = 'scriptlog?level=' + encodeURIComponent(level.toLowerCase()) + '&n=100' + (since ? '&startDate=' + encodeURIComponent(since.getTime()) : ''); return this.apiRequest('GET', path, {}, { useMasterKey: true }); } @@ -151,12 +151,12 @@ export default class ParseApp { return Promise.resolve(null); } - let fileMetaData = release.files[fileName]; + const fileMetaData = release.files[fileName]; if (fileMetaData && fileMetaData.source) { return Promise.resolve(fileMetaData.source); } - let params = { + const params = { version: fileMetaData.version, checksum: fileMetaData.checksum } @@ -187,7 +187,7 @@ export default class ParseApp { if (release.length === 0) { this.latestRelease.release = null; } else { - let latestRelease = release[0]; + const latestRelease = release[0]; this.latestRelease.release = { version: latestRelease.version, @@ -206,7 +206,7 @@ export default class ParseApp { if (versions.cloud) { versions = versions.cloud; } - for (let c in checksums) { + for (const c in checksums) { this.latestRelease.files[c] = { checksum: checksums[c], version: versions[c], @@ -227,7 +227,7 @@ export default class ParseApp { return Promise.resolve(this.classCounts.counts[className]); } } - let p = new Parse.Query(className).count({ useMasterKey: true }); + const p = new Parse.Query(className).count({ useMasterKey: true }); p.then(count => { this.classCounts.counts[className] = count; this.classCounts.lastFetched[className] = new Date(); @@ -237,7 +237,7 @@ export default class ParseApp { getRelationCount(relation) { this.setParseKeys(); - let p = relation.query().count({ useMasterKey: true }); + const p = relation.query().count({ useMasterKey: true }); return p; } @@ -248,7 +248,7 @@ export default class ParseApp { getAnalyticsOverview(time) { time = Math.round(time.getTime() / 1000); - let audiencePromises = [ + const audiencePromises = [ 'daily_users', 'weekly_users', 'monthly_users', @@ -265,7 +265,7 @@ export default class ParseApp { return { xhr, promise } }); - let billingPromises = [ + const billingPromises = [ 'billing_file_storage', 'billing_database_storage', 'billing_data_transfer' @@ -273,7 +273,7 @@ export default class ParseApp { AJAX.abortableGet('/apps/' + this.slug + '/' + billing) )); - let allPromises = audiencePromises.concat(billingPromises); + const allPromises = audiencePromises.concat(billingPromises); return { 'dailyActiveUsers': allPromises[0], @@ -291,14 +291,14 @@ export default class ParseApp { } getAnalyticsTimeSeries(query) { - let path = '/apps/' + this.slug + '/analytics?' + encodeFormData(null, query); + const path = '/apps/' + this.slug + '/analytics?' + encodeFormData(null, query); let { promise, xhr } = AJAX.abortableGet(path); promise = promise.then(({ requested_data }) => requested_data); return { promise, xhr }; } getAnalyticsSlowQueries(className, os, version, from, to) { - let path = '/apps/' + this.slug + '/slow_queries?' + encodeFormData(null, { + const path = '/apps/' + this.slug + '/slow_queries?' + encodeFormData(null, { className: className || '', os: os || '', version: version || '', @@ -312,45 +312,45 @@ export default class ParseApp { } getAppleCerts() { - let path = '/apps/' + this.slug + '/apple_certificates'; + const path = '/apps/' + this.slug + '/apple_certificates'; return AJAX.get(path).then(({ certs }) => certs); } uploadAppleCert(file) { - let path = '/apps/' + this.slug + '/dashboard_ajax/push_certificate'; - let data = new FormData(); + const path = '/apps/' + this.slug + '/dashboard_ajax/push_certificate'; + const data = new FormData(); data.append('new_apple_certificate', file); return AJAX.post(path, data).then(({ cert }) => cert); } deleteAppleCert(id) { - let path = '/apps/' + this.slug + '/apple_certificates/' + id; + const path = '/apps/' + this.slug + '/apple_certificates/' + id; return AJAX.del(path); } uploadSSLPublicCertificate(file) { - let path = '/apps/' + this.slug + '/update_hosting_certificates'; - let data= new FormData(); + const path = '/apps/' + this.slug + '/update_hosting_certificates'; + const data = new FormData(); data.append('new_hosting_certificate[certificate_data]', file); return AJAX.put(path, data); } uploadSSLPrivateKey(file) { - let path = '/apps/' + this.slug + '/update_hosting_certificates'; - let data= new FormData(); + const path = '/apps/' + this.slug + '/update_hosting_certificates'; + const data = new FormData(); data.append('new_hosting_certificate[key_data]', file); return AJAX.put(path, data); } saveSettingsFields(fields) { - let path = '/apps/' + this.slug; - let appFields = {}; - for (let f in fields) { + const path = '/apps/' + this.slug; + const appFields = {}; + for (const f in fields) { appFields['parse_app[' + f + ']'] = fields[f]; } - let promise = AJAX.put(path, appFields); + const promise = AJAX.put(path, appFields); promise.then(({ successes }) => { - for (let f in fields) { + for (const f in fields) { this.settings.fields[f] = successes[f]; } }); @@ -362,9 +362,9 @@ export default class ParseApp { if (new Date() - this.settings.lastFetched < 60000) { return Promise.resolve(this.settings.fields); } - let path = '/apps/' + this.slug + '/dashboard_ajax/settings'; + const path = '/apps/' + this.slug + '/dashboard_ajax/settings'; return AJAX.get(path).then((fields) => { - for (let f in fields) { + for (const f in fields) { this.settings.fields[f] = fields[f]; this.settings.lastFetched = new Date(); } @@ -373,17 +373,17 @@ export default class ParseApp { } cleanUpFiles() { - let path = '/apps/' + this.slug + '/cleanup_files'; + const path = '/apps/' + this.slug + '/cleanup_files'; return AJAX.put(path); } exportData() { - let path = '/apps/' + this.slug + '/export_data'; + const path = '/apps/' + this.slug + '/export_data'; return AJAX.put(path); } resetMasterKey(password) { - let path = '/apps/' + this.slug + '/reset_master_key'; + const path = '/apps/' + this.slug + '/reset_master_key'; return AJAX.post( path, { password_confirm_reset_master_key: password } @@ -395,16 +395,16 @@ export default class ParseApp { clearCollection(className) { if (this.serverInfo.parseServerVersion == 'Parse.com') { - let path = `/apps/${this.slug}/collections/${className}/clear`; + const path = `/apps/${this.slug}/collections/${className}/clear`; return AJAX.del(path); } else { - let path = `purge/${className}`; + const path = `purge/${className}`; return this.apiRequest('DELETE', path, {}, { useMasterKey: true }); } } validateCollaborator(email) { - let path = '/apps/' + this.slug + '/collaborations/validate?email=' + encodeURIComponent(email); + const path = '/apps/' + this.slug + '/collaborations/validate?email=' + encodeURIComponent(email); return AJAX.get(path); } @@ -426,23 +426,23 @@ export default class ParseApp { } fetchPushNotifications(type, page, limit) { - let query = new Parse.Query('_PushStatus'); + const query = new Parse.Query('_PushStatus'); if (type != 'all') { query.equalTo('source', type || 'rest'); } - query.skip(page*limit); + query.skip(page * limit); query.limit(limit); query.descending('createdAt'); return query.find({ useMasterKey: true }); } fetchPushAudienceSizeSuggestion() { - let path = '/apps/' + this.slug + '/push_notifications/audience_size_suggestion'; + const path = '/apps/' + this.slug + '/push_notifications/audience_size_suggestion'; return AJAX.get(path); } fetchPushDetails(objectId) { - let query = new Parse.Query('_PushStatus'); + const query = new Parse.Query('_PushStatus'); query.equalTo('objectId', objectId); return query.first({ useMasterKey: true }); } @@ -465,13 +465,13 @@ export default class ParseApp { } fetchAvailableDevices() { - let path = '/apps/' + this.slug + '/dashboard_ajax/available_devices'; + const path = '/apps/' + this.slug + '/dashboard_ajax/available_devices'; return AJAX.get(path); } removeCollaboratorById(id) { - let path = '/apps/' + this.slug + '/collaborations/' + id.toString(); - let promise = AJAX.del(path) + const path = '/apps/' + this.slug + '/collaborations/' + id.toString(); + const promise = AJAX.del(path) promise.then(() => { //TODO: this currently works because everything that uses collaborators // happens to re-render after this call anyway, but really the collaborators @@ -482,8 +482,8 @@ export default class ParseApp { } addCollaborator(email) { - let path = '/apps/' + this.slug + '/collaborations'; - let promise = AJAX.post(path, {'collaboration[email]': email}); + const path = '/apps/' + this.slug + '/collaborations'; + const promise = AJAX.post(path, {'collaboration[email]': email}); promise.then(({ data }) => { //TODO: this currently works because everything that uses collaborators // happens to re-render after this call anyway, but really the collaborators @@ -494,8 +494,8 @@ export default class ParseApp { } setRequestLimit(limit) { - let path = '/plans/' + this.slug + '?new_limit=' + limit.toString(); - let promise = AJAX.put(path); + const path = '/plans/' + this.slug + '?new_limit=' + limit.toString(); + const promise = AJAX.put(path); promise.then(() => { this.settings.fields.fields.pricing_plan.request_limit = limit; }); @@ -503,8 +503,8 @@ export default class ParseApp { } setAppName(name) { - let path = '/apps/' + this.slug; - let promise = AJAX.put(path, {'parse_app[name]': name}); + const path = '/apps/' + this.slug; + const promise = AJAX.put(path, {'parse_app[name]': name}); promise.then(() => { this.name = name; }); @@ -512,8 +512,8 @@ export default class ParseApp { } setAppStoreURL(type, url) { - let path = '/apps/' + this.slug; - let promise = AJAX.put(path, {['parse_app[parse_app_metadata][url][' + type + ']']: url}); + const path = '/apps/' + this.slug; + const promise = AJAX.put(path, {['parse_app[parse_app_metadata][url][' + type + ']']: url}); promise.then(() => { this.settings.fields.fields.urls.unshift({platform: type, url: url}); }); @@ -521,8 +521,8 @@ export default class ParseApp { } setInProduction(inProduction) { - let path = '/apps/' + this.slug; - let promise = AJAX.put(path, {'parse_app[parse_app_metadata][production]': inProduction ? 'true' : 'false'}); + const path = '/apps/' + this.slug; + const promise = AJAX.put(path, {'parse_app[parse_app_metadata][production]': inProduction ? 'true' : 'false'}); promise.then(() => { this.production = inProduction; }); @@ -530,7 +530,7 @@ export default class ParseApp { } launchExperiment(objectId, formData) { - let path = `/apps/${this.slug}/push_notifications/${objectId}/launch_experiment`; + const path = `/apps/${this.slug}/push_notifications/${objectId}/launch_experiment`; return AJAX.post(path, formData); } @@ -538,22 +538,22 @@ export default class ParseApp { if (!where) { where = {}; } - let path = '/apps/' + this.slug + '/export_data'; + const path = '/apps/' + this.slug + '/export_data'; return AJAX.put(path, { name: className, where: where }); } getExportProgress() { - let path = '/apps/' + this.slug + '/export_progress'; + const path = '/apps/' + this.slug + '/export_progress'; return AJAX.get(path); } getAvailableJobs() { - let path = 'cloud_code/jobs/data'; + const path = 'cloud_code/jobs/data'; return this.apiRequest('GET', path, {}, { useMasterKey: true }); } getJobStatus() { - let query = new Parse.Query('_JobStatus'); + const query = new Parse.Query('_JobStatus'); query.descending('createdAt'); return query.find({ useMasterKey: true }).then((status) => { status = status.map((jobStatus) => { @@ -582,8 +582,8 @@ export default class ParseApp { } getMigrations() { - let path = '/apps/' + this.slug + '/migrations'; - let obj = AJAX.abortableGet(path); + const path = '/apps/' + this.slug + '/migrations'; + const obj = AJAX.abortableGet(path); this.hasCheckedForMigraton = true obj.promise.then(({ migration }) => { this.migration = migration; @@ -593,13 +593,13 @@ export default class ParseApp { beginMigration(connectionString) { this.hasCheckedForMigraton = false; - let path = '/apps/' + this.slug + '/migrations'; + const path = '/apps/' + this.slug + '/migrations'; return AJAX.post(path, {connection_string: connectionString}); } changeConnectionString(newConnectionString) { - let path = '/apps/' + this.slug + '/change_connection_string'; - let promise = AJAX.post(path, {connection_string: newConnectionString}); + const path = '/apps/' + this.slug + '/change_connection_string'; + const promise = AJAX.post(path, {connection_string: newConnectionString}); promise.then(() => { this.settings.fields.fields.opendb_connection_string = newConnectionString; }); @@ -608,20 +608,20 @@ export default class ParseApp { stopMigration() { //We will need to pass the real ID here if we decide to have migrations deletable by id. For now, from the users point of view, there is only one migration per app. - let path = '/apps/' + this.slug + '/migrations/0'; + const path = '/apps/' + this.slug + '/migrations/0'; return AJAX.del(path); } commitMigration() { //Migration IDs are not to be exposed, so pass 0 as ID and let rails fetch the correct ID - let path = '/apps/' + this.slug + '/migrations/0/commit'; + const path = '/apps/' + this.slug + '/migrations/0/commit'; //No need to update anything, UI will autorefresh once request goes through and mowgli enters FINISH/DONE state return AJAX.post(path); } setRequireRevocableSessions(require) { - let path = '/apps/' + this.slug; - let promise = AJAX.put(path, {'parse_app[require_revocable_session]': require ? 'true' : 'false'}); + const path = '/apps/' + this.slug; + const promise = AJAX.put(path, {'parse_app[require_revocable_session]': require ? 'true' : 'false'}); promise.then(() => { //TODO: this currently works because everything that uses this // happens to re-render after this call anyway, but really this @@ -632,8 +632,8 @@ export default class ParseApp { } setExpireInactiveSessions(require) { - let path = '/apps/' + this.slug; - let promise = AJAX.put(path, {'parse_app[expire_revocable_session]': require ? 'true' : 'false'}); + const path = '/apps/' + this.slug; + const promise = AJAX.put(path, {'parse_app[expire_revocable_session]': require ? 'true' : 'false'}); promise.then(() => { //TODO: this currently works because everything that uses this // happens to re-render after this call anyway, but really this @@ -644,8 +644,8 @@ export default class ParseApp { } setRevokeSessionOnPasswordChange(require) { - let path = '/apps/' + this.slug; - let promise = AJAX.put(path, {'parse_app[revoke_on_password_reset]': require ? 'true' : 'false'}); + const path = '/apps/' + this.slug; + const promise = AJAX.put(path, {'parse_app[revoke_on_password_reset]': require ? 'true' : 'false'}); promise.then(() => { //TODO: this currently works because everything that uses this // happens to re-render after this call anyway, but really this @@ -656,8 +656,8 @@ export default class ParseApp { } setEnableNewMethodsByDefault(require) { - let path = '/apps/' + this.slug; - let promise = AJAX.put(path, {'parse_app[auth_options_attributes][_enable_by_default_as_bool]': require ? 'true' : 'false'}); + const path = '/apps/' + this.slug; + const promise = AJAX.put(path, {'parse_app[auth_options_attributes][_enable_by_default_as_bool]': require ? 'true' : 'false'}); promise.then(() => { //TODO: this currently works because everything that uses this // happens to re-render after this call anyway, but really this @@ -668,8 +668,8 @@ export default class ParseApp { } setAllowUsernameAndPassword(require) { - let path = '/apps/' + this.slug; - let promise = AJAX.put(path, {'parse_app[auth_options_attributes][username_attributes][enabled_as_bool]': require ? 'true' : 'false'}); + const path = '/apps/' + this.slug; + const promise = AJAX.put(path, {'parse_app[auth_options_attributes][username_attributes][enabled_as_bool]': require ? 'true' : 'false'}); promise.then(() => { //TODO: this currently works because everything that uses this // happens to re-render after this call anyway, but really this @@ -680,8 +680,8 @@ export default class ParseApp { } setAllowAnonymousUsers(require) { - let path = '/apps/' + this.slug; - let promise = AJAX.put(path, {'parse_app[auth_options_attributes][anonymous_attributes][enabled_as_bool]': require ? 'true' : 'false'}); + const path = '/apps/' + this.slug; + const promise = AJAX.put(path, {'parse_app[auth_options_attributes][anonymous_attributes][enabled_as_bool]': require ? 'true' : 'false'}); promise.then(() => { //TODO: this currently works because everything that uses this // happens to re-render after this call anyway, but really this @@ -692,8 +692,8 @@ export default class ParseApp { } setAllowCustomAuthentication(require) { - let path = '/apps/' + this.slug; - let promise = AJAX.put(path, {'parse_app[auth_options_attributes][custom_attributes][enabled_as_bool]': require ? 'true' : 'false'}); + const path = '/apps/' + this.slug; + const promise = AJAX.put(path, {'parse_app[auth_options_attributes][custom_attributes][enabled_as_bool]': require ? 'true' : 'false'}); promise.then(() => { //TODO: this currently works because everything that uses this // happens to re-render after this call anyway, but really this @@ -704,8 +704,8 @@ export default class ParseApp { } setConnectedFacebookApps(idList, secretList) { - let path = '/apps/' + this.slug; - let promise = AJAX.put(path, { + const path = '/apps/' + this.slug; + const promise = AJAX.put(path, { 'parse_app[auth_options_attributes][facebook_attributes][app_ids_as_list]': idList.join(','), 'parse_app[auth_options_attributes][facebook_attributes][app_secrets_as_list]': secretList.join(','), }); @@ -717,14 +717,14 @@ export default class ParseApp { } addConnectedFacebookApp(newId, newSecret) { - let allIds = (this.settings.fields.fields.auth_options_attributes.facebook.app_ids || []).concat(newId); - let allSecrets = (this.settings.fields.fields.auth_options_attributes.facebook.app_secrets || []).concat(newSecret); + const allIds = (this.settings.fields.fields.auth_options_attributes.facebook.app_ids || []).concat(newId); + const allSecrets = (this.settings.fields.fields.auth_options_attributes.facebook.app_secrets || []).concat(newSecret); return this.setConnectedFacebookApps(allIds, allSecrets); } setAllowFacebookAuth(enable) { - let path = '/apps/' + this.slug; - let promise = AJAX.put(path, { + const path = '/apps/' + this.slug; + const promise = AJAX.put(path, { 'parse_app[auth_options_attributes][facebook_attributes][enabled_as_bool]': enable ? 'true' : 'false', }); promise.then(() => { @@ -734,8 +734,8 @@ export default class ParseApp { } setConnectedTwitterApps(consumerKeyList) { - let path = '/apps/' + this.slug; - let promise = AJAX.put(path, { + const path = '/apps/' + this.slug; + const promise = AJAX.put(path, { 'parse_app[auth_options_attributes][twitter_attributes][consumer_keys_as_list]': consumerKeyList.join(','), }); promise.then(() => { @@ -745,13 +745,13 @@ export default class ParseApp { } addConnectedTwitterApp(newConsumerKey) { - let allKeys = (this.settings.fields.fields.auth_options_attributes.twitter.consumer_keys || []).concat(newConsumerKey); + const allKeys = (this.settings.fields.fields.auth_options_attributes.twitter.consumer_keys || []).concat(newConsumerKey); return this.setConnectedTwitterApps(allKeys); } setAllowTwitterAuth(allow) { - let path = '/apps/' + this.slug; - let promise = AJAX.put(path, { + const path = '/apps/' + this.slug; + const promise = AJAX.put(path, { 'parse_app[auth_options_attributes][twitter_attributes][enabled_as_bool]': allow ? 'true' : 'false', }); promise.then(() => { @@ -769,8 +769,8 @@ export default class ParseApp { } addGCMCredentials(sender_id, api_key) { - let path = '/apps/' + this.slug + '/update_push_notifications' - let promise = AJAX.post(path, { + const path = '/apps/' + this.slug + '/update_push_notifications' + const promise = AJAX.post(path, { gcm_sender_id: sender_id, gcm_api_key: api_key }); @@ -781,8 +781,8 @@ export default class ParseApp { } deleteGCMPushCredentials(GCMSenderID) { - let path = '/apps/' + this.slug + '/delete_gcm_push_credential?gcm_sender_id='+GCMSenderID; - let promise = AJAX.get(path); + const path = '/apps/' + this.slug + '/delete_gcm_push_credential?gcm_sender_id=' + GCMSenderID; + const promise = AJAX.get(path); promise.then(() => { this.settings.fields.fields.gcm_credentials = this.settings.fields.fields.gcm_credentials.filter(cred => cred.sender_id != GCMSenderID diff --git a/src/lib/Position.js b/src/lib/Position.js index 491ee773bb..a9b41dcc2c 100644 --- a/src/lib/Position.js +++ b/src/lib/Position.js @@ -16,14 +16,14 @@ export default class Position { } static inDocument(node) { - let pos = Position.inWindow(node); + const pos = Position.inWindow(node); pos.x += window.pageXOffset; pos.y += window.pageYOffset; return pos; } static inWindow(node) { - let rect = node.getBoundingClientRect(); + const rect = node.getBoundingClientRect(); return new Position(rect.left, rect.top); } } diff --git a/src/lib/PropTypes.js b/src/lib/PropTypes.js index 692913d8a0..2d7a2ddb92 100644 --- a/src/lib/PropTypes.js +++ b/src/lib/PropTypes.js @@ -23,7 +23,7 @@ function wrapType(type, id) { type.isRequired._values = type._values; } type.describe = function(description) { - let wrapped = function(...args) { + const wrapped = function(...args) { return type.apply(type, args); } wrapped._id = type._id; diff --git a/src/lib/PushUtils.js b/src/lib/PushUtils.js index 6a9e7b16b8..fa09691f58 100644 --- a/src/lib/PushUtils.js +++ b/src/lib/PushUtils.js @@ -17,7 +17,7 @@ import React from 'react'; import stringList from 'lib/stringList'; // formats pointers into human readable form -let pointerToReadbleValue = (value) => { +const pointerToReadbleValue = (value) => { return value.className + ':' + value.objectId } @@ -27,12 +27,12 @@ let pointerToReadbleValue = (value) => { * @param {Object} * @return {String} */ -let objectToReadable = (value) => { +const objectToReadable = (value) => { if (value === undefined || value === null) { return ''; } - let typeValue = value['__type']; + const typeValue = value['__type']; let res = ''; switch(typeValue) { case 'Pointer': @@ -69,11 +69,11 @@ let objectToReadable = (value) => { * @param {Boolean} * @return {String} */ -let humanizedList = (value, inclusive, all) => { +const humanizedList = (value, inclusive, all) => { if(!value.constructor === Array){ return ''; } - let join = all ? 'and' : 'or'; + const join = all ? 'and' : 'or'; let prefix = ''; let res = ''; switch (value.length) { @@ -89,7 +89,7 @@ let humanizedList = (value, inclusive, all) => { break; default: prefix = all ? 'all of' : 'any of'; - res = `${join} ${objectToReadable(value[value.length-1])}`; + res = `${join} ${objectToReadable(value[value.length - 1])}`; break; } return res; @@ -106,7 +106,7 @@ let humanizedList = (value, inclusive, all) => { * @param {Object} * @return {Array} */ -let formatConstraintComponent = (key, operation, value, schema) => { +const formatConstraintComponent = (key, operation, value, schema) => { let res = null; switch (operation) { case '$lt': @@ -130,16 +130,16 @@ let formatConstraintComponent = (key, operation, value, schema) => { case '$in': case '$nin': case '$all': - let isInclusive = operation === '$in'; + const isInclusive = operation === '$in'; if(!value.constructor === Array) { res = [key, `constraint is malformed (${operation} operator requires an array)`, '']; } else if (!schema[key]) { res = ['', `Cannot perform operation on non-existent column ${key}`, '']; } else if (schema[key]['type'] === 'Array'){ - let isAll = operation === '$all'; + const isAll = operation === '$all'; res = [key, - isInclusive || isAll ? 'contains' : 'does not contain', - humanizedList(value, isInclusive, isAll)]; + isInclusive || isAll ? 'contains' : 'does not contain', + humanizedList(value, isInclusive, isAll)]; } break; default: @@ -156,9 +156,9 @@ let formatConstraintComponent = (key, operation, value, schema) => { * @param {Object} * @return {Array} */ -let formatStructure = (key, constraints, schema) => { - let rows = []; - for(let prop in constraints){ +const formatStructure = (key, constraints, schema) => { + const rows = []; + for(const prop in constraints){ if(Object.prototype.hasOwnProperty.call(constraints, prop)){ rows.push(formatConstraintComponent(key, prop, constraints[prop], schema)); } @@ -182,7 +182,7 @@ export function formatConstraint(key, constraints, schema) { rows.push(formatStructure(key, constraints, schema)); } else if(constraints.constructor === Array) { // legacy comment: Not sure how we want to display grouped subclauses - for(let i = 0; i { +const devicesToReadableList = (devices) => { return devices.map((device) => { return PushConstants.DEVICE_MAP[device]; }); @@ -220,9 +220,9 @@ export function shortInfoBuilder(query, schema) { return ''; } - let platformString = query.deviceType && query.deviceType['$in'] ? devicesToReadableList(query.deviceType['$in']).join(', ') : ''; - let otherConstraints = []; - for(let entry in query){ + const platformString = query.deviceType && query.deviceType['$in'] ? devicesToReadableList(query.deviceType['$in']).join(', ') : ''; + const otherConstraints = []; + for(const entry in query){ if(entry !== 'deviceType'){ //filter out deviceType entry formatConstraint(entry, query[entry], schema).forEach( (constraint) => { @@ -248,10 +248,10 @@ export function largeInfoBuilder(query, schema, styles = {}) { if(!query) { return; } - let platforms = query.deviceType && query.deviceType['$in'] ? devicesToReadableList(query.deviceType['$in']) : []; - let platformRows = []; + const platforms = query.deviceType && query.deviceType['$in'] ? devicesToReadableList(query.deviceType['$in']) : []; + const platformRows = []; - for (let platform in platforms) { + for (const platform in platforms) { platformRows.push(
  • {platforms[platform]} @@ -259,8 +259,8 @@ export function largeInfoBuilder(query, schema, styles = {}) { ); } - let conditionRows = []; - for(let entry in query){ + const conditionRows = []; + for(const entry in query){ if(entry !== 'deviceType'){ //filter out deviceType entry formatConstraint(entry, query[entry], schema).forEach( (constraint) => { @@ -294,7 +294,7 @@ export function largeInfoBuilder(query, schema, styles = {}) { ) } -let tableInfoBuilderHelper = (styles, key, description, value) => { +const tableInfoBuilderHelper = (styles, key, description, value) => { return ( {key} @@ -313,14 +313,14 @@ export function tableInfoBuilder(query, schema, styles = {}) { return; } - let platforms = query.deviceType && query.deviceType['$in'] ? devicesToReadableList(query.deviceType['$in']) : []; + const platforms = query.deviceType && query.deviceType['$in'] ? devicesToReadableList(query.deviceType['$in']) : []; // special case: ex: {deviceType: "ios"} if (query.deviceType && query.deviceType.constructor === String) { platforms.push(query.deviceType) } - let platformStr = stringList(platforms, 'or'); - let tableInfoRows = []; + const platformStr = stringList(platforms, 'or'); + const tableInfoRows = []; if (platformStr) { tableInfoRows.push( @@ -332,7 +332,7 @@ export function tableInfoBuilder(query, schema, styles = {}) { ); } - for(let entry in query){ + for(const entry in query){ if(entry !== 'deviceType'){ //filter out deviceType entry formatConstraint(entry, query[entry], schema).forEach( (constraint) => { @@ -345,7 +345,7 @@ export function tableInfoBuilder(query, schema, styles = {}) { ); } else { // case 2: contraint = [key, description, value] - let [key, description, value] = constraint; + const [key, description, value] = constraint; tableInfoRows.push(tableInfoBuilderHelper(styles, key, description, value)); } } @@ -366,9 +366,9 @@ export function formatCountDetails(count, approximate) { } export function formatAudienceSchema(classes) { - let schema = {}; + const schema = {}; if(classes){ - let installations = classes.get('_Installation'); + const installations = classes.get('_Installation'); if(typeof(installations) !== 'undefined'){ installations.forEach((type, col) => { schema[col] = type; diff --git a/src/lib/StringEscaping.js b/src/lib/StringEscaping.js index 0e5966d086..d875a3997c 100644 --- a/src/lib/StringEscaping.js +++ b/src/lib/StringEscaping.js @@ -14,12 +14,12 @@ const UNESCAPE_MAP = { '"': '"' }; const ESCAPE_MAP = {}; -for (let k in UNESCAPE_MAP) { +for (const k in UNESCAPE_MAP) { ESCAPE_MAP[UNESCAPE_MAP[k]] = k; } -let escapeMatcher = RegExp('(?:' + (Object.keys(ESCAPE_MAP).join('|')) + ')', 'g'); -let unescapeMatcher = RegExp('(?:' + (Object.keys(UNESCAPE_MAP).join('|')) + ')', 'g'); +const escapeMatcher = RegExp('(?:' + (Object.keys(ESCAPE_MAP).join('|')) + ')', 'g'); +const unescapeMatcher = RegExp('(?:' + (Object.keys(UNESCAPE_MAP).join('|')) + ')', 'g'); export function escape(str) { return str.replace(escapeMatcher, function(ch) { diff --git a/src/lib/encodeFormData.js b/src/lib/encodeFormData.js index e873e5883f..5743bb0f0b 100644 --- a/src/lib/encodeFormData.js +++ b/src/lib/encodeFormData.js @@ -19,14 +19,14 @@ export default function encodeFormData(key, value, prevKey) { if (value && typeof value.toJSON === 'function') { return encodeURI(field) + '=' + encodeURI(value.toJSON()); } - let pieces = []; + const pieces = []; if (Array.isArray(value)) { for (let i = 0; i < value.length; i++) { pieces.push(encodeFormData('', value[i], field)); } return pieces.join('&'); } - for (let k in value) { + for (const k in value) { pieces.push(encodeFormData(k, value[k], field)); } return pieces.join('&'); diff --git a/src/lib/englishOrdinalIndicator.js b/src/lib/englishOrdinalIndicator.js index 83f88acdb2..b41408fb21 100644 --- a/src/lib/englishOrdinalIndicator.js +++ b/src/lib/englishOrdinalIndicator.js @@ -5,7 +5,7 @@ * This source code is licensed under the license found in the LICENSE file in * the root directory of this source tree. */ -let numberSuffix = (number) => { +const numberSuffix = (number) => { if (number > 3 && number < 21) { return 'th'; } diff --git a/src/lib/getSiteDomain.js b/src/lib/getSiteDomain.js index a80945c89f..b2da5a0bcc 100644 --- a/src/lib/getSiteDomain.js +++ b/src/lib/getSiteDomain.js @@ -6,6 +6,6 @@ * the root directory of this source tree. */ export default function getSiteDomain() { - let host = location.host.split('.'); + const host = location.host.split('.'); return location.protocol + '//' + host.slice(host.length - 2).join('.'); } diff --git a/src/lib/howLongAgo.js b/src/lib/howLongAgo.js index 04cd5a4d94..d5b92a04a6 100644 --- a/src/lib/howLongAgo.js +++ b/src/lib/howLongAgo.js @@ -22,7 +22,7 @@ export default function howLongAgo(date) { if (isNaN(date)) { return 'unknown time ago'; } - let delta = new Date() - date; + const delta = new Date() - date; if (delta < 0) { return 'in the future'; } diff --git a/src/lib/isInsidePopover.js b/src/lib/isInsidePopover.js index f2ec37a3c0..517911d396 100644 --- a/src/lib/isInsidePopover.js +++ b/src/lib/isInsidePopover.js @@ -1,12 +1,12 @@ export default function isInsidePopover(node) { - let cur = node.parentNode; - while (cur && cur.nodeType === 1) { - // If id starts with "fixed_wrapper", we consider it as the - // root element of the Popover component - if (/^fixed_wrapper/g.test(cur.id)) { - return true; - } - cur = cur.parentNode; + let cur = node.parentNode; + while (cur && cur.nodeType === 1) { + // If id starts with "fixed_wrapper", we consider it as the + // root element of the Popover component + if (/^fixed_wrapper/g.test(cur.id)) { + return true; + } + cur = cur.parentNode; } return false; } diff --git a/src/lib/keyMirror.js b/src/lib/keyMirror.js index 1a0ef1a3f0..8a92d9a203 100644 --- a/src/lib/keyMirror.js +++ b/src/lib/keyMirror.js @@ -10,7 +10,7 @@ * themselves */ export default function keyMirror(keys) { - let map = {}; + const map = {}; for (let i = 0; i < keys.length; i++) { map[keys[i]] = keys[i]; } diff --git a/src/lib/passwordStrength.js b/src/lib/passwordStrength.js index 84141adbae..046b46b892 100644 --- a/src/lib/passwordStrength.js +++ b/src/lib/passwordStrength.js @@ -21,14 +21,14 @@ export default function passwordStrength(password) { } // We approximate entropy by determining which character sets are included in // the password string. - let seen = { + const seen = { az: false, AZ: false, num: false, sym: false }; for (let i = password.length; i--;) { - let c = password.charCodeAt(i); + const c = password.charCodeAt(i); if (c > 47 && c < 58) { seen.num = true; } else if (c > 64 && c < 91) { @@ -38,11 +38,11 @@ export default function passwordStrength(password) { } } let range = 0; - for (let r in seen) { + for (const r in seen) { if (seen[r]) { range += rangeSize[r]; } } - let entropy = Math.log(range) / Math.log(2) * password.length; + const entropy = Math.log(range) / Math.log(2) * password.length; return (entropy > 60 ? 2 : 1); } diff --git a/src/lib/prettyNumber.js b/src/lib/prettyNumber.js index b1208e85bb..e469f557a5 100644 --- a/src/lib/prettyNumber.js +++ b/src/lib/prettyNumber.js @@ -15,8 +15,8 @@ export default function prettyNumber(number, places) { places = 3; } if (number.toFixed().length < places) { - let fullLength = number.toString().length; - let truncatedLength = number.toFixed().length; + const fullLength = number.toString().length; + const truncatedLength = number.toFixed().length; if (fullLength > truncatedLength) { // has a decimal piece return number.toFixed(places - truncatedLength); @@ -29,6 +29,6 @@ export default function prettyNumber(number, places) { shortened /= 1000; suffixIndex++; } - let remainder = places - shortened.toFixed().length; + const remainder = places - shortened.toFixed().length; return shortened.toFixed(remainder) + SUFFIXES[suffixIndex]; } diff --git a/src/lib/queryFromFilters.js b/src/lib/queryFromFilters.js index bd74075c65..7f7671cf88 100644 --- a/src/lib/queryFromFilters.js +++ b/src/lib/queryFromFilters.js @@ -22,9 +22,9 @@ export default function queryFromFilters(className, filters) { } function addQueryConstraintFromObject(query, filter, constraintType) { - let compareTo = JSON.parse(filter.get('compareTo')); - for (let key of Object.keys(compareTo)) { - query[constraintType](filter.get('field')+'.'+key, compareTo[key]); + const compareTo = JSON.parse(filter.get('compareTo')); + for (const key of Object.keys(compareTo)) { + query[constraintType](filter.get('field') + '.' + key, compareTo[key]); } } diff --git a/src/lib/renderFlowFooterChanges.js b/src/lib/renderFlowFooterChanges.js index 0f6c1243f8..29fab9a102 100644 --- a/src/lib/renderFlowFooterChanges.js +++ b/src/lib/renderFlowFooterChanges.js @@ -23,12 +23,12 @@ import setDifference from 'lib/setDifference'; // Note: key_name is snake_case because in most cases it will come directly from ruby, which // uses snake_case export default (changes, initial, fieldOptions) => { - let booleanChanges = []; - let stringChangesWithTo = []; - let stringChanges = []; - let additions = []; - let setChanges = []; - for (let key in changes) { + const booleanChanges = []; + const stringChangesWithTo = []; + const stringChanges = []; + const additions = []; + const setChanges = []; + for (const key in changes) { if (fieldOptions[key]) { if (fieldOptions[key].type === 'boolean') { @@ -52,16 +52,16 @@ export default (changes, initial, fieldOptions) => { {fieldOptions[key].showTo ? to {changes[key]} : null} ); } else if (fieldOptions[key].type === 'set') { - let additionsToSet = setDifference(changes[key], initial[key], fieldOptions[key].equalityPredicate); - let removalsFromSet = setDifference(initial[key], changes[key], fieldOptions[key].equalityPredicate); + const additionsToSet = setDifference(changes[key], initial[key], fieldOptions[key].equalityPredicate); + const removalsFromSet = setDifference(initial[key], changes[key], fieldOptions[key].equalityPredicate); - let friendlyAddition = additionsToSet.length > 1 ? fieldOptions[key].friendlyNamePlural : fieldOptions[key].friendlyName; - let friendlyRemoval = removalsFromSet.length > 1 ? fieldOptions[key].friendlyNamePlural : fieldOptions[key].friendlyName; + const friendlyAddition = additionsToSet.length > 1 ? fieldOptions[key].friendlyNamePlural : fieldOptions[key].friendlyName; + const friendlyRemoval = removalsFromSet.length > 1 ? fieldOptions[key].friendlyNamePlural : fieldOptions[key].friendlyName; if (additionsToSet.length > 0) { - setChanges.push(added {additionsToSet.length} {friendlyAddition}); + setChanges.push(added {additionsToSet.length} {friendlyAddition}); } if (removalsFromSet.length > 0) { - setChanges.push(removed {removalsFromSet.length} {friendlyRemoval}); + setChanges.push(removed {removalsFromSet.length} {friendlyRemoval}); } } else { @@ -73,11 +73,11 @@ export default (changes, initial, fieldOptions) => { } } - let renderChangeList = (prefix, changes, isLastList) => { + const renderChangeList = (prefix, changes, isLastList) => { return joinWithFinal(prefix, changes, ', ', isLastList ? ' and ' : ', '); }; - let changesList = [ + const changesList = [ { changes: booleanChanges, prefix: null, @@ -99,7 +99,7 @@ export default (changes, initial, fieldOptions) => { prefix: 'changed your ', }, ]; - let allChangeNodes = changesList.filter(({ changes }) => changes.length > 0).map(({ changes, prefix }, index, wholeList) => + const allChangeNodes = changesList.filter(({ changes }) => changes.length > 0).map(({ changes, prefix }, index, wholeList) => renderChangeList(prefix, changes, index === wholeList.length - 1) ); return diff --git a/src/lib/setDifference.js b/src/lib/setDifference.js index d6853452df..723746f406 100644 --- a/src/lib/setDifference.js +++ b/src/lib/setDifference.js @@ -6,5 +6,5 @@ * the root directory of this source tree. */ export default function(first, second, equalityPredicate) { - return first.filter(itemFromFirst => !second.find(itemFromSecond => equalityPredicate(itemFromFirst, itemFromSecond))); + return first.filter(itemFromFirst => !second.find(itemFromSecond => equalityPredicate(itemFromFirst, itemFromSecond))); } diff --git a/src/lib/stores/AnalyticsQueryStore.js b/src/lib/stores/AnalyticsQueryStore.js index eceadd274d..3f03763432 100644 --- a/src/lib/stores/AnalyticsQueryStore.js +++ b/src/lib/stores/AnalyticsQueryStore.js @@ -57,15 +57,15 @@ const LABEL_TO_KEY_MAPPING = { }; // This is basically a const, but it's not declared inline. -let KEY_TO_LABEL_MAPPING = {}; -for (let key in LABEL_TO_KEY_MAPPING) { +const KEY_TO_LABEL_MAPPING = {}; +for (const key in LABEL_TO_KEY_MAPPING) { KEY_TO_LABEL_MAPPING[LABEL_TO_KEY_MAPPING[key]] = key; } const LAST_FETCH_TIMEOUT = 60000; -let queryToPayload = (query) => { - let payload = { +const queryToPayload = (query) => { + const payload = { sources: [LABEL_TO_KEY_MAPPING[query.source]], enabled: query.enabled, type: LABEL_TO_KEY_MAPPING[query.type], @@ -110,8 +110,8 @@ let queryToPayload = (query) => { return payload; }; -let payloadToQuery = (payload) => { - let query = { +const payloadToQuery = (payload) => { + const query = { name: payload.name, source: KEY_TO_LABEL_MAPPING[payload.sources[0]], enabled: payload.enabled, @@ -167,7 +167,7 @@ export const ActionTypes = keyMirror([ function AnalyticsQueryStore(state, action) { action.app.setParseKeys(); - let urlPrefix = `/apps/${action.app.slug}/explorer`; + const urlPrefix = `/apps/${action.app.slug}/explorer`; switch (action.type) { case ActionTypes.LIST: @@ -182,7 +182,7 @@ function AnalyticsQueryStore(state, action) { type = 'recent'; } return get(`${urlPrefix}/more?type=${type}&skip=0`).then((results) => { - let queries = {}; + const queries = {}; if (results) { results.forEach((payload) => { queries[payload.objectId] = payloadToQuery(payload); @@ -195,7 +195,7 @@ function AnalyticsQueryStore(state, action) { return post(urlPrefix, queryToPayload(action.query)).then((result) => { result.objectId = result.id; - let realResult = result[LABEL_TO_KEY_MAPPING[action.query.source]]; + const realResult = result[LABEL_TO_KEY_MAPPING[action.query.source]]; return state.setIn(['queries', result.id], { ...action.query, result: realResult }); }); case ActionTypes.UPDATE: diff --git a/src/lib/stores/ConfigStore.js b/src/lib/stores/ConfigStore.js index d30907b800..300ae9c49e 100644 --- a/src/lib/stores/ConfigStore.js +++ b/src/lib/stores/ConfigStore.js @@ -38,8 +38,8 @@ function ConfigStore(state, action) { { useMasterKey: true } ).then(() => { return state - .setIn(['params', action.param], action.value) - .setIn(['masterKeyOnly', action.param], action.masterKeyOnly); + .setIn(['params', action.param], action.value) + .setIn(['masterKeyOnly', action.param], action.masterKeyOnly); }); case ActionTypes.DELETE: return Parse._request( diff --git a/src/lib/stores/JobsStore.js b/src/lib/stores/JobsStore.js index 8147dbdec6..e7965833fd 100644 --- a/src/lib/stores/JobsStore.js +++ b/src/lib/stores/JobsStore.js @@ -35,7 +35,7 @@ function JobsStore(state, action) { case ActionTypes.CREATE: path = 'cloud_code/jobs'; return Parse._request('POST', path, action.schedule, {useMasterKey: true}).then((result) => { - let { ...schedule } = action.schedule.job_schedule; + const { ...schedule } = action.schedule.job_schedule; schedule.objectId = result.objectId; schedule.startAfter = schedule.startAfter || new Date().toISOString(); return state.set('jobs', state.get('jobs').push(schedule)); @@ -43,9 +43,9 @@ function JobsStore(state, action) { case ActionTypes.EDIT: path = `cloud_code/jobs/${action.jobId}`; return Parse._request('PUT', path, action.updates, {useMasterKey: true}).then(() => { - let index = state.get('jobs').findIndex((j) => j.objectId === action.jobId); - let current = state.get('jobs').get(index); - let { ...update } = action.updates.job_schedule; + const index = state.get('jobs').findIndex((j) => j.objectId === action.jobId); + const current = state.get('jobs').get(index); + const { ...update } = action.updates.job_schedule; update.objectId = current.objectId; update.timeOfDay = update.timeOfDay || current.timeOfDay; return state.set('jobs', state.get('jobs').set(index, update)); @@ -53,7 +53,7 @@ function JobsStore(state, action) { case ActionTypes.DELETE: path = `cloud_code/jobs/${action.jobId}`; return Parse._request('DELETE', path, {}, {useMasterKey: true}).then(() => { - let index = state.get('jobs').findIndex((j) => j.objectId === action.jobId); + const index = state.get('jobs').findIndex((j) => j.objectId === action.jobId); return state.set('jobs', state.get('jobs').delete(index)); }, () => { return state; diff --git a/src/lib/stores/PushAudiencesStore.js b/src/lib/stores/PushAudiencesStore.js index 0cc42e05a8..2ecc6e501b 100644 --- a/src/lib/stores/PushAudiencesStore.js +++ b/src/lib/stores/PushAudiencesStore.js @@ -37,27 +37,27 @@ function PushAudiencesStore(state, action) { }); case ActionTypes.CREATE: return Parse._request('POST', 'push_audiences', { query: action.query, name: action.name, }, { useMasterKey: true }) - .then(({ new_audience }) => { - return state.update('audiences',(audiences) => { - return audiences.unshift({ - createdAt: new Date(), - name: action.name, - objectId: new_audience ? new_audience.objectId || -1 : -1, - count: 0, - query: JSON.parse(action.query), - }); + .then(({ new_audience }) => { + return state.update('audiences',(audiences) => { + return audiences.unshift({ + createdAt: new Date(), + name: action.name, + objectId: new_audience ? new_audience.objectId || -1 : -1, + count: 0, + query: JSON.parse(action.query), }); }); + }); case ActionTypes.DESTROY: return Parse._request('DELETE', `push_audiences/${action.objectId}`, {}, { useMasterKey: true }) - .then(() => { - return state.update('audiences',(audiences) => { - let index = audiences.findIndex(function(audience) { - return audience.objectId === action.objectId; - }); - return audiences.delete(index); + .then(() => { + return state.update('audiences',(audiences) => { + const index = audiences.findIndex(function(audience) { + return audience.objectId === action.objectId; }); + return audiences.delete(index); }); + }); case ActionTypes.ABORT_FETCH: return Promise.resolve(state); } diff --git a/src/lib/stores/SchemaStore.js b/src/lib/stores/SchemaStore.js index 2faf186dd5..2f84617682 100644 --- a/src/lib/stores/SchemaStore.js +++ b/src/lib/stores/SchemaStore.js @@ -35,8 +35,8 @@ function SchemaStore(state, action) { {}, { useMasterKey: true } ).then(({ results }) => { - let classes = {}; - let CLPs = {}; + const classes = {}; + const CLPs = {}; if (results) { results.forEach(({ className, fields, classLevelPermissions }) => { classes[className] = Map(fields); @@ -57,8 +57,8 @@ function SchemaStore(state, action) { { useMasterKey: true } ).then(({ fields, classLevelPermissions }) => { return state - .setIn(['classes', action.className], Map(fields)) - .setIn(['CLPs', action.className], Map(classLevelPermissions)); + .setIn(['classes', action.className], Map(fields)) + .setIn(['CLPs', action.className], Map(classLevelPermissions)); }); case ActionTypes.DROP_CLASS: return action.app.apiRequest( @@ -68,11 +68,11 @@ function SchemaStore(state, action) { { useMasterKey: true } ).then(() => { return state - .deleteIn(['classes', action.className]) - .deleteIn(['CLPs', action.className]); + .deleteIn(['classes', action.className]) + .deleteIn(['CLPs', action.className]); }); case ActionTypes.ADD_COLUMN: - let newField = { + const newField = { [action.name]: { type: action.columnType, required: action.required, @@ -91,7 +91,7 @@ function SchemaStore(state, action) { return state.setIn(['classes', action.className], Map(fields)); }); case ActionTypes.DROP_COLUMN: - let droppedField = { + const droppedField = { [action.name]: { __op: 'Delete' } diff --git a/src/lib/stores/StateManager.js b/src/lib/stores/StateManager.js index 216dcbfa67..d771efc945 100644 --- a/src/lib/stores/StateManager.js +++ b/src/lib/stores/StateManager.js @@ -42,7 +42,7 @@ export function setAppState(name, app, state) { if (!name) { throw new Error('Cannot set state without a state identifier'); } - let prev = getAppState(app.applicationId, name); + const prev = getAppState(app.applicationId, name); appStates[app.applicationId][name] = state; return prev; } @@ -62,7 +62,7 @@ export function setGlobalState(name, state) { if (!name) { throw new Error('Cannot set state without a state identifier'); } - let prev = getGlobalState(name); + const prev = getGlobalState(name); globalStates[name] = state; return prev; } diff --git a/src/lib/stores/StoreManager.js b/src/lib/stores/StoreManager.js index dd12cbf4de..b5016abce3 100644 --- a/src/lib/stores/StoreManager.js +++ b/src/lib/stores/StoreManager.js @@ -7,7 +7,7 @@ */ import * as StateManager from 'lib/stores/StateManager'; -let stores = {}; +const stores = {}; let subCount = 0; export function registerStore(name, store, isGlobal) { @@ -25,14 +25,14 @@ export function registerStore(name, store, isGlobal) { } export function getStore(name) { - let storeData = stores[name]; + const storeData = stores[name]; if (!storeData) { throw new Error( 'Unknown store! Attempted to retrieve store with the name ' + name ); } - let stateGetter = (storeData.isGlobal ? + const stateGetter = (storeData.isGlobal ? StateManager.getGlobalState : StateManager.getAppState ); @@ -41,8 +41,8 @@ export function getStore(name) { getData: stateGetter.bind(null, name), isGlobal: storeData.isGlobal, dispatch(type, params, app) { - let action = {...params, type, app}; - let newState = storeData.store(stateGetter(name, app), action); + const action = {...params, type, app}; + const newState = storeData.store(stateGetter(name, app), action); if (newState instanceof Promise) { return newState.then((result) => { if (storeData.isGlobal) { @@ -50,7 +50,7 @@ export function getStore(name) { } else { StateManager.setAppState(name, app, result); } - for (let id in storeData.subscribers) { + for (const id in storeData.subscribers) { storeData.subscribers[id](result); } }); @@ -60,13 +60,13 @@ export function getStore(name) { } else { StateManager.setAppState(name, app, newState); } - for (let id in storeData.subscribers) { + for (const id in storeData.subscribers) { storeData.subscribers[id](newState); } } }, subscribe(cb) { - let id = 'sub' + subCount++; + const id = 'sub' + subCount++; storeData.subscribers[id] = cb; return id; }, diff --git a/src/lib/stores/WebhookStore.js b/src/lib/stores/WebhookStore.js index 2e390efef6..e7037fd3f8 100644 --- a/src/lib/stores/WebhookStore.js +++ b/src/lib/stores/WebhookStore.js @@ -21,13 +21,13 @@ function WebhookStore(state, action) { action.app.setParseKeys(); switch (action.type) { case ActionTypes.FETCH: - let functionsPromise = Parse._request( + const functionsPromise = Parse._request( 'GET', 'hooks/functions', {}, { useMasterKey: true } ); - let triggersPromise = Parse._request( + const triggersPromise = Parse._request( 'GET', 'hooks/triggers', {}, @@ -35,12 +35,12 @@ function WebhookStore(state, action) { ); return Promise.all([functionsPromise, triggersPromise]).then(( [functions, - triggers] + triggers] ) => { return Map({ lastFetch: new Date(), webhooks: List(functions.concat(triggers))}); }); case ActionTypes.CREATE: - let addHookToStore = hook => state.set('webhooks', state.get('webhooks').push(hook)); + const addHookToStore = hook => state.set('webhooks', state.get('webhooks').push(hook)); if (action.functionName !== undefined) { return Parse._request( 'POST', @@ -73,7 +73,7 @@ function WebhookStore(state, action) { }, { useMasterKey: true } ).then((hook) => { - let index = state.get('webhooks').findIndex(existingHook => existingHook.functionName === hook.functionName); + const index = state.get('webhooks').findIndex(existingHook => existingHook.functionName === hook.functionName); return state.setIn(['webhooks', index], hook); }) } else { @@ -85,7 +85,7 @@ function WebhookStore(state, action) { }, { useMasterKey: true } ).then(hook => { - let index = state.get('webhooks').findIndex(existingHook => + const index = state.get('webhooks').findIndex(existingHook => existingHook.className === hook.className && existingHook.triggerName === hook.triggerName ); return state.setIn(['webhooks', index], hook); diff --git a/src/lib/stringList.js b/src/lib/stringList.js index f5779c21ba..398e640f72 100644 --- a/src/lib/stringList.js +++ b/src/lib/stringList.js @@ -17,7 +17,7 @@ * @return {String} human - friendly list */ export default function stringList(strings, endDelineator = 'and') { - let progress = []; + const progress = []; strings.forEach((s, i) => { if (i > 0) { if (i === strings.length - 1) { diff --git a/src/lib/subscribeTo.js b/src/lib/subscribeTo.js index 331b342012..8840823270 100644 --- a/src/lib/subscribeTo.js +++ b/src/lib/subscribeTo.js @@ -36,14 +36,14 @@ export default function subscribeTo(name, prop) { } }, []) - let dispatch = (type, params={}) => { + const dispatch = (type, params = {}) => { if (store.isGlobal) { return store.dispatch(type, params); } return store.dispatch(type, params, currentApp); }; - let extras = { + const extras = { [prop]: { data, dispatch, diff --git a/src/lib/tests/Authentication.test.js b/src/lib/tests/Authentication.test.js index df2fe102de..2c1b980029 100644 --- a/src/lib/tests/Authentication.test.js +++ b/src/lib/tests/Authentication.test.js @@ -62,79 +62,79 @@ function createAuthenticationResult(isAuthenticated, matchingUsername, appsUserH describe('Authentication', () => { it('does not authenticate with no users', () => { - let authentication = new Authentication(null, false); + const authentication = new Authentication(null, false); expect(authentication.authenticate({name: 'parse.dashboard', pass: 'abc123'})) .toEqual(createAuthenticationResult(false, null, null)); }); it('does not authenticate with no auth', () => { - let authentication = new Authentication(unencryptedUsers, false); + const authentication = new Authentication(unencryptedUsers, false); expect(authentication.authenticate(null)) .toEqual(createAuthenticationResult(false, null, null)); }); it('does not authenticate invalid user', () => { - let authentication = new Authentication(unencryptedUsers, false); + const authentication = new Authentication(unencryptedUsers, false); expect(authentication.authenticate({name: 'parse.invalid', pass: 'abc123'})) .toEqual(createAuthenticationResult(false, null, null)); }); it('does not authenticate valid user with invalid unencrypted password', () => { - let authentication = new Authentication(unencryptedUsers, false); + const authentication = new Authentication(unencryptedUsers, false); expect(authentication.authenticate({name: 'parse.dashboard', pass: 'xyz789'})) .toEqual(createAuthenticationResult(false, null, null)); }); it('authenticates valid user with valid unencrypted password', () => { - let authentication = new Authentication(unencryptedUsers, false); + const authentication = new Authentication(unencryptedUsers, false); expect(authentication.authenticate({name: 'parse.dashboard', pass: 'abc123'})) .toEqual(createAuthenticationResult(true, 'parse.dashboard', null)); }); it('returns apps if valid user', () => { - let authentication = new Authentication(unencryptedUsers, false); + const authentication = new Authentication(unencryptedUsers, false); expect(authentication.authenticate({name: 'parse.apps', pass: 'xyz789'})) .toEqual(createAuthenticationResult(true, 'parse.apps', apps)); }); it('authenticates valid user with valid encrypted password', () => { - let authentication = new Authentication(encryptedUsers, true); + const authentication = new Authentication(encryptedUsers, true); expect(authentication.authenticate({name: 'parse.dashboard', pass: 'abc123'})) .toEqual(createAuthenticationResult(true, 'parse.dashboard', null)); }); it('does not authenticate valid user with invalid encrypted password', () => { - let authentication = new Authentication(encryptedUsers, true); + const authentication = new Authentication(encryptedUsers, true); expect(authentication.authenticate({name: 'parse.dashboard', pass: 'xyz789'})) .toEqual(createAuthenticationResult(false, null, null)); }); it('authenticates valid user with valid username and usernameOnly', () => { - let authentication = new Authentication(unencryptedUsers, false); + const authentication = new Authentication(unencryptedUsers, false); expect(authentication.authenticate({name: 'parse.dashboard'}, true)) .toEqual(createAuthenticationResult(true, 'parse.dashboard', null)); }); it('does not authenticate valid user with valid username and no usernameOnly', () => { - let authentication = new Authentication(unencryptedUsers, false); + const authentication = new Authentication(unencryptedUsers, false); expect(authentication.authenticate({name: 'parse.dashboard'})) .toEqual(createAuthenticationResult(false, null, null)); }); it('authenticates valid user with valid username and usernameOnly and encrypted password', () => { - let authentication = new Authentication(encryptedUsers, true); + const authentication = new Authentication(encryptedUsers, true); expect(authentication.authenticate({name: 'parse.dashboard'}, true)) .toEqual(createAuthenticationResult(true, 'parse.dashboard', null)); }); it('makes readOnly auth when specified', () => { - let authentication = new Authentication(unencryptedUsers, false); + const authentication = new Authentication(unencryptedUsers, false); expect(authentication.authenticate({name: 'parse.readonly', pass: 'abc123'})) .toEqual(createAuthenticationResult(true, 'parse.readonly', null, true)); }); it('makes readOnly auth when specified in apps', () => { - let authentication = new Authentication(unencryptedUsers, false); + const authentication = new Authentication(unencryptedUsers, false); expect(authentication.authenticate({name: 'parse.readonly.apps', pass: 'abc123'})) .toEqual(createAuthenticationResult(true, 'parse.readonly.apps', readOnlyApps, false)); }); diff --git a/src/lib/tests/ColumnPreferences.test.js b/src/lib/tests/ColumnPreferences.test.js index ff70a9e5f5..3a09b9f3f3 100644 --- a/src/lib/tests/ColumnPreferences.test.js +++ b/src/lib/tests/ColumnPreferences.test.js @@ -11,7 +11,7 @@ jest.dontMock('../ColumnPreferences'); const ColumnPreferences = require('../ColumnPreferences'); -let mockStorage = {}; +const mockStorage = {}; window.localStorage = { setItem(key, value) { mockStorage[key] = value; diff --git a/src/lib/tests/DateUtils.test.js b/src/lib/tests/DateUtils.test.js index 080fa67013..1b667ffeea 100644 --- a/src/lib/tests/DateUtils.test.js +++ b/src/lib/tests/DateUtils.test.js @@ -33,8 +33,8 @@ describe('shortMonth', () => { describe('nextMonth', () => { it('returns the first day of the next month', () => { - let start = new Date(2001, 2, 3, 4, 5, 6); - let next = DateUtils.nextMonth(start); + const start = new Date(2001, 2, 3, 4, 5, 6); + const next = DateUtils.nextMonth(start); expect(next.getFullYear()).toBe(2001); expect(next.getMonth()).toBe(3); expect(next.getDate()).toBe(1); @@ -46,8 +46,8 @@ describe('nextMonth', () => { describe('prevMonth', () => { it('returns the first day of the previous month', () => { - let start = new Date(2001, 2, 3, 4, 5, 6); - let next = DateUtils.prevMonth(start); + const start = new Date(2001, 2, 3, 4, 5, 6); + const next = DateUtils.prevMonth(start); expect(next.getFullYear()).toBe(2001); expect(next.getMonth()).toBe(1); expect(next.getDate()).toBe(1); diff --git a/src/lib/tests/e2e.js b/src/lib/tests/e2e.js index a1d72f6f96..b8c1b1ec20 100644 --- a/src/lib/tests/e2e.js +++ b/src/lib/tests/e2e.js @@ -25,7 +25,7 @@ var dashboardSettings = { describe('e2e', () => { it('loads the dashboard on /dashboard', (done) => { - let app = express(); + const app = express(); let server; var p = new Promise(resolve => { app.use('/dashboard', ParseDashboard(dashboardSettings)); @@ -34,18 +34,18 @@ describe('e2e', () => { return p.then(() => { return rp('http://localhost:5051/dashboard'); }) - .then(result => { - let bundleLocation = result.match(/