Skip to content

Commit

Permalink
Render form correctly when editing
Browse files Browse the repository at this point in the history
Render form correctly when editing

Display edited fields

Populate form fields

Render form correctly when editing
  • Loading branch information
saulipurhonen committed Jun 4, 2021
1 parent 246da81 commit 84a3dcb
Show file tree
Hide file tree
Showing 2 changed files with 111 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -87,21 +87,18 @@ const useStyles = makeStyles(theme => ({
width: "95%",
},
},
"& h2, h3, h4": {
"& h2, h3, h4, h5, h6": {
margin: theme.spacing(1, 0),
},
<<<<<<< HEAD
=======
"& .MuiPaper-elevation2": {
paddingRight: theme.spacing(1),
"& .array": { margin: 0 },
"& h2, h3, h4": { margin: theme.spacing(1), width: "95%" },
"& h3, h4": { margin: theme.spacing(1) },
"& button": { margin: theme.spacing(0, 1) },
},
"& .MuiSelect-outlined": {
marginRight: 0,
},
>>>>>>> 4fe3185 (Form edit E2E tests)
},
},
}))
Expand Down
120 changes: 109 additions & 11 deletions src/components/NewDraftWizard/WizardForms/WizardJSONSchemaParser.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import AddIcon from "@material-ui/icons/Add"
import RemoveIcon from "@material-ui/icons/Remove"
import * as _ from "lodash"
import { useFieldArray, useFormContext } from "react-hook-form"
import { useSelector } from "react-redux"

/*
* Highlight style for required fields
Expand Down Expand Up @@ -99,7 +100,7 @@ const traverseValues = (object: any) => {
default: {
console.error(`
No initial value parsing support for type ${object["type"]} yet.
Pretty printed version of object with unsupported type:
${JSON.stringify(object, null, 2)}
`)
Expand All @@ -113,8 +114,11 @@ const traverseValues = (object: any) => {
*/

