draft-js#ContentState JavaScript Examples
The following examples show how to use
draft-js#ContentState.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ScriptEditor.jsx From Spoke with MIT License | 6 votes |
getEditorState() {
const { scriptFields, scriptText } = this.props;
const decorator = this.getCompositeDecorator(scriptFields);
let editorState;
if (scriptText) {
editorState = EditorState.createWithContent(
ContentState.createFromText(scriptText),
decorator
);
} else {
editorState = EditorState.createEmpty(decorator);
}
return editorState;
}
Example #2
Source File: WYSIWYG.jsx From saasgear with MIT License | 6 votes |
WYSIWYGEditor = ({ editorContent = '', onChange, className }) => {
const [editorState, setEditorState] = useState(EditorState.createEmpty());
function onEditorStateChange(state) {
setEditorState(state);
return onChange(draftToHtml(convertToRaw(state.getCurrentContent())));
}
useEffect(() => {
if (editorContent === '') {
setEditorState(EditorState.createEmpty());
} else {
const contentState = EditorState.createWithContent(
ContentState.createFromBlockArray(htmlToDraft(editorContent)),
);
setEditorState(contentState);
}
}, [editorContent]);
return (
<Wrapper>
<Editor
editorState={editorState}
wrapperClassName="editor-wrapper"
editorClassName="editor"
toolbarClassName="toolbar"
onEditorStateChange={onEditorStateChange}
/>
</Wrapper>
);
}
Example #3
Source File: index.js From spring-boot-ecommerce with Apache License 2.0 | 5 votes |
function toEditorState(text) {
return ContentState.createFromText(text);
}
Example #4
Source File: convertFromHTML.js From the-eye-knows-the-garbage with MIT License | 5 votes |
convertFromHTML = function convertFromHTML(_ref2) {
var _ref2$htmlToStyle = _ref2.htmlToStyle,
htmlToStyle = _ref2$htmlToStyle === void 0 ? defaultHTMLToStyle : _ref2$htmlToStyle,
_ref2$htmlToEntity = _ref2.htmlToEntity,
htmlToEntity = _ref2$htmlToEntity === void 0 ? defaultHTMLToEntity : _ref2$htmlToEntity,
_ref2$textToEntity = _ref2.textToEntity,
textToEntity = _ref2$textToEntity === void 0 ? defaultTextToEntity : _ref2$textToEntity,
_ref2$htmlToBlock = _ref2.htmlToBlock,
htmlToBlock = _ref2$htmlToBlock === void 0 ? defaultHTMLToBlock : _ref2$htmlToBlock;
return function (html) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
flat: false
};
var DOMBuilder = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : getSafeBodyFromHTML;
var generateKey = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : genKey;
var contentState = ContentState.createFromText('');
var createEntityWithContentState = function createEntityWithContentState() {
if (contentState.createEntity) {
var _contentState;
contentState = (_contentState = contentState).createEntity.apply(_contentState, arguments);
return contentState.getLastCreatedEntityKey();
}
return Entity.create.apply(Entity, arguments);
};
var getEntityWithContentState = function getEntityWithContentState() {
if (contentState.getEntity) {
var _contentState2;
return (_contentState2 = contentState).getEntity.apply(_contentState2, arguments);
}
return Entity.get.apply(Entity, arguments);
};
var mergeEntityDataWithContentState = function mergeEntityDataWithContentState() {
if (contentState.mergeEntityData) {
var _contentState3;
contentState = (_contentState3 = contentState).mergeEntityData.apply(_contentState3, arguments);
return;
}
Entity.mergeData.apply(Entity, arguments);
};
var replaceEntityDataWithContentState = function replaceEntityDataWithContentState() {
if (contentState.replaceEntityData) {
var _contentState4;
contentState = (_contentState4 = contentState).replaceEntityData.apply(_contentState4, arguments);
return;
}
Entity.replaceData.apply(Entity, arguments);
};
var contentBlocks = convertFromHTMLtoContentBlocks(html, handleMiddleware(htmlToStyle, baseProcessInlineTag), handleMiddleware(htmlToEntity, defaultHTMLToEntity), handleMiddleware(textToEntity, defaultTextToEntity), handleMiddleware(htmlToBlock, baseCheckBlockType), createEntityWithContentState, getEntityWithContentState, mergeEntityDataWithContentState, replaceEntityDataWithContentState, options, DOMBuilder, generateKey);
var blockMap = BlockMapBuilder.createFromArray(contentBlocks);
var firstBlockKey = contentBlocks[0].getKey();
return contentState.merge({
blockMap: blockMap,
selectionBefore: SelectionState.createEmpty(firstBlockKey),
selectionAfter: SelectionState.createEmpty(firstBlockKey)
});
};
}
Example #5
Source File: Reviews.js From Next.js-e-commerce-online-store with MIT License | 4 votes |
export default function Reviews({ id, reviewList }) {
const [ isEditorReadOnly, setIsEditorReadOnly ] = useState(false)
const [ sameEmailError, setSameEmailError ] = useState(false)
const formik = useFormik({
initialValues: { name: '', email: '', message: '' },
onSubmit: async (values, { resetForm }) => {
setIsEditorReadOnly(true)
await fetch(`/api/postReview?productId=${id}&name=${values.name}&email=${values.email}&reviewText=${encodeURIComponent(values.message)}`)
.then(res => {
if (res.status >= 400) {
if (res.status === 400) {
console.log(res.status, res)
setSameEmailError(res.statusText)
const err = new Error(res.statustext)
setIsEditorReadOnly(false)
throw err
} else if (res.status > 400) {
setSameEmailError(false)
const err = new Error('Error')
setIsEditorReadOnly(false)
throw err
}
}
return res.json()
})
.then(data => {
resetForm()
setEditorState(EditorState.push(editorState, ContentState.createFromText('')))
setSameEmailError(false)
const publishedReview = data.data.createReview.data
reviewList.push(publishedReview)
setIsEditorReadOnly(false)
const headingElement = document.getElementById('heading')
headingElement.scrollIntoView({ behavior: 'smooth' })
})
.catch(err => console.error(err))
},
validationSchema: schema
})
const [ reviews, setReviews ] = useState(reviewList)
const value = formik.values.message
const prepareDraft = value => {
const draft = htmlToDraft(value)
const contentState = ContentState.createFromBlockArray(draft.contentBlocks)
const editorState = EditorState.createWithContent(contentState)
return editorState
}
const setFieldValue = val => formik.setFieldValue('message', val)
const [ editorState, setEditorState ] = useState(value ? prepareDraft(value) : EditorState.createEmpty())
const onEditorStateChange = editorState => {
const forFormik = draftToHtml(
convertToRaw(editorState.getCurrentContent())
)
setFieldValue(forFormik)
setEditorState(editorState)
}
return (
<ReviewsDiv>
<div className="heading" id="heading">
{
reviews.length === 0
? 'No reviews so far. Be the first!'
: 'Reviews'
}
</div>
<div className="reviews">
{
reviews
.sort((a, b) => (
// sort by date, newest first ↓
new Date(b.attributes.createdAt).getTime() - new Date(a.attributes.createdAt).getTime()
))
.map(review => (
<div className="review" key={review.id}>
<div>
Reviewed at <b>{review.attributes.createdAt.slice(0, 10)}</b> by <b>{review.attributes.name}</b>:
</div>
<div dangerouslySetInnerHTML={{__html: review.attributes.reviewText}} className="review-text"></div>
</div>
))
}
</div>
<form className="form" onSubmit={formik.handleSubmit}>
<div className="input-group">
<div className="input-group-prepend">
<span className="input-group-text" id="inputGroup-sizing-default">Name</span>
</div>
<input
type="text"
aria-label="Sizing example input"
aria-describedby="inputGroup-sizing-default"
pattern="[A-Za-z ]{1,32}"
title="1 to 32 letters, no special symbols, except space"
minLength="1"
name="name"
id="name"
required
className="form-control"
value={formik.values.name}
onChange={formik.handleChange}
/>
</div>
{formik.errors.name && <h1 className="feedback-msgs">{formik.errors.name}</h1>}
<div className="input-group">
<div className="input-group-prepend">
<span className="input-group-text" id="inputGroup-sizing-default">E-mail</span>
</div>
<input
type="email"
aria-label="Sizing example input"
aria-describedby="inputGroup-sizing-default"
minLength="3"
name="email"
id="email"
required
className="form-control"
value={formik.values.email}
onChange={formik.handleChange}
/>
</div>
{formik.errors.email && <h1 className="feedback-msgs">{formik.errors.email}</h1>}
<div className="editor-top-wrapper">
<Editor
editorState={editorState}
readOnly={isEditorReadOnly}
toolbarHidden={isEditorReadOnly}
toolbarClassName="toolbar"
wrapperClassName="wrapper"
editorClassName="editor"
onEditorStateChange={onEditorStateChange}
toolbar={{
options: ['inline', 'blockType', 'fontSize', 'fontFamily', 'list', 'textAlign', 'colorPicker', 'link', 'embedded', 'emoji', 'image', 'remove', 'history'],
colorPicker: { popupClassName: 'colorPickerPopup' },
link: { popupClassName: 'linkPopup' },
emoji: { popupClassName: 'emojiPopup' },
embedded: { popupClassName: 'embeddedPopup' },
image: { popupClassName: 'imagePopup' }
}}
/>
</div>
{formik.errors.message && <div className="feedback-msgs">{formik.errors.message}</div>}
{
sameEmailError
? <div className="feedback-msgs">{sameEmailError}</div>
: null
}
<button type="submit" className="post-button btn btn-primary" disabled={isEditorReadOnly}>
Post Review
</button>
</form>
</ReviewsDiv>
)
}
Example #6
Source File: index.js From spring-boot-ecommerce with Apache License 2.0 | 4 votes |
EditorCore = function (_React$Component) {
_inherits(EditorCore, _React$Component);
function EditorCore(props) {
_classCallCheck(this, EditorCore);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props));
_this.cancelForceUpdateImmediate = function () {
clearImmediate(_this.forceUpdateImmediate);
_this.forceUpdateImmediate = null;
};
_this.handlePastedText = function (text, html) {
var editorState = _this.state.editorState;
if (html) {
var contentState = editorState.getCurrentContent();
var selection = editorState.getSelection();
var fragment = customHTML2Content(html, contentState);
var pastedContent = Modifier.replaceWithFragment(contentState, selection, fragment);
var newContent = pastedContent.merge({
selectionBefore: selection,
selectionAfter: pastedContent.getSelectionAfter().set('hasFocus', true)
});
_this.setEditorState(EditorState.push(editorState, newContent, 'insert-fragment'), true);
return 'handled';
}
return 'not-handled';
};
_this.plugins = List(List(props.plugins).flatten(true));
var editorState = void 0;
if (props.value !== undefined) {
if (props.value instanceof EditorState) {
editorState = props.value || EditorState.createEmpty();
} else {
editorState = EditorState.createEmpty();
}
} else {
editorState = EditorState.createEmpty();
}
editorState = _this.generatorDefaultValue(editorState);
_this.state = {
plugins: _this.reloadPlugins(),
editorState: editorState,
customStyleMap: {},
customBlockStyleMap: {},
compositeDecorator: null
};
if (props.value !== undefined) {
_this.controlledMode = true;
}
return _this;
}
EditorCore.ToEditorState = function ToEditorState(text) {
var createEmptyContentState = ContentState.createFromText(decodeContent(text) || '');
var editorState = EditorState.createWithContent(createEmptyContentState);
return EditorState.forceSelection(editorState, createEmptyContentState.getSelectionAfter());
};
EditorCore.prototype.getDefaultValue = function getDefaultValue() {
var _props = this.props,
defaultValue = _props.defaultValue,
value = _props.value;
return value || defaultValue;
};
EditorCore.prototype.Reset = function Reset() {
var defaultValue = this.getDefaultValue();
var contentState = defaultValue ? defaultValue.getCurrentContent() : ContentState.createFromText('');
var updatedEditorState = EditorState.push(this.state.editorState, contentState, 'remove-range');
this.setEditorState(EditorState.forceSelection(updatedEditorState, contentState.getSelectionBefore()));
};
EditorCore.prototype.SetText = function SetText(text) {
var createTextContentState = ContentState.createFromText(text || '');
var editorState = EditorState.push(this.state.editorState, createTextContentState, 'change-block-data');
this.setEditorState(EditorState.moveFocusToEnd(editorState), true);
};
EditorCore.prototype.getChildContext = function getChildContext() {
return {
getEditorState: this.getEditorState,
setEditorState: this.setEditorState
};
};
EditorCore.prototype.reloadPlugins = function reloadPlugins() {
var _this2 = this;
return this.plugins && this.plugins.size ? this.plugins.map(function (plugin) {
// 如果插件有 callbacks 方法,则认为插件已经加载。
if (plugin.callbacks) {
return plugin;
}
// 如果插件有 constructor 方法,则构造插件
if (plugin.hasOwnProperty('constructor')) {
var pluginConfig = _extends(_this2.props.pluginConfig, plugin.config || {}, defaultPluginConfig);
return plugin.constructor(pluginConfig);
}
// else 无效插件
console.warn('>> 插件: [', plugin.name, '] 无效。插件或许已经过期。');
return false;
}).filter(function (plugin) {
return plugin;
}).toArray() : [];
};
EditorCore.prototype.componentWillMount = function componentWillMount() {
var plugins = this.initPlugins().concat([toolbar]);
var customStyleMap = {};
var customBlockStyleMap = {};
var customBlockRenderMap = Map(DefaultDraftBlockRenderMap);
var toHTMLList = List([]);
// initialize compositeDecorator
var compositeDecorator = new CompositeDecorator(plugins.filter(function (plugin) {
return plugin.decorators !== undefined;
}).map(function (plugin) {
return plugin.decorators;
}).reduce(function (prev, curr) {
return prev.concat(curr);
}, []));
// initialize Toolbar
var toolbarPlugins = List(plugins.filter(function (plugin) {
return !!plugin.component && plugin.name !== 'toolbar';
}));
// load inline styles...
plugins.forEach(function (plugin) {
var styleMap = plugin.styleMap,
blockStyleMap = plugin.blockStyleMap,
blockRenderMap = plugin.blockRenderMap,
toHtml = plugin.toHtml;
if (styleMap) {
for (var key in styleMap) {
if (styleMap.hasOwnProperty(key)) {
customStyleMap[key] = styleMap[key];
}
}
}
if (blockStyleMap) {
for (var _key in blockStyleMap) {
if (blockStyleMap.hasOwnProperty(_key)) {
customBlockStyleMap[_key] = blockStyleMap[_key];
customBlockRenderMap = customBlockRenderMap.set(_key, {
element: null
});
}
}
}
if (toHtml) {
toHTMLList = toHTMLList.push(toHtml);
}
if (blockRenderMap) {
for (var _key2 in blockRenderMap) {
if (blockRenderMap.hasOwnProperty(_key2)) {
customBlockRenderMap = customBlockRenderMap.set(_key2, blockRenderMap[_key2]);
}
}
}
});
configStore.set('customStyleMap', customStyleMap);
configStore.set('customBlockStyleMap', customBlockStyleMap);
configStore.set('blockRenderMap', customBlockRenderMap);
configStore.set('customStyleFn', this.customStyleFn.bind(this));
configStore.set('toHTMLList', toHTMLList);
this.setState({
toolbarPlugins: toolbarPlugins,
compositeDecorator: compositeDecorator
});
this.setEditorState(EditorState.set(this.state.editorState, { decorator: compositeDecorator }), false, false);
};
EditorCore.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
if (this.forceUpdateImmediate) {
this.cancelForceUpdateImmediate();
}
if (this.controlledMode) {
var decorators = nextProps.value.getDecorator();
var editorState = decorators ? nextProps.value : EditorState.set(nextProps.value, { decorator: this.state.compositeDecorator });
this.setState({
editorState: editorState
});
}
};
EditorCore.prototype.componentWillUnmount = function componentWillUnmount() {
this.cancelForceUpdateImmediate();
};
// 处理 value
EditorCore.prototype.generatorDefaultValue = function generatorDefaultValue(editorState) {
var defaultValue = this.getDefaultValue();
if (defaultValue) {
return defaultValue;
}
return editorState;
};
EditorCore.prototype.getStyleMap = function getStyleMap() {
return configStore.get('customStyleMap');
};
EditorCore.prototype.setStyleMap = function setStyleMap(customStyleMap) {
configStore.set('customStyleMap', customStyleMap);
this.render();
};
EditorCore.prototype.initPlugins = function initPlugins() {
var _this3 = this;
var enableCallbacks = ['focus', 'getEditorState', 'setEditorState', 'getStyleMap', 'setStyleMap'];
return this.getPlugins().map(function (plugin) {
enableCallbacks.forEach(function (callbackName) {
if (plugin.callbacks.hasOwnProperty(callbackName)) {
plugin.callbacks[callbackName] = _this3[callbackName].bind(_this3);
}
});
return plugin;
});
};
EditorCore.prototype.focusEditor = function focusEditor(ev) {
this.refs.editor.focus(ev);
if (this.props.readOnly) {
this._focusDummy.focus();
}
if (this.props.onFocus) {
this.props.onFocus(ev);
}
};
EditorCore.prototype._focus = function _focus(ev) {
if (!ev || !ev.nativeEvent || !ev.nativeEvent.target) {
return;
}
if (document.activeElement && document.activeElement.getAttribute('contenteditable') === 'true') {
return;
}
return this.focus(ev);
};
EditorCore.prototype.focus = function focus(ev) {
var _this4 = this;
var event = ev && ev.nativeEvent;
if (event && event.target === this._editorWrapper) {
var editorState = this.state.editorState;
var selection = editorState.getSelection();
if (!selection.getHasFocus()) {
if (selection.isCollapsed()) {
return this.setState({
editorState: EditorState.moveSelectionToEnd(editorState)
}, function () {
_this4.focusEditor(ev);
});
}
}
}
this.focusEditor(ev);
};
EditorCore.prototype.getPlugins = function getPlugins() {
return this.state.plugins.slice();
};
EditorCore.prototype.getEventHandler = function getEventHandler() {
var _this5 = this;
var enabledEvents = ['onUpArrow', 'onDownArrow', 'handleReturn', 'onFocus', 'onBlur', 'onTab', 'handlePastedText'];
var eventHandler = {};
enabledEvents.forEach(function (event) {
eventHandler[event] = _this5.generatorEventHandler(event);
});
return eventHandler;
};
EditorCore.prototype.getEditorState = function getEditorState() {
var needFocus = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
if (needFocus) {
this.refs.editor.focus();
}
return this.state.editorState;
};
EditorCore.prototype.setEditorState = function setEditorState(editorState) {
var _this6 = this;
var focusEditor = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var triggerChange = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
var newEditorState = editorState;
this.getPlugins().forEach(function (plugin) {
if (plugin.onChange) {
var updatedEditorState = plugin.onChange(newEditorState);
if (updatedEditorState) {
newEditorState = updatedEditorState;
}
}
});
if (this.props.onChange && triggerChange) {
this.props.onChange(newEditorState);
// close this issue https://github.com/ant-design/ant-design/issues/5788
// when onChange not take any effect
// `<Editor />` won't rerender cause no props is changed.
// add an timeout here,
// if props.onChange not trigger componentWillReceiveProps,
// we will force render Editor with previous editorState,
if (this.controlledMode) {
this.forceUpdateImmediate = setImmediate(function () {
return _this6.setState({
editorState: new EditorState(_this6.state.editorState.getImmutable())
});
});
}
}
if (!this.controlledMode) {
this.setState({ editorState: newEditorState }, focusEditor ? function () {
return setImmediate(function () {
return _this6.refs.editor.focus();
});
} : noop);
}
};
EditorCore.prototype.handleKeyBinding = function handleKeyBinding(ev) {
if (this.props.onKeyDown) {
ev.ctrlKey = hasCommandModifier(ev);
var keyDownResult = this.props.onKeyDown(ev);
if (keyDownResult) {
return keyDownResult;
}
return getDefaultKeyBinding(ev);
}
return getDefaultKeyBinding(ev);
};
EditorCore.prototype.handleKeyCommand = function handleKeyCommand(command) {
if (this.props.multiLines) {
return this.eventHandle('handleKeyBinding', command);
}
return command === 'split-block' ? 'handled' : 'not-handled';
};
EditorCore.prototype.getBlockStyle = function getBlockStyle(contentBlock) {
var customBlockStyleMap = configStore.get('customBlockStyleMap');
var type = contentBlock.getType();
if (customBlockStyleMap.hasOwnProperty(type)) {
return customBlockStyleMap[type];
}
return '';
};
EditorCore.prototype.blockRendererFn = function blockRendererFn(contentBlock) {
var blockRenderResult = null;
this.getPlugins().forEach(function (plugin) {
if (plugin.blockRendererFn) {
var result = plugin.blockRendererFn(contentBlock);
if (result) {
blockRenderResult = result;
}
}
});
return blockRenderResult;
};
EditorCore.prototype.eventHandle = function eventHandle(eventName) {
var _props2;
var plugins = this.getPlugins();
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key3 = 1; _key3 < _len; _key3++) {
args[_key3 - 1] = arguments[_key3];
}
for (var i = 0; i < plugins.length; i++) {
var plugin = plugins[i];
if (plugin.callbacks[eventName] && typeof plugin.callbacks[eventName] === 'function') {
var _plugin$callbacks;
var result = (_plugin$callbacks = plugin.callbacks)[eventName].apply(_plugin$callbacks, args);
if (result === true) {
return 'handled';
}
}
}
return this.props.hasOwnProperty(eventName) && (_props2 = this.props)[eventName].apply(_props2, args) === true ? 'handled' : 'not-handled';
};
EditorCore.prototype.generatorEventHandler = function generatorEventHandler(eventName) {
var _this7 = this;
return function () {
for (var _len2 = arguments.length, args = Array(_len2), _key4 = 0; _key4 < _len2; _key4++) {
args[_key4] = arguments[_key4];
}
return _this7.eventHandle.apply(_this7, [eventName].concat(args));
};
};
EditorCore.prototype.customStyleFn = function customStyleFn(styleSet) {
if (styleSet.size === 0) {
return {};
}
var plugins = this.getPlugins();
var resultStyle = {};
for (var i = 0; i < plugins.length; i++) {
if (plugins[i].customStyleFn) {
var styled = plugins[i].customStyleFn(styleSet);
if (styled) {
_extends(resultStyle, styled);
}
}
}
return resultStyle;
};
EditorCore.prototype.render = function render() {
var _classnames,
_this8 = this;
var _props3 = this.props,
prefixCls = _props3.prefixCls,
toolbars = _props3.toolbars,
style = _props3.style,
readOnly = _props3.readOnly,
multiLines = _props3.multiLines;
var _state = this.state,
editorState = _state.editorState,
toolbarPlugins = _state.toolbarPlugins;
var customStyleMap = configStore.get('customStyleMap');
var blockRenderMap = configStore.get('blockRenderMap');
var eventHandler = this.getEventHandler();
var Toolbar = toolbar.component;
var cls = classnames((_classnames = {}, _classnames[prefixCls + '-editor'] = true, _classnames.readonly = readOnly, _classnames.oneline = !multiLines, _classnames));
return React.createElement(
'div',
{ style: style, className: cls, onClick: this._focus.bind(this) },
React.createElement(Toolbar, { editorState: editorState, prefixCls: prefixCls, className: prefixCls + '-toolbar', plugins: toolbarPlugins, toolbars: toolbars }),
React.createElement(
'div',
{ className: prefixCls + '-editor-wrapper', ref: function ref(ele) {
return _this8._editorWrapper = ele;
}, style: style, onClick: function onClick(ev) {
return ev.preventDefault();
} },
React.createElement(Editor, _extends({}, this.props, eventHandler, { ref: 'editor', customStyleMap: customStyleMap, customStyleFn: this.customStyleFn.bind(this), editorState: editorState, handleKeyCommand: this.handleKeyCommand.bind(this), keyBindingFn: this.handleKeyBinding.bind(this), onChange: this.setEditorState.bind(this), blockStyleFn: this.getBlockStyle.bind(this), blockRenderMap: blockRenderMap, handlePastedText: this.handlePastedText, blockRendererFn: this.blockRendererFn.bind(this) })),
readOnly ? React.createElement('input', { style: focusDummyStyle, ref: function ref(ele) {
return _this8._focusDummy = ele;
}, onBlur: eventHandler.onBlur }) : null,
this.props.children
)
);
};
return EditorCore;
}(React.Component)
Example #7
Source File: Mention.react.js From spring-boot-ecommerce with Apache License 2.0 | 4 votes |
Mention = function (_React$Component) {
_inherits(Mention, _React$Component);
function Mention(props) {
_classCallCheck(this, Mention);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props));
_this.onEditorChange = function (editorState) {
var selection = editorState.getSelection();
_this._decorator = editorState.getDecorator();
var content = editorState.getCurrentContent();
if (_this.props.onChange) {
_this.setState({
selection: selection
}, function () {
_this.props.onChange(content, exportContent(content));
});
} else {
_this.setState({
editorState: editorState,
selection: selection
});
}
};
_this.onFocus = function (e) {
if (_this.props.onFocus) {
_this.props.onFocus(e);
}
};
_this.onBlur = function (e) {
if (_this.props.onBlur) {
_this.props.onBlur(e);
}
};
_this.onKeyDown = function (e) {
if (_this.props.onKeyDown) {
_this.props.onKeyDown(e);
}
};
_this.reset = function () {
/*eslint-disable*/
_this._editor.Reset();
/*eslint-enable*/
};
_this.mention = createMention({
prefix: _this.getPrefix(props),
tag: props.tag,
mode: props.mode,
mentionStyle: props.mentionStyle
});
_this.Suggestions = _this.mention.Suggestions;
_this.plugins = [_this.mention];
_this.state = {
suggestions: props.suggestions,
value: props.value && EditorState.createWithContent(props.value, new CompositeDecorator(_this.mention.decorators)),
selection: SelectionState.createEmpty()
};
if (typeof props.defaultValue === 'string') {
// eslint-disable-next-line
console.warn('The property `defaultValue` now allow `EditorState` only, see http://react-component.github.io/editor-mention/examples/defaultValue.html ');
}
if (props.value !== undefined) {
_this.controlledMode = true;
}
return _this;
}
Mention.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
var suggestions = nextProps.suggestions;
var selection = this.state.selection;
var value = nextProps.value;
if (value && selection) {
value = EditorState.acceptSelection(EditorState.createWithContent(value, this._decorator), selection);
}
this.setState({
suggestions: suggestions,
value: value
});
};
Mention.prototype.getPrefix = function getPrefix() {
var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.props;
return Array.isArray(props.prefix) ? props.prefix : [props.prefix];
};
Mention.prototype.render = function render() {
var _classnames,
_this2 = this;
var _props = this.props,
prefixCls = _props.prefixCls,
style = _props.style,
tag = _props.tag,
multiLines = _props.multiLines,
editorKey = _props.editorKey,
suggestionStyle = _props.suggestionStyle,
placeholder = _props.placeholder,
defaultValue = _props.defaultValue,
className = _props.className,
notFoundContent = _props.notFoundContent,
getSuggestionContainer = _props.getSuggestionContainer,
readOnly = _props.readOnly,
disabled = _props.disabled,
placement = _props.placement,
mode = _props.mode;
var suggestions = this.state.suggestions;
var Suggestions = this.Suggestions;
var editorClass = classnames(className, (_classnames = {}, _classnames[prefixCls + '-wrapper'] = true, _classnames.readonly = readOnly, _classnames.disabled = disabled, _classnames.multilines = multiLines, _classnames));
var editorProps = this.controlledMode ? { value: this.state.value } : {};
var defaultValueState = defaultValue && EditorState.createWithContent(typeof defaultValue === 'string' ? ContentState.createFromText(defaultValue) : defaultValue, this._decorator);
return React.createElement(
'div',
{ className: editorClass, style: style, ref: function ref(wrapper) {
return _this2._wrapper = wrapper;
} },
React.createElement(
EditorCore,
_extends({
ref: function ref(editor) {
return _this2._editor = editor;
},
prefixCls: prefixCls,
style: style,
multiLines: multiLines,
editorKey: editorKey,
plugins: this.plugins,
defaultValue: defaultValueState,
placeholder: placeholder,
onFocus: this.onFocus,
onBlur: this.onBlur,
onKeyDown: this.onKeyDown,
onChange: this.onEditorChange
}, editorProps, {
readOnly: readOnly || disabled
}),
React.createElement(Suggestions, {
mode: tag ? 'immutable' : mode,
prefix: this.getPrefix(),
prefixCls: prefixCls,
style: suggestionStyle,
placement: placement,
notFoundContent: notFoundContent,
suggestions: suggestions,
getSuggestionContainer: getSuggestionContainer ? function () {
return getSuggestionContainer(_this2._wrapper);
} : null,
onSearchChange: this.props.onSearchChange,
onSelect: this.props.onSelect,
noRedup: this.props.noRedup
})
)
);
};
return Mention;
}(React.Component)
Example #8
Source File: EditorUtilities.spec.js From wix-style-react with MIT License | 4 votes |
describe('EditorUtilities', () => {
const linkEntity = {
text: 'Test',
url: 'http://wix.com',
};
let editorState;
beforeEach(() => {
editorState = EditorState.createEmpty();
});
describe('hasStyle', () => {
it('should return true when editor contains a style', () => {
const newEditorState = EditorUtilities.toggleStyle(
editorState,
inlineStyleTypes.bold,
);
expect(
EditorUtilities.hasStyle(newEditorState, inlineStyleTypes.bold),
).toBe(true);
});
it(`should return false when editor contains a style but the selection does not`, () => {
let newEditorState = EditorUtilities.toggleStyle(
editorState,
inlineStyleTypes.bold,
);
newEditorState = EditorState.moveSelectionToEnd(editorState);
expect(
EditorUtilities.hasStyle(newEditorState, inlineStyleTypes.bold),
).toBe(false);
});
});
describe('hasBlockType', () => {
it('should return true when editor contains a block type', () => {
const newEditorState = EditorUtilities.toggleBlockType(
editorState,
blockTypes.bulletedList,
);
expect(
EditorUtilities.hasBlockType(newEditorState, blockTypes.bulletedList),
).toBe(true);
});
it(`should return false when editor contains a block type but the selection does not`, () => {
let newEditorState = EditorUtilities.toggleBlockType(
editorState,
inlineStyleTypes.bulletedList,
);
newEditorState = EditorState.moveSelectionToEnd(editorState);
expect(
EditorUtilities.hasBlockType(newEditorState, blockTypes.bulletedList),
).toBe(false);
});
});
describe('hasEntity', () => {
it('should return true when editor contains an entity', () => {
const newEditorState = EditorUtilities.toggleLink(
editorState,
linkEntity,
);
expect(EditorUtilities.hasEntity(newEditorState, entityTypes.link)).toBe(
true,
);
});
it(`should return false when editor contains an entity but the selection does not`, () => {
let newEditorState = EditorUtilities.toggleLink(editorState, linkEntity);
newEditorState = EditorState.moveSelectionToEnd(editorState);
expect(EditorUtilities.hasEntity(newEditorState, entityTypes.link)).toBe(
false,
);
});
});
it('should attach the specified style to a block', () => {
const newEditorState = EditorUtilities.toggleStyle(
editorState,
inlineStyleTypes.italic,
);
expect(
EditorUtilities.hasStyle(newEditorState, inlineStyleTypes.italic),
).toBe(true);
});
it('should attach the specified type to a block', () => {
const newEditorState = EditorUtilities.toggleBlockType(
editorState,
blockTypes.numberedList,
);
expect(
EditorUtilities.hasBlockType(newEditorState, blockTypes.numberedList),
).toBe(true);
});
describe('toggleLink', () => {
it('should attach the specified entity to a block', () => {
const newEditorState = EditorUtilities.toggleLink(
editorState,
linkEntity,
);
expect(EditorUtilities.hasEntity(newEditorState, entityTypes.link)).toBe(
true,
);
});
it('should insert the text of the specified entity to a block', () => {
const initialText = editorState.getCurrentContent().getPlainText();
const newEditorState = EditorUtilities.toggleLink(
editorState,
linkEntity,
);
const currentText = newEditorState.getCurrentContent().getPlainText();
expect(initialText).toEqual('');
expect(currentText).toEqual(linkEntity.text);
});
});
describe('getSelectedText', () => {
it('should be empty when no text is selected', () => {
expect(EditorUtilities.getSelectedText(editorState)).toEqual('');
});
it('should return the selected text', () => {
const expectedText = 'Test2';
editorState = EditorState.createWithContent(
ContentState.createFromText(`Test1\n${expectedText}\nTest3`),
);
const middleBlock = editorState.getCurrentContent().getBlocksAsArray()[1];
const anchorOffset = editorState.getSelection().getStartOffset();
const newEditorState = EditorState.acceptSelection(
editorState,
new SelectionState({
anchorOffset,
anchorKey: middleBlock.getKey(),
focusOffset: anchorOffset + middleBlock.getText().length,
focusKey: middleBlock.getKey(),
}),
);
expect(EditorUtilities.getSelectedText(newEditorState)).toEqual(
expectedText,
);
});
});
});
Example #9
Source File: AddEditActivity.js From medha-STPC with GNU Affero General Public License v3.0 | 4 votes |
AddEditActivity = props => {
let history = useHistory();
const dateFrom = "dateFrom";
const dateTo = "dateTo";
const [editorState, setEditorState] = useState(EditorState.createEmpty());
const [backDrop, setBackDrop] = useState(false);
const [formState, setFormState] = useState({
isValid: false,
values: {
dateFrom: moment(),
dateTo: moment()
},
touched: {},
errors: {},
isSuccess: false,
showPassword: false,
editActivity: props.location.editActivity
? props.location.editActivity
: false,
dataForEdit: props.location.dataForEdit
? props.location.dataForEdit
: false,
counter: 0,
testCounter: 0,
stream: [],
files: null,
descriptionError: false,
discriptionMinLengthError: false,
previewFile: {},
showPreview: false,
showEditPreview: props.location.editActivity
? props.location.dataForEdit.upload_logo
? true
: false
: false,
showNoImage: props.location.editActivity
? false
: props.location.editActivity
});
if (formState.dataForEdit && !formState.counter) {
if (props.location["dataForEdit"]) {
if (props.location["dataForEdit"]["title"]) {
formState.values["activityname"] =
props.location["dataForEdit"]["title"];
}
if (props.location["dataForEdit"]["activitytype"]) {
formState.values["activitytype"] =
props.location["dataForEdit"]["activitytype"]["id"];
}
if (
props.location["dataForEdit"]["academic_year"] &&
props.location["dataForEdit"]["academic_year"]["id"]
) {
formState.values["academicyear"] =
props.location["dataForEdit"]["academic_year"]["id"];
}
if (props.location["dataForEdit"]["streams"]) {
formState.values["stream"] = props.location["dataForEdit"]["streams"];
}
if (props.location["dataForEdit"]["address"]) {
formState.values["address"] = props.location["dataForEdit"]["address"];
}
if (props.location["dataForEdit"]["education_year"]) {
formState.values["educationyear"] =
props.location["dataForEdit"]["education_year"];
}
if (props.location["dataForEdit"]["activity_status"]) {
formState.values["activitystatus"] =
props.location["dataForEdit"]["activity_status"];
}
if (
props.location["dataForEdit"]["question_set"] &&
props.location["dataForEdit"]["question_set"]
) {
formState.values["questionSet"] =
props.location["dataForEdit"]["question_set"]["id"];
}
if (props.location["dataForEdit"]["description"]) {
// formState.values["description"] = props["dataForEdit"]["description"];
const blocksFromHtml = htmlToDraft(
props.location["dataForEdit"]["description"]
);
const { contentBlocks, entityMap } = blocksFromHtml;
const contentState = ContentState.createFromBlockArray(
contentBlocks,
entityMap
);
const editorState = EditorState.createWithContent(contentState);
setEditorState(editorState);
}
if (props.location["dataForEdit"]["trainer_name"]) {
formState.values["trainer"] =
props.location["dataForEdit"]["trainer_name"];
}
if (
props.location["dataForEdit"]["contact"] &&
props.location["dataForEdit"]["contact"]["id"]
) {
formState.values["college"] =
props.location["dataForEdit"]["contact"]["id"];
}
if (props.location["dataForEdit"]["start_date_time"]) {
formState.values[dateFrom] = moment(
props.location["dataForEdit"]["start_date_time"]
);
}
if (props.location["dataForEdit"]["end_date_time"]) {
formState.values[dateTo] = moment(
props.location["dataForEdit"]["end_date_time"]
);
}
if (
props.location["dataForEdit"]["upload_logo"] &&
props.location["dataForEdit"]["upload_logo"]["id"]
) {
formState.files = props.location["dataForEdit"]["upload_logo"];
// formState.values["files"] =
// props.location["dataForEdit"]["upload_logo"]["name"];
}
}
formState.counter += 1;
}
if (props.location.state && !formState.counter) {
if (props.location.state.contactNumber && props.location.state.otp) {
formState.values["contact"] = props.location.state.contactNumber;
formState.values["otp"] = props.location.state.otp;
}
formState.counter += 1;
}
// const [selectedDateFrom, setSelectedDateFrom] = React.useState(new Date());
// const [selectedDateTo, setSelectedDateTo] = React.useState(new Date());
const { setLoaderStatus } = useContext(LoaderContext);
const educationyearlist = [
{ name: "First", id: "First" },
{ name: "Second", id: "Second" },
{ name: "Third", id: "Third" }
];
const activityNameList = [
{ name: "Soft Skills 1", id: "Soft Skills 1" },
{ name: "Soft Skills 2", id: "Soft Skills 2" },
{ name: "Career Awareness 1", id: "Career Awareness 1" },
{ name: "Career Awareness 2", id: "Career Awareness 2" },
{ name: "Job Preparation 1", id: "Job Preparation 1" },
{ name: "Job Preparation 2", id: "Job Preparation 2" },
{ name: "Job Preparation 3", id: "Job Preparation 3" },
{ name: "Industrial Visit", id: "Industrial Visit" },
{ name: "Industry Talk", id: "Industry Talk" }
];
const activityStatus = [
{ name: "Scheduled", id: "scheduled" },
{ name: "Completed", id: "completed" },
{ name: "Cancelled", id: "cancelled" }
];
const [stream, setStream] = useState([]);
const [isFailed, setIsFailed] = useState(false);
const classes = useStyles();
const [collegelist, setcollegelist] = useState(
props.collegeListForTest ? props.collegeListForTest : []
);
const [streamlist, setstreamlist] = useState(
props.streamListForTest ? props.streamListForTest : []
);
const [collegeStreamList, setCollegeStreamList] = useState(
props.collegeStreamListForTest ? props.collegeStreamListForTest : []
);
const [activityType, setActivityType] = useState(
props.activityTypeListForTest ? props.activityTypeListForTest : []
);
const [questionSetData, setQuestionSetData] = useState(
props.questionSetListForTest ? props.questionSetListForTest : []
);
if (
!formState.dataForEdit &&
props.isDataForTesting &&
!formState.testCounter
) {
const html = "<p>Test Data</p>";
const contentBlock = htmlToDraft(html);
if (contentBlock) {
const contentState = ContentState.createFromBlockArray(
contentBlock.contentBlocks
);
const editorState = EditorState.createWithContent(contentState);
setEditorState(editorState);
formState.testCounter += 1;
}
}
useEffect(() => {
serviceProvider
.serviceProviderForGetRequest(QUESTION_SET)
.then(res => {
setQuestionSetData(res.data);
})
.catch(error => {});
getColleges();
getStreams();
getActivityTypes();
}, []);
const getActivityTypes = async () => {
const activityTypeUrl =
strapiApiConstants.STRAPI_DB_URL +
strapiApiConstants.STRAPI_ACTIVITY_TYPE;
await serviceProvider
.serviceProviderForGetRequest(activityTypeUrl)
.then(res => {
setActivityType(res.data);
})
.catch(error => {});
};
const getStreams = () => {
axios
.get(strapiApiConstants.STRAPI_DB_URL + strapiApiConstants.STRAPI_STREAMS)
.then(res => {
const list = res.data.map(({ id, name }) => ({
id,
name
}));
setstreamlist(list);
if (formState.dataForEdit) {
const streamIds = props.location["dataForEdit"]["streams"].map(
stream => stream.id
);
const selectedStream = list.filter(stream => {
if (includes(streamIds, stream.id)) {
return stream;
}
});
setStream(selectedStream);
}
});
};
useEffect(() => {
setLoaderStatus(true);
if (
formState.values.hasOwnProperty("college") &&
formState.values["college"] &&
collegelist.length > 0
) {
const college = collegelist.find(
college => college.contact.id == formState.values["college"]
);
const collegeStreamIds = college.stream_strength.map(s => s.stream.id);
const list = streamlist.filter(stream => {
if (includes(collegeStreamIds, stream.id)) {
return stream;
}
});
setCollegeStreamList(list);
}
setLoaderStatus(false);
}, [formState.values["college"], collegelist, streamlist]);
const handleSubmit = event => {
event.preventDefault();
setBackDrop(true);
let isValid = false;
let checkAllFieldsValid = formUtilities.checkAllKeysPresent(
formState.values,
ActivityFormSchema
);
if (checkAllFieldsValid) {
/** Evaluated only if all keys are valid inside formstate */
formState.errors = formUtilities.setErrors(
formState.values,
ActivityFormSchema,
true,
dateFrom,
dateTo
);
if (formUtilities.checkEmpty(formState.errors)) {
isValid = true;
}
} else {
/** This is used to find out which all required fields are not filled */
formState.values = formUtilities.getListOfKeysNotPresent(
formState.values,
ActivityFormSchema
);
formState.errors = formUtilities.setErrors(
formState.values,
ActivityFormSchema,
true,
dateFrom,
dateTo
);
}
formState.descriptionError = false;
if (
convertToRaw(editorState.getCurrentContent()).blocks &&
convertToRaw(editorState.getCurrentContent()).blocks.length
) {
let arrayToCheckIn = convertToRaw(editorState.getCurrentContent()).blocks;
let validationCounter = 0;
let validationMinCounter = 0;
for (let i in arrayToCheckIn) {
if (
arrayToCheckIn[i]["text"] &&
arrayToCheckIn[i]["text"].trim().length !== 0
) {
validationCounter += 1;
break;
}
}
if (validationCounter === 0) {
formState.descriptionError = true;
}
for (let i in arrayToCheckIn) {
if (
arrayToCheckIn[i]["text"] &&
arrayToCheckIn[i]["text"].trim().length > 320
) {
validationMinCounter += 1;
break;
}
}
if (validationMinCounter !== 0) {
formState.discriptionMinLengthError = true;
}
}
if (
isValid &&
!formState.descriptionError &&
!formState.discriptionMinLengthError
) {
/** CALL POST FUNCTION */
postActivityData();
/** Call axios from here */
setFormState(formState => ({
...formState,
isValid: true
}));
} else {
setBackDrop(false);
setFormState(formState => ({
...formState,
isValid: false
}));
}
};
const postActivityData = () => {
let postData;
if (formState.editActivity) {
postData = databaseUtilities.editActivity(
formState.showPreview,
formState.values["activityname"],
formState.values["activitytype"],
formState.values["college"],
formState.values[dateFrom],
formState.values[dateTo],
formState.values["educationyear"],
formState.values["address"],
draftToHtml(convertToRaw(editorState.getCurrentContent())),
formState.values["trainer"],
stream.map(stream => stream.id),
formState["dataForEdit"]["id"],
formState.files,
formState.values["questionSet"],
formState.values["activitystatus"]
);
serviceProvider
.serviceProviderForPutRequest(
strapiApiConstants.STRAPI_DB_URL + strapiApiConstants.STRAPI_ACTIVITY,
formState.dataForEdit.id,
postData
)
.then(response => {
setFormState({ ...formState, isSuccess: true });
history.push({
pathname: routeConstants.MANAGE_ACTIVITY,
isDataEdited: true,
editedData: response.data,
fromEditActivity: true
});
setBackDrop(false);
})
.catch(err => {
setIsFailed(true);
setBackDrop(false);
});
} else {
postData = databaseUtilities.addActivity(
formState.values["activityname"],
formState.values["activitytype"],
formState.values["college"],
formState.values[dateFrom],
formState.values[dateTo],
formState.values["educationyear"],
formState.values["address"],
draftToHtml(convertToRaw(editorState.getCurrentContent())),
formState.values["trainer"],
stream.map(stream => stream.id),
formState.files,
formState.values["questionSet"]
);
serviceProvider
.serviceProviderForPostRequest(
strapiApiConstants.STRAPI_DB_URL + strapiApiConstants.STRAPI_ACTIVITY,
postData
)
.then(({ data }) => {
history.push({
pathname: routeConstants.MANAGE_ACTIVITY,
isDataAdded: true,
addedData: data,
fromAddActivity: true
});
setBackDrop(false);
})
.catch(err => {
setIsFailed(true);
setBackDrop(false);
});
}
};
const getColleges = async () => {
await serviceProvider
.serviceProviderForGetRequest(
strapiApiConstants.STRAPI_DB_URL + strapiApiConstants.STRAPI_COLLEGES,
{ pageSize: -1 }
)
.then(res => {
setcollegelist(
res.data.result.map(({ id, name, contact, stream_strength }) => ({
id,
name,
contact,
stream_strength
}))
);
});
};
const handleChangefile = e => {
e.persist();
setFormState(formState => ({
...formState,
values: {
...formState.values,
[e.target.name]: e.target.files[0].name
},
touched: {
...formState.touched,
[e.target.name]: true
},
files: e.target.files[0],
previewFile: URL.createObjectURL(e.target.files[0]),
showPreview: true,
showEditPreview: false,
showNoImage: false
}));
if (formState.errors.hasOwnProperty(e.target.name)) {
delete formState.errors[e.target.name];
}
};
const handleChange = e => {
/** TO SET VALUES IN FORMSTATE */
e.persist();
setFormState(formState => ({
...formState,
values: {
...formState.values,
[e.target.name]:
e.target.type === "checkbox" ? e.target.checked : e.target.value
},
touched: {
...formState.touched,
[e.target.name]: true
}
}));
if (formState.errors.hasOwnProperty(e.target.name)) {
delete formState.errors[e.target.name];
}
};
const handleChangeAutoComplete = (eventName, event, value) => {
/**TO SET VALUES OF AUTOCOMPLETE */
if (value !== null) {
if (eventName === "college") {
setFormState(formState => ({
...formState,
values: {
...formState.values,
[eventName]: value.contact.id
},
touched: {
...formState.touched,
[eventName]: true
}
}));
} else {
setFormState(formState => ({
...formState,
values: {
...formState.values,
[eventName]: value.id
},
touched: {
...formState.touched,
[eventName]: true
}
}));
}
if (formState.errors.hasOwnProperty(eventName)) {
delete formState.errors[eventName];
}
} else {
if (eventName === "college") {
delete formState.values["stream"];
formState.stream = [];
setCollegeStreamList([]);
setStream([]);
}
delete formState.values[eventName];
}
};
const handleStreamChange = (eventName, event, value) => {
/**TO SET VALUES OF AUTOCOMPLETE */
if (value !== null) {
setFormState(formState => ({
...formState,
values: {
...formState.values,
[eventName]: value
},
touched: {
...formState.touched,
[eventName]: true
}
}));
if (formState.errors.hasOwnProperty(eventName)) {
delete formState.errors[eventName];
}
setStream(value);
}
};
const handleDateChange = (dateObject, event) => {
if (formState.errors.hasOwnProperty(dateObject)) {
delete formState.errors[dateObject];
}
setFormState(formState => ({
...formState,
values: {
...formState.values,
[dateObject]: event
},
touched: {
...formState.touched,
[dateObject]: true
},
isStateClearFilter: false
}));
};
const hasError = field => (formState.errors[field] ? true : false);
return (
<Grid>
<Grid item xs={12} className={classes.title}>
<Typography variant="h4" gutterBottom>
{formState.editActivity
? genericConstants.EDIT_ACTIVITY_TEXT
: genericConstants.ADD_ACTIVITY_TEXT}
</Typography>
{isFailed && formState.editActivity ? (
<Collapse in={isFailed}>
<Alert
severity="error"
action={
<IconButton
aria-label="close"
color="inherit"
size="small"
onClick={() => {
setIsFailed(false);
}}
>
<CloseIcon fontSize="inherit" />
</IconButton>
}
>
{genericConstants.ALERT_ERROR_DATA_EDITED_MESSAGE}
</Alert>
</Collapse>
) : null}
{isFailed && !formState.editActivity ? (
<Collapse in={isFailed}>
<Alert
severity="error"
action={
<IconButton
aria-label="close"
color="inherit"
size="small"
onClick={() => {
setIsFailed(false);
}}
>
<CloseIcon fontSize="inherit" />
</IconButton>
}
>
{genericConstants.ALERT_ERROR_DATA_ADDED_MESSAGE}
</Alert>
</Collapse>
) : null}
</Grid>
<Grid spacing={3}>
<Card>
<form autoComplete="off" noValidate>
<CardContent>
<Grid item xs={12} md={6} xl={3}>
<Grid container className={classes.formgridInputFile}>
<Grid item md={10} xs={12}>
<div className={classes.imageDiv}>
{formState.showPreview ? (
<Img
alt="abc"
loader={<Spinner />}
className={classes.UploadImage}
src={formState.previewFile}
/>
) : null}
{!formState.showPreview && !formState.showEditPreview ? (
<div className={classes.DefaultNoImage}></div>
) : null}
{/* {formState.showEditPreview&&formState.dataForEdit.upload_logo===null? <div class={classes.DefaultNoImage}></div>:null} */}
{formState.showEditPreview &&
formState.dataForEdit["upload_logo"] !== null &&
formState.dataForEdit["upload_logo"] !== undefined &&
formState.dataForEdit["upload_logo"] !== {} ? (
<Img
src={
strapiApiConstants.STRAPI_DB_URL_WITHOUT_HASH +
formState.dataForEdit["upload_logo"]["url"]
}
loader={<Spinner />}
className={classes.UploadImage}
/>
) : null}
{formState.showNoImage ? (
<Img
src="/images/noImage.png"
loader={<Spinner />}
className={classes.UploadImage}
/>
) : null}
</div>
</Grid>
</Grid>
<Grid container className={classes.MarginBottom}>
<Grid item md={10} xs={12}>
<TextField
fullWidth
id="files"
margin="normal"
name="files"
placeholder="Upload Logo"
onChange={handleChangefile}
required
type="file"
inputProps={{ accept: "image/*" }}
//value={formState.values["files"] || ""}
error={hasError("files")}
helperText={
hasError("files")
? formState.errors["files"].map(error => {
return error + " ";
})
: null
}
variant="outlined"
className={classes.inputFile}
/>
<label htmlFor={get(ActivityFormSchema["files"], "id")}>
<Button
variant="contained"
color="primary"
component="span"
fullWidth
className={classes.InputFileButton}
startIcon={<AddOutlinedIcon />}
>
ADD NEW FILE
</Button>
</label>
</Grid>
</Grid>
</Grid>
<Divider className={classes.divider} />
<Grid item xs={12} md={6} xl={3}>
<Grid container spacing={3} className={classes.formgrid}>
<Grid item md={12} xs={12}>
<Autocomplete
id="activitytype"
className={classes.root}
options={activityType}
getOptionLabel={option => option.name}
onChange={(event, value) => {
handleChangeAutoComplete("activitytype", event, value);
}}
value={
activityType[
activityType.findIndex(function (item, i) {
return item.id === formState.values.activitytype;
})
] || null
}
renderInput={params => (
<TextField
{...params}
error={hasError("activitytype")}
label="Activity Type"
variant="outlined"
name="tester"
helperText={
hasError("activitytype")
? formState.errors["activitytype"].map(error => {
return error + " ";
})
: null
}
/>
)}
/>
</Grid>
</Grid>
<Grid container spacing={3} className={classes.formgrid}>
<Grid item md={12} xs={12}>
<Autocomplete
id="activityname"
className={classes.root}
options={activityNameList}
getOptionLabel={option => option.name}
onChange={(event, value) => {
handleChangeAutoComplete("activityname", event, value);
}}
value={
activityNameList[
activityNameList.findIndex(function (item, i) {
return item.id === formState.values["activityname"];
})
] || null
}
renderInput={params => (
<TextField
{...params}
error={hasError("activityname")}
label="Activity Name"
variant="outlined"
required
name="activityname"
helperText={
hasError("activityname")
? formState.errors["activityname"].map(error => {
return error + " ";
})
: null
}
/>
)}
/>
</Grid>
</Grid>
<Grid container spacing={3} className={classes.MarginBottom}>
<Grid item md={12} xs={12} className={"descriptionBox"}>
<Grid
className={
formState.descriptionError ||
formState.discriptionMinLengthError
? classes.descriptionBoxError
: classes.descriptionBox
}
>
<Card className={classes.streamoffer}>
<InputLabel
htmlFor="outlined-stream-card"
fullwidth={true.toString()}
error={
formState.descriptionError ||
formState.discriptionMinLengthError
}
>
{genericConstants.DESCRIPTION}
</InputLabel>
<div className="rdw-root">
<Editor
id="description-editor"
editorState={editorState}
toolbarClassName="rdw-toolbar"
wrapperClassName="rdw-wrapper"
editorClassName="rdw-editor"
value={editorState}
onEditorStateChange={data => {
formState.descriptionError = false;
formState.discriptionMinLengthError = false;
setEditorState(data);
}}
/>
</div>
{formState.descriptionError ? (
<FormHelperText error={true}>
Description is required
</FormHelperText>
) : null}
{formState.discriptionMinLengthError ? (
<FormHelperText error={true}>
Description length should be less than 320
characters
</FormHelperText>
) : null}
</Card>
</Grid>
</Grid>
</Grid>
<Grid container spacing={3} className={classes.MarginBottom}>
<Grid item md={6} xs={12}>
<CustomDateTimePicker
onChange={event => {
handleDateChange(dateFrom, event);
}}
value={formState.values[dateFrom] || null}
name={dateFrom}
label={get(ActivityFormSchema[dateFrom], "label")}
placeholder={get(
ActivityFormSchema[dateFrom],
"placeholder"
)}
fullWidth
error={hasError(dateFrom)}
helperText={
hasError(dateFrom)
? formState.errors[dateFrom].map(error => {
return error + " ";
})
: null
}
/>
</Grid>
<Grid item md={6} xs={12}>
<CustomDateTimePicker
onChange={event => {
handleDateChange(dateTo, event);
}}
value={formState.values[dateTo] || null}
name={dateTo}
label={get(ActivityFormSchema[dateTo], "label")}
placeholder={get(
ActivityFormSchema[dateTo],
"placeholder"
)}
fullWidth
error={hasError(dateTo)}
helperText={
hasError(dateTo)
? formState.errors[dateTo].map(error => {
return error + " ";
})
: null
}
/>
</Grid>
</Grid>
<Grid container spacing={3} className={classes.MarginBottom}>
<Grid item md={12} xs={12}>
<TextField
label="Address"
name="address"
value={formState.values["address"] || ""}
variant="outlined"
required
fullWidth
id="addressId"
onChange={handleChange}
error={hasError("address")}
helperText={
hasError("address")
? formState.errors["address"].map(error => {
return error + " ";
})
: null
}
/>
</Grid>
</Grid>
<Grid container spacing={3} className={classes.MarginBottom}>
<Grid item md={12} xs={12}>
<Autocomplete
id="collegeId"
className={classes.root}
options={collegelist}
getOptionLabel={option => option.name}
onChange={(event, value) => {
handleChangeAutoComplete("college", event, value);
}}
value={
collegelist[
collegelist.findIndex(function (item, i) {
return item.contact.id === formState.values.college;
})
] || null
}
renderInput={params => (
<TextField
{...params}
error={hasError("college")}
label="College"
variant="outlined"
required
name="tester"
helperText={
hasError("college")
? formState.errors["college"].map(error => {
return error + " ";
})
: null
}
/>
)}
/>
</Grid>
</Grid>
<Grid container spacing={3} className={classes.MarginBottom}>
<Grid item md={12} xs={12} className={classes.root}>
<Autocomplete
multiple={true}
id="collegeStreamID"
required
options={collegeStreamList}
getOptionLabel={option => option.name}
onChange={(event, value) => {
handleStreamChange("stream", event, value);
}}
value={stream}
filterSelectedOptions
renderInput={params => (
<TextField
{...params}
error={hasError("stream")}
label="Stream"
variant="outlined"
required
name="tester"
helperText={
hasError("stream")
? formState.errors["stream"].map(error => {
return error + " ";
})
: null
}
/>
)}
/>
</Grid>
</Grid>
</Grid>
<Divider className={classes.divider} />
<Grid item xs={12} md={6} xl={3}>
<Grid container spacing={3} className={classes.formgrid}>
<Grid item md={6} xs={12}>
<Autocomplete
id="educationYearId"
className={classes.root}
options={educationyearlist}
getOptionLabel={option => option.name}
onChange={(event, value) => {
handleChangeAutoComplete("educationyear", event, value);
}}
value={
educationyearlist[
educationyearlist.findIndex(function (item, i) {
return item.id === formState.values.educationyear;
})
] || null
}
renderInput={params => (
<TextField
{...params}
error={hasError("educationyear")}
label="Education Year"
variant="outlined"
name="tester"
helperText={
hasError("educationyear")
? formState.errors["educationyear"].map(error => {
return error + " ";
})
: null
}
/>
)}
/>
</Grid>
{formState.editActivity ? (
<Grid item md={6} xs={12}>
<Autocomplete
id="combo-box-demo"
className={classes.root}
options={activityStatus}
getOptionLabel={option => option.name}
onChange={(event, value) => {
handleChangeAutoComplete(
"activitystatus",
event,
value
);
}}
value={
activityStatus[
activityStatus.findIndex(function (item, i) {
return (
item.id === formState.values.activitystatus
);
})
] || null
}
renderInput={params => (
<TextField
{...params}
error={hasError("activitystatus")}
label="Activity Status"
variant="outlined"
name="tester"
helperText={
hasError("activitystatus")
? formState.errors["activitystatus"].map(
error => {
return error + " ";
}
)
: null
}
/>
)}
/>
</Grid>
) : null}
</Grid>
<Grid container spacing={3} className={classes.formgrid}>
<Grid item md={6} xs={12}>
<TextField
label="Trainer Name"
name="trainer"
id="trainerId"
value={formState.values["trainer"] || ""}
variant="outlined"
required
fullWidth
onChange={handleChange}
error={hasError("trainer")}
helperText={
hasError("trainer")
? formState.errors["trainer"].map(error => {
return error + " ";
})
: null
}
/>
</Grid>
<Grid item md={6} xs={12}>
<Autocomplete
id="question_set"
className={classes.root}
options={questionSetData}
placeholder={"Select Question Set"}
getOptionLabel={option => option.name}
onChange={(event, value) => {
handleChangeAutoComplete("questionSet", event, value);
}}
required
value={
questionSetData[
questionSetData.findIndex(function (item, i) {
return item.id === formState.values["questionSet"];
})
] || null
}
renderInput={params => (
<TextField
{...params}
label={"Question-Set"}
variant="outlined"
required
placeholder={"Select Question Set"}
error={hasError("questionSet")}
helperText={
hasError("questionSet")
? formState.errors["questionSet"].map(error => {
return error + " ";
})
: null
}
/>
)}
/>
</Grid>
</Grid>
</Grid>
</CardContent>
<Grid item xs={12} className={classes.CardActionGrid}>
<CardActions className={classes.btnspace}>
<Grid item xs={12}>
<Grid item xs={12} md={6} xl={3}>
{formState.editActivity ? (
<Grid container spacing={3}>
<Grid item md={2} xs={12}>
<YellowButton
color="primary"
type="submit"
mfullWidth
variant="contained"
style={{ marginRight: "18px" }}
onClick={handleSubmit}
>
<span>{genericConstants.SAVE_BUTTON_TEXT}</span>
</YellowButton>
</Grid>
<Grid item md={2} xs={12}>
<GrayButton
color="primary"
type="submit"
mfullWidth
variant="contained"
onClick={() => {
history.push(routeConstants.MANAGE_ACTIVITY);
}}
>
<span>{genericConstants.CANCEL_BUTTON_TEXT}</span>
</GrayButton>
</Grid>
</Grid>
) : (
<Grid container spacing={3}>
<Grid item md={2} xs={12}>
<YellowButton
id="submitActivity"
color="primary"
type="submit"
mfullWidth
variant="contained"
style={{ marginRight: "18px" }}
onClick={handleSubmit}
>
<span>{genericConstants.SAVE_BUTTON_TEXT}</span>
</YellowButton>
</Grid>
<Grid item md={2} xs={12}>
<GrayButton
color="primary"
type="submit"
mfullWidth
variant="contained"
onClick={() => {
history.push(routeConstants.MANAGE_ACTIVITY);
}}
>
<span>{genericConstants.CANCEL_BUTTON_TEXT}</span>
</GrayButton>
</Grid>
</Grid>
)}
</Grid>
</Grid>
</CardActions>
</Grid>
</form>
</Card>
</Grid>
<Backdrop className={classes.backDrop} open={backDrop}>
<CircularProgress color="inherit" />
</Backdrop>
</Grid>
);
}
Example #10
Source File: AddEditEvent.js From medha-STPC with GNU Affero General Public License v3.0 | 4 votes |
AddEditEvent = props => {
const [editorState, setEditorState] = React.useState(
EditorState.createEmpty()
);
const { setLoaderStatus } = useContext(LoaderContext);
const classes = useStyles();
const history = useHistory();
/** Initializiing form state value */
const [formState, setFormState] = useState({
isValid: false,
values: {
dateFrom: moment(),
dateTo: moment()
},
touched: {},
errors: {},
stateId: null,
setAllColleges: true,
isSuccess: false,
showPassword: false,
isEditEvent: props["editEvent"] ? props["editEvent"] : false,
dataForEdit: props["dataForEdit"] ? props["dataForEdit"] : {},
counter: 0,
files: {},
filess: {},
descriptionError: false,
discriptionMinLengthError: false,
dataToShowForCollegeMultiSelect: [],
eventCollegeIds: [],
dataToShowForStreamMultiSelect: [],
eventStreamsIds: [],
isCollegeAdminDoesNotHaveEditPreviliges: false,
deleteImage: false,
previewFile: {},
showPreviewImage: false,
showPreviewEditImage: false,
showPreviewNoImage: false,
showAddPreviewNoImage: true,
dynamicBar: [{ index: Math.random() }],
dynamicBarError: [],
dynamicEducationBar: [{ index: Math.random() }],
dynamicEducationBarError: [],
isCollegeAdmin:
auth.getUserInfo() !== null &&
auth.getUserInfo().role !== null &&
auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
? true
: false,
isStateClearFilter: false,
isContainDateValidation: true,
isDateValidated: false
});
const [collegeInfo] = useState({
college:
auth.getUserInfo() !== null &&
auth.getUserInfo().role !== null &&
auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
? auth.getUserInfo().studentInfo.organization
: {},
state:
auth.getUserInfo() !== null &&
auth.getUserInfo().role !== null &&
auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
? auth.getUserInfo().state
: {},
rpc:
auth.getUserInfo() !== null &&
auth.getUserInfo().role !== null &&
auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
? auth.getUserInfo().rpc
: {},
zone:
auth.getUserInfo() !== null &&
auth.getUserInfo().role !== null &&
auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
? auth.getUserInfo().zone
: {}
});
const [backdrop, setBackDrop] = useState(false);
const [states, setStates] = useState([]);
const [zones, setZones] = useState([]);
const [rpcs, setRpcs] = useState([]);
const [colleges, setColleges] = useState([]);
const [streams, setStreams] = useState(
props.streamOption ? props.streamOption : []
);
const inputLabel = React.useRef(null);
const [questionSetData, setQuestionSetData] = useState(
props.questionOption ? props.questionOption : []
);
const [qualifications, setQualifications] = useState([
{ id: 1, value: "secondary", name: "Secondary" },
{ id: 2, value: "graduation", name: "Graduation" },
{ id: 3, value: "senior_secondary", name: "Senior Secondary" },
{ id: 4, name: "Diploma", value: "diploma" },
{ id: 5, name: "ITI", value: "iti" },
// { id: 4, value: "undergraduate", name: "Undergraduate" },
{ id: 6, value: "postgraduate", name: "Postgraduate" },
{ id: 7, value: "other", name: "Other" }
]);
const [qualificationsDataBackup] = useState([
{ id: 1, value: "secondary", name: "Secondary" },
{ id: 2, value: "graduation", name: "Graduation" },
{ id: 3, value: "senior_secondary", name: "Senior Secondary" },
{ id: 4, name: "Diploma", value: "diploma" },
{ id: 5, name: "ITI", value: "iti" },
// { id: 4, value: "undergraduate", name: "Undergraduate" },
{ id: 6, value: "postgraduate", name: "Postgraduate" },
{ id: 7, value: "other", name: "Other" }
]);
const [educations, setEducations] = useState([
{ id: 1, value: "First" },
{ id: 2, value: "Second" },
{ id: 3, value: "Third" }
]);
const [educationsDataBackup] = useState([
{ id: 1, value: "First" },
{ id: 2, value: "Second" },
{ id: 3, value: "Third" }
]);
if (formState.isEditEvent && !formState.counter) {
setLoaderStatus(true);
/** Part for editing state */
if (props["dataForEdit"]) {
if (props["dataForEdit"]["title"]) {
formState.values[eventName] = props["dataForEdit"]["title"];
}
if (props["dataForEdit"]["description"]) {
formState.values[description] = props["dataForEdit"]["description"];
const blocksFromHtml = htmlToDraft(props["dataForEdit"]["description"]);
const { contentBlocks, entityMap } = blocksFromHtml;
const contentState = ContentState.createFromBlockArray(
contentBlocks,
entityMap
);
const editorState = EditorState.createWithContent(contentState);
setEditorState(editorState);
}
if (props["dataForEdit"]["start_date_time"]) {
formState.values[dateFrom] = props["dataForEdit"]["start_date_time"];
//formState.defaultDate = date;
}
if (props["dataForEdit"]["end_date_time"]) {
formState.values[dateTo] = props["dataForEdit"]["end_date_time"];
}
if (props["dataForEdit"]["address"]) {
formState.values[address] = props["dataForEdit"]["address"];
}
if (props["dataForEdit"]["rpc"] && props["dataForEdit"]["rpc"]["id"]) {
formState.values[rpc] = props["dataForEdit"]["rpc"]["id"];
}
if (props["dataForEdit"]["zone"] && props["dataForEdit"]["zone"]["id"]) {
formState.values[zone] = props["dataForEdit"]["zone"]["id"];
}
if (
props["dataForEdit"]["question_set"] &&
props["dataForEdit"]["question_set"]["id"]
) {
formState.values[questionSet] =
props["dataForEdit"]["question_set"]["id"];
}
if (
props["dataForEdit"]["state"] &&
props["dataForEdit"]["state"]["id"]
) {
formState.values[state] = props["dataForEdit"]["state"]["id"];
}
if (
props["dataForEdit"] &&
props["dataForEdit"]["educations"] &&
props["dataForEdit"]["educations"].length
) {
let dynamicEducationBar = [];
for (let i in props["dataForEdit"]["educations"]) {
let tempEducationDynamicBarValue = {};
tempEducationDynamicBarValue["index"] = Math.random();
tempEducationDynamicBarValue["id"] =
props["dataForEdit"]["educations"][i]["id"];
tempEducationDynamicBarValue[education] =
props["dataForEdit"]["educations"][i]["education_year"];
tempEducationDynamicBarValue[educationpercentage] =
props["dataForEdit"]["educations"][i]["percentage"];
dynamicEducationBar.push(tempEducationDynamicBarValue);
}
formState.dynamicEducationBar = dynamicEducationBar;
}
if (
props["dataForEdit"] &&
props["dataForEdit"]["qualifications"] &&
props["dataForEdit"]["qualifications"].length
) {
let dynamicBar = [];
for (let i in props["dataForEdit"]["qualifications"]) {
let tempDynamicBarValue = {};
tempDynamicBarValue["index"] = Math.random();
tempDynamicBarValue["id"] =
props["dataForEdit"]["qualifications"][i]["id"];
tempDynamicBarValue[qualification] =
props["dataForEdit"]["qualifications"][i]["qualification"];
tempDynamicBarValue[percentage] =
props["dataForEdit"]["qualifications"][i]["percentage"];
dynamicBar.push(tempDynamicBarValue);
}
formState.dynamicBar = dynamicBar;
}
if (props["dataForEdit"] && props["dataForEdit"]["upload_logo"]) {
formState.showPreviewEditImage = true;
formState.showAddPreviewNoImage = false;
}
if (
props["dataForEdit"] &&
props["dataForEdit"]["upload_logo"] === null
) {
formState.showPreviewNoImage = true;
formState.showAddPreviewNoImage = true;
}
}
formState.counter += 1;
}
/** Use effect to populate Question Set */
useEffect(() => {
serviceProvider
.serviceProviderForGetRequest(QUESTION_SET)
.then(res => {
setQuestionSetData(res.data);
})
.catch(error => {});
}, []);
/** Streams data for Prepopulating */
const prePopulateStreamsData = streamsData => {
if (props["editEvent"]) {
if (
props["dataForEdit"]["streams"] &&
props["dataForEdit"]["streams"].length
) {
let array = [];
streamsData.map(stream => {
for (let i in props["dataForEdit"]["streams"]) {
if (props["dataForEdit"]["streams"][i]["id"] === stream["id"]) {
array.push(stream);
}
}
});
setFormState(formState => ({
...formState,
dataToShowForStreamMultiSelect: array
}));
let finalDataStream = [];
for (let i in props["dataForEdit"]["streams"]) {
finalDataStream.push(props["dataForEdit"]["streams"][i]["id"]);
}
formState.values[stream] = finalDataStream;
}
}
};
const prePopulateCollegeData = collegeData => {
if (props["editEvent"]) {
if (
props["dataForEdit"]["contacts"] &&
props["dataForEdit"]["contacts"].length
) {
let array = [];
collegeData.map(college => {
for (let i in props["dataForEdit"]["contacts"]) {
if (props["dataForEdit"]["contacts"][i]["id"] === college["id"]) {
array.push(college);
}
}
});
let setAllColleges = false;
if (collegeData.length === props["dataForEdit"]["contacts"].length) {
setAllColleges = true;
}
setFormState(formState => ({
...formState,
dataToShowForCollegeMultiSelect: array,
setAllColleges: setAllColleges
}));
let finalData = [];
for (let i in props["dataForEdit"]["contacts"]) {
finalData.push(props["dataForEdit"]["contacts"][i]["contact"]["id"]);
}
formState.values[college] = finalData;
}
} else {
let collegeArrayToSet = [];
collegeData.map(c => {
collegeArrayToSet.push(c.id);
});
setFormState(formState => ({
...formState,
values: {
...formState.values,
[college]: collegeArrayToSet
},
dataToShowForCollegeMultiSelect: collegeData
}));
}
};
/** Setting educations and qualifications */
useEffect(() => {
setLoaderStatus(true);
let paramsForPageSize = {
pageSize: -1
};
if (formState.isCollegeAdmin) {
setStates([collegeInfo.state]);
} else {
serviceProvider
.serviceProviderForGetRequest(STATES_URL, paramsForPageSize)
.then(res => {
res.data.result.map(s => {
if (s.name === "Uttar Pradesh") {
formState.stateId = s.id;
}
});
setStates(res.data.result);
})
.catch(error => {
console.log("error", error);
});
}
let educationDataForEdit = [
{ id: 1, value: "First" },
{ id: 2, value: "Second" },
{ id: 3, value: "Third" }
];
if (formState.isEditEvent) {
let tempEducationData = educationDataForEdit;
let educationPercentageArray = props["dataForEdit"]["educations"];
for (let i in educationPercentageArray) {
let id = educationPercentageArray[i]["education_year"];
for (let j in tempEducationData) {
if (tempEducationData[j]["value"] === id)
tempEducationData.splice(j, 1);
}
}
setEducations(tempEducationData);
}
let dataForEditing = [
{ id: 1, value: "secondary", name: "Secondary" },
{ id: 2, value: "graduation", name: "Graduation" },
{ id: 3, value: "senior_secondary", name: "Senior Secondary" },
{ id: 4, value: "undergraduate", name: "Undergraduate" },
{ id: 5, value: "postgraduate", name: "Postgraduate" },
{ id: 6, value: "other", name: "Other" }
];
if (formState.isEditEvent) {
let tempQualificationData = dataForEditing;
let qualificationPercentageArray = props["dataForEdit"]["qualifications"];
for (let i in qualificationPercentageArray) {
let id = qualificationPercentageArray[i]["qualification"];
for (let j in tempQualificationData) {
if (tempQualificationData[j]["value"] === id)
tempQualificationData.splice(j, 1);
}
}
setQualifications(tempQualificationData);
}
if (!formState.isCollegeAdmin) {
serviceProvider
.serviceProviderForGetRequest(STREAM_URL, paramsForPageSize)
.then(res => {
setStreams(res.data.result);
prePopulateStreamsData(res.data.result);
})
.catch(error => {
console.log("errorstream", error);
});
} else if (formState.isCollegeAdmin) {
let streamData = [];
auth.getUserInfo().studentInfo.organization.stream_strength.map(data => {
streamData.push(data["stream"]);
});
setStreams(streamData);
prePopulateStreamsData(streamData);
}
setLoaderStatus(false);
}, []);
/** Setting rpc, zone on state change */
useEffect(() => {
if (
formState.values.hasOwnProperty(state) &&
formState.values[state] !== null &&
formState.values[state] !== undefined
) {
fetchZoneRpcData();
}
}, [formState.values[state]]);
/** Common function to get zones, rpcs after changing state */
async function fetchZoneRpcData() {
setLoaderStatus(true);
if (
formState.values.hasOwnProperty(state) &&
formState.values[state] !== null &&
formState.values[state] !== undefined &&
formState.values[state] !== ""
) {
let zones_url =
STATES_URL +
"/" +
formState.values[state] +
"/" +
strapiApiConstants.STRAPI_ZONES;
if (!formState.isCollegeAdmin) {
await serviceProvider
.serviceProviderForGetRequest(zones_url)
.then(res => {
setZones(res.data.result);
})
.catch(error => {
console.log("error", error);
});
} else if (formState.isCollegeAdmin) {
setZones([collegeInfo.zone]);
}
let rpcs_url =
STATES_URL +
"/" +
formState.values[state] +
"/" +
strapiApiConstants.STRAPI_RPCS;
if (!formState.isCollegeAdmin) {
await serviceProvider
.serviceProviderForGetRequest(rpcs_url)
.then(res => {
if (Array.isArray(res.data)) {
setRpcs(res.data[0].result);
} else {
setRpcs(res.data.result);
}
})
.catch(error => {
console.log("error", error);
});
} else if (formState.isCollegeAdmin) {
setRpcs([collegeInfo.rpc]);
}
}
setLoaderStatus(false);
}
useEffect(() => {}, []);
useEffect(() => {
fetchCollegeData();
}, []);
/** Function to get college data after selcting zones and rpc's */
async function fetchCollegeData() {
setLoaderStatus(true);
let params = {
pageSize: -1
};
if (!formState.isCollegeAdmin) {
await serviceProvider
.serviceProviderForGetRequest(COLLEGE_URL, params)
.then(res => {
setColleges(res.data.result);
prePopulateCollegeData(res.data.result);
})
.catch(error => {
console.log("error", error);
});
} else if (formState.isCollegeAdmin) {
setColleges([collegeInfo.college]);
prePopulateCollegeData([collegeInfo.college]);
}
setLoaderStatus(false);
}
const hasError = field => (formState.errors[field] ? true : false);
const handleChange = e => {
e.persist();
setFormState(formState => ({
...formState,
values: {
...formState.values,
[e.target.name]:
e.target.type === "checkbox" ? e.target.checked : e.target.value
},
touched: {
...formState.touched,
[e.target.name]: true
}
}));
if (formState.errors.hasOwnProperty(e.target.name)) {
delete formState.errors[e.target.name];
}
};
const checkErrorInDynamicBar = (field, currentDynamicBarValue) => {
if (field === "qualification" || field === "percentage") {
let errorData = { error: false, value: "" };
if (formState.dynamicBarError.length) {
formState.dynamicBarError.map(barErrorValue => {
if (barErrorValue["index"] === currentDynamicBarValue["index"]) {
if (barErrorValue.hasOwnProperty(field)) {
errorData.error = true;
errorData.value = barErrorValue[field];
}
}
});
}
return errorData;
} else if (field === "education" || field === "educationpercentage") {
let errorEducationData = { error: false, value: "" };
if (formState.dynamicEducationBarError.length) {
formState.dynamicEducationBarError.map(barErrorValue => {
if (barErrorValue["index"] === currentDynamicBarValue["index"]) {
if (barErrorValue.hasOwnProperty(field)) {
errorEducationData.error = true;
errorEducationData.value = barErrorValue[field];
}
}
});
}
return errorEducationData;
}
};
/** Adding a new row in dynamic bar */
const addNewRow = (e, extendBarName) => {
e.persist();
if (extendBarName === "qualification") {
setFormState(formState => ({
...formState,
dynamicBar: [...formState.dynamicBar, { index: Math.random() }]
}));
} else if (extendBarName === "education") {
setFormState(formState => ({
...formState,
dynamicEducationBar: [
...formState.dynamicEducationBar,
{ index: Math.random() }
]
}));
}
};
/** To delete a value from dynamic bar */
const clickOnDelete = (record, index) => {
setFormState(formState => ({
...formState,
dynamicBar: formState.dynamicBar.filter(r => r !== record)
}));
setFormState(formState => ({
...formState,
dynamicEducationBar: formState.dynamicEducationBar.filter(
r => r !== record
)
}));
if (record[qualification]) {
let qualificationsTempArray = [];
qualificationsTempArray = qualifications;
qualificationsDataBackup.map(qualificationData => {
if (record["qualification"] === qualificationData["value"]) {
qualificationsTempArray.push(qualificationData);
}
});
setQualifications(qualificationsTempArray);
}
if (record[education]) {
let qualificationsTempArray = [];
qualificationsTempArray = educations;
educationsDataBackup.map(qualificationData => {
if (record["education"] === qualificationData["value"]) {
qualificationsTempArray.push(qualificationData);
}
});
setEducations(qualificationsTempArray);
}
};
/** Handling multi select values for dynamic bar */
const handleChangeForDynamicGrid = (
eventName,
event,
selectedValueForAutoComplete,
dynamicGridValue,
isAutoComplete,
isTextBox
) => {
event.persist();
if (eventName === "qualification" || eventName === "percentage") {
/**TO SET VALUES OF AUTOCOMPLETE */
if (isAutoComplete) {
if (selectedValueForAutoComplete !== null) {
setFormState(formState => ({
...formState,
dynamicBar: formState.dynamicBar.map(r => {
if (r["index"] === dynamicGridValue["index"]) {
let qualificationsTempArray = [];
qualifications.map(qualificationData => {
if (
qualificationData["id"] !==
selectedValueForAutoComplete["id"]
) {
qualificationsTempArray.push(qualificationData);
}
});
setQualifications(qualificationsTempArray);
r["id"] = selectedValueForAutoComplete["id"];
r[eventName] = selectedValueForAutoComplete["value"];
return r;
} else {
return r;
}
})
}));
} else {
/** This is used to remove clear out data form auto complete when we click cross icon of auto complete */
setFormState(formState => ({
...formState,
dynamicBar: formState.dynamicBar.map(r => {
if (r["index"] === dynamicGridValue["index"]) {
let qualificationsTempArray = [];
qualificationsTempArray = qualifications;
qualificationsDataBackup.map(qualificationData => {
if (r[eventName] === qualificationData["value"]) {
qualificationsTempArray.push(qualificationData);
}
});
setQualifications(qualificationsTempArray);
delete r[eventName];
return r;
} else {
return r;
}
})
}));
}
}
if (isTextBox) {
if (
event.target.value === "" ||
regexForPercentage.test(event.target.value)
) {
if (event.target.value.length <= 2) {
setFormState(formState => ({
...formState,
dynamicBar: formState.dynamicBar.map(r => {
if (r["index"] === dynamicGridValue["index"]) {
r[eventName] = event.target.value;
if (r[eventName] === "") {
delete r[eventName];
}
return r;
} else {
return r;
}
})
}));
}
}
}
/** Clear errors if any */
formState.dynamicBarError.map(errorValues => {
if (errorValues["index"] === dynamicGridValue["index"]) {
delete errorValues[eventName];
}
});
} else if (
eventName === "education" ||
eventName === "educationpercentage"
) {
if (isAutoComplete) {
if (selectedValueForAutoComplete !== null) {
setFormState(formState => ({
...formState,
dynamicEducationBar: formState.dynamicEducationBar.map(r => {
if (r["index"] === dynamicGridValue["index"]) {
let educationsTempArray = [];
educations.map(educationData => {
if (
educationData["id"] !== selectedValueForAutoComplete["id"]
) {
educationsTempArray.push(educationData);
}
});
setEducations(educationsTempArray);
r["id"] = selectedValueForAutoComplete["id"];
r[eventName] = selectedValueForAutoComplete["value"];
return r;
} else {
return r;
}
})
}));
} else {
/** This is used to remove clear out data form auto complete when we click cross icon of auto complete */
setFormState(formState => ({
...formState,
dynamicEducationBar: formState.dynamicEducationBar.map(r => {
if (r["index"] === dynamicGridValue["index"]) {
let educationsTempArray = [];
educationsTempArray = educations;
educationsDataBackup.map(educationData => {
if (r[eventName] === educationData["value"]) {
educationsTempArray.push(educationData);
}
});
setQualifications(educationsTempArray);
delete r[eventName];
return r;
} else {
return r;
}
})
}));
}
}
if (isTextBox) {
if (
event.target.value === "" ||
regexForPercentage.test(event.target.value)
) {
if (event.target.value.length <= 2) {
setFormState(formState => ({
...formState,
dynamicEducationBar: formState.dynamicEducationBar.map(r => {
if (r["index"] === dynamicGridValue["index"]) {
r[eventName] = event.target.value;
if (r[eventName] === "") {
delete r[eventName];
}
return r;
} else {
return r;
}
})
}));
}
}
}
/** Clear errors if any */
formState.dynamicBarError.map(errorValues => {
if (errorValues["index"] === dynamicGridValue["index"]) {
delete errorValues[eventName];
}
});
}
};
/** Validate DynamicGrid */
const validateDynamicGridValues = () => {
let validationCounter = 0;
/** Empty the error array of dynamic bar */
formState.dynamicBarError = [];
formState.dynamicBar.map(value => {
let valueToPutInDynmicBarError = {};
valueToPutInDynmicBarError["index"] = value["index"];
/** Validate dynamikc bar */
if (
value.hasOwnProperty(qualification) &&
!value.hasOwnProperty(percentage)
) {
valueToPutInDynmicBarError[percentage] =
"Percentage is required as Qualification is present";
validationCounter += 1;
} else if (
value.hasOwnProperty(percentage) &&
!value.hasOwnProperty(qualification)
) {
valueToPutInDynmicBarError[qualification] =
"Qualification is required as percentage is present";
validationCounter += 1;
}
formState.dynamicBarError.push(valueToPutInDynmicBarError);
});
formState.dynamicEducationBarError = [];
formState.dynamicEducationBar.map(value => {
let valueToPutInDynmicBarError = {};
valueToPutInDynmicBarError["index"] = value["index"];
/** Validate dynamikc bar */
if (
value.hasOwnProperty(education) &&
!value.hasOwnProperty(educationpercentage)
) {
valueToPutInDynmicBarError[educationpercentage] =
"Percentage is required as Education is present";
validationCounter += 1;
} else if (
value.hasOwnProperty(educationpercentage) &&
!value.hasOwnProperty(education)
) {
valueToPutInDynmicBarError[education] =
"Education is required as percentage is present";
validationCounter += 1;
}
formState.dynamicEducationBarError.push(valueToPutInDynmicBarError);
});
if (validationCounter > 0) {
return false;
} else {
return true;
}
};
const getDynamicBarData = () => {
let qualificationsPercentageArrayValues = [];
formState.dynamicBar.map(field => {
let qualificationPercentageValue = {};
if (
field.hasOwnProperty(qualification) &&
field.hasOwnProperty(percentage)
) {
qualificationPercentageValue["qualification"] = field[qualification];
qualificationPercentageValue["percentage"] = parseInt(
field[percentage]
);
qualificationsPercentageArrayValues.push(qualificationPercentageValue);
}
});
return qualificationsPercentageArrayValues;
};
const getDynamicEducationData = () => {
let educationsPercentageArrayValues = [];
formState.dynamicEducationBar.map(field => {
let educationPercentageValue = {};
if (
field.hasOwnProperty(education) &&
field.hasOwnProperty(educationpercentage)
) {
educationPercentageValue["education_year"] = field[education];
educationPercentageValue["percentage"] = parseInt(
field[educationpercentage]
);
educationsPercentageArrayValues.push(educationPercentageValue);
}
});
return educationsPercentageArrayValues;
};
/** Handle change for autocomplete fields */
const handleChangeAutoComplete = (eventName, event, value) => {
/**TO SET VALUES OF AUTOCOMPLETE */
if (formState.errors.hasOwnProperty(eventName)) {
delete formState.errors[eventName];
}
if (value !== null) {
setFormState(formState => ({
...formState,
values: {
...formState.values,
[eventName]: value.id
},
touched: {
...formState.touched,
[eventName]: true
},
isStateClearFilter: false
}));
} else {
let setStateFilterValue = false;
/** If we click cross for state the zone and rpc should clear off! */
if (eventName === state) {
/**
This flag is used to determine that state is cleared which clears
off zone and rpc by setting their value to null
*/
setStateFilterValue = true;
/**
When state is cleared then clear rpc and zone
*/
setRpcs([]);
setZones([]);
setColleges([]);
// setStreams([]);
delete formState.values[zone];
delete formState.values[rpc];
formState.dataToShowForCollegeMultiSelect = [];
} else if (eventName === rpc || eventName === zone) {
setColleges([]);
formState.dataToShowForCollegeMultiSelect = [];
}
setFormState(formState => ({
...formState,
isStateClearFilter: setStateFilterValue
}));
/** This is used to remove clear out data form auto complete when we click cross icon of auto complete */
delete formState.values[eventName];
}
};
const handleCheckBox = event => {
/** If the checkbox is checked */
if (!formState.setAllColleges) {
/** Delete current value */
delete formState.values[college];
/** Set validations */
EventSchema.college.required = false;
EventSchema.college.validations = {};
/** Delete if errors present */
delete formState.errors[college];
/** Set college list when all collgees check box is checked */
let collegeArrayToSet = [];
colleges.map(c => {
collegeArrayToSet.push(c.id);
});
setFormState(formState => ({
...formState,
setAllColleges: !formState.setAllColleges,
values: {
...formState.values,
[college]: collegeArrayToSet
},
dataToShowForCollegeMultiSelect: colleges
}));
} else {
delete formState.values[college];
EventSchema.college.required = true;
EventSchema.college.validations = {
required: {
value: "true",
message: "College is required"
}
};
/** Delete if errors present */
delete formState.errors[college];
setFormState(formState => ({
...formState,
setAllColleges: !formState.setAllColleges,
dataToShowForCollegeMultiSelect: []
}));
}
};
const handleSubmit = event => {
event.preventDefault();
setBackDrop(true);
let isValid = false;
if (formState.isCollegeAdmin && !formState.isEditEvent) {
setDataForCollegeAdmin();
} else {
formState.values[state] = formState.stateId;
}
/** Validate DynamicGrid */
let isDynamicBarValid;
/** Check validity of dynamic bar */
isDynamicBarValid = validateDynamicGridValues();
let checkAllFieldsValid = formUtilities.checkAllKeysPresent(
formState.values,
EventSchema
);
if (checkAllFieldsValid) {
/** Evaluated only if all keys are valid inside formstate */
formState.errors = formUtilities.setErrors(
formState.values,
EventSchema,
true,
dateFrom,
dateTo
);
/** Check date validation */
if (formUtilities.checkEmpty(formState.errors)) {
isValid = true;
}
/** */
} else {
/** This is used to find out which all required fields are not filled */
formState.values = formUtilities.getListOfKeysNotPresent(
formState.values,
EventSchema
);
formState.errors = formUtilities.setErrors(
formState.values,
EventSchema,
true,
dateFrom,
dateTo
);
}
formState.descriptionError = false;
if (
convertToRaw(editorState.getCurrentContent()).blocks &&
convertToRaw(editorState.getCurrentContent()).blocks.length
) {
let arrayToCheckIn = convertToRaw(editorState.getCurrentContent()).blocks;
let validationCounter = 0;
let validationMinCounter = 0;
for (let i in arrayToCheckIn) {
if (
arrayToCheckIn[i]["text"] &&
arrayToCheckIn[i]["text"].trim().length !== 0
) {
validationCounter += 1;
break;
}
}
if (validationCounter === 0) {
formState.descriptionError = true;
}
for (let i in arrayToCheckIn) {
if (
arrayToCheckIn[i]["text"] &&
arrayToCheckIn[i]["text"].trim().length > 320
) {
validationMinCounter += 1;
break;
}
}
if (validationMinCounter !== 0) {
formState.discriptionMinLengthError = true;
}
}
if (
isValid &&
!formState.descriptionError &&
!formState.discriptionMinLengthError &&
isDynamicBarValid
) {
/** CALL POST FUNCTION */
postEventData();
/** Call axios from here */
setFormState(formState => ({
...formState,
isValid: true
}));
} else {
setFormState(formState => ({
...formState,
isValid: false
}));
setBackDrop(false);
}
};
const setDataForCollegeAdmin = () => {
formState.values[zone] = collegeInfo.zone.id;
formState.values[rpc] = collegeInfo.rpc.id;
formState.values[college] = [collegeInfo.college.contact.id];
formState.values[state] = collegeInfo.state.id;
};
const postEventData = () => {
/** Setting quaalifications */
let qualificationPercentageArray = [];
qualificationPercentageArray = getDynamicBarData();
/** Setting educations */
let educationPercentageArray = [];
educationPercentageArray = getDynamicEducationData();
/** Data to post */
let postData = databaseUtilities.addEvent(
formState.values[eventName],
draftToHtml(convertToRaw(editorState.getCurrentContent())),
formState.values[dateFrom],
formState.values[dateTo],
formState.values[address],
formState.values[zone] ? formState.values[zone] : null,
formState.values[rpc] ? formState.values[rpc] : null,
qualificationPercentageArray,
educationPercentageArray,
formState.values[college] ? formState.values[college] : null,
formState.values[stream] ? formState.values[stream] : null,
formState.values[state] ? formState.values[state] : null,
formState.values[questionSet] ? formState.values[questionSet] : null
);
if (formState.isEditEvent) {
serviceProvider
.serviceProviderForPutRequest(
EVENTS_URL,
formState.dataForEdit["id"],
postData
)
.then(res => {
if (formState.files.name) {
postImage(res.data.id);
} else {
history.push({
pathname: routeConstants.MANAGE_EVENT,
fromeditEvent: true,
isDataEdited: true,
editedEventData: res.data,
addResponseMessage: "",
editedData: {}
});
}
setBackDrop(false);
})
.catch(error => {
console.log("puterror", error);
history.push({
pathname: routeConstants.MANAGE_EVENT,
fromeditEvent: true,
isDataEdited: false,
editResponseMessage: "",
editedData: {}
});
setBackDrop(false);
});
} else {
serviceProvider
.serviceProviderForPostRequest(EVENTS_URL, postData)
.then(res => {
if (formState.files.name) {
postImage(res.data.id);
} else {
history.push({
pathname: routeConstants.MANAGE_EVENT,
fromAddEvent: true,
isDataAdded: true,
addedEventData: res.data,
addResponseMessage: "",
addedData: {}
});
}
setBackDrop(false);
})
.catch(error => {
console.log("posterror", error);
history.push({
pathname: routeConstants.MANAGE_EVENT,
fromeditEvent: true,
isDataEdited: false,
editResponseMessage: "",
editedData: {}
});
setBackDrop(false);
});
}
};
const postImage = id => {
let postImageData = databaseUtilities.uploadDocument(
formState.files,
ref,
id,
field
);
serviceProvider
.serviceProviderForPostRequest(DOCUMENT_URL, postImageData)
.then(res => {
history.push({
pathname: routeConstants.MANAGE_EVENT,
fromAddEvent: true,
isDataAdded: true,
addResponseMessage: "",
addedData: {}
});
})
.catch(err => {
console.log("error", err);
});
};
const handleFileChange = event => {
event.persist();
setFormState(formState => ({
...formState,
values: {
...formState.values,
[event.target.name]: event.target.value
},
touched: {
...formState.touched,
[event.target.name]: true
},
files: event.target.files[0],
previewFile: URL.createObjectURL(event.target.files[0]),
showPreviewEditImage: false,
showPreviewNoImage: false,
showPreviewImage: true,
showAddPreviewNoImage: false
}));
/** This is used to remove any existing errors if present in text field */
if (formState.errors.hasOwnProperty(event.target.name)) {
delete formState.errors[event.target.name];
}
};
const handleDateChange = (dateObject, event) => {
if (formState.errors.hasOwnProperty(dateObject)) {
delete formState.errors[dateObject];
}
setFormState(formState => ({
...formState,
values: {
...formState.values,
[dateObject]: event
},
touched: {
...formState.touched,
[dateObject]: true
},
isStateClearFilter: false
}));
};
const handleMultiSelectChange = (eventName, event, value) => {
let multiarray = [];
delete formState.errors[eventName];
if (eventName === college) {
formState.dataToShowForCollegeMultiSelect = value;
for (var i = 0; i < value.length; i++) {
multiarray.push(value[i]["contact"].id);
}
}
if (eventName === stream) {
formState.dataToShowForStreamMultiSelect = value;
for (var i = 0; i < value.length; i++) {
multiarray.push(value[i].id);
}
}
if (value !== null) {
setFormState(formState => ({
...formState,
values: {
...formState.values,
[eventName]: multiarray
},
touched: {
...formState.touched,
[eventName]: true
},
isStateClearFilter: false
}));
} else {
delete formState.values[eventName];
}
};
return (
<Grid>
<Grid item xs={12} className={classes.title}>
<Typography variant="h4" gutterBottom>
{props["editEvent"] ? "Edit Event" : genericConstants.ADD_EVENT_TEXT}
</Typography>
</Grid>
<Grid spacing={3}>
<Card>
<form autoComplete="off" noValidate onSubmit={handleSubmit} id="form">
<CardContent>
<Grid item xs={12} md={6} xl={3}>
<Grid container className={classes.formgridInputFile}>
<Grid item md={10} xs={12}>
<div className={classes.imageDiv}>
{
formState.showPreviewImage ? (
<Img
src={formState.previewFile}
alt="abc"
loader={<Spinner />}
className={classes.UploadImage}
/>
) : null
// <div class={classes.DefaultNoImage}></div>
}
{formState.showPreviewEditImage &&
formState.dataForEdit["upload_logo"] !== null &&
formState.dataForEdit["upload_logo"] !== undefined &&
formState.dataForEdit["upload_logo"] !== {} ? (
<Img
src={
strapiApiConstants.STRAPI_DB_URL_WITHOUT_HASH +
formState.dataForEdit["upload_logo"]["url"]
}
loader={<Spinner />}
className={classes.UploadImage}
/>
) : null}
{formState.showPreviewNoImage ? (
<Img
src={"../"}
loader={<Spinner />}
className={classes.UploadImage}
/>
) : null}
{formState.showAddPreviewNoImage ? (
<div className={classes.DefaultNoImage}></div>
) : null}
</div>
</Grid>
</Grid>
<Grid container className={classes.MarginBottom}>
<Grid item md={10} xs={12}>
<TextField
fullWidth
id={get(EventSchema[files], "id")}
name={files}
onChange={handleFileChange}
required
type={get(EventSchema[files], "type")}
value={formState.values[files] || ""}
error={hasError(files)}
inputProps={{ accept: "image/*" }}
helperText={
hasError(files)
? formState.errors[files].map(error => {
return error + " ";
})
: null
}
variant="outlined"
className={classes.inputFile}
/>
<label htmlFor={get(EventSchema[files], "id")}>
<Button
variant="contained"
color="primary"
component="span"
fullWidth
className={classes.InputFileButton}
startIcon={<AddOutlinedIcon />}
>
ADD NEW EVENT LOGO
</Button>
</label>
</Grid>
</Grid>
</Grid>
<Divider className={classes.divider} />
<Grid item xs={12} md={6} xl={3}>
<Grid container spacing={3} className={classes.formgrid}>
<Grid item md={12} xs={12}>
<TextField
label={get(EventSchema[eventName], "label")}
id={get(EventSchema[eventName], "id")}
name={eventName}
placeholder={get(EventSchema[eventName], "placeholder")}
value={formState.values[eventName] || ""}
error={hasError(eventName)}
variant="outlined"
required
fullWidth
onChange={handleChange}
helperText={
hasError(eventName)
? formState.errors[eventName].map(error => {
return error + " ";
})
: null
}
/>
</Grid>
</Grid>
<Grid container spacing={3} className={classes.MarginBottom}>
<Grid item md={12} xs={12} className={"descriptionBox"}>
<Grid
className={
formState.descriptionError ||
formState.discriptionMinLengthError
? classes.descriptionBoxError
: classes.descriptionBox
}
>
<Card className={classes.streamoffer}>
<InputLabel
htmlFor="outlined-stream-card"
fullwidth={true.toString()}
error={
formState.descriptionError ||
formState.discriptionMinLengthError
}
>
{genericConstants.DESCRIPTION}
</InputLabel>
<div className="rdw-root">
<Editor
editorState={editorState}
toolbarClassName="rdw-toolbar"
wrapperClassName="rdw-wrapper"
editorClassName="rdw-editor"
onEditorStateChange={data => {
formState.descriptionError = false;
formState.discriptionMinLengthError = false;
setEditorState(data);
}}
/>
</div>
{formState.descriptionError ? (
<FormHelperText error={true}>
Description is required
</FormHelperText>
) : null}
{formState.discriptionMinLengthError ? (
<FormHelperText error={true}>
Description length should be less than 320
characters
</FormHelperText>
) : null}
</Card>
</Grid>
</Grid>
</Grid>
<Grid container spacing={3} className={classes.MarginBottom}>
<Grid item md={6} xs={12}>
<CustomDateTimePicker
id={get(EventSchema[dateFrom], "id")}
onChange={event => {
handleDateChange(dateFrom, event);
}}
value={formState.values[dateFrom] || null}
name={dateFrom}
label={get(EventSchema[dateFrom], "label")}
placeholder={get(EventSchema[dateFrom], "placeholder")}
fullWidth
error={hasError(dateFrom)}
helperText={
hasError(dateFrom)
? formState.errors[dateFrom].map(error => {
return error + " ";
})
: null
}
/>
</Grid>
<Grid item md={6} xs={12}>
<CustomDateTimePicker
id={get(EventSchema[dateTo], "id")}
onChange={event => {
handleDateChange(dateTo, event);
}}
value={formState.values[dateTo] || null}
name={dateTo}
label={get(EventSchema[dateTo], "label")}
placeholder={get(EventSchema[dateTo], "placeholder")}
fullWidth
error={hasError(dateTo)}
helperText={
hasError(dateTo)
? formState.errors[dateTo].map(error => {
return error + " ";
})
: null
}
/>
</Grid>
</Grid>
<Grid container spacing={3} className={classes.MarginBottom}>
<Grid item md={12} xs={12}>
<TextField
label={get(EventSchema[address], "label")}
id={get(EventSchema[address], "id")}
name={address}
placeholder={get(EventSchema[address], "placeholder")}
value={formState.values[address] || ""}
error={hasError(address)}
variant="outlined"
required
multiline
fullWidth
onChange={handleChange}
helperText={
hasError(address)
? formState.errors[address].map(error => {
return error + " ";
})
: null
}
/>
</Grid>
</Grid>
<Grid
container
spacing={3}
className={classes.MarginBottom}
></Grid>
<Grid container spacing={3} className={classes.MarginBottom}>
{!formState.isCollegeAdmin ? (
<Grid item md={12} xs={12}>
<FormControlLabel
control={
<Checkbox
checked={formState.setAllColleges}
onChange={handleCheckBox}
name="selectAllColleges"
color="yellow"
/>
}
label="Select All Colleges"
/>
</Grid>
) : null}
<Grid item md={12} xs={12}>
{formState.isCollegeAdmin && !formState.isEditEvent ? (
<ReadOnlyTextField
id={get(EventSchema[college], "id")}
label={get(EventSchema[college], "label")}
defaultValue={collegeInfo.college.name}
/>
) : (
<Autocomplete
id={get(EventSchema[college], "id")}
multiple
limitTags={2}
options={colleges}
getOptionLabel={option => option.name}
onChange={(event, value) => {
handleMultiSelectChange(college, event, value);
}}
filterSelectedOptions
name={college}
disabled={
(formState.isCollegeAdmin && formState.isEditEvent) ||
formState.setAllColleges
? true
: false
}
value={
formState.dataToShowForCollegeMultiSelect || null
}
renderInput={params => (
<TextField
{...params}
error={hasError(college)}
helperText={
hasError(college)
? formState.errors[college].map(error => {
return error + " ";
})
: null
}
placeholder={get(
EventSchema[college],
"placeholder"
)}
value={option => option.id}
name={college}
key={option => option.id}
label={get(EventSchema[college], "label")}
variant="outlined"
/>
)}
/>
)}
</Grid>
</Grid>
<Grid container spacing={3} className={classes.MarginBottom}>
<Grid item md={6} xs={12}>
<Autocomplete
id={get(EventSchema[stream], "id")}
multiple
options={streams}
getOptionLabel={option => option.name}
onChange={(event, value) => {
handleMultiSelectChange(stream, event, value);
}}
disabled={
formState.isCollegeAdmin &&
formState.isEditEvent &&
formState.isCollegeAdminDoesNotHaveEditPreviliges
? true
: false
}
filterSelectedOptions
name={stream}
value={formState.dataToShowForStreamMultiSelect || null}
renderInput={params => (
<TextField
{...params}
error={hasError(stream)}
helperText={
hasError(stream)
? formState.errors[stream].map(error => {
return error + " ";
})
: null
}
placeholder={get(EventSchema[stream], "placeholder")}
value={option => option.id}
name={stream}
key={option => option.id}
label={get(EventSchema[stream], "label")}
variant="outlined"
/>
)}
/>
</Grid>
<Grid item md={6} xs={12}>
<Autocomplete
id={get(EventSchema[questionSet], "id")}
className={classes.root}
options={questionSetData}
placeholder={get(EventSchema[questionSet], "placeholder")}
getOptionLabel={option => option.name}
onChange={(event, value) => {
handleChangeAutoComplete(questionSet, event, value);
}}
value={
questionSetData[
questionSetData.findIndex(function (item, i) {
return item.id === formState.values[questionSet];
})
] || null
}
renderInput={params => (
<TextField
{...params}
label={get(EventSchema[questionSet], "label")}
variant="outlined"
placeholder={get(
EventSchema[questionSet],
"placeholder"
)}
error={hasError(questionSet)}
helperText={
hasError(questionSet)
? formState.errors[questionSet].map(error => {
return error + " ";
})
: null
}
/>
)}
/>
</Grid>
</Grid>
</Grid>
<Divider className={classes.divider} />
<Grid item xs={12} md={6} xl={3}>
<Grid container spacing={1} className={classes.formgrid}>
<Grid item md={12} xs={12} className={classes.streamcard}>
<Card className={classes.streamoffer}>
<InputLabel
htmlFor="outlined-stream-card"
fullwidth={true.toString()}
>
{genericConstants.QUALIFICATIONANDPERCENTAGE}
</InputLabel>
{formState.dynamicBar.map((val, idx) => {
let qualificationId = `qualification-${idx}`,
percentageId = `percentage-${idx}`;
return (
<Card
id="outlined-stream-card"
fullwidth={true.toString()}
className={classes.streamcardcontent}
key={idx}
>
<CardContent>
<Grid container spacing={1}>
<Grid item xs={5}>
<FormControl
variant="outlined"
fullWidth
className={classes.formControl}
>
<InputLabel
ref={inputLabel}
id="demo-simple-select-outlined-label"
></InputLabel>
<Autocomplete
id={qualificationId}
options={qualifications}
disabled={
formState.isCollegeAdmin &&
formState.isEditEvent &&
formState.isCollegeAdminDoesNotHaveEditPreviliges
? true
: false
}
getOptionLabel={option => option.name}
onChange={(event, value) => {
handleChangeForDynamicGrid(
qualification,
event,
value,
val,
true,
false
);
}}
data-id={idx}
name={qualificationId}
value={
qualificationsDataBackup[
qualificationsDataBackup.findIndex(
function (item, i) {
return (
item.value ===
formState.dynamicBar[idx][
qualification
]
);
}
)
] || null
}
renderInput={params => (
<TextField
{...params}
value={option => option.id}
name={qualificationId}
error={
checkErrorInDynamicBar(
qualification,
val
)["error"]
}
helperText={
checkErrorInDynamicBar(
qualification,
val
)["error"]
? checkErrorInDynamicBar(
qualification,
val
)["value"]
: null
}
placeholder={get(
EventSchema[qualification],
"placeholder"
)}
key={option => option.id}
label={get(
EventSchema[qualification],
"label"
)}
variant="outlined"
/>
)}
/>
</FormControl>
</Grid>
<Grid item xs={5}>
<TextField
label="Percentage"
name={percentageId}
variant="outlined"
fullWidth
disabled={
formState.isCollegeAdmin &&
formState.isEditEvent &&
formState.isCollegeAdminDoesNotHaveEditPreviliges
? true
: false
}
data-id={idx}
id={percentageId}
value={
formState.dynamicBar[idx][percentage] ||
""
}
error={
checkErrorInDynamicBar(percentage, val)[
"error"
]
}
helperText={
checkErrorInDynamicBar(percentage, val)[
"error"
]
? checkErrorInDynamicBar(
percentage,
val
)["value"]
: null
}
placeholder={get(
EventSchema[percentage],
"placeholder"
)}
onChange={event => {
handleChangeForDynamicGrid(
percentage,
event,
null,
val,
false,
true
);
}}
/>
</Grid>
<Grid item xs={2}>
{idx > 0 ? (
<DeleteForeverOutlinedIcon
onClick={e =>
formState.isCollegeAdmin &&
formState.isEditEvent &&
formState.isCollegeAdminDoesNotHaveEditPreviliges
? null
: clickOnDelete(val, idx)
}
style={
formState.isCollegeAdmin &&
formState.isEditEvent &&
formState.isCollegeAdminDoesNotHaveEditPreviliges
? { color: "gray", fontSize: "24px" }
: { color: "red", fontSize: "24px" }
}
/>
) : (
""
)}
</Grid>
</Grid>
</CardContent>
</Card>
);
})}
<div className={classes.btnspaceadd}>
<Grid item xs={12} md={3} lg={3} xl={3}>
<YellowButton
type="button"
color="primary"
variant="contained"
disabled={
formState.isCollegeAdmin &&
formState.isEditEvent &&
formState.isCollegeAdminDoesNotHaveEditPreviliges
? true
: qualifications.length
? false
: true
}
className={classes.add_more_btn}
onClick={e => {
addNewRow(e, qualification);
}}
>
{genericConstants.ADD_MORE_TEXT}
</YellowButton>
</Grid>
</div>
</Card>
</Grid>
</Grid>
</Grid>
<Divider className={classes.divider} />
<Grid item xs={12} md={6} xl={3}>
<Grid container spacing={1} className={classes.formgrid}>
<Grid item md={12} xs={12} className={classes.streamcard}>
<Card className={classes.streamoffer}>
<InputLabel
htmlFor="outlined-stream-card"
fullwidth={true.toString()}
>
{genericConstants.EDUCATIONANDPERCENTAGE}
</InputLabel>
{formState.dynamicEducationBar.map((val, idx) => {
let qualificationId = `education-${idx}`,
percentageId = `percentage-${idx}`;
return (
<Card
id="outlined-stream-card"
fullwidth={true.toString()}
className={classes.streamcardcontent}
key={idx}
>
<CardContent>
<Grid container spacing={1}>
<Grid item xs={5}>
<FormControl
variant="outlined"
fullWidth
className={classes.formControl}
>
<InputLabel
ref={inputLabel}
id="demo-simple-select-outlined-label"
></InputLabel>
<Autocomplete
id={qualificationId}
options={educations}
disabled={
formState.isCollegeAdmin &&
formState.isEditEvent &&
formState.isCollegeAdminDoesNotHaveEditPreviliges
? true
: false
}
getOptionLabel={option => option.value}
onChange={(event, value) => {
handleChangeForDynamicGrid(
education,
event,
value,
val,
true,
false
);
}}
data-id={idx}
name={qualificationId}
value={
educationsDataBackup[
educationsDataBackup.findIndex(
function (item, i) {
return (
item.value ===
formState.dynamicEducationBar[
idx
][education]
);
}
)
] || null
}
renderInput={params => (
<TextField
{...params}
value={option => option.id}
name={qualificationId}
error={
checkErrorInDynamicBar(
education,
val
)["error"]
}
helperText={
checkErrorInDynamicBar(
education,
val
)["error"]
? checkErrorInDynamicBar(
education,
val
)["value"]
: null
}
placeholder={get(
EventSchema[education],
"placeholder"
)}
key={option => option.id}
label={get(
EventSchema[education],
"label"
)}
variant="outlined"
/>
)}
/>
</FormControl>
</Grid>
<Grid item xs={5}>
<TextField
label="Percentage"
name={percentageId}
variant="outlined"
fullWidth
disabled={
formState.isCollegeAdmin &&
formState.isEditEvent &&
formState.isCollegeAdminDoesNotHaveEditPreviliges
? true
: false
}
data-id={idx}
id={percentageId}
value={
formState.dynamicEducationBar[idx][
educationpercentage
] || ""
}
error={
checkErrorInDynamicBar(
educationpercentage,
val
)["error"]
}
helperText={
checkErrorInDynamicBar(
educationpercentage,
val
)["error"]
? checkErrorInDynamicBar(
educationpercentage,
val
)["value"]
: null
}
placeholder={get(
EventSchema[educationpercentage],
"placeholder"
)}
onChange={event => {
handleChangeForDynamicGrid(
educationpercentage,
event,
null,
val,
false,
true
);
}}
/>
</Grid>
<Grid item xs={2}>
{idx > 0 ? (
<DeleteForeverOutlinedIcon
onClick={e =>
formState.isCollegeAdmin &&
formState.isEditEvent &&
formState.isCollegeAdminDoesNotHaveEditPreviliges
? null
: clickOnDelete(val, idx)
}
style={
formState.isCollegeAdmin &&
formState.isEditEvent &&
formState.isCollegeAdminDoesNotHaveEditPreviliges
? { color: "gray", fontSize: "24px" }
: { color: "red", fontSize: "24px" }
}
/>
) : (
""
)}
</Grid>
</Grid>
</CardContent>
</Card>
);
})}
<div className={classes.btnspaceadd}>
<Grid item xs={12} md={3} lg={3} xl={3}>
<YellowButton
type="button"
color="primary"
disabled={
formState.isCollegeAdmin &&
formState.isEditEvent &&
formState.isCollegeAdminDoesNotHaveEditPreviliges
? true
: educations.length
? false
: true
}
variant="contained"
className={classes.add_more_btn}
onClick={e => {
addNewRow(e, education);
}}
>
{genericConstants.ADD_MORE_TEXT}
</YellowButton>
</Grid>
</div>
</Card>
</Grid>
</Grid>
</Grid>
</CardContent>
<Grid item xs={12} className={classes.CardActionGrid}>
<CardActions className={classes.btnspace}>
<Grid item xs={12}>
<Grid item xs={12} md={6} xl={3}>
<Grid container spacing={3}>
<Grid item md={2} xs={12}>
<YellowButton
type="submit"
color="primary"
variant="contained"
disabled={
formState.isCollegeAdmin &&
formState.isEditEvent &&
formState.isCollegeAdminDoesNotHaveEditPreviliges
? true
: false
}
>
{genericConstants.SAVE_BUTTON_TEXT}
</YellowButton>
</Grid>
<Grid item md={2} xs={12}>
<GrayButton
type="button"
color="primary"
variant="contained"
to={routeConstants.MANAGE_EVENT}
>
{genericConstants.CANCEL_BUTTON_TEXT}
</GrayButton>
</Grid>
</Grid>
</Grid>
</Grid>
</CardActions>
</Grid>
</form>
</Card>
</Grid>
<Backdrop className={classes.backDrop} open={backdrop}>
<CircularProgress color="inherit" />
</Backdrop>
</Grid>
);
}