1
0
Fork 0
mirror of synced 2024-08-18 19:41:30 +12:00

Refactored approach to parsing multiselect values and ensuring any parsed values trigger a field update

This commit is contained in:
Dean 2022-10-26 15:13:27 +01:00
parent c17cfc2666
commit 5e61575e30
2 changed files with 33 additions and 23 deletions

View file

@ -1,6 +1,6 @@
<script>
import Picker from "./Picker.svelte"
import { createEventDispatcher } from "svelte"
import { createEventDispatcher, onMount } from "svelte"
export let value = []
export let id = null
@ -16,8 +16,33 @@
export let autoWidth = false
const dispatch = createEventDispatcher()
const parseValues = value => {
return Array.isArray(value)
? value.reduce((acc, entry) => {
if (typeof ele === "string" && entry.trim() === "") {
return acc
}
let processedOption = String(entry)
if (options.indexOf(processedOption) > -1) {
acc.push(processedOption)
}
return acc
}, [])
: []
}
let loaded = false
$: combinedValues = value ? [...value].concat(options) : []
$: superSet = new Set(combinedValues)
$: if (loaded && options.length != superSet.size) {
// ensure that the values being pushed in are valid.
dispatch("change", parseValues(value))
}
$: selectedLookupMap = getSelectedLookupMap(value)
$: optionLookupMap = getOptionLookupMap(options)
$: fieldText = getFieldText(value, optionLookupMap, placeholder)
$: isOptionSelected = optionValue => selectedLookupMap[optionValue] === true
$: toggleOption = makeToggleOption(selectedLookupMap, value)
@ -70,6 +95,10 @@
}
}
}
onMount(() => {
loaded = true
})
</script>
<Picker

View file

@ -128,23 +128,6 @@
return fields.find(field => get(field).name === name)
}
const getDefault = (defaultValue, schema, type) => {
// Remove any values not present in the field schema
// Convert any values supplied to string
if (Array.isArray(defaultValue) && type == "array") {
return defaultValue.reduce((acc, entry) => {
let processedOption = String(entry)
let schemaOptions = schema.constraints.inclusion
if (schemaOptions.indexOf(processedOption) > -1) {
acc.push(processedOption)
}
return acc
}, [])
} else {
return defaultValue
}
}
const formApi = {
registerField: (
field,
@ -170,10 +153,8 @@
table
)
const parsedDefault = getDefault(defaultValue, schema?.[field], type)
// If we've already registered this field then keep some existing state
let initialValue = Helpers.deepGet(initialValues, field) ?? parsedDefault
let initialValue = Helpers.deepGet(initialValues, field) ?? defaultValue
let initialError = null
let fieldId = `id-${Helpers.uuid()}`
const existingField = getField(field)
@ -206,11 +187,11 @@
error: initialError,
disabled:
disabled || fieldDisabled || (isAutoColumn && !editAutoColumns),
defaultValue: parsedDefault,
defaultValue,
validator,
lastUpdate: Date.now(),
},
fieldApi: makeFieldApi(field, parsedDefault),
fieldApi: makeFieldApi(field, defaultValue),
fieldSchema: schema?.[field] ?? {},
})