F OpenNebula/one#7441: Add new Card Button component (#4572)

Add new Card Buttons to Toggle controller
This commit is contained in:
Alejandro authored and GitHub committed 2026-10-20 09:47:38 +02:00
1 parent 1458f0b95f
commit 07cbbfd7ab
5 files changed
+286 -60

No files matched your search

@@ -16,17 +16,10 @@
import { memo, useCallback, useEffect } from 'react'
import PropTypes from 'prop-types'
import { TEXT_VARIANTS, TEXT_WEIGHTS } from '@ConstantsModule'
import {
styled,
FormControl,
ToggleButtonGroup,
ToggleButton,
FormHelperText,
Box,
alpha,
} from '@mui/material'
import { styled, FormControl, FormHelperText, Box } from '@mui/material'
import { useController } from 'react-hook-form'
import { Text } from '@modules/components/primitives/Text'
import { CardButton } from '@modules/components/primitives/Buttons/Card'
import { ErrorHelper } from '@modules/components/composed/Forms/FormControl/ErrorHelper'
import { AdornmentWithTooltip as Tooltip } from '@modules/components/composed/Forms/FormControl/Tooltip'
import { generateKey } from '@UtilsModule'
@@ -65,14 +58,23 @@ export const ToggleController = memo(
useEffect(() => {
if (optionSelected) {
const exists = values?.find((option) => option.value === optionSelected)
const selectedValues = Array.isArray(optionSelected)
? optionSelected
: [optionSelected]
const exists = selectedValues.every((selectedValue) =>
values?.some((option) => option.value === selectedValue)
)
!exists && onChange()
}
}, [])
const handleChange = useCallback(
(_, newValues) => {
(newValues) => {
onBlur()
if (!readOnly && (!notNull || newValues)) {
const hasSelection = Array.isArray(newValues)
? newValues.length > 0
: newValues !== null && newValues !== undefined
if (!readOnly && (!notNull || hasSelection)) {
onChange(newValues)
if (typeof onConditionChange === 'function') {
onConditionChange(newValues)
@@ -82,6 +84,29 @@ export const ToggleController = memo(
[onChange, onConditionChange, readOnly, notNull]
)
const handleCardChange = useCallback(
(optionValue) => {
const selectedValues = Array.isArray(optionSelected)
? optionSelected
: []
const isSelected = multiple
? selectedValues.includes(optionValue)
: optionSelected === optionValue
const newValues = multiple
? isSelected
? selectedValues.filter((value) => value !== optionValue)
: [...selectedValues, optionValue]
: isSelected
? null
: optionValue
handleChange(newValues)
},
[handleChange, multiple, optionSelected]
)
// Safe loading of default value
useEffect(() => {
if (
@@ -106,52 +131,41 @@ export const ToggleController = memo(
{tooltip && <Tooltip title={tooltip} />}
</Label>
)}
<ToggleButtonGroup
fullWidth
ref={ref}
<Box
id={cy}
onChange={handleChange}
value={optionSelected}
exclusive={!multiple}
role="group"
data-cy={cy}
{...fieldProps}
sx={(theme) => ({
display: 'flex',
gap: `${theme.scale[500]}px`,
})}
>
{values?.map(({ text, value = '', description }) => (
<ToggleButton
key={`${name}-${value}`}
value={value}
sx={(theme) => ({
p: 1,
'&.Mui-selected': {
borderColor: theme.palette.primary.main,
backgroundColor: alpha(theme.palette.primary.main, 0.18),
boxShadow: `inset 0 0 0 1px ${theme.palette.primary.main}`,
color: theme.palette.primary.main,
},
'&.Mui-selected:hover': {
backgroundColor: alpha(theme.palette.primary.main, 0.26),
},
})}
>
<Box sx={{ display: 'flex', flexDirection: 'column' }}>
<Text
value={text}
variant={TEXT_VARIANTS.BODY_SMALL}
weight={TEXT_WEIGHTS.REGULAR}
/>
{description && (
<Text
component="span"
value={description}
variant={TEXT_VARIANTS.CAPTION}
weight={TEXT_WEIGHTS.REGULAR}
/>
)}
</Box>
</ToggleButton>
))}
</ToggleButtonGroup>
{values?.map(
(
{ text, value = '', description, startIcon, isDisabled = false },
index
) => (
<CardButton
key={`${name}-${value}`}
ref={index === 0 ? ref : undefined}
value={value}
text={text}
description={description}
startIcon={startIcon}
startIconSize="small"
isSelected={
multiple
? Array.isArray(optionSelected) &&
optionSelected.includes(value)
: optionSelected === value
}
isDisabled={fieldProps.disabled || isDisabled || readOnly}
onBlur={onBlur}
onClick={() => handleCardChange(value)}
/>
)
)}
</Box>
{Boolean(message) && (
<FormHelperText data-cy={`${cy}-error`}>
<ErrorHelper label={message} />
@@ -159,11 +173,7 @@ export const ToggleController = memo(
)}
</FormControl>
)
},
(prevProps, nextProps) =>
prevProps.values.length === nextProps.values.length &&
prevProps.label === nextProps.label &&
prevProps.tooltip === nextProps.tooltip
}
)
ToggleController.propTypes = {
@@ -0,0 +1,118 @@
/* ------------------------------------------------------------------------- *
* Copyright 2002-2026, 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 { Box } from '@mui/material'
import { Component, forwardRef } from 'react'
import PropTypes from 'prop-types'
import clsx from 'clsx'
import { getStyles } from '@modules/components/primitives/Buttons/Card/styles'
import { Text } from '@modules/components/primitives/Text'
import { Tooltip } from '@modules/components/primitives/Tooltip/Default'
import { renderIcon } from '@UtilsModule'
/**
* Card-shaped selectable button.
*
* @param {object} root0 - Params
* @param {string|Component} root0.text - Button text
* @param {string|Component} root0.description - Optional supporting text
* @param {Component} root0.startIcon - Icon displayed above the text
* @param {string} root0.startIconSize - Size of the start icon (either 'small' or 'big')
* @param {*} root0.value - Option value
* @param {boolean} root0.isSelected - Whether the button is selected
* @param {boolean} root0.isDisabled - Whether the button is disabled
* @param {Function} root0.onClick - Click handler
* @returns {Component} Card button component
*/
export const CardButton = forwardRef(
(
{
text = '',
description,
startIcon,
startIconSize = 'small',
value,
isSelected = false,
isDisabled = false,
onClick,
className,
...opts
},
ref
) => {
const handleClick = (event) => {
if (isDisabled) return
onClick?.(event, value)
}
return (
<Tooltip title={description ?? ''} placement="top">
<span style={{ display: 'inline-flex', width: 'fit-content' }}>
<Box
component="button"
type="button"
ref={ref}
value={value}
disabled={isDisabled}
aria-pressed={isSelected}
aria-disabled={isDisabled}
className={clsx('card-button-container', className, {
selected: isSelected,
disabled: isDisabled,
})}
data-cy={opts?.['data-cy'] ?? opts?.dataCy}
onClick={handleClick}
sx={(theme) => getStyles({ theme })}
{...opts}
>
{startIcon && (
<Box
component="span"
className={`card-button-icon ${startIconSize}`}
>
{renderIcon(startIcon)}
</Box>
)}
{text && (
<Text
component="span"
className="card-button-text"
value={text}
/>
)}
</Box>
</span>
</Tooltip>
)
}
)
CardButton.propTypes = {
text: PropTypes.node,
description: PropTypes.node,
startIcon: PropTypes.oneOfType([PropTypes.node, PropTypes.elementType]),
startIconSize: PropTypes.oneOf(['small', 'big']),
value: PropTypes.any,
isSelected: PropTypes.bool,
isDisabled: PropTypes.bool,
isReadOnly: PropTypes.bool,
onClick: PropTypes.func,
className: PropTypes.string,
}
CardButton.displayName = 'CardButton'
@@ -0,0 +1,96 @@
/* ------------------------------------------------------------------------- *
* Copyright 2002-2026, 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. *
* ------------------------------------------------------------------------- */
/**
* @param {object} root0 - Params
* @param {object} root0.theme - Current theme in use
* @returns {object} - Button SX style
*/
export const getStyles = ({ theme }) => {
const icon = {
color: theme.palette.icon.primary,
'& svg': {
width: `${theme.scale[600]}px`,
height: `${theme.scale[600]}px`,
strokeWidth: 1.5,
},
'&.big svg': {
width: `${theme.scale[800]}px`,
height: `${theme.scale[800]}px`,
},
}
const text = {
textAlign: 'center',
color: theme.palette.text.body,
fontSize: {
xs: theme.fontSize.body.sm.mobile,
sm: theme.fontSize.body.sm.tablet,
md: theme.fontSize.body.sm.desktop,
},
fontWeight: 500,
lineHeight: {
xs: theme.lineHeight.body.sm.mobile,
sm: theme.lineHeight.body.sm.tablet,
md: theme.lineHeight.body.sm.desktop,
},
}
return {
cursor: 'pointer',
display: 'flex',
minWidth: `${theme.scale[1500]}px`,
flexDirection: 'column',
alignItems: 'center',
gap: `${theme.scale[200]}px`,
padding: `${theme.scale[150]}px ${theme.scale[400]}px`,
borderRadius: `${theme.borderRadius.xlg}px`,
border: `${theme.borderWidth.sm}px solid ${theme.palette.border.primary}`,
backgroundColor: theme.palette.surface.primary,
'& .card-button-icon': icon,
'& .card-button-text': text,
'&:hover': {
backgroundColor: theme.palette.surface.actionHover4,
},
'&.disabled': {
backgroundColor: theme.palette.surface.actionHover4,
'& .card-button-icon': {
color: theme.palette.icon.onDisabled,
},
'& .card-button-text': {
color: theme.palette.text.onDisabled,
},
},
'&:active': {
backgroundColor: theme.palette.surface.primary,
outlineOffset: `${theme.borderWidth.sm}px`,
outline: `${theme.borderWidth.sm}px solid ${theme.palette.border.focus2}`,
},
'&.selected': {
padding: `${theme.scale[150] - 1}px ${theme.scale[400] - 1}px`,
border: `${theme.borderWidth.md}px solid ${theme.palette.border.focus2}`,
},
}
}
@@ -14,6 +14,7 @@
* limitations under the License. *
* ------------------------------------------------------------------------- */
export * from '@modules/components/primitives/Buttons/Card'
export * from '@modules/components/primitives/Buttons/Checkbox'
export * from '@modules/components/primitives/Buttons/Default'
export * from '@modules/components/primitives/Buttons/Group'
@@ -61,6 +61,7 @@ export const DESCRIPTION = {
export const HYPERVISOR_FIELD = (isUpdate) => ({
name: 'HYPERVISOR',
type: INPUT_TYPES.TOGGLE,
notNull: true,
values: arrayToOptions(Object.values(HYPERVISORS), {
addEmpty: false,
getText: (hypervisor) => hypervisor.toUpperCase(),