All files / src/composables useUnsavedChanges.ts

100% Statements 28/28
100% Branches 24/24
100% Functions 8/8
100% Lines 25/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67                  643x 5356x 725x 725x   4631x 1599x   4413x 4413x 1599x   3032x 2185x   643x                             1084x 1084x   1084x     1233x 1233x 1233x 334x 334x 334x         1084x 1411x         1x     1084x    
import { computed, nextTick, ref, watch } from 'vue'
 
/**
 * A comparable form of a form's values. Empty values (undefined, null, '',
 * [] and {}) are left out and keys sorted, so a field component turning an
 * absent value into an empty one, or rebuilding an object in another key
 * order, is no change for the user.
 */
export function formSnapshot(value: unknown): string {
  const clean = (input: unknown): unknown => {
    if (Array.isArray(input)) {
      const items = input.map(clean)
      return items.length ? items : undefined
    }
    if (input && typeof input === 'object' && !(input instanceof Date)) {
      const entries = Object.keys(input as Record<string, unknown>)
        .sort()
        .map((key) => [key, clean((input as Record<string, unknown>)[key])] as const)
        .filter(([, item]) => item !== undefined)
      return entries.length ? Object.fromEntries(entries) : undefined
    }
    if (input === null || input === '' || input === undefined) return undefined
    return input
  }
  return JSON.stringify(clean(value)) ?? ''
}
 
/**
 * Whether a sidebar's form changed since it was opened, for BaseFormSidebar's
 * `dirty` (it then asks before dropping the changes).
 *
 * @param current the form's values
 * @param opened truthy while the form is open; a new value is a new form
 *   (another record opened), compared from then on
 *
 * The values compared to are read two ticks after the opening, once the field
 * components have set their initial values: nobody types in two ticks.
 */
export function useUnsavedChanges(current: () => unknown, opened: () => unknown) {
  const baseline = ref<string | null>(null)
  let opening = 0
 
  watch(
    opened,
    async (value) => {
      const run = ++opening
      baseline.value = null
      if (!value) return
      await nextTick()
      await nextTick()
      if (run === opening) baseline.value = formSnapshot(current())
    },
    { immediate: true, flush: 'post' }
  )
 
  const dirty = computed(
    () => baseline.value !== null && formSnapshot(current()) !== baseline.value
  )
 
  /** The values are saved: compared from them on */
  function markSaved() {
    baseline.value = formSnapshot(current())
  }
 
  return { dirty, markSaved }
}