Skip to content
Snippets Groups Projects
Commit 808250b8 authored by Konrad Mohrfeldt's avatar Konrad Mohrfeldt :koala:
Browse files

feat: make auto-save behaviour optional in form helpers

parent c236590e
No related branches found
No related tags found
No related merge requests found
...@@ -6,7 +6,7 @@ import { ...@@ -6,7 +6,7 @@ import {
RetrieveOperation, RetrieveOperation,
} from '@rokoli/bnb' } from '@rokoli/bnb'
import { ID, PartialUpdateOperation, useServerErrorFields, useServerErrors } from '@rokoli/bnb/drf' import { ID, PartialUpdateOperation, useServerErrorFields, useServerErrors } from '@rokoli/bnb/drf'
import { watchDebounced } from '@vueuse/core' import { extendRef, watchDebounced } from '@vueuse/core'
import { sort } from 'fast-sort' import { sort } from 'fast-sort'
import { cloneDeep, isEqual } from 'lodash' import { cloneDeep, isEqual } from 'lodash'
import { import {
...@@ -277,6 +277,7 @@ type UseCopyOptions<T> = { ...@@ -277,6 +277,7 @@ type UseCopyOptions<T> = {
clone?: (v: T) => T clone?: (v: T) => T
isEqual?: (v1: T, v2: T) => boolean isEqual?: (v1: T, v2: T) => boolean
save?: (value: T) => unknown save?: (value: T) => unknown
noAutoSave?: boolean
shallow?: boolean shallow?: boolean
debounce?: number debounce?: number
} }
...@@ -292,17 +293,18 @@ export function useCopy<T>(state: MaybeRefOrGetter<T>, options: UseCopyOptions<T ...@@ -292,17 +293,18 @@ export function useCopy<T>(state: MaybeRefOrGetter<T>, options: UseCopyOptions<T
value.value = _clone(toValue(state)) value.value = _clone(toValue(state))
}) })
watchDebounced( function triggerSave() {
value, const _value = value.value
(newValue) => { if (_save && !_isEqual(_value, toValue(state))) {
if (_save && !_isEqual(newValue, toValue(state))) { _save(_value)
_save(newValue) }
} }
},
{ deep: true, debounce },
)
return value if (!options.noAutoSave) {
watchDebounced(value, triggerSave, { deep: true, debounce })
}
return extendRef(value, { triggerSave }, { enumerable: true })
} }
export function useAPIObjectFieldCopy<T extends APIObject, K extends keyof T = keyof T, V = T[K]>( export function useAPIObjectFieldCopy<T extends APIObject, K extends keyof T = keyof T, V = T[K]>(
...@@ -325,5 +327,9 @@ export function useAPIObjectFieldCopy<T extends APIObject, K extends keyof T = k ...@@ -325,5 +327,9 @@ export function useAPIObjectFieldCopy<T extends APIObject, K extends keyof T = k
const state = computed<V>(() => _object.value[key] as V) const state = computed<V>(() => _object.value[key] as V)
const value = useCopy<V>(state, { ...options, save }) const value = useCopy<V>(state, { ...options, save })
return reactive({ value, isSaving, errors }) function triggerSave() {
value.triggerSave()
}
return reactive({ value, save: triggerSave, isSaving, errors })
} }
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment