Move a couple of files to typescript and remove unnecessary $timeout

Change-type: patch
Signed-off-by: Stevche Radevski <stevche@balena.io>
This commit is contained in:
Stevche Radevski 2019-12-06 11:06:20 +01:00 committed by Lorenzo Alberto Maria Ambrosi
parent 4e1f071951
commit 388852d6b7
8 changed files with 394 additions and 447 deletions

View File

@ -150,6 +150,7 @@ const TargetSelector = (props) => {
}
TargetSelector.propTypes = {
targets: propTypes.array,
disabled: propTypes.bool,
openDriveSelector: propTypes.func,
selection: propTypes.object,

View File

@ -14,158 +14,124 @@
* limitations under the License.
*/
'use strict'
import * as _ from 'lodash';
import * as propTypes from 'prop-types';
import * as React from 'react';
import styled from 'styled-components';
import * as TargetSelector from '../../components/drive-selector/target-selector.jsx';
import * as SvgIcon from '../../components/svg-icon/svg-icon.jsx';
import * as selectionState from '../../models/selection-state';
import * as settings from '../../models/settings';
import * as store from '../../models/store';
import * as analytics from '../../modules/analytics';
import * as exceptionReporter from '../../modules/exception-reporter';
import * as driveConstraints from '../../../../shared/drive-constraints';
import * as utils from '../../../../shared/utils';
const _ = require('lodash')
const propTypes = require('prop-types')
const React = require('react')
const driveConstraints = require('../../../../shared/drive-constraints')
const utils = require('../../../../shared/utils')
const TargetSelector = require('../../components/drive-selector/target-selector.jsx')
const SvgIcon = require('../../components/svg-icon/svg-icon.jsx')
const selectionState = require('../../models/selection-state')
const settings = require('../../models/settings')
const store = require('../../models/store')
const analytics = require('../../modules/analytics')
const exceptionReporter = require('../../modules/exception-reporter')
const StepBorder = styled.div<{
disabled: boolean;
left?: boolean;
right?: boolean;
}>`
height: 2px;
background-color: ${props =>
props.disabled
? props.theme.customColors.dark.disabled.foreground
: props.theme.customColors.dark.foreground};
position: absolute;
width: 124px;
top: 19px;
left: ${props => (props.left ? '-67px' : undefined)};
right: ${props => (props.right ? '-67px' : undefined)};
`;
/**
* @summary Get drive list label
* @function
* @public
*
* @returns {String} - 'list' of drives separated by newlines
*
* @example
* console.log(getDriveListLabel())
* > 'My Drive (/dev/disk1)\nMy Other Drive (/dev/disk2)'
*/
const getDriveListLabel = () => {
return _.join(_.map(selectionState.getSelectedDrives(), (drive) => {
return `${drive.description} (${drive.displayName})`
}), '\n')
}
return _.join(
_.map(selectionState.getSelectedDrives(), (drive: any) => {
return `${drive.description} (${drive.displayName})`;
}),
'\n',
);
};
/**
* @summary Open drive selector
* @function
* @public
* @param {Object} DriveSelectorService - drive selector service
*
* @example
* openDriveSelector(DriveSelectorService);
*/
const openDriveSelector = async (DriveSelectorService) => {
const openDriveSelector = async (DriveSelectorService: any) => {
try {
const drive = await DriveSelectorService.open()
const drive = await DriveSelectorService.open();
if (!drive) {
return
return;
}
selectionState.selectDrive(drive.device)
selectionState.selectDrive(drive.device);
analytics.logEvent('Select drive', {
device: drive.device,
unsafeMode: settings.get('unsafeMode') && !settings.get('disableUnsafeMode'),
applicationSessionUuid: store.getState().toJS().applicationSessionUuid,
flashingWorkflowUuid: store.getState().toJS().flashingWorkflowUuid
})
unsafeMode:
settings.get('unsafeMode') && !settings.get('disableUnsafeMode'),
applicationSessionUuid: (store as any).getState().toJS().applicationSessionUuid,
flashingWorkflowUuid: (store as any).getState().toJS().flashingWorkflowUuid,
});
} catch (error) {
exceptionReporter.report(error)
exceptionReporter.report(error);
}
}
};
/**
* @summary Reselect a drive
* @function
* @public
* @param {Object} DriveSelectorService - drive selector service
*
* @example
* reselectDrive(DriveSelectorService);
*/
const reselectDrive = (DriveSelectorService) => {
openDriveSelector(DriveSelectorService)
const reselectDrive = (DriveSelectorService: any) => {
openDriveSelector(DriveSelectorService);
analytics.logEvent('Reselect drive', {
applicationSessionUuid: store.getState().toJS().applicationSessionUuid,
flashingWorkflowUuid: store.getState().toJS().flashingWorkflowUuid
})
}
applicationSessionUuid: (store as any).getState().toJS().applicationSessionUuid,
flashingWorkflowUuid: (store as any).getState().toJS().flashingWorkflowUuid,
});
};
/**
* @summary Get memoized selected drives
* @function
* @public
*
* @example
* getMemoizedSelectedDrives()
*/
const getMemoizedSelectedDrives = utils.memoize(selectionState.getSelectedDrives, _.isEqual)
const getMemoizedSelectedDrives = utils.memoize(
selectionState.getSelectedDrives,
_.isEqual,
);
/**
* @summary Should the drive selection button be shown
* @function
* @public
*
* @returns {Boolean}
*
* @example
* shouldShowDrivesButton()
*/
const shouldShowDrivesButton = () => {
return !settings.get('disableExplicitDriveSelection')
}
return !settings.get('disableExplicitDriveSelection');
};
const getDriveSelectionStateSlice = () => ({
showDrivesButton: shouldShowDrivesButton(),
driveListLabel: getDriveListLabel(),
targets: getMemoizedSelectedDrives()
})
targets: getMemoizedSelectedDrives(),
});
const DriveSelector = ({
export const DriveSelector = ({
webviewShowing,
disabled,
nextStepDisabled,
hasDrive,
flashing,
DriveSelectorService
}) => {
DriveSelectorService,
}: any) => {
// TODO: inject these from redux-connector
const [ {
showDrivesButton,
driveListLabel,
targets
}, setStateSlice ] = React.useState(getDriveSelectionStateSlice())
const [
{ showDrivesButton, driveListLabel, targets },
setStateSlice,
] = React.useState(getDriveSelectionStateSlice());
React.useEffect(() => {
return store.observe(() => {
setStateSlice(getDriveSelectionStateSlice())
})
}, [])
return (store as any).observe(() => {
setStateSlice(getDriveSelectionStateSlice());
});
}, []);
const showStepConnectingLines = !webviewShowing || !flashing
const showStepConnectingLines = !webviewShowing || !flashing;
return (
<div className="box text-center relative">
{showStepConnectingLines && (
<React.Fragment>
<div
className="step-border-left"
disabled={disabled}
></div>
<div
className="step-border-right"
disabled={nextStepDisabled}
></div>
<StepBorder disabled={disabled} left />
<StepBorder disabled={nextStepDisabled} right />
</React.Fragment>
)}
<div className="center-block">
<SvgIcon
paths={[ '../../assets/drive.svg' ]}
disabled={disabled}
/>
<SvgIcon paths={['../../assets/drive.svg']} disabled={disabled} />
</div>
<div className="space-vertical-large">
@ -182,15 +148,14 @@ const DriveSelector = ({
/>
</div>
</div>
)
}
);
};
DriveSelector.propTypes = {
webviewShowing: propTypes.bool,
disabled: propTypes.bool,
nextStepDisabled: propTypes.bool,
hasDrive: propTypes.bool,
flashing: propTypes.bool
}
module.exports = DriveSelector
flashing: propTypes.bool,
DriveSelectorService: propTypes.object,
};

