import React, { useState, useEffect } from 'react'; import useDeepCompareEffect from 'use-deep-compare-effect'; import { STATUS } from 'foremanReact/constants'; import { translate as __ } from 'foremanReact/common/I18n'; import PropTypes from 'prop-types'; import { useDispatch, useSelector } from 'react-redux'; import { Form, FormGroup, TextInput, TextArea, Checkbox, ActionGroup, Button, Tile, Grid, GridItem } from '@patternfly/react-core'; import { createContentView } from '../ContentViewsActions'; import { selectCreateContentViews, selectCreateContentViewStatus, selectCreateContentViewError } from './ContentViewCreateSelectors'; import { LabelDependencies, LabelAutoPublish } from './ContentViewFormComponents'; import ContentViewIcon from '../components/ContentViewIcon'; import './CreateContentViewForm.scss'; const CreateContentViewForm = ({ setModalOpen }) => { const dispatch = useDispatch(); const [name, setName] = useState(''); const [label, setLabel] = useState(''); const [description, setDescription] = useState(''); const [composite, setComposite] = useState(false); const [component, setComponent] = useState(true); const [autoPublish, setAutoPublish] = useState(false); const [dependencies, setDependencies] = useState(false); const [redirect, setRedirect] = useState(false); const [saving, setSaving] = useState(false); const [labelValidated, setLabelValidated] = useState('default'); const handleLabelChange = (newLabel, _event) => { setLabel(newLabel); if (newLabel === '') { setLabelValidated('default'); } else if (/^[\w-]+$/.test(newLabel)) { setLabelValidated('success'); } else { setLabelValidated('error'); } }; const response = useSelector(selectCreateContentViews); const status = useSelector(selectCreateContentViewStatus); const error = useSelector(selectCreateContentViewError); useDeepCompareEffect(() => { const { id } = response; if (id && status === STATUS.RESOLVED && saving) { setSaving(false); setRedirect(true); } else if (status === STATUS.ERROR) { setSaving(false); } }, [response, status, error, saving]); const onSave = () => { setSaving(true); dispatch(createContentView({ name, label, description, composite, solve_dependencies: dependencies, auto_publish: (autoPublish && composite), })); }; useEffect( () => { setLabel(name.replace(/[^A-Za-z0-9_-]/g, '_')); }, [name], ); if (redirect) { const { id } = response; if (composite) { window.location.assign(`/content_views/${id}#/contentviews`); } else { window.location.assign(`/content_views/${id}#/repositories`); } } const submitDisabled = !name?.length || !label?.length || saving || redirect || labelValidated === 'error'; return (
); }; CreateContentViewForm.propTypes = { setModalOpen: PropTypes.func, }; CreateContentViewForm.defaultProps = { setModalOpen: null, }; export default CreateContentViewForm;