UNPKG

@bigfishtv/cockpit

Version:

91 lines (84 loc) 2.89 kB
/** * Modal Utilities * @module Utilities/modalUtils */ import deepEqual from 'deep-equal' import { post } from '../api/xhrUtils' import { modalHandler } from '../components/modal/ModalHost' /** * Takes Component, and formValue. Intended for modals that directly update a formValue selection * @param {React.Component} Component - Modal React Component * @param {ReactForms.Value} formValue - selected formValue instance e.g. formValue.select('for_modal') * @param {Boolean} isNew - new instance/editing existing * @param {Function} onSave - function called on modal save * @param {Function} onClose - function called on modal close */ export function handleEdit( Component, formValue, isNew = false, onSave = handleModalFormSave, onClose = handleModalFormClose ) { modalHandler.add({ Component: Component, props: { formValue, isNew, onSave: onSave.bind(this, formValue), onClose: onClose.bind(this, formValue), }, }) } /** * Uses oldFormValue instance and updates with value of newForValue * @param {ReactForms.Value} oldFormValue * @param {ReactForms.Value} newFormValue */ export function handleModalFormSave(oldFormValue, newFormValue) { oldFormValue.update(newFormValue.value) } /** * Called on modal form close, if wasn't saved and was a new instance then delete that instance * @param {ReactForms.Value} oldFormValue * @param {ReactForms.Value} newFormValue * @param {Boolean} didSave * @param {Boolean} isNew */ export function handleModalFormClose(oldFormValue, newFormValue, didSave, isNew) { if (!didSave && isNew) { const index = oldFormValue.keyPath[oldFormValue.keyPath.length - 1] const parent = oldFormValue.parent const Items = parent.value.filter((item, i) => i !== index) parent.update(Items) } } /** * Posts data directly to url on modal close if new or edited. Will attempt to smartly generate 'queryUrl' if 'model' is provided * @param {Object} props - Object of props * @param {String} props.subject * @param {String} props.queryUrl * @param {Array} props.data * @param {Array} props.oldValue * @param {Array} props.newValue * @param {Boolean} props.isNew */ export function handleSave(props) { const { queryUrl, data, oldValue, newValue, subject, isNew } = props const model = props.model ? props.model : subject ? subject.toLowerCase().replace(' ', '_') + 's' : null let url = null if (queryUrl) url = queryUrl else if (model && isNew) url = '/admin/' + model + '/add.json' else if (model && oldValue.id) url = '/admin/' + model + '/edit/' + oldValue.id + '.json' if (isNew || !deepEqual(oldValue, newValue)) { post({ url, subject: props.subject, data: newValue, callback: newItem => { const newData = isNew ? [...data, newItem] : data.map(item => (item.id === oldValue.id ? newItem : item)) props.callback(newData) }, }) } }