View File

@ -14,214 +14,221 @@
* limitations under the License.
*/
'use strict'
import * as _ from 'lodash';
import * as path from 'path';
import * as React from 'react';
import { Modal, Txt } from 'rendition';
import * as ProgressButton from '../../components/progress-button/progress-button.jsx';
import * as SvgIcon from '../../components/svg-icon/svg-icon.jsx';
import * as availableDrives from '../../models/available-drives';
import * as flashState from '../../models/flash-state';
import * as selection from '../../models/selection-state';
import * as store from '../../models/store';
import * as analytics from '../../modules/analytics';
import * as driveScanner from '../../modules/drive-scanner';
import * as imageWriter from '../../modules/image-writer';
import * as progressStatus from '../../modules/progress-status';
import * as notification from '../../os/notification';
import * as constraints from '../../../../shared/drive-constraints';
import * as messages from '../../../../shared/messages';
const React = require('react')
const _ = require('lodash')
const COMPLETED_PERCENTAGE = 100;
const SPEED_PRECISION = 2;
const { Modal, Txt } = require('rendition')
const messages = require('../../../../shared/messages')
const flashState = require('../../models/flash-state')
const driveScanner = require('../../modules/drive-scanner')
const progressStatus = require('../../modules/progress-status')
const notification = require('../../os/notification')
const analytics = require('../../modules/analytics')
const imageWriter = require('../../modules/image-writer')
const path = require('path')
const store = require('../../models/store')
const constraints = require('../../../../shared/drive-constraints')
const availableDrives = require('../../models/available-drives')
const selection = require('../../models/selection-state')
const SvgIcon = require('../../components/svg-icon/svg-icon.jsx')
const ProgressButton = require('../../components/progress-button/progress-button.jsx')
const COMPLETED_PERCENTAGE = 100
const SPEED_PRECISION = 2
const getWarningMessages = (drives, image) => {
const warningMessages = []
const getWarningMessages = (drives: any, image: any) => {
const warningMessages = [];
for (const drive of drives) {
if (constraints.isDriveSizeLarge(drive)) {
warningMessages.push(messages.warning.largeDriveSize(drive))
warningMessages.push(messages.warning.largeDriveSize(drive));
} else if (!constraints.isDriveSizeRecommended(drive, image)) {
warningMessages.push(messages.warning.unrecommendedDriveSize(image, drive))
warningMessages.push(
messages.warning.unrecommendedDriveSize(image, drive),
);
}
// TODO(Shou): we should consider adding the same warning dialog for system drives and remove unsafe mode
}
return warningMessages
}
return warningMessages;
};
const getErrorMessageFromCode = (errorCode) => {
const getErrorMessageFromCode = (errorCode: string) => {
// TODO: All these error codes to messages translations
// should go away if the writer emitted user friendly
// messages on the first place.
if (errorCode === 'EVALIDATION') {
return messages.error.validation()
return messages.error.validation();
} else if (errorCode === 'EUNPLUGGED') {
return messages.error.driveUnplugged()
return messages.error.driveUnplugged();
} else if (errorCode === 'EIO') {
return messages.error.inputOutput()
return messages.error.inputOutput();
} else if (errorCode === 'ENOSPC') {
return messages.error.notEnoughSpaceInDrive()
return messages.error.notEnoughSpaceInDrive();
} else if (errorCode === 'ECHILDDIED') {
return messages.error.childWriterDied()
return messages.error.childWriterDied();
}
return ''
}
return '';
};
const flashImageToDrive = async ($timeout, $state) => {
const devices = selection.getSelectedDevices()
const image = selection.getImage()
const drives = _.filter(availableDrives.getDrives(), (drive) => {
return _.includes(devices, drive.device)
})
const flashImageToDrive = async (goToSuccess: () => void) => {
const devices = selection.getSelectedDevices();
const image: any = selection.getImage();
const drives = _.filter(availableDrives.getDrives(), (drive: any) => {
return _.includes(devices, drive.device);
});
// eslint-disable-next-line no-magic-numbers
if (drives.length === 0 || flashState.isFlashing()) {
return ''
return '';
}
// Trigger Angular digests along with store updates, as the flash state
// updates. The angular components won't update without it.
// TODO: Remove once moved entirely to React
const unsubscribe = store.observe($timeout)
// Stop scanning drives when flashing
// otherwise Windows throws EPERM
driveScanner.stop()
driveScanner.stop();
const iconPath = '../../assets/icon.png'
const basename = path.basename(image.path)
const iconPath = '../../assets/icon.png';
const basename = path.basename(image.path);
try {
await imageWriter.flash(image.path, drives)
await imageWriter.flash(image.path, drives);
if (!flashState.wasLastFlashCancelled()) {
const flashResults = flashState.getFlashResults()
const flashResults: any = flashState.getFlashResults();
notification.send('Flash complete!', {
body: messages.info.flashComplete(basename, drives, flashResults.results.devices),
icon: iconPath
})
$state.go('success')
body: messages.info.flashComplete(
basename,
drives as any,
flashResults.results.devices,
),
icon: iconPath,
});
goToSuccess();
}
} catch (error) {
// When flashing is cancelled before starting above there is no error
if (!error) {
return ''
return '';
}
notification.send('Oops! Looks like the flash failed.', {
body: messages.error.flashFailure(path.basename(image.path), drives),
icon: iconPath
})
icon: iconPath,
});
let errorMessage = getErrorMessageFromCode(error.code)
let errorMessage = getErrorMessageFromCode(error.code);
if (!errorMessage) {
error.image = basename
analytics.logException(error)
errorMessage = messages.error.genericFlashError()
error.image = basename;
analytics.logException(error);
errorMessage = messages.error.genericFlashError();
}
return errorMessage
return errorMessage;
} finally {
availableDrives.setDrives([])
driveScanner.start()
unsubscribe()
availableDrives.setDrives([]);
driveScanner.start();
}
// Return ''
}
return '';
};
/**
* @summary Get progress button label
* @function
* @public
*
* @returns {String} progress button label
*
* @example
* const label = FlashController.getProgressButtonLabel()
*/
* @summary Get progress button label
* @function
* @public
*
* @returns {String} progress button label
*
* @example
* const label = FlashController.getProgressButtonLabel()
*/
const getProgressButtonLabel = () => {
if (!flashState.isFlashing()) {
return 'Flash!'
return 'Flash!';
}
return progressStatus.fromFlashState(flashState.getFlashState())
}
return progressStatus.fromFlashState(flashState.getFlashState());
};
const formatSeconds = (totalSeconds) => {
const formatSeconds = (totalSeconds: number) => {
if (!totalSeconds && !_.isNumber(totalSeconds)) {
return ''
return '';
}
// eslint-disable-next-line no-magic-numbers
const minutes = Math.floor(totalSeconds / 60)
const minutes = Math.floor(totalSeconds / 60);
// eslint-disable-next-line no-magic-numbers
const seconds = Math.floor(totalSeconds - minutes * 60)
const seconds = Math.floor(totalSeconds - minutes * 60);
return `${minutes}m${seconds}s`
}
return `${minutes}m${seconds}s`;
};
const Flash = ({
shouldFlashStepBeDisabled, lastFlashErrorCode, progressMessage,
$timeout, $state, DriveSelectorService
}) => {
const state = flashState.getFlashState()
const isFlashing = flashState.isFlashing()
const flashErrorCode = lastFlashErrorCode()
export const Flash = ({
shouldFlashStepBeDisabled,
lastFlashErrorCode,
progressMessage,
goToSuccess,
DriveSelectorService,
}: any) => {
const state: any = flashState.getFlashState();
const isFlashing = flashState.isFlashing();
const flashErrorCode = lastFlashErrorCode();
const [ warningMessages, setWarningMessages ] = React.useState([])
const [ errorMessage, setErrorMessage ] = React.useState('')
const [warningMessages, setWarningMessages] = React.useState<string[]>([]);
const [errorMessage, setErrorMessage] = React.useState('');
const handleWarningResponse = async (shouldContinue) => {
setWarningMessages([])
const handleWarningResponse = async (shouldContinue: boolean) => {
setWarningMessages([]);
if (!shouldContinue) {
DriveSelectorService.open()
return
DriveSelectorService.open();
return;
}
setErrorMessage(await flashImageToDrive($timeout, $state))
}
setErrorMessage(await flashImageToDrive(goToSuccess));
};
const handleFlashErrorResponse = (shouldRetry) => {
setErrorMessage('')
flashState.resetState()
const handleFlashErrorResponse = (shouldRetry: boolean) => {
setErrorMessage('');
flashState.resetState();
if (shouldRetry) {
analytics.logEvent('Restart after failure', {
applicationSessionUuid: store.getState().toJS().applicationSessionUuid,
flashingWorkflowUuid: store.getState().toJS().flashingWorkflowUuid
})
applicationSessionUuid: (store as any).getState().toJS().applicationSessionUuid,
flashingWorkflowUuid: (store as any).getState().toJS().flashingWorkflowUuid,
});
} else {
selection.clear()
}
selection.clear();
}
};
const tryFlash = async () => {
const devices = selection.getSelectedDevices()
const image = selection.getImage()
const drives = _.filter(availableDrives.getDrives(), (drive) => {
return _.includes(devices, drive.device)
})
const devices = selection.getSelectedDevices();
const image = selection.getImage();
const drives = _.filter(availableDrives.getDrives(), (drive: any) => {
return _.includes(devices, drive.device);
});
// eslint-disable-next-line no-magic-numbers
if (drives.length === 0 || flashState.isFlashing()) {
return
return;
}
const hasDangerStatus = constraints.hasListDriveImageCompatibilityStatus(drives, image)
const hasDangerStatus = constraints.hasListDriveImageCompatibilityStatus(
drives,
image,
);
if (hasDangerStatus) {
setWarningMessages(getWarningMessages(drives, image))
return
setWarningMessages(getWarningMessages(drives, image));
return;
}
setErrorMessage(await flashImageToDrive($timeout, $state))
}
setErrorMessage(await flashImageToDrive(goToSuccess));
};
return <React.Fragment>
return (
<React.Fragment>
<div className="box text-center">
<div className="center-block">
<SvgIcon paths={[ '../../assets/flash.svg' ]} disabled={shouldFlashStepBeDisabled}/>
<SvgIcon
paths={['../../assets/flash.svg']}
disabled={shouldFlashStepBeDisabled}
/>
</div>
<div className="space-vertical-large">
@ -232,53 +239,65 @@ const Flash = ({
percentage={state.percentage}
label={getProgressButtonLabel()}
disabled={Boolean(flashErrorCode) || shouldFlashStepBeDisabled}
callback={tryFlash}>
</ProgressButton>
callback={tryFlash}
></ProgressButton>
{
isFlashing && <button className="button button-link button-abort-write" onClick={imageWriter.cancel}>
{isFlashing && (
<button
className="button button-link button-abort-write"
onClick={imageWriter.cancel}
>
<span className="glyphicon glyphicon-remove-sign"></span>
</button>
}
{
!_.isNil(state.speed) && state.percentage !== COMPLETED_PERCENTAGE &&
)}
{!_.isNil(state.speed) && state.percentage !== COMPLETED_PERCENTAGE && (
<p className="step-footer step-footer-split">
{Boolean(state.speed) && <span >{`${state.speed.toFixed(SPEED_PRECISION)} MB/s`}</span>}
{!_.isNil(state.eta) && <span>{`ETA: ${formatSeconds(state.eta)}` }</span>}
{Boolean(state.speed) && (
<span>{`${state.speed.toFixed(SPEED_PRECISION)} MB/s`}</span>
)}
{!_.isNil(state.eta) && (
<span>{`ETA: ${formatSeconds(state.eta)}`}</span>
)}
</p>
}
)}
{
Boolean(state.failed) && <div className="target-status-wrap">
{Boolean(state.failed) && (
<div className="target-status-wrap">
<div className="target-status-line target-status-failed">
<span className="target-status-dot"></span>
<span className="target-status-quantity">{state.failed}</span>
<span className="target-status-message">{progressMessage.failed(state.failed)} </span>
<span className="target-status-message">
{progressMessage.failed(state.failed)}{' '}
</span>
</div>
</div>
}
)}
</div>
</div>
{/* eslint-disable-next-line no-magic-numbers */}
{warningMessages && warningMessages.length > 0 && <Modal
{warningMessages && warningMessages.length > 0 && (
<Modal
width={400}
titleElement={'Attention'}
cancel={() => handleWarningResponse(false)}
done={() => handleWarningResponse(true)}
cancelButtonProps={{
children: 'Change'
children: 'Change',
}}
action={'Continue'}
primaryButtonProps={{ primary: false, warning: true }}
>
{
_.map(warningMessages, (message) => <Txt whitespace="pre-line" mt={2}>{message}</Txt>)
}
{_.map(warningMessages, message => (
<Txt whitespace="pre-line" mt={2}>
{message}
</Txt>
))}
</Modal>
}
)}
{errorMessage && <Modal
{errorMessage && (
<Modal
width={400}
titleElement={'Attention'}
cancel={() => handleFlashErrorResponse(false)}
@ -287,9 +306,7 @@ const Flash = ({
>
<Txt>{errorMessage}</Txt>
</Modal>
}
)}
</React.Fragment>
}
module.exports = Flash
);
};

View File

@ -28,8 +28,8 @@ import * as middleEllipsis from '../../utils/middle-ellipsis';
import * as messages from '../../../../shared/messages';
import { bytesToClosestUnit } from '../../../../shared/units';
import * as DriveSelector from './DriveSelector';
import * as Flash from './Flash';
import { DriveSelector } from './DriveSelector';
import { Flash } from './Flash';
const getDrivesTitle = (selection: any) => {
const drives = selection.getSelectedDrives();
@ -55,7 +55,7 @@ const getImageBasename = (selection: any) => {
return selectionImageName || imageBasename;
};
const MainPage = ({ DriveSelectorService, $timeout, $state }: any) => {
const MainPage = ({ DriveSelectorService, $state }: any) => {
const setRefresh = React.useState(false)[1];
const [isWebviewShowing, setIsWebviewShowing] = React.useState(false);
React.useEffect(() => {
@ -127,8 +127,7 @@ const MainPage = ({ DriveSelectorService, $timeout, $state }: any) => {
<div className="col-xs">
<Flash
DriveSelectorService={DriveSelectorService}
$timeout={$timeout}
$state={$state}
goToSuccess={() => $state.go('success')}
shouldFlashStepBeDisabled={shouldFlashStepBeDisabled}
lastFlashErrorCode={lastFlashErrorCode}
progressMessage={progressMessage}

View File

@ -49,7 +49,7 @@ const Main = angular.module(MODULE_NAME, [
Main.component(
'mainPage',
react2angular(MainPage, [], ['DriveSelectorService', '$timeout', '$state']),
react2angular(MainPage, [], ['DriveSelectorService', '$state']),
);
Main.config(($stateProvider: any) => {

View File

@ -64,28 +64,6 @@ img[disabled] {
font-weight: 300;
}
%step-border {
height: 2px;
background-color: $palette-theme-dark-foreground;
position: absolute;
width: 124px;
top: 19px;
&[disabled] {
background-color: $palette-theme-dark-disabled-foreground;
}
}
.page-main .step-border-left {
@extend %step-border;
left: -67px;
}
.page-main .step-border-right {
@extend %step-border;
right: -67px;
}
.page-main .step-tooltip {
display: block;
margin: -5px auto -20px;

View File

@ -31,6 +31,8 @@ const {
const { colors } = require('./theme')
const theme = {
// TODO: Standardize how the colors are specified to match with rendition's format.
customColors: colors,
button: {
border: {
width: '0',

View File

@ -6342,21 +6342,6 @@ img[disabled] {
font-size: 16px;
font-weight: 300; }
.page-main .step-border-left, .page-main .step-border-right {
height: 2px;
background-color: #fff;
position: absolute;
width: 124px;
top: 19px; }
.page-main .step-border-left[disabled], .page-main .step-border-right[disabled] {
background-color: #787c7f; }
.page-main .step-border-left {
left: -67px; }
.page-main .step-border-right {
right: -67px; }
.page-main .step-tooltip {
display: block;
margin: -5px auto -20px;