48 lines
1.2 KiB
TypeScript
48 lines
1.2 KiB
TypeScript
import { computed, onScopeDispose, ref, watch, type ComputedRef, type Ref } from 'vue'
|
|
import { useUnsavedWorkStore } from '@/stores/unsavedWork'
|
|
|
|
interface UnsavedWorkRegistrationOptions<T extends object> {
|
|
key: string
|
|
label: ComputedRef<string>
|
|
isOpen: Ref<boolean>
|
|
model: T
|
|
requiredPermission: ComputedRef<string | null>
|
|
}
|
|
|
|
export function useUnsavedWorkRegistration<T extends object>(
|
|
options: UnsavedWorkRegistrationOptions<T>,
|
|
) {
|
|
const store = useUnsavedWorkStore()
|
|
const snapshot = computed(() => JSON.stringify(options.model))
|
|
const baseline = ref(snapshot.value)
|
|
|
|
function sync() {
|
|
if (!options.isOpen.value) {
|
|
store.remove(options.key)
|
|
return
|
|
}
|
|
|
|
store.upsert({
|
|
key: options.key,
|
|
label: options.label.value,
|
|
dirty: snapshot.value !== baseline.value,
|
|
requiredPermission: options.requiredPermission.value,
|
|
})
|
|
}
|
|
|
|
function captureBaseline() {
|
|
baseline.value = snapshot.value
|
|
sync()
|
|
}
|
|
|
|
watch(
|
|
[options.isOpen, snapshot, options.label, options.requiredPermission],
|
|
sync,
|
|
{ flush: 'sync' },
|
|
)
|
|
sync()
|
|
onScopeDispose(() => store.remove(options.key))
|
|
|
|
return { captureBaseline }
|
|
}
|