const buildFields = (schema: any): ?React.Node => {
// console.log(schema)
const devSchema = { ...schema, properties: { processing: schema.properties.processing } }
// console.log(devSchema)
try {
return traverseFields(schema, [])
return traverseFields(devSchema, [])
} catch (error) {
console.error(error)
}
Expand Down Expand Up @@ -180,6 +184,9 @@ const traverseFields = (
let required = object?.else?.required ?? object.required
let requireFirstItem = false

// console.log("obj: ", object)
// console.log(requiredProperties)

// Require first field of section if parent section is a required property
if (
requireFirst ||
Expand Down Expand Up @@ -230,7 +237,7 @@ const traverseFields = (
default: {
console.error(`
No field parsing support for type ${object.type} yet.
Pretty printed version of object with unsupported type:
${JSON.stringify(object, null, 2)}
`)
Expand All @@ -251,6 +258,7 @@ type FormSectionProps = {
*/
const FormSection = (props: FormSectionProps) => {
const { name, label, level } = props

return (
<ConnectForm>
{({ errors }) => {
Expand Down Expand Up @@ -311,15 +319,96 @@ const FormOneOfField = ({
nestedField?: any,
required?: any,
}) => {
// console.log("nestedField: ", nestedField)
const options = object.oneOf
// console.log("options: ", options)

// Get the fieldValue when rendering a saved/submitted form
// For e.g. obj.required is ["label", "url"] and nestedField is {id: "sth1", label: "sth2", url: "sth3"}
// Get object from state and set default values if child of oneOf field has values
// Fetching current object values from state rather than via getValues() method gets values on first call. The getValues method results in empty object on first call
const currentObject = useSelector(state => state.currentObject) || {}
// console.log(currentObject)

// Pathname can include index number eg. [0]
// const cleanedPath = path[0].split("[")[0]

// Run & Analysis Reference Alignment ei toimi oikein

const values = currentObject[path]
? currentObject
: currentObject[Object.keys(currentObject).filter(item => path.includes(item))] || {}

// console.log(path)

let fieldValue = ""

const flattenObject = (obj, prefix = "") =>
Object.keys(obj).reduce((acc, k) => {
const pre = prefix.length ? prefix + "." : ""
if (typeof obj[k] === "object") Object.assign(acc, flattenObject(obj[k], pre + k))
else acc[pre + k] = obj[k]
return acc
}, {})

// console.log("values: ", values)
// console.log("path: ", path)

if (Object.keys(values).length > 0) {
for (const item of path) {
if (values[item]) {
const itemValues = values[item]
const parentPath = Object.keys(itemValues) ? Object.keys(itemValues) : ""
// console.log("values: ", values)
// // console.log("item: ", item)
// console.log("item values: ", itemValues)
// const parentPath = Object.keys(itemValues) ? Object.keys(itemValues)[0] : ""
// console.log("options: ", options)
// console.log("parentPath: ", parentPath)
// console.log("isNaN parentPath: ", isNaN(parentPath[0]))

// Match key from currentObject to option property.
// Field key can be deeply nested and therefore we need to have multiple cases for finding correct value.
if (isNaN(parentPath[0])) {
fieldValue = (options.find(option => option.properties[parentPath])
? // Eg. Sample > Sample Names > Sample Data Type
options.find(option => option.properties[parentPath])
: // Eg. Run > Run Type > Reference Alignment
options.find(
option => option.properties[Object.keys(flattenObject(itemValues))[0].split(".").slice(-1)[0]]
)
)?.title
} else {
// Eg. Experiment > Expected Base Call Table > Processing > Single Processing
if (typeof itemValues === "string") {
// console.log(2)
fieldValue = options.find(option => option.type === "string").title
}
// Eg. Experiment > Expected Base Call Table > Processing > Complex Processing
else {
// console.log(3)
const fieldKey = Object.keys(values[item][0])[0]
// console.log("fieldKey: ", fieldKey)
// console.log(
// "options find: ",
// options.find(option => option.items?.properties[fieldKey])
// )
fieldValue = options.find(option => option.items?.properties[fieldKey]).title
}
}
}
}
}

// console.log("nestedField: ", nestedField)

// Eg. Study > Study Links
if (nestedField) {
for (let obj of options) {
obj.required.every(val => Object.keys(nestedField).includes(val)) ? (fieldValue = obj.title) : ""
for (let option of options) {
option.required.every(val => (Object.keys(nestedField).includes(val) ? (fieldValue = option.title) : ""))
}
}

const [field, setField] = useState(fieldValue)

const handleChange = event => setField(event.target.value)
Expand Down Expand Up @@ -528,7 +617,9 @@ const FormCheckBoxArray = ({ name, label, required, options }: FormSelectFieldPr
<strong>{label}</strong> - check from following options
</p>
<ConnectForm>
{({ register, errors }) => {
{({ register, errors, getValues }) => {
const values = getValues()[name]

const error = _.get(errors, name)
const { ref, ...rest } = register(name)

Expand All @@ -539,7 +630,15 @@ const FormCheckBoxArray = ({ name, label, required, options }: FormSelectFieldPr
<FormControlLabel
key={option}
control={
<Checkbox name={name} {...rest} inputRef={ref} value={option} color="primary" defaultValue="" />
<Checkbox
name={name}
{...rest}
inputRef={ref}
value={option}
checked={values && values?.includes(option) ? true : false}
color="primary"
defaultValue=""
/>
}
label={option}
/>
Expand Down Expand Up @@ -571,8 +670,6 @@ const FormArray = ({ object, path, required }: FormArrayProps) => {

const { fields, append, remove } = useFieldArray({ name })

const currentObject = useSelector(state => state.currentObject) || {}

return (
<div className="array" key={`${name}-array`}>
<Typography key={`${name}-header`} variant={`h${level}`}>
Expand All @@ -582,6 +679,7 @@ const FormArray = ({ object, path, required }: FormArrayProps) => {
const [lastPathItem] = path.slice(-1)
const pathWithoutLastItem = path.slice(0, -1)
const lastPathItemWithIndex = `${lastPathItem}[${index}]`

if (items.oneOf) {
const pathForThisIndex = [...pathWithoutLastItem, lastPathItemWithIndex]

Expand All @@ -599,7 +697,7 @@ const FormArray = ({ object, path, required }: FormArrayProps) => {
const properties = object.items.properties

return (
<div className="arrayRow" key={`${name}[${index}]`}>
<Box px={1} className="arrayRow" key={`${name}[${index}]`}>
<Paper elevation={2}>
{Object.keys(items).map(item => {
const pathForThisIndex = [...pathWithoutLastItem, lastPathItemWithIndex, item]
Expand All @@ -609,7 +707,7 @@ const FormArray = ({ object, path, required }: FormArrayProps) => {
<IconButton onClick={() => remove(index)}>
<RemoveIcon />
</IconButton>
</div>
</Box>
)
})}

Expand Down

0 comments on commit 84a3dcb

Please sign in to comment.