F OpenNebula/one#5422: Add attach disk form (#1389)

This commit is contained in:
Sergio Betanzos authored and GitHub committed 2021-07-30 13:17:50 +02:00
1 parent c9f419ac5a
commit 599f79bf09
76 files changed
+1494 -468

No files matched your search

@@ -46,8 +46,8 @@ const useStyles = makeStyles({
const DialogConfirmation = memo(
({
open,
title,
open = true,
title = '',
subheader,
contentProps,
handleAccept,
@@ -105,7 +105,7 @@ const DialogConfirmation = memo(
}
)
DialogConfirmation.propTypes = {
export const DialogPropTypes = {
open: PropTypes.bool.isRequired,
title: PropTypes.string.isRequired,
subheader: PropTypes.string,
@@ -121,18 +121,7 @@ DialogConfirmation.propTypes = {
])
}
DialogConfirmation.defaultProps = {
open: true,
title: 'Confirmation dialog',
subheader: undefined,
contentProps: undefined,
handleAccept: undefined,
acceptButtonProps: undefined,
handleCancel: undefined,
cancelButtonProps: undefined,
handleEntering: undefined,
children: undefined
}
DialogConfirmation.propTypes = DialogPropTypes
DialogConfirmation.displayName = 'DialogConfirmation'
@@ -13,113 +13,78 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
import React, { memo } from 'react'
/* eslint-disable jsdoc/require-jsdoc */
import * as React from 'react'
import PropTypes from 'prop-types'
import {
useMediaQuery,
Button,
Dialog,
DialogTitle,
DialogContent,
DialogActions
} from '@material-ui/core'
import clsx from 'clsx'
import { makeStyles } from '@material-ui/core'
import { useForm, FormProvider } from 'react-hook-form'
import { yupResolver } from '@hookform/resolvers'
import { SubmitButton } from 'client/components/FormControl'
import { Tr } from 'client/components/HOC'
import { T } from 'client/constants'
import DialogConfirmation, { DialogPropTypes } from 'client/components/Dialogs/DialogConfirmation'
const DialogForm = memo(
({
open,
title,
values,
resolver,
onSubmit,
onCancel,
submitButtonProps,
children
}) => {
const isMobile = useMediaQuery(theme => theme.breakpoints.only('xs'))
const methods = useForm({
mode: 'onBlur',
reValidateMode: 'onSubmit',
defaultValues: values,
resolver: yupResolver(resolver())
})
return (
<Dialog
fullScreen={isMobile}
open={open}
maxWidth="lg"
scroll="paper"
PaperProps={{
style: {
height: isMobile ? '100%' : '80%',
width: isMobile ? '100%' : '80%'
}
}}
>
<DialogTitle>{Tr(title)}</DialogTitle>
<DialogContent dividers>
<FormProvider {...methods}>{children}</FormProvider>
</DialogContent>
{(onCancel || onSubmit) && (
<DialogActions>
{onCancel && (
<Button onClick={onCancel}>
{Tr(T.Cancel)}
</Button>
)}
{onSubmit && (
<SubmitButton
color='secondary'
data-cy="dg-form-submit-button"
isSubmitting={methods.formState.isSubmitting}
onClick={methods.handleSubmit(onSubmit)}
label={Tr(T.Save)}
{...submitButtonProps}
/>
)}
</DialogActions>
)}
</Dialog>
)
const useStyles = makeStyles(theme => ({
content: {
width: '80vw',
height: '60vh',
maxWidth: '100%',
maxHeight: '100%',
overflow: 'hidden',
display: 'flex',
flexDirection: 'column',
[theme.breakpoints.only('xs')]: {
width: '100vw',
height: '100vh'
}
}
)
}))
export const DialogFormPropTypes = {
open: PropTypes.bool.isRequired,
title: PropTypes.string.isRequired,
const DialogForm = ({ values, resolver, handleSubmit, dialogProps, children }) => {
const classes = useStyles()
const { className, ...contentProps } = dialogProps.contentProps ?? {}
dialogProps.contentProps = {
className: clsx(classes.content, className),
...contentProps
}
const methods = useForm({
mode: 'onBlur',
reValidateMode: 'onSubmit',
defaultValues: values,
resolver: yupResolver(resolver())
})
return (
<DialogConfirmation
handleAccept={handleSubmit && methods.handleSubmit(handleSubmit)}
acceptButtonProps={{
isSubmitting: methods.formState.isSubmitting
}}
{...dialogProps}
>
<FormProvider {...methods}>
{children}
</FormProvider>
</DialogConfirmation>
)
}
DialogForm.propTypes = {
values: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.any),
PropTypes.objectOf(PropTypes.any)
]),
resolver: PropTypes.func.isRequired,
onSubmit: PropTypes.func,
onCancel: PropTypes.func,
submitButtonProps: PropTypes.objectOf(PropTypes.any),
handleSubmit: PropTypes.func,
dialogProps: DialogPropTypes,
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.node),
PropTypes.node
PropTypes.node,
PropTypes.func
])
}
DialogForm.propTypes = DialogFormPropTypes
DialogForm.defaultProps = {
open: true,
title: 'Title dialog form',
values: {},
resolver: {},
onSubmit: undefined,
onCancel: undefined,
submitButtonProps: undefined,
children: null
}
export default DialogForm
@@ -17,11 +17,11 @@
import React, { useEffect } from 'react'
import PropTypes from 'prop-types'
import clsx from 'clsx'
import { makeStyles, Backdrop, CircularProgress } from '@material-ui/core'
import { useFetch } from 'client/hooks'
import { DialogConfirmation } from 'client/components/Dialogs'
import clsx from 'clsx'
const useStyles = makeStyles(theme => ({
backdrop: {
@@ -13,13 +13,13 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
import DialogForm, { DialogFormPropTypes } from 'client/components/Dialogs/DialogForm'
import DialogForm from 'client/components/Dialogs/DialogForm'
import DialogRequest from 'client/components/Dialogs/DialogRequest'
import DialogConfirmation from 'client/components/Dialogs/DialogConfirmation'
import DialogConfirmation, { DialogPropTypes } from 'client/components/Dialogs/DialogConfirmation'
export {
DialogForm,
DialogFormPropTypes,
DialogRequest,
DialogConfirmation
DialogConfirmation,
DialogPropTypes
}
@@ -68,6 +68,8 @@ const AutocompleteController = memo(
label={Tr(label)}
inputProps={{ ...inputProps, 'data-cy': cy }}
error={Boolean(error)}
variant='outlined'
margin='dense'
helperText={
Boolean(error) && <ErrorHelper label={error?.message} />
}
@@ -32,7 +32,7 @@ const CheckboxController = memo(
<Controller
render={({ onChange, value = false }) => (
<Tooltip title={Tr(tooltip) ?? ''}>
<FormControl error={Boolean(error)}>
<FormControl error={Boolean(error)} margin='dense'>
<FormControlLabel
control={
<Checkbox
@@ -13,17 +13,17 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
import React, { memo, createElement } from 'react'
import React, { memo } from 'react'
import PropTypes from 'prop-types'
import { TextField, MenuItem } from '@material-ui/core'
import { TextField } from '@material-ui/core'
import { Controller } from 'react-hook-form'
import { ErrorHelper } from 'client/components/FormControl'
import { Tr } from 'client/components/HOC'
const SelectController = memo(
({ control, cy, name, label, multiple, native, values, error, fieldProps }) => {
({ control, cy, name, label, multiple, values, error, fieldProps }) => {
const defaultValue = multiple ? [values?.[0]?.value] : values?.[0]?.value
return (
@@ -36,7 +36,9 @@ const SelectController = memo(
color='secondary'
select
fullWidth
SelectProps={{ displayEmpty: true, multiple, native }}
variant='outlined'
margin='dense'
SelectProps={{ native: true, multiple }}
label={Tr(label)}
inputProps={{ 'data-cy': cy }}
error={Boolean(error)}
@@ -44,11 +46,11 @@ const SelectController = memo(
FormHelperTextProps={{ 'data-cy': `${cy}-error` }}
{...fieldProps}
>
{values?.map(({ text, value = '' }) => createElement(
native ? 'option' : MenuItem,
{ key: `${name}-${value}`, value },
text
))}
{values?.map(({ text, value = '' }) =>
<option key={`${name}-${value}`} value={value}>
{text}
</option>
)}
</TextField>
)}
name={name}
@@ -67,7 +69,6 @@ SelectController.propTypes = {
name: PropTypes.string.isRequired,
label: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
multiple: PropTypes.bool,
native: PropTypes.bool,
values: PropTypes.arrayOf(PropTypes.object).isRequired,
error: PropTypes.oneOfType([
PropTypes.bool,
@@ -82,7 +83,6 @@ SelectController.defaultProps = {
name: '',
label: '',
multiple: false,
native: false,
values: [],
error: false,
fieldProps: undefined
@@ -33,7 +33,6 @@ const SliderController = memo(
<Grid container spacing={2} alignItems="center">
<Grid item xs>
<Slider
color='secondary'
value={typeof value === 'number' ? value : 0}
aria-labelledby={`slider-${name}`}
@@ -50,6 +49,8 @@ const SliderController = memo(
value={value ?? ''}
error={Boolean(error)}
type='number'
variant='outlined'
margin='dense'
inputProps={{
'data-cy': `${cy}-input`,
'aria-labelledby': `slider-${name}`,
@@ -32,6 +32,8 @@ const TextController = memo(
color='secondary'
value={value ?? ''}
type={type}
variant='outlined'
margin='dense'
{...(label && { label: Tr(label) })}
inputProps={{ 'data-cy': cy }}
error={Boolean(error)}
@@ -102,15 +102,21 @@ const CustomStepper = ({
))}
</Stepper>
<Box marginY={2} textAlign='end'>
<Button onClick={handleBack} disabled={disabledBack} data-cy='stepper-back-button'>
<Button
data-cy='stepper-back-button'
disabled={disabledBack}
onClick={handleBack}
size='small'
>
{Tr(T.Back)}
</Button>
<SubmitButton
color='secondary'
data-cy='stepper-next-button'
onClick={handleNext}
isSubmitting={isSubmitting}
label={activeStep === lastStep ? Tr(T.Finish) : Tr(T.Next)}
onClick={handleNext}
size='small'
/>
</Box>
</>
@@ -0,0 +1,139 @@
/* ------------------------------------------------------------------------- *
* Copyright 2002-2021, OpenNebula Project, OpenNebula Systems *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may *
* not use this file except in compliance with the License. You may obtain *
* a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import * as React from 'react'
import PropTypes from 'prop-types'
import {
Button,
ClickAwayListener,
Grow,
Paper,
Popper,
MenuItem,
MenuList
} from '@material-ui/core'
import { NavArrowDown } from 'iconoir-react'
import { useDialog } from 'client/hooks'
import { DialogForm } from 'client/components/Dialogs'
import { FormWithSchema } from 'client/components/Forms'
import FormStepper from 'client/components/FormStepper'
import { Translate } from 'client/components/HOC'
const ButtonToTriggerForm = ({ buttonProps = {}, title, options = [] }) => {
const isGroupButton = options.length > 1
const [anchorEl, setAnchorEl] = React.useState(null)
const open = Boolean(anchorEl)
const { display, show, hide, values: Form } = useDialog()
const { steps, defaultValues, resolver, fields, onSubmit: handleSubmit } = Form ?? {}
const handleTriggerSubmit = async formData => {
await handleSubmit(formData)
hide()
}
const openDialogForm = form => {
show(form)
handleClose()
}
const handleToggle = evt => setAnchorEl(prev => prev ? null : evt.currentTarget)
const handleClose = () => setAnchorEl(null)
return (
<>
<Button
color='secondary'
size='small'
variant='contained'
aria-describedby={buttonProps.cy ?? 'main-button-form'}
disabled={!options.length}
endIcon={isGroupButton && <NavArrowDown />}
onClick={evt =>
!isGroupButton ? openDialogForm(options[0].form) : handleToggle(evt)
}
{...buttonProps}
>
<Translate word={title} />
</Button>
{isGroupButton && (
<Popper
open={open}
anchorEl={anchorEl}
id={buttonProps.cy ?? 'main-button-form'}
transition
disablePortal
>
{({ TransitionProps }) => (
<Grow {...TransitionProps}>
<Paper variant='outlined'>
<ClickAwayListener onClickAway={handleClose}>
<MenuList disablePadding>
{options.map(({ cy, name, form = {}, onSubmit }) => (
<MenuItem
key={name}
data-cy={cy}
onClick={() => openDialogForm({ ...form, onSubmit })}
>
<Translate word={name} />
</MenuItem>
))}
</MenuList>
</ClickAwayListener>
</Paper>
</Grow>
)}
</Popper>
)}
{display && (
<DialogForm
resolver={resolver}
values={defaultValues}
handleSubmit={!steps ? handleTriggerSubmit : undefined}
dialogProps={{ title, handleCancel: hide }}
>
{steps ? (
<FormStepper steps={steps} schema={resolver} onSubmit={handleTriggerSubmit}/>
) : (
<FormWithSchema cy='form-dg' fields={fields} />
)}
</DialogForm>
)}
</>
)
}
ButtonToTriggerForm.propTypes = {
buttonProps: PropTypes.object,
title: PropTypes.string,
options: PropTypes.arrayOf(
PropTypes.shape({
cy: PropTypes.string,
name: PropTypes.string,
form: PropTypes.object
})
),
handleSubmit: PropTypes.func
}
ButtonToTriggerForm.displayName = 'VmStorageTab'
export default ButtonToTriggerForm
@@ -42,7 +42,7 @@ const FormWithSchema = ({ id, cy, fields }) => {
return (
<Grid container spacing={1}>
{fields?.map(
{fields?.map?.(
({ name, type, htmlType, values, dependOf, grid, ...restOfProps }) => {
const dataCy = `${cy}-${name}`
const inputName = id ? `${id}.${name}` : name
@@ -0,0 +1,162 @@
/* ------------------------------------------------------------------------- *
* Copyright 2002-2021, OpenNebula Project, OpenNebula Systems *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may *
* not use this file except in compliance with the License. You may obtain *
* a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
import * as yup from 'yup'
import { INPUT_TYPES, T, HYPERVISORS } from 'client/constants'
const { kvm, vcenter, firecracker, lxc } = HYPERVISORS
export const TARGET = {
name: 'TARGET',
label: 'Target device',
notOnHypervisors: [vcenter, firecracker, lxc],
tooltip: `
Device to map image disk.
If set, it will overwrite the default device mapping.`,
type: INPUT_TYPES.TEXT,
validation: yup
.string()
.trim()
.notRequired()
.default(undefined)
}
export const READONLY = {
name: 'READONLY',
label: 'Read only',
notOnHypervisors: [vcenter],
type: INPUT_TYPES.SELECT,
values: [
{ text: '', value: '' },
{ text: T.Yes, value: 'YES' },
{ text: T.No, value: 'NO' }
],
validation: yup
.string()
.trim()
.notRequired()
.default(undefined)
}
export const DEV_PREFIX = {
name: 'DEV_PREFIX',
label: 'BUS',
notOnHypervisors: [vcenter, firecracker, lxc],
type: INPUT_TYPES.SELECT,
values: [
{ text: '', value: '' },
{ text: 'Virtio', value: 'vd' },
{ text: 'CSI/SATA', value: 'sd' },
{ text: 'Parallel ATA (IDE)', value: 'hd' },
{ text: 'Custom', value: 'custom' }
],
validation: yup
.string()
.trim()
.notRequired()
.default(undefined)
}
export const VCENTER_ADAPTER_TYPE = {
name: 'VCENTER_ADAPTER_TYPE',
label: 'Bus adapter controller',
notOnHypervisors: [kvm, firecracker],
type: INPUT_TYPES.SELECT,
values: [
{ text: '', value: '' },
{ text: 'lsiLogic', value: 'lsiLogic' },
{ text: 'ide', value: 'ide' },
{ text: 'busLogic', value: 'busLogic' },
{ text: 'Custom', value: 'custom' }
],
validation: yup
.string()
.trim()
.notRequired()
.default(undefined)
}
export const VCENTER_DISK_TYPE = {
name: 'VCENTER_DISK_TYPE',
label: 'Disk provisioning type',
notOnHypervisors: [kvm, firecracker],
type: INPUT_TYPES.SELECT,
values: [
{ text: '', value: '' },
{ text: 'Thin', value: 'thin' },
{ text: 'Thick', value: 'thick' },
{ text: 'Eager Zeroed Thick', value: 'eagerZeroedThick' },
{ text: 'Custom', value: 'custom' }
],
validation: yup
.string()
.trim()
.notRequired()
.default(undefined)
}
export const CACHE = {
name: 'CACHE',
label: 'Cache',
notOnHypervisors: [vcenter, firecracker, lxc],
type: INPUT_TYPES.SELECT,
values: [
{ text: '', value: '' },
{ text: 'Default', value: 'default' },
{ text: 'Writethrough', value: 'writethrough' },
{ text: 'Writeback', value: 'writeback' },
{ text: 'Directsync', value: 'directsync' },
{ text: 'Unsafe', value: 'unsafe' }
],
validation: yup
.string()
.trim()
.notRequired()
.default(undefined)
}
export const IO = {
name: 'IO',
label: 'IO Policy',
notOnHypervisors: [vcenter, firecracker, lxc],
type: INPUT_TYPES.SELECT,
values: [
{ text: '', value: '' },
{ text: 'Threads', value: 'threads' },
{ text: 'Native', value: 'native' }
],
validation: yup
.string()
.trim()
.notRequired()
.default(undefined)
}
export const DISCARD = {
name: 'DISCARD',
label: 'Discard',
notOnHypervisors: [vcenter, firecracker, lxc],
type: INPUT_TYPES.SELECT,
values: [
{ text: '', value: '' },
{ text: 'Ignore', value: 'ignore' },
{ text: 'Unmap', value: 'unmap' }
],
validation: yup
.string()
.trim()
.notRequired()
.default(undefined)
}
@@ -0,0 +1,46 @@
/* ------------------------------------------------------------------------- *
* Copyright 2002-2021, OpenNebula Project, OpenNebula Systems *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may *
* not use this file except in compliance with the License. You may obtain *
* a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import React, { useCallback } from 'react'
import FormWithSchema from 'client/components/Forms/FormWithSchema'
import {
SCHEMA,
FIELDS
} from 'client/components/Forms/Vm/AttachDiskForm/ImageSteps/AdvancedOptions/schema'
import { T } from 'client/constants'
export const STEP_ID = 'advanced'
const AdvancedOptions = ({ hypervisor } = {}) => ({
id: STEP_ID,
label: T.AdvancedOptions,
resolver: () => SCHEMA(hypervisor),
optionsValidate: { abortEarly: false },
content: useCallback(
() => (
<FormWithSchema
cy='attach-disk-advanced'
id={STEP_ID}
fields={FIELDS(hypervisor)}
/>
),
[hypervisor]
)
})
export default AdvancedOptions
@@ -0,0 +1,49 @@
/* ------------------------------------------------------------------------- *
* Copyright 2002-2021, OpenNebula Project, OpenNebula Systems *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may *
* not use this file except in compliance with the License. You may obtain *
* a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import * as yup from 'yup'
import * as COMMON_FIELDS from 'client/components/Forms/Vm/AttachDiskForm/CommonFields'
import { INPUT_TYPES, HYPERVISORS } from 'client/constants'
import { getValidationFromFields } from 'client/utils'
const { vcenter } = HYPERVISORS
const SIZE = {
name: 'SIZE',
label: 'Size on instantiate',
tooltip: `
The size of the disk will be modified to match
this size when the template is instantiated`,
notOnHypervisors: [vcenter],
type: INPUT_TYPES.TEXT,
htmlType: 'number',
validation: yup
.number()
.typeError('Size value must be a number')
.notRequired()
.default(undefined)
}
export const FIELDS = hypervisor => [
SIZE,
...Object.values(COMMON_FIELDS)
]
.map(field => typeof field === 'function' ? field(hypervisor) : field)
.filter(({ notOnHypervisors } = {}) => !notOnHypervisors?.includes?.(hypervisor))
export const SCHEMA = hypervisor =>
yup.object(getValidationFromFields(FIELDS(hypervisor)))
@@ -0,0 +1,68 @@
/* ------------------------------------------------------------------------- *
* Copyright 2002-2021, OpenNebula Project, OpenNebula Systems *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may *
* not use this file except in compliance with the License. You may obtain *
* a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import React, { useCallback } from 'react'
import { useListForm } from 'client/hooks'
import { ImagesTable } from 'client/components/Tables'
import {
SCHEMA
} from 'client/components/Forms/Vm/AttachDiskForm/ImageSteps/ImagesTable/schema'
import { T } from 'client/constants'
export const STEP_ID = 'image'
const ImageStep = () => ({
id: STEP_ID,
label: T.Image,
resolver: () => SCHEMA,
content: useCallback(
({ data, setFormData }) => {
const selectedImage = data?.[0]
const {
handleSelect,
handleClear
} = useListForm({ key: STEP_ID, setList: setFormData })
const handleSelectedRows = rows => {
const { original } = rows?.[0] ?? {}
const { ID, NAME, UID, UNAME } = original ?? {}
const image = {
IMAGE_ID: ID,
IMAGE: NAME,
IMAGE_UID: UID,
IMAGE_UNAME: UNAME
}
ID !== undefined ? handleSelect(image) : handleClear()
}
return (
<ImagesTable
singleSelect
onlyGlobalSearch
onlyGlobalSelectedRows
initialState={{ selectedRowIds: { [selectedImage?.IMAGE_ID]: true } }}
onSelectedRowsChange={handleSelectedRows}
/>
)
}, [])
})
export default ImageStep
@@ -0,0 +1,23 @@
/* ------------------------------------------------------------------------- *
* Copyright 2002-2021, OpenNebula Project, OpenNebula Systems *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may *
* not use this file except in compliance with the License. You may obtain *
* a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
import * as yup from 'yup'
export const SCHEMA = yup
.array(yup.object())
.min(1, 'Select image')
.max(1, 'Max. one image selected')
.required('Image field is required')
.default([])
@@ -0,0 +1,38 @@
/* ------------------------------------------------------------------------- *
* Copyright 2002-2021, OpenNebula Project, OpenNebula Systems *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may *
* not use this file except in compliance with the License. You may obtain *
* a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import * as yup from 'yup'
import ImagesTable from 'client/components/Forms/Vm/AttachDiskForm/ImageSteps/ImagesTable'
import AdvancedOptions from 'client/components/Forms/Vm/AttachDiskForm/ImageSteps/AdvancedOptions'
const Steps = stepProps => {
const image = ImagesTable(stepProps)
const advanced = AdvancedOptions(stepProps)
const steps = [image, advanced]
const resolver = () => yup.object({
[image.id]: image.resolver(),
[advanced.id]: advanced.resolver()
})
const defaultValues = resolver().default()
return { steps, defaultValues, resolver }
}
export default Steps
@@ -0,0 +1,44 @@
/* ------------------------------------------------------------------------- *
* Copyright 2002-2021, OpenNebula Project, OpenNebula Systems *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may *
* not use this file except in compliance with the License. You may obtain *
* a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import React, { useCallback } from 'react'
import FormWithSchema from 'client/components/Forms/FormWithSchema'
import {
SCHEMA,
FIELDS
} from 'client/components/Forms/Vm/AttachDiskForm/VolatileSteps/AdvancedOptions/schema'
import { T } from 'client/constants'
export const STEP_ID = 'advanced'
const AdvancedOptions = ({ hypervisor } = {}) => ({
id: STEP_ID,
label: T.AdvancedOptions,
resolver: () => SCHEMA(hypervisor),
optionsValidate: { abortEarly: false },
content: useCallback(
() => <FormWithSchema
cy='attach-disk-advanced'
fields={FIELDS(hypervisor)}
id={STEP_ID}
/>,
[hypervisor]
)
})
export default AdvancedOptions
@@ -0,0 +1,29 @@
/* ------------------------------------------------------------------------- *
* Copyright 2002-2021, OpenNebula Project, OpenNebula Systems *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may *
* not use this file except in compliance with the License. You may obtain *
* a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import * as yup from 'yup'
import {
TARGET, READONLY, CACHE, IO, DISCARD, DEV_PREFIX, VCENTER_DISK_TYPE
} from 'client/components/Forms/Vm/AttachDiskForm/CommonFields'
import { getValidationFromFields } from 'client/utils'
export const FIELDS = hypervisor => [
TARGET, READONLY, CACHE, IO, DISCARD, DEV_PREFIX, VCENTER_DISK_TYPE
].filter(({ notOnHypervisors } = {}) => !notOnHypervisors?.includes?.(hypervisor))
export const SCHEMA = hypervisor =>
yup.object(getValidationFromFields(FIELDS(hypervisor)))
@@ -0,0 +1,44 @@
/* ------------------------------------------------------------------------- *
* Copyright 2002-2021, OpenNebula Project, OpenNebula Systems *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may *
* not use this file except in compliance with the License. You may obtain *
* a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import React, { useCallback } from 'react'
import FormWithSchema from 'client/components/Forms/FormWithSchema'
import {
SCHEMA,
FIELDS
} from 'client/components/Forms/Vm/AttachDiskForm/VolatileSteps/BasicConfiguration/schema'
import { T } from 'client/constants'
export const STEP_ID = 'configuration'
const BasicConfiguration = ({ hypervisor } = {}) => ({
id: STEP_ID,
label: T.Configuration,
resolver: () => SCHEMA(hypervisor),
optionsValidate: { abortEarly: false },
content: useCallback(
() => <FormWithSchema
cy='attach-disk-configuration'
fields={FIELDS(hypervisor)}
id={STEP_ID}
/>,
[hypervisor]
)
})
export default BasicConfiguration
@@ -0,0 +1,110 @@
/* ------------------------------------------------------------------------- *
* Copyright 2002-2021, OpenNebula Project, OpenNebula Systems *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may *
* not use this file except in compliance with the License. You may obtain *
* a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import * as yup from 'yup'
import { INPUT_TYPES, HYPERVISORS } from 'client/constants'
import { getValidationFromFields } from 'client/utils'
const { vcenter } = HYPERVISORS
const SIZE = {
name: 'SIZE',
label: 'Size',
type: INPUT_TYPES.TEXT,
htmlType: 'number',
validation: yup
.number()
.typeError('Size value must be a number')
.required('Size field is required')
.default(undefined)
}
const TYPE = hypervisor => ({
name: 'TYPE',
label: 'Disk type',
type: INPUT_TYPES.SELECT,
values: hypervisor === vcenter
? [{ text: 'FS', value: 'fs' }]
: [
{ text: 'FS', value: 'fs' },
{ text: 'Swap', value: 'swap' }
],
validation: yup
.string()
.trim()
.notRequired()
.default('fs')
})
const FORMAT = hypervisor => {
const typeFieldName = TYPE(hypervisor).name
return {
name: 'FORMAT',
label: 'Format',
type: INPUT_TYPES.SELECT,
dependOf: typeFieldName,
htmlType: type => type === 'swap' ? INPUT_TYPES.HIDDEN : undefined,
values: hypervisor === vcenter
? [{ text: 'Raw', value: 'raw' }]
: [
{ text: 'Raw', value: 'raw' },
{ text: 'qcow2', value: 'qcow2' }
],
validation: yup
.string()
.trim()
.when(typeFieldName, (type, schema) => type === 'swap'
? schema.notRequired()
: schema.required('Format field is required')
)
.default('raw')
}
}
const FILESYSTEM = hypervisor => ({
name: 'FS',
label: 'Filesystem',
notOnHypervisors: [vcenter],
type: INPUT_TYPES.SELECT,
dependOf: TYPE(hypervisor).name,
htmlType: type => type === 'swap' ? INPUT_TYPES.HIDDEN : undefined,
values: [ // TODO: sunstone-config => support_fs ???
{ text: '', value: '' },
{ text: 'ext4', value: 'ext4' },
{ text: 'ext3', value: 'ext3' },
{ text: 'ext2', value: 'ext2' },
{ text: 'xfs', value: 'xfs' }
],
validation: yup
.string()
.trim()
.notRequired()
.default(undefined)
})
export const FIELDS = hypervisor => [
SIZE,
TYPE,
FORMAT,
FILESYSTEM
]
.map(field => typeof field === 'function' ? field(hypervisor) : field)
.filter(({ notOnHypervisors } = {}) => !notOnHypervisors?.includes?.(hypervisor))
export const SCHEMA = hypervisor =>
yup.object(getValidationFromFields(FIELDS(hypervisor)))
@@ -0,0 +1,38 @@
/* ------------------------------------------------------------------------- *
* Copyright 2002-2021, OpenNebula Project, OpenNebula Systems *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may *
* not use this file except in compliance with the License. You may obtain *
* a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import * as yup from 'yup'
import BasicConfiguration from 'client/components/Forms/Vm/AttachDiskForm/VolatileSteps/BasicConfiguration'
import AdvancedOptions from 'client/components/Forms/Vm/AttachDiskForm/VolatileSteps/AdvancedOptions'
const Steps = stepProps => {
const configuration = BasicConfiguration(stepProps)
const advancedOptions = AdvancedOptions(stepProps)
const steps = [configuration, advancedOptions]
const resolver = () => yup.object({
[configuration.id]: configuration.resolver(),
[advancedOptions.id]: advancedOptions.resolver()
})
const defaultValues = resolver().default()
return { steps, defaultValues, resolver }
}
export default Steps
@@ -0,0 +1,22 @@
/* ------------------------------------------------------------------------- *
* Copyright 2002-2021, OpenNebula Project, OpenNebula Systems *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may *
* not use this file except in compliance with the License. You may obtain *
* a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
import ImageSteps from 'client/components/Forms/Vm/AttachDiskForm/ImageSteps'
import VolatileSteps from 'client/components/Forms/Vm/AttachDiskForm/VolatileSteps'
export {
ImageSteps,
VolatileSteps
}
@@ -13,47 +13,24 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
import * as React from 'react'
/* eslint-disable jsdoc/require-jsdoc */
import PropTypes from 'prop-types'
import { LinearProgress } from '@material-ui/core'
import { SCHEMA, FIELDS } from 'client/components/Forms/Vm/ResizeCapacityForm/schema'
import { useFetch, useSocket } from 'client/hooks'
import { useVmApi } from 'client/features/One'
const ResizeCapacityForm = ({ vm } = {}) => {
const { TEMPLATE = {} } = vm ?? {}
import VmTabs from 'client/components/Tabs/Vm'
const VmDetail = React.memo(({ id }) => {
const { getHooksSocket } = useSocket()
const { getVm } = useVmApi()
const {
data,
fetchRequest,
loading,
error
} = useFetch(getVm, getHooksSocket({ resource: 'vm', id }))
const handleRefetch = () => fetchRequest(id, { reload: true })
React.useEffect(() => {
fetchRequest(id)
}, [id])
if ((!data && !error) || loading) {
return <LinearProgress color='secondary' style={{ width: '100%' }} />
return {
resolver: () => SCHEMA,
defaultValues: SCHEMA.cast(TEMPLATE, { stripUnknown: true }),
fields: FIELDS
}
if (error) {
return <div>{error || 'Error'}</div>
}
return <VmTabs data={data} handleRefetch={handleRefetch} />
})
VmDetail.propTypes = {
id: PropTypes.string.isRequired
}
VmDetail.displayName = 'VmDetail'
ResizeCapacityForm.propTypes = {
vm: PropTypes.object
}
export default VmDetail
ResizeCapacityForm.displayName = 'ResizeCapacityForm'
export default ResizeCapacityForm
@@ -65,7 +65,6 @@ const PHYSICAL_CPU = {
.required('Physical CPU field is required')
.positive()
.default(undefined)
.resolve()
}
const VIRTUAL_CPU = {
@@ -74,8 +73,8 @@ const VIRTUAL_CPU = {
type: INPUT_TYPES.TEXT,
htmlType: 'number',
tooltip: `
Number of virtual cpus. This value is optional, the default
hypervisor behavior is used, usually one virtual CPU.`,
Number of virtual cpus. This value is optional, the default
hypervisor behavior is used, usually one virtual CPU.`,
validation: yup
.number()
.typeError('Virtual CPU value must be a number')
@@ -0,0 +1,21 @@
/* ------------------------------------------------------------------------- *
* Copyright 2002-2021, OpenNebula Project, OpenNebula Systems *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may *
* not use this file except in compliance with the License. You may obtain *
* a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
import ResizeCapacityForm from 'client/components/Forms/Vm/ResizeCapacityForm'
export * from 'client/components/Forms/Vm/AttachDiskForm'
export {
ResizeCapacityForm
}
@@ -75,7 +75,7 @@ const Group = () => {
<HeaderPopover
id="group-list"
icon={<GroupIcon />}
buttonProps={{ 'data-cy': 'header-group-button', variant: 'outlined' }}
buttonProps={{ 'data-cy': 'header-group-button' }}
headerTitle="Switch group"
>
{({ handleClose }) => (
@@ -59,7 +59,9 @@ const HeaderPopover = React.memo(({
aria-controls={anchorId}
aria-describedby={anchorId}
aria-haspopup='true'
variant='outlined'
onClick={handleOpen}
size='small'
{...buttonProps}
style={{ margin: '0 2px' }}
>
@@ -34,7 +34,7 @@ const User = React.memo(() => {
id='user-menu'
buttonLabel={user?.NAME}
icon={<UserIcon />}
buttonProps={{ 'data-cy': 'header-user-button', variant: 'outlined' }}
buttonProps={{ 'data-cy': 'header-user-button' }}
disablePadding
>
{() => (
@@ -55,7 +55,7 @@ const View = () => {
<HeaderPopover
id='view-list'
icon={<ViewIcon />}
buttonProps={{ 'data-cy': 'header-view-button', variant: 'outlined' }}
buttonProps={{ 'data-cy': 'header-view-button' }}
headerTitle='Switch view'
>
{({ handleClose }) => (
@@ -27,8 +27,7 @@ const Zone = memo(() => (
id='zone-menu'
icon={<ZoneIcon />}
buttonProps={{
'data-cy': 'header-zone-button',
variant: 'outlined'
'data-cy': 'header-zone-button'
}}
disablePadding
>
@@ -25,6 +25,9 @@ const useStyles = makeStyles(theme => ({
flexDirection: 'column',
height: '100%'
},
topPane: {
flex: 1
},
separator: {
position: 'relative',
cursor: 'row-resize',
@@ -103,24 +106,28 @@ const SplitPane = ({ children, containerProps }) => {
})
React.useEffect(() => {
if (!topHeight) {
if (!topHeight && children[1]) {
setTopHeight(document.body.clientHeight / 2)
topRef.current.style.flex = 'none'
}
topRef.current.style.height = `${topHeight}px`
}, [topHeight])
topRef.current.style.height = children[1]
? `${topHeight}px`
: `${splitPaneRef.current?.clientHeight}px`
}, [topHeight, children[1]])
return (
<div {...containerProps} className={classes.splitPane} ref={splitPaneRef}>
<div style={{ flex: 1 }} ref={topRef}>
<div className={classes.topPane} ref={topRef}>
{children[0]}
</div>
<Divider
className={classes.separator}
onTouchStart={onMouseDown}
onMouseDown={onMouseDown}
/>
{!!children[1] && (
<Divider
className={classes.separator}
onTouchStart={onMouseDown}
onMouseDown={onMouseDown}
/>
)}
{children[1]}
</div>
)
@@ -14,7 +14,7 @@
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import CategoryFilter from 'client/components/Tables/Enhanced/Utils/CategoryFilter'
import { CategoryFilter } from 'client/components/Tables/Enhanced/Utils'
import * as DatastoreModel from 'client/models/Datastore'
export default [
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import * as React from 'react'
import PropTypes from 'prop-types'
@@ -23,8 +22,17 @@ import { UseFiltersInstanceProps } from 'react-table'
import { Tr } from 'client/components/HOC'
const CategoryFilter = ({ title, column, accessorOption, multiple }) => {
/** @type {UseFiltersInstanceProps} */
/**
* Render category filter to table.
*
* @param {object} props - Props
* @param {string} props.title - Title category
* @param {UseFiltersInstanceProps} props.column - Column to filter by
* @param {string} [props.accessorOption] - Name of property option
* @param {boolean} [props.multiple] - If `true`, can be more than one filter
* @returns {React.JSXElementConstructor} Component JSX
*/
const CategoryFilter = ({ title, column, accessorOption, multiple = false }) => {
const {
setFilter,
id,
@@ -13,14 +13,13 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
/* eslint-disable jsdoc/check-types */
/* eslint-disable jsdoc/valid-types */
import * as React from 'react'
import PropTypes from 'prop-types'
import clsx from 'clsx'
import { makeStyles, fade, debounce, InputBase } from '@material-ui/core'
import { Search as SearchIcon } from 'iconoir-react'
import { UseGlobalFiltersInstanceProps, UseGlobalFiltersState } from 'react-table'
const useStyles = makeStyles(({ spacing, palette, shape, breakpoints }) => ({
search: {
@@ -55,14 +54,21 @@ const useStyles = makeStyles(({ spacing, palette, shape, breakpoints }) => ({
}
}))
const GlobalFilter = ({ useTableProps }) => {
/**
* Render search input.
*
* @param {object} props - Props
* @param {string} props.className - Class to wrapper root
* @param {UseGlobalFiltersInstanceProps} props.useTableProps - Table props
* @returns {React.JSXElementConstructor} Component JSX
*/
const GlobalFilter = ({ useTableProps, className }) => {
const classes = useStyles()
/**
* @type {import('react-table').UseGlobalFiltersInstanceProps &
* { state: import('react-table').UseGlobalFiltersState }}
*/
const { setGlobalFilter, state: { globalFilter } } = useTableProps
const { setGlobalFilter, state } = useTableProps
/** @type {UseGlobalFiltersState} */
const { globalFilter } = state
const [value, setValue] = React.useState(() => globalFilter)
@@ -72,7 +78,7 @@ const GlobalFilter = ({ useTableProps }) => {
)
return (
<div className={classes.search}>
<div className={clsx(classes.search, className)}>
<div className={classes.searchIcon}>
<SearchIcon />
</div>
@@ -94,6 +100,7 @@ const GlobalFilter = ({ useTableProps }) => {
}
GlobalFilter.propTypes = {
className: PropTypes.string,
useTableProps: PropTypes.object.isRequired
}
@@ -0,0 +1,65 @@
/* ------------------------------------------------------------------------- *
* Copyright 2002-2021, OpenNebula Project, OpenNebula Systems *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may *
* not use this file except in compliance with the License. You may obtain *
* a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
import * as React from 'react'
import PropTypes from 'prop-types'
import { TableProps } from 'react-table'
import { makeStyles, Chip } from '@material-ui/core'
const useStyles = makeStyles({
root: {
display: 'flex',
flexWrap: 'wrap',
gap: 6,
alignItems: 'center'
}
})
/**
* Render all selected rows.
*
* @param {object} props - Props
* @param {TableProps} props.useTableProps - Table props
* @returns {React.JSXElementConstructor} Component JSX
*/
const GlobalSelectedRows = ({ useTableProps }) => {
const classes = useStyles()
const { preFilteredRows, state: { selectedRowIds } } = useTableProps
const selectedRows = preFilteredRows.filter(row => !!selectedRowIds[row.id])
return (
<div className={classes.root}>
{React.useMemo(() =>
selectedRows?.map(({ original, id, toggleRowSelected }) => (
<Chip key={id}
label={original?.NAME ?? id}
onDelete={() => toggleRowSelected(false)}
/>
)),
[selectedRows[0]?.id]
)}
</div>
)
}
GlobalSelectedRows.propTypes = {
useTableProps: PropTypes.object.isRequired
}
GlobalSelectedRows.displayName = ' GlobalSelectedRows'
export default GlobalSelectedRows
@@ -21,6 +21,7 @@ import PropTypes from 'prop-types'
import { makeStyles, MenuItem, MenuList, Chip } from '@material-ui/core'
import { SortDown, ArrowDown, ArrowUp } from 'iconoir-react'
import { TableInstance, UseSortByInstanceProps, UseSortByState } from 'react-table'
import HeaderPopover from 'client/components/Header/Popover'
import { T } from 'client/constants'
@@ -34,19 +35,25 @@ const useStyles = makeStyles({
}
})
/**
* Render all selected sorters.
*
* @param {object} props - Props
* @param {TableInstance} props.useTableProps - Table props
* @returns {React.JSXElementConstructor} Component JSX
*/
const GlobalSort = ({ useTableProps }) => {
const classes = useStyles()
React.useEffect(() => () => setSortBy([]), [])
const { headers, state } = useTableProps
/**
* @type {
* import('react-table').UseSortByInstanceProps &
* import('react-table').TableInstance &
* { state: import('react-table').UseSortByState }
* }
*/
const { headers, setSortBy, state: { sortBy } } = useTableProps
/** @type {UseSortByInstanceProps} */
const { setSortBy } = useTableProps
/** @type {UseSortByState} */
const { sortBy } = state
React.useEffect(() => () => setSortBy([]), [])
const headersNotSorted = React.useMemo(() =>
headers.filter(({ isSorted, canSort, isVisible }) =>
@@ -74,8 +81,7 @@ const GlobalSort = ({ useTableProps }) => {
buttonLabel={T.SortBy}
buttonProps={{
'data-cy': 'sort-by-button',
disabled: headersNotSorted.length === 0,
variant: 'outlined'
disabled: headersNotSorted.length === 0
}}
popoverProps= {{
anchorOrigin: {
@@ -15,6 +15,7 @@
* ------------------------------------------------------------------------- */
import CategoryFilter from 'client/components/Tables/Enhanced/Utils/CategoryFilter'
import GlobalFilter from 'client/components/Tables/Enhanced/Utils/GlobalFilter'
import GlobalSelectedRows from 'client/components/Tables/Enhanced/Utils/GlobalSelectedRows'
import GlobalSort from 'client/components/Tables/Enhanced/Utils/GlobalSort'
import LabelFilter from 'client/components/Tables/Enhanced/Utils/LabelFilter'
@@ -23,6 +24,7 @@ export * from 'client/components/Tables/Enhanced/Utils/utils'
export {
CategoryFilter,
GlobalFilter,
GlobalSelectedRows,
GlobalSort,
LabelFilter
}
@@ -13,9 +13,18 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import { Column } from 'react-table'
import { CategoryFilter } from 'client/components/Tables/Enhanced/Utils'
/**
* Add filters defined in view yaml to columns.
*
* @param {object} config -
* @param {object[]} config.filters
* - List of criteria to filter the columns.
* @param {Column[]} config.columns - Columns
* @returns {object} Column with filters
*/
export const createColumns = ({ filters = {}, columns = [] }) => {
if (Object.keys(filters).length === 0) return columns
@@ -25,18 +34,23 @@ export const createColumns = ({ filters = {}, columns = [] }) => {
const filterById = !!filters[String(id.toLowerCase())]
const filterByAccessor =
typeof accessor === 'string' &&
!!filters[String(accessor.toLowerCase())]
typeof accessor === 'string' &&
!!filters[String(accessor.toLowerCase())]
return {
...column,
...((filterById || filterByAccessor) &&
createCategoryFilter(Header)
...((filterById || filterByAccessor) && createCategoryFilter(Header)
)
}
})
}
/**
* Create category filter as column.
*
* @param {string} title - Title
* @returns {Column} - Category filter
*/
export const createCategoryFilter = title => ({
disableFilters: false,
Filter: ({ column }) => CategoryFilter({
@@ -21,16 +21,16 @@ import clsx from 'clsx'
import { makeStyles, useMediaQuery, Card, CardContent } from '@material-ui/core'
import { UseTableInstanceProps } from 'react-table'
import GlobalFilter from 'client/components/Tables/Enhanced/Utils/GlobalFilter'
import { GlobalFilter } from 'client/components/Tables/Enhanced/Utils'
const useToolbarStyles = makeStyles({
root: {
display: 'flex'
},
rootNoFilters: {
gridColumn: '1/3',
gridColumn: '1 / -1',
'& ~ div': {
gridColumn: '1/3'
gridColumn: '1 / -1'
}
},
content: {
@@ -47,7 +47,7 @@ const useToolbarStyles = makeStyles({
}
})
const Filters = ({ useTableProps }) => {
const Filters = ({ onlyGlobalSearch, useTableProps }) => {
const classes = useToolbarStyles()
const isMobile = useMediaQuery(theme => theme.breakpoints.down('sm'))
@@ -64,8 +64,13 @@ const Filters = ({ useTableProps }) => {
) : null)
), [rows])
if (isMobile) {
return <GlobalFilter useTableProps={useTableProps} />
if (isMobile || onlyGlobalSearch) {
return (
<GlobalFilter
className={classes.rootNoFilters}
useTableProps={useTableProps}
/>
)
}
const noFilters = filters.length === 0
@@ -86,10 +91,12 @@ const Filters = ({ useTableProps }) => {
}
Filters.propTypes = {
onlyGlobalSearch: PropTypes.bool,
useTableProps: PropTypes.object
}
Filters.defaultProps = {
onlyGlobalSearch: false,
useTableProps: {}
}
@@ -26,17 +26,17 @@ import {
useRowSelect,
useSortBy,
useTable,
useMountedLayoutEffect,
// types
UseRowSelectRowProps
} from 'react-table'
import SplitPane from 'client/components/SplitPane'
import Toolbar from 'client/components/Tables/Enhanced/toolbar'
import Pagination from 'client/components/Tables/Enhanced/pagination'
import Filters from 'client/components/Tables/Enhanced/filters'
import EnhancedTableStyles from 'client/components/Tables/Enhanced/styles'
import { Translate, ConditionalWrap } from 'client/components/HOC'
import { Translate } from 'client/components/HOC'
import { T } from 'client/constants'
const EnhancedTable = ({
@@ -45,12 +45,15 @@ const EnhancedTable = ({
data,
fetchMore,
getRowId,
initialState,
isLoading,
onlyGlobalSearch,
onlyGlobalSelectedRows,
onSelectedRowsChange,
pageSize = 10,
renderAllSelected = true,
renderDetail,
RowComponent,
showPageCount
showPageCount,
singleSelect = false
}) => {
const classes = EnhancedTableStyles()
@@ -85,7 +88,8 @@ const EnhancedTable = ({
autoResetSortBy: false,
// -------------------------------------
initialState: {
pageSize
pageSize,
...initialState
}
},
useGlobalFilter,
@@ -98,6 +102,7 @@ const EnhancedTable = ({
const {
getTableProps,
prepareRow,
toggleAllRowsSelected,
preFilteredRows,
rows,
page,
@@ -106,10 +111,11 @@ const EnhancedTable = ({
state: { pageIndex, selectedRowIds }
} = useTableProps
const selectedRows = React.useMemo(
() => preFilteredRows.filter(row => !!selectedRowIds[row.id]),
[preFilteredRows, selectedRowIds]
)
useMountedLayoutEffect(() => {
const selectedRows = preFilteredRows.filter(row => !!selectedRowIds[row.id])
onSelectedRowsChange?.(selectedRows)
}, [selectedRowIds])
const handleChangePage = newPage => {
gotoPage(newPage)
@@ -120,98 +126,100 @@ const EnhancedTable = ({
}
return (
<ConditionalWrap
condition={selectedRows?.length > 0}
wrap={children => <SplitPane>{children}</SplitPane>}
>
<Box {...getTableProps()} className={classes.root}>
<div className={classes.toolbar}>
{!isFetching && <Toolbar useTableProps={useTableProps} />}
<div className={classes.pagination}>
{page?.length > 0 && (
<Pagination
handleChangePage={handleChangePage}
useTableProps={useTableProps}
count={rows.length}
showPageCount={showPageCount}
/>
)}
</div>
</div>
{isLoading && (
<LinearProgress size='1em' color='secondary' className={classes.loading} />
<Box {...getTableProps()} className={classes.root}>
<div className={classes.toolbar}>
{/* TOOLBAR */}
{!isFetching && (
<Toolbar
onlyGlobalSelectedRows={onlyGlobalSelectedRows}
useTableProps={useTableProps}
/>
)}
<div className={classes.table}>
{!isFetching && <Filters useTableProps={useTableProps} />}
<div className={classes.body}>
{/* NO DATA MESSAGE */}
{!isFetching && page?.length === 0 && (
<span className={classes.noDataMessage}>
<InfoEmpty />
<Translate word={T.NoDataAvailable} />
</span>
)}
{/* DATALIST PER PAGE */}
{page.map(row => {
prepareRow(row)
/** @type {UseRowSelectRowProps} */
const { getRowProps, original, values, toggleRowSelected, isSelected } = row
const { key, ...rowProps } = getRowProps()
return (
<RowComponent
{...rowProps}
key={key}
original={original}
value={values}
className={isSelected ? 'selected' : ''}
onClick={() => toggleRowSelected(!isSelected)}
/>
)
})}
</div>
{/* PAGINATION */}
<div className={classes.pagination}>
{page?.length > 0 && (
<Pagination
handleChangePage={handleChangePage}
useTableProps={useTableProps}
count={rows.length}
showPageCount={showPageCount}
/>
)}
</div>
</Box>
</div>
{selectedRows?.length > 0 && (
<div style={{ display: 'flex', flexDirection: 'column', overflow: 'auto' }}>
{selectedRows?.length === 1 && renderDetail
? renderDetail?.(selectedRows[0]?.values)
: renderAllSelected && (
<pre>
<code>
{JSON.stringify(Object.keys(selectedRowIds)?.join(', '), null, 2)}
</code>
</pre>
)
}
</div>
{isLoading && (
<LinearProgress size='1em' color='secondary' className={classes.loading} />
)}
</ConditionalWrap>
<div className={classes.table}>
{/* FILTERS */}
{!isFetching && (
<Filters
onlyGlobalSearch={onlyGlobalSearch}
useTableProps={useTableProps}
/>
)}
<div className={classes.body}>
{/* NO DATA MESSAGE */}
{!isFetching && page?.length === 0 && (
<span className={classes.noDataMessage}>
<InfoEmpty />
<Translate word={T.NoDataAvailable} />
</span>
)}
{/* DATALIST PER PAGE */}
{page.map(row => {
prepareRow(row)
/** @type {UseRowSelectRowProps} */
const { getRowProps, original, values, toggleRowSelected, isSelected } = row
const { key, ...rowProps } = getRowProps()
return (
<RowComponent
{...rowProps}
key={key}
original={original}
value={values}
className={isSelected ? 'selected' : ''}
onClick={() => {
singleSelect && toggleAllRowsSelected(false)
toggleRowSelected(!isSelected)
}}
/>
)
})}
</div>
</div>
</Box>
)
}
EnhancedTable.propTypes = {
export const EnhancedTableProps = {
canFetchMore: PropTypes.bool,
columns: PropTypes.array,
data: PropTypes.array,
fetchMore: PropTypes.func,
getRowId: PropTypes.func,
initialState: PropTypes.object,
isLoading: PropTypes.bool,
onlyGlobalSearch: PropTypes.bool,
onlyGlobalSelectedRows: PropTypes.bool,
onSelectedRowsChange: PropTypes.func,
pageSize: PropTypes.number,
renderAllSelected: PropTypes.bool,
renderDetail: PropTypes.func,
RowComponent: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.node),
PropTypes.node,
PropTypes.func
]),
showPageCount: PropTypes.bool
showPageCount: PropTypes.bool,
singleSelect: PropTypes.bool
}
EnhancedTable.propTypes = EnhancedTableProps
export default EnhancedTable
@@ -45,9 +45,10 @@ const Pagination = ({
return (
<>
<Button
onClick={handleBackButtonClick}
disabled={pageIndex === 0}
aria-label='previous page'
disabled={pageIndex === 0}
onClick={handleBackButtonClick}
size='small'
>
<NavArrowLeft />
{T.Previous}
@@ -56,9 +57,10 @@ const Pagination = ({
{`${pageIndex + 1} of ${showPageCount ? pageCount : 'many'}`}
</span>
<Button
onClick={handleNextButtonClick}
disabled={pageIndex >= Math.ceil(count / pageSize) - 1}
aria-label='next page'
disabled={pageIndex >= Math.ceil(count / pageSize) - 1}
onClick={handleNextButtonClick}
size='small'
>
{T.Next}
<NavArrowRight />
@@ -15,14 +15,13 @@
* ------------------------------------------------------------------------- */
import { makeStyles } from '@material-ui/core'
import { addOpacityToColor } from 'client/utils'
export default makeStyles(
({ palette, typography, breakpoints, shadows }) => ({
root: {
height: '100%',
display: 'flex',
flexDirection: 'column'
flexDirection: 'column',
overflow: 'auto'
},
toolbar: {
...typography.body1,
@@ -68,15 +67,14 @@ export default makeStyles(
backgroundColor: palette.background.paper,
fontWeight: typography.fontWeightMedium,
fontSize: '1em',
border: `1px solid ${palette.divider}`,
borderRadius: 6,
display: 'flex',
gap: 8,
boxShadow: shadows[1],
'&:hover': {
backgroundColor: palette.action.hover
},
'&.selected': {
backgroundColor: addOpacityToColor(palette.secondary.main, 0.2),
border: `2px solid ${palette.secondary.main}`
}
}
@@ -19,7 +19,7 @@ import PropTypes from 'prop-types'
import { makeStyles, useMediaQuery } from '@material-ui/core'
import GlobalSort from 'client/components/Tables/Enhanced/Utils/GlobalSort'
import { GlobalSelectedRows, GlobalSort } from 'client/components/Tables/Enhanced/Utils'
const useToolbarStyles = makeStyles({
root: {
@@ -30,12 +30,12 @@ const useToolbarStyles = makeStyles({
}
})
const Toolbar = ({ useTableProps }) => {
const Toolbar = ({ onlyGlobalSelectedRows = false, useTableProps = {} }) => {
const classes = useToolbarStyles()
const isMobile = useMediaQuery(theme => theme.breakpoints.down('sm'))
if (isMobile) {
return null
if (isMobile || onlyGlobalSelectedRows) {
return <GlobalSelectedRows useTableProps={useTableProps} />
}
return (
@@ -46,11 +46,8 @@ const Toolbar = ({ useTableProps }) => {
}
Toolbar.propTypes = {
onlyGlobalSelectedRows: PropTypes.bool,
useTableProps: PropTypes.object
}
Toolbar.defaultProps = {
useTableProps: {}
}
export default Toolbar
@@ -14,7 +14,7 @@
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import CategoryFilter from 'client/components/Tables/Enhanced/Utils/CategoryFilter'
import { CategoryFilter } from 'client/components/Tables/Enhanced/Utils'
import * as HostModel from 'client/models/Host'
const getTotalOfResources = resources => [resources?.ID ?? []].flat().length || 0
@@ -14,7 +14,7 @@
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import CategoryFilter from 'client/components/Tables/Enhanced/Utils/CategoryFilter'
import { CategoryFilter } from 'client/components/Tables/Enhanced/Utils'
import * as ImageModel from 'client/models/Image'
const getTotalOfResources = resources => [resources?.ID ?? []].flat().length || 0
@@ -20,12 +20,11 @@ import { useAuth } from 'client/features/Auth'
import { useFetch } from 'client/hooks'
import { useImage, useImageApi } from 'client/features/One'
import { SkeletonTable, EnhancedTable } from 'client/components/Tables'
import { SkeletonTable, EnhancedTable, EnhancedTableProps } from 'client/components/Tables'
import ImageColumns from 'client/components/Tables/Images/columns'
import ImageRow from 'client/components/Tables/Images/row'
import ImageDetail from 'client/components/Tables/Images/detail'
const ImagesTable = () => {
const ImagesTable = props => {
const columns = React.useMemo(() => ImageColumns, [])
const images = useImage()
@@ -47,10 +46,13 @@ const ImagesTable = () => {
data={images}
isLoading={loading || reloading}
getRowId={row => String(row.ID)}
renderDetail={row => <ImageDetail id={row.ID} />}
RowComponent={ImageRow}
{...props}
/>
)
}
ImagesTable.propTypes = EnhancedTableProps
ImagesTable.displayName = 'ImagesTable'
export default ImagesTable
@@ -14,7 +14,7 @@
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import CategoryFilter from 'client/components/Tables/Enhanced/Utils/CategoryFilter'
import { CategoryFilter } from 'client/components/Tables/Enhanced/Utils'
import * as MarketplaceAppModel from 'client/models/MarketplaceApp'
export default [
@@ -14,7 +14,7 @@
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import CategoryFilter from 'client/components/Tables/Enhanced/Utils/CategoryFilter'
import { CategoryFilter } from 'client/components/Tables/Enhanced/Utils'
import * as MarketplaceModel from 'client/models/Datastore'
const getTotalOfResources = resources => [resources?.ID ?? []].flat().length || 0
@@ -21,7 +21,9 @@ import { makeStyles, Button } from '@material-ui/core'
import { Filter as FilterIcon } from 'iconoir-react'
import { UseGlobalFiltersInstanceProps, UseFiltersState } from 'react-table'
import GlobalFilter from 'client/components/Tables/Enhanced/Utils/GlobalFilter'
import { GlobalFilter } from 'client/components/Tables/Enhanced/Utils'
import { Tr } from 'client/components/HOC'
import { T } from 'client/constants'
const useToolbarStyles = makeStyles(theme => ({
filterWrapper: {
@@ -51,7 +53,7 @@ const Toolbar = ({ useTableProps }) => {
<Button startIcon={<FilterIcon />}
className={classes.filterButton}
>
Filters
{Tr(T.Filters)}
</Button>
<GlobalFilter
preGlobalFilteredRows={preGlobalFilteredRows}
@@ -14,7 +14,7 @@
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import CategoryFilter from 'client/components/Tables/Enhanced/Utils/CategoryFilter'
import { CategoryFilter } from 'client/components/Tables/Enhanced/Utils'
import * as Helper from 'client/models/Helper'
export default [
@@ -20,16 +20,15 @@ import { useAuth } from 'client/features/Auth'
import { useFetch } from 'client/hooks'
import { useVm, useVmApi } from 'client/features/One'
import { SkeletonTable, EnhancedTable } from 'client/components/Tables'
import { SkeletonTable, EnhancedTable, EnhancedTableProps } from 'client/components/Tables'
import { createColumns } from 'client/components/Tables/Enhanced/Utils'
import VmColumns from 'client/components/Tables/Vms/columns'
import VmRow from 'client/components/Tables/Vms/row'
import VmDetail from 'client/components/Tables/Vms/detail'
const INITIAL_ELEMENT = 0
const INTERVAL_ON_FIRST_RENDER = 2_000
const VmsTable = () => {
const VmsTable = props => {
const vms = useVm()
const { getVms } = useVmApi()
const { view, getResourceView, filterPool } = useAuth()
@@ -75,9 +74,12 @@ const VmsTable = () => {
isLoading={loading || reloading}
getRowId={row => String(row.ID)}
RowComponent={VmRow}
renderDetail={row => <VmDetail id={row.ID} />}
{...props}
/>
)
}
VmsTable.propTypes = EnhancedTableProps
VmsTable.displayName = 'VmsTable'
export default VmsTable
@@ -14,7 +14,7 @@
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import CategoryFilter from 'client/components/Tables/Enhanced/Utils/CategoryFilter'
import { CategoryFilter } from 'client/components/Tables/Enhanced/Utils'
import * as ZoneModel from 'client/models/Zone'
export default [
@@ -15,7 +15,7 @@
* ------------------------------------------------------------------------- */
import ClustersTable from 'client/components/Tables/Clusters'
import DatastoresTable from 'client/components/Tables/Datastores'
import EnhancedTable from 'client/components/Tables/Enhanced'
import EnhancedTable, { EnhancedTableProps } from 'client/components/Tables/Enhanced'
import GroupsTable from 'client/components/Tables/Groups'
import HostsTable from 'client/components/Tables/Hosts'
import ImagesTable from 'client/components/Tables/Images'
@@ -34,6 +34,7 @@ import ZonesTable from 'client/components/Tables/Zones'
export {
SkeletonTable,
EnhancedTable,
EnhancedTableProps,
VirtualizedTable,
ClustersTable,
@@ -61,7 +61,7 @@ const Select = React.forwardRef(
margin='dense'
onChange={handleChange}
select
SelectProps={{ displayEmpty: true, native: true }}
SelectProps={{ native: true }}
value={newValue}
variant='outlined'
>
@@ -30,6 +30,7 @@
* ------------------------------------------------------------------------- */
import * as React from 'react'
import PropTypes from 'prop-types'
import { makeStyles } from '@material-ui/core'
import { List } from 'client/components/Tabs/Common'
import { ACTIONS } from 'client/constants'
@@ -44,6 +45,17 @@ const SPECIAL_ATTRIBUTES = {
VCENTER_VERSION: { edit: false, delete: false }
}
const useStyles = makeStyles({
container: {
gridColumn: '1 / -1'
},
item: {
'& > *:first-child': {
flex: '1 1 20%'
}
}
})
const AttributePanel = React.memo(({
title,
attributes = {},
@@ -52,6 +64,8 @@ const AttributePanel = React.memo(({
handleAdd,
actions
}) => {
const classes = useStyles()
const formatAttributes = Object.entries(attributes)
.map(([name, value]) => ({
name,
@@ -68,9 +82,9 @@ const AttributePanel = React.memo(({
return (
<List
containerProps={{ style: { gridColumn: '1 / -1' } }}
containerProps={{ className: classes.container }}
itemProps={{ dense: true, className: classes.item }}
subListProps={{ disablePadding: true }}
itemProps={{ dense: true }}
title={title}
list={formatAttributes}
handleAdd={actions?.includes?.(ACTIONS.ADD_ATTRIBUTE) && handleAdd}
@@ -98,7 +98,7 @@ const AttributeList = ({
{list.map(attr => renderList(attr))}
{/* ADD ACTION */}
{handleAdd && (
<ListItem className={classes.item}>
<ListItem className={clsx(classes.item, itemClassName)}>
<AttributeCreateForm handleAdd={handleAdd} />
</ListItem>
)}
@@ -18,56 +18,35 @@ import * as React from 'react'
import PropTypes from 'prop-types'
import { useVmApi } from 'client/features/One'
import { useDialog } from 'client/hooks'
import { TabContext } from 'client/components/Tabs/TabProvider'
import { DialogForm } from 'client/components/Dialogs'
import FormWithSchema from 'client/components/Forms/FormWithSchema'
import { SCHEMA, FIELDS } from 'client/formSchema/Vm/resize'
import InformationPanel from 'client/components/Tabs/Vm/Capacity/information'
import * as VirtualMachine from 'client/models/VirtualMachine'
import * as Helper from 'client/models/Helper'
import { T } from 'client/constants'
const VmCapacityTab = ({ tabProps: { actions = [] } = {} }) => {
const { display, show, hide } = useDialog()
const { resize } = useVmApi()
const { handleRefetch, data: vm = {} } = React.useContext(TabContext)
const { ID, TEMPLATE } = vm
const { ID } = vm
const hypervisor = VirtualMachine.getHypervisor(vm)
const actionsAvailable = Helper.getActionsAvailable(actions, hypervisor)
const handleResize = async formData => {
const handleResizeCapacity = async formData => {
const { enforce, ...restOfData } = formData
const template = Helper.jsonToXml({ ROOT: restOfData })
const template = Helper.jsonToXml(restOfData)
const response = await resize(ID, { enforce, template })
String(response) === String(ID) && await handleRefetch?.()
hide()
}
return (
<>
<InformationPanel
actions={actionsAvailable}
handleOpenResizeDialog={show}
vm={vm}
/>
{display && (
<DialogForm
title={`${T.ResizeCapacity}`}
resolver={() => SCHEMA}
values={SCHEMA.cast(TEMPLATE, { stripUnknown: true })}
onCancel={hide}
onSubmit={handleResize}
>
<FormWithSchema cy='form-dg-vm-resize' fields={FIELDS} />
</DialogForm>
)}
</>
<InformationPanel
actions={actionsAvailable}
handleResizeCapacity={handleResizeCapacity}
vm={vm}
/>
)
}
@@ -16,51 +16,19 @@
/* eslint-disable jsdoc/require-jsdoc */
import * as React from 'react'
import PropTypes from 'prop-types'
import { makeStyles, Paper, Typography, Button } from '@material-ui/core'
import { Paper, Typography } from '@material-ui/core'
import ButtonToTriggerForm from 'client/components/Forms/ButtonToTriggerForm'
import { ResizeCapacityForm } from 'client/components/Forms/Vm'
import { Tr } from 'client/components/HOC'
import useCapacityTabStyles from 'client/components/Tabs/Vm/Capacity/styles'
import * as VirtualMachine from 'client/models/VirtualMachine'
import { prettyBytes } from 'client/utils'
import { T, VM_ACTIONS } from 'client/constants'
const useStyles = makeStyles(theme => ({
root: {
marginBlock: '0.8em',
padding: '1em',
display: 'grid',
gap: '1em',
gridAutoFlow: 'column',
[theme.breakpoints.down('sm')]: {
gridAutoFlow: 'initial'
}
},
item: {
[theme.breakpoints.down('sm')]: {
display: 'flex',
gap: '1em',
'& > *': {
width: '50%'
}
}
},
actions: {
[theme.breakpoints.down('sm')]: {
borderBottom: `1px solid ${theme.palette.divider}`,
padding: '1em'
},
[theme.breakpoints.up('md')]: {
order: 1,
textAlign: 'end'
}
},
title: {
fontWeight: theme.typography.fontWeightBold
}
}))
const InformationPanel = ({ actions, vm = {}, handleOpenResizeDialog }) => {
const classes = useStyles()
const InformationPanel = ({ actions, vm = {}, handleResizeCapacity }) => {
const classes = useCapacityTabStyles()
const { TEMPLATE } = vm
const isVCenter = VirtualMachine.isVCenter(vm)
@@ -101,15 +69,12 @@ const InformationPanel = ({ actions, vm = {}, handleOpenResizeDialog }) => {
<Paper variant='outlined' className={classes.root}>
<div className={classes.actions}>
{actions?.includes?.(VM_ACTIONS.RESIZE_CAPACITY) && (
<Button
data-cy='resize'
size='small'
color='secondary'
onClick={handleOpenResizeDialog}
variant='contained'
>
{Tr(T.Resize)}
</Button>
<ButtonToTriggerForm
buttonProps={{ 'data-cy': 'resize-capacity' }}
handleSubmit={handleResizeCapacity}
title={T.Resize}
options={[{ form: ResizeCapacityForm({ vm }) }]}
/>
)}
</div>
{capacity.map(({ name, value }) => (
@@ -127,7 +92,7 @@ const InformationPanel = ({ actions, vm = {}, handleOpenResizeDialog }) => {
}
InformationPanel.propTypes = {
handleOpenResizeDialog: PropTypes.function,
handleResizeCapacity: PropTypes.func,
actions: PropTypes.array,
vm: PropTypes.object
}
@@ -0,0 +1,51 @@
/* ------------------------------------------------------------------------- *
* Copyright 2002-2021, OpenNebula Project, OpenNebula Systems *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may *
* not use this file except in compliance with the License. You may obtain *
* a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
import { makeStyles } from '@material-ui/core'
export default makeStyles(theme => ({
root: {
marginBlock: '0.8em',
padding: '1em',
display: 'grid',
gap: '1em',
gridAutoFlow: 'column',
[theme.breakpoints.down('sm')]: {
gridAutoFlow: 'initial'
}
},
item: {
[theme.breakpoints.down('sm')]: {
display: 'flex',
gap: '1em',
'& > *': {
width: '50%'
}
}
},
actions: {
[theme.breakpoints.down('sm')]: {
borderBottom: `1px solid ${theme.palette.divider}`,
padding: '1em'
},
[theme.breakpoints.up('md')]: {
order: 1,
textAlign: 'end'
}
},
title: {
fontWeight: theme.typography.fontWeightBold
}
}))
@@ -21,8 +21,9 @@ import { TabContext } from 'client/components/Tabs/TabProvider'
const NavArrowDown = <span style={{ writingMode: 'vertical-rl' }}>{'>'}</span>
const VmConfigurationTab = data => {
const { data: { TEMPLATE, USER_TEMPLATE } = {} } = React.useContext(TabContext)
const VmConfigurationTab = () => {
const { data: vm = {} } = React.useContext(TabContext)
const { TEMPLATE, USER_TEMPLATE } = vm
return (
<div>
@@ -44,7 +45,7 @@ const VmConfigurationTab = data => {
</AccordionSummary>
<AccordionDetails>
<pre>
<code>
<code style={{ whiteSpace: 'break-spaces' }}>
{JSON.stringify(TEMPLATE, null, 2)}
</code>
</pre>
@@ -64,9 +64,9 @@ const VmInfoTab = ({ tabProps = {} }) => {
}
const handleAttributeInXml = async (newValue, path) => {
const newTemplate = cloneObject({ USER_TEMPLATE })
const newTemplate = cloneObject(USER_TEMPLATE)
set(newTemplate, `USER_TEMPLATE.${path}`, newValue)
set(newTemplate, path, newValue)
const xml = Helper.jsonToXml(newTemplate)
@@ -16,53 +16,62 @@
/* eslint-disable jsdoc/require-jsdoc */
import * as React from 'react'
import PropTypes from 'prop-types'
import { Button } from '@material-ui/core'
import { useDialog } from 'client/hooks'
import { useVmApi } from 'client/features/One'
import { TabContext } from 'client/components/Tabs/TabProvider'
import { DialogConfirmation } from 'client/components/Dialogs'
import StorageList from 'client/components/Tabs/Vm/Storage/List'
import { Tr } from 'client/components/HOC'
import ButtonToTriggerForm from 'client/components/Forms/ButtonToTriggerForm'
import { ImageSteps, VolatileSteps } from 'client/components/Forms/Vm'
import * as VirtualMachine from 'client/models/VirtualMachine'
import * as Helper from 'client/models/Helper'
import { T, VM_ACTIONS } from 'client/constants'
const VmStorageTab = ({ tabProps = {} }) => {
const { display, show, hide } = useDialog()
const { data: vm } = React.useContext(TabContext)
const { actions = [] } = tabProps
const VmStorageTab = ({ tabProps: { actions = [] } = {} }) => {
const { attachDisk } = useVmApi()
const { handleRefetch, data: vm = {} } = React.useContext(TabContext)
const { ID } = vm
const disks = VirtualMachine.getDisks(vm)
const hypervisor = VirtualMachine.getHypervisor(vm)
const actionsAvailable = Helper.getActionsAvailable(actions, hypervisor)
const handleAttachDisk = async ({ image, advanced, configuration }) => {
const imageSelected = image?.[0]
const root = { ...imageSelected, ...advanced, ...configuration }
const template = Helper.jsonToXml({ DISK: root })
const response = await attachDisk(ID, template)
String(response) === String(ID) && await handleRefetch?.()
}
return (
<>
{actionsAvailable?.includes?.(VM_ACTIONS.ATTACH_DISK) && (
<Button
data-cy='attach-disk'
size='small'
color='secondary'
onClick={show}
variant='contained'
>
{Tr(T.AttachDisk)}
</Button>
<ButtonToTriggerForm
buttonProps={{ 'data-cy': 'attach-disk' }}
title={T.AttachDisk}
options={[
{
cy: 'attach-image-disk',
name: T.Image,
form: ImageSteps({ hypervisor }),
onSubmit: handleAttachDisk
},
{
cy: 'attach-volatile-disk',
name: T.Volatile,
form: VolatileSteps({ hypervisor }),
onSubmit: handleAttachDisk
}
]}
/>
)}
<StorageList actions={actionsAvailable} disks={disks} />
{display && (
<DialogConfirmation
title={T.AttachDisk}
handleAccept={hide}
handleCancel={hide}
>
<p>TODO: should define in view yaml ??</p>
</DialogConfirmation>
)}
</>
)
}
@@ -16,8 +16,11 @@
/* eslint-disable jsdoc/require-jsdoc */
import * as React from 'react'
import PropTypes from 'prop-types'
import { LinearProgress } from '@material-ui/core'
import { useFetch, useSocket } from 'client/hooks'
import { useAuth } from 'client/features/Auth'
import { useVmApi } from 'client/features/One'
import Tabs from 'client/components/Tabs'
import { stringToCamelCase, stringToCamelSpace } from 'client/utils'
@@ -45,10 +48,26 @@ const loadTab = tabName => ({
storage: Storage
}[tabName])
const VmTabs = ({ data, handleRefetch }) => {
const VmTabs = React.memo(({ id }) => {
const { getHooksSocket } = useSocket()
const { getVm } = useVmApi()
const {
data,
fetchRequest,
loading,
error
} = useFetch(getVm, getHooksSocket({ resource: 'vm', id }))
const handleRefetch = () => fetchRequest(id, { reload: true })
const [tabsAvailable, setTabs] = React.useState(() => [])
const { view, getResourceView } = useAuth()
React.useEffect(() => {
fetchRequest(id)
}, [id])
React.useEffect(() => {
const infoTabs = getResourceView('VM')?.['info-tabs'] ?? {}
@@ -66,16 +85,19 @@ const VmTabs = ({ data, handleRefetch }) => {
?.filter(Boolean))
}, [view])
if ((!data && !error) || loading) {
return <LinearProgress color='secondary' style={{ width: '100%' }} />
}
return (
<TabProvider initialState={{ data, handleRefetch }}>
<Tabs tabs={tabsAvailable} />
</TabProvider>
)
}
})
VmTabs.propTypes = {
data: PropTypes.object.isRequired,
handleRefetch: PropTypes.func
id: PropTypes.string.isRequired
}
VmTabs.displayName = 'VmTabs'
@@ -20,6 +20,7 @@ module.exports = {
Next: 'Next',
SortBy: 'Sort by',
Filter: 'Filter',
Filters: 'Filters',
All: 'All',
On: 'On',
@@ -54,6 +55,8 @@ module.exports = {
AddAction: 'Add action',
/* questions */
Yes: 'Yes',
No: 'No',
DoYouWantProceed: 'Do you want proceed?',
/* Scheduling */
@@ -101,6 +104,7 @@ module.exports = {
NoDataAvailable: 'There is no data available',
/* steps form */
AdvancedOptions: 'Advanced options',
/* steps form - flow */
ApplicationOverview: 'Application overview',
WhereWillItRun: 'Where will it run?',
@@ -237,6 +241,8 @@ module.exports = {
Memory: 'Memory',
CostCpu: 'Cost / CPU',
CostMByte: 'Cost / MByte',
/* VM schema - storage */
Volatile: 'Volatile',
/* VM schema - network */
NIC: 'NIC',
Alias: 'Alias',
+8
View File
@@ -502,6 +502,14 @@ export const VM_ACTIONS = {
UPDATE_CONF: 'update_configuration'
}
/** @enum {string} Hypervisors */
export const HYPERVISORS = {
kvm: 'kvm',
vcenter: 'vcenter',
firecracker: 'firecracker',
lxc: 'lxc'
}
/**
* @enum {(
* 'none' |
@@ -18,9 +18,18 @@ import * as React from 'react'
import { Container, Box } from '@material-ui/core'
import * as Tables from 'client/components/Tables'
import { ImagesTable } from 'client/components/Tables'
import Detail from 'client/components/Tables/Images/detail'
import SplitPane from 'client/components/SplitPane'
function Images () {
const [selectedRows, onSelectedRowsChange] = React.useState()
const selectedRowIds = React.useMemo(
() => selectedRows?.map(row => row.id),
[selectedRows]
)
return (
<Box
height={1}
@@ -30,7 +39,24 @@ function Images () {
flexDirection='column'
component={Container}
>
<Tables.ImagesTable />
<SplitPane>
<ImagesTable onSelectedRowsChange={onSelectedRowsChange} />
{selectedRows?.length > 0 && (
<div style={{ display: 'flex', flexDirection: 'column', overflow: 'auto' }}>
{selectedRows?.length === 1
? <Detail id={selectedRows[0]?.values.ID} />
: (
<pre>
<code>
{JSON.stringify(Object.keys(selectedRowIds)?.join(', '), null, 2)}
</code>
</pre>
)
}
</div>
)}
</SplitPane>
</Box>
)
}
@@ -37,7 +37,7 @@ export const USERNAME = {
autoFocus: true,
required: true,
autoComplete: 'username',
variant: 'outlined'
margin: 'normal'
}
}
@@ -54,7 +54,7 @@ export const PASSWORD = {
fieldProps: {
required: true,
autoComplete: 'current-password',
variant: 'outlined'
margin: 'normal'
}
}
@@ -81,7 +81,7 @@ export const TOKEN = {
fieldProps: {
autoFocus: true,
required: true,
variant: 'outlined'
margin: 'normal'
}
}
@@ -116,7 +116,9 @@ export const GROUP = {
.nullable()
.default(FILTER_POOL.ALL_RESOURCES),
grid: { md: 12 },
fieldProps: { variant: 'outlined' }
fieldProps: {
margin: 'normal'
}
}
export const FORM_USER_FIELDS = [USERNAME, PASSWORD, REMEMBER]
@@ -31,9 +31,7 @@ const SCHEME = {
.trim()
.required('Scheme field is required')
.default(DEFAULT_SCHEME),
grid: { md: 12 },
native: true,
fieldProps: { variant: 'outlined' }
grid: { md: 12 }
}
const LANGUAGES = {
@@ -47,9 +45,7 @@ const LANGUAGES = {
.trim()
.required('Language field is required')
.default(DEFAULT_LANGUAGE),
grid: { md: 12 },
native: true,
fieldProps: { variant: 'outlined' }
grid: { md: 12 }
}
const DISABLE_ANIMATIONS = {
@@ -18,9 +18,16 @@ import * as React from 'react'
import { Container, Box } from '@material-ui/core'
import * as Tables from 'client/components/Tables'
import { VmsTable } from 'client/components/Tables'
import VmTabs from 'client/components/Tabs/Vm'
import SplitPane from 'client/components/SplitPane'
function VirtualMachines () {
const [selectedRows, onSelectedRowsChange] = React.useState([])
const getRowIds = () =>
JSON.stringify(selectedRows?.map(row => row.id).join(', '), null, 2)
return (
<Box
height={1}
@@ -30,7 +37,18 @@ function VirtualMachines () {
flexDirection='column'
component={Container}
>
<Tables.VmsTable />
<SplitPane>
<VmsTable onSelectedRowsChange={onSelectedRowsChange} />
{selectedRows?.length > 0 && (
<div style={{ display: 'flex', flexDirection: 'column', overflow: 'auto' }}>
{selectedRows?.length === 1
? <VmTabs id={selectedRows[0]?.values.ID} />
: <pre><code>{getRowIds()}</code></pre>
}
</div>
)}
</SplitPane>
</Box>
)
}
@@ -45,4 +45,5 @@ export const rename = createAction('vm/rename', vmService.rename)
export const resize = createAction('vm/resize', vmService.resize)
export const changePermissions = createAction('vm/chmod', vmService.changePermissions)
export const changeOwnership = createAction('vm/chown', vmService.changeOwnership)
export const attachDisk = createAction('vm/attach/disk', vmService.attachDisk)
export const detachNic = createAction('vm/detach/nic', vmService.detachNic)
@@ -44,6 +44,7 @@ export const useVmApi = () => {
unwrapDispatch(actions.changePermissions({ id, permissions })),
changeOwnership: (id, ownership) =>
unwrapDispatch(actions.changeOwnership({ id, ownership })),
attachDisk: (id, template) => unwrapDispatch(actions.attachDisk({ id, template })),
detachNic: (id, nic) => unwrapDispatch(actions.detachNic({ id, nic }))
}
}
@@ -220,6 +220,28 @@ export const vmService = ({
return res?.data
},
/**
* Attaches a new disk to the virtual machine.
*
* @param {object} params - Request parameters
* @param {string|number} params.id - Virtual machine id
* @param {string} params.template
* - A string containing a single DISK vector attribute
* @returns {number} Virtual machine id
* @throws Fails when response isn't code 200
*/
attachDisk: async ({ id, template }) => {
const name = Actions.VM_DISK_ATTACH
const command = { name, ...Commands[name] }
const config = requestConfig({ id, template }, command)
const res = await RestClient.request(config)
if (!res?.id || res?.id !== httpCodes.ok.id) throw res?.data
return res?.data
},
/**
* Detaches a network interface from a virtual machine.
*
+3 -2
View File
@@ -19,11 +19,12 @@ import { j2xParser as Parser } from 'fast-xml-parser'
/**
* @param {object} json - JSON
* @param {boolean} [addRoot] - Add ROOT element as parent
* @returns {string} Xml in string format
*/
export const jsonToXml = json => {
export const jsonToXml = (json, addRoot = true) => {
const parser = new Parser()
return parser.parse(json)
return parser.parse(addRoot ? { ROOT: json } : json)
}
/**
@@ -23,6 +23,7 @@ import {
VM_LCM_STATES,
NIC_ALIAS_IP_ATTRS,
HISTORY_ACTIONS,
HYPERVISORS,
T,
StateInfo
} from 'client/constants'
@@ -77,7 +78,7 @@ export const getHypervisor = vm => String(getLastHistory(vm)?.VM_MAD).toLowerCas
* @param {object} vm - Virtual machine
* @returns {boolean} If the hypervisor is vCenter
*/
export const isVCenter = vm => getHypervisor(vm) === 'vcenter'
export const isVCenter = vm => getHypervisor(vm) === HYPERVISORS.vcenter
/**
* @param {object} vm - Virtual machine