All files / src/stores walkthrough.ts

100% Statements 60/60
100% Branches 22/22
100% Functions 18/18
100% Lines 55/55

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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176                                      6x       4x 120x 120x 120x 120x     120x       120x     120x 120x     114x 114x 114x       23x 23x 16x 23x 23x     1x                 94x                 94x 92x 92x       21x               21x 21x 21x 21x   21x     21x     21x 21x         27x 21x 17x       105x       8x 7x 7x 7x   1x           3x 3x 3x   1x           5x 5x 5x   1x         3x               6x 6x 6x 6x     120x                                    
import { defineStore } from 'pinia'
import { ref } from 'vue'
import api from '@/services/api'
 
/**
 * Product walkthrough state, persisted on the user (GET/PUT /v1/users/preferences)
 * so a help panel seen on one device stays hidden on every other one.
 */
export interface WalkthroughState {
  /** Ids of the help panels already seen: never shown again automatically */
  seenSteps: string[]
  /** "Later": no panel is shown before this instant (ISO date) */
  snoozedUntil: string | null
  /** "Don't show again": no panel is shown until the user resets the walkthrough */
  dismissed: boolean
}
 
/** Start of the next local day: "later" postpones the walkthrough to tomorrow. */
export function startOfTomorrow(now: Date = new Date()): Date {
  return new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1)
}
 
// @implements UC-ONBOARD-001.1, UC-ONBOARD-002.1, UC-ONBOARD-003.1
export const useWalkthroughStore = defineStore('walkthrough', () => {
  const seenSteps = ref<string[]>([])
  const snoozedUntil = ref<string | null>(null)
  const dismissed = ref(false)
  const loaded = ref(false)
  // Closing a tour (× or Escape) only hides the rest of it until the next
  // session: unlike "later" and "don't show again", this is not persisted.
  const pausedForSession = ref(false)
 
  // Saves are chained so two quick "next" clicks can't reach the API out of
  // order and leave an older seenSteps list as the stored one.
  let saveChain: Promise<void> = Promise.resolve()
  // Bumped by every local change: a preferences response requested before one
  // (or while a save was in flight) may predate it and must not overwrite it.
  let revision = 0
  let pendingSaves = 0
 
  function apply(state: Partial<WalkthroughState> | undefined) {
    seenSteps.value = Array.isArray(state?.seenSteps) ? [...state.seenSteps] : []
    snoozedUntil.value = state?.snoozedUntil ?? null
    dismissed.value = state?.dismissed === true
  }
 
  async function load() {
    try {
      const response = await api.get('/v1/users/preferences')
      apply(response.data?.walkthrough)
      pausedForSession.value = false
      loaded.value = true
    } catch (error) {
      // Without a known state, showing nothing beats re-showing seen panels
      console.error('Failed to load walkthrough state:', error)
    }
  }
 
  /**
   * Call right before requesting the preferences another page fetches, and
   * pass the result to `hydrate` with the response.
   */
  function hydrationToken(): number | null {
    return pendingSaves > 0 ? null : revision
  }
 
  /**
   * Takes the state from a preferences response another page already fetched,
   * unless the state changed locally since it was requested (e.g. a restart
   * clicked while the page was still loading).
   */
  function hydrate(state: Partial<WalkthroughState> | undefined, token: number | null) {
    if (token !== revision) return
    apply(state)
    loaded.value = true
  }
 
  function snapshot(): WalkthroughState {
    return {
      seenSteps: [...seenSteps.value],
      snoozedUntil: snoozedUntil.value,
      dismissed: dismissed.value
    }
  }
 
  function save(): Promise<void> {
    const walkthrough = snapshot()
    revision++
    pendingSaves++
    const next = saveChain
      .then(async () => {
        await api.put('/v1/users/preferences', { walkthrough })
      })
      .finally(() => {
        pendingSaves--
      })
    // A failed save must not block the following ones
    saveChain = next.catch(() => undefined)
    return next
  }
 
  /** Whether help panels may be shown automatically right now. */
  function canShow(now: Date = new Date()): boolean {
    if (!loaded.value || dismissed.value || pausedForSession.value) return false
    if (snoozedUntil.value && new Date(snoozedUntil.value).getTime() > now.getTime()) return false
    return true
  }
 
  function isSeen(stepId: string): boolean {
    return seenSteps.value.includes(stepId)
  }
 
  async function markSeen(stepId: string) {
    if (isSeen(stepId)) return
    seenSteps.value = [...seenSteps.value, stepId]
    try {
      await save()
    } catch (error) {
      console.error('Failed to save walkthrough progress:', error)
    }
  }
 
  /** "Later": hide every panel until tomorrow. */
  async function snooze(now: Date = new Date()) {
    snoozedUntil.value = startOfTomorrow(now).toISOString()
    try {
      await save()
    } catch (error) {
      console.error('Failed to snooze walkthrough:', error)
    }
  }
 
  /** "Don't show again": hide every panel until the walkthrough is reset. */
  async function dismiss() {
    dismissed.value = true
    try {
      await save()
    } catch (error) {
      console.error('Failed to dismiss walkthrough:', error)
    }
  }
 
  function pauseForSession() {
    pausedForSession.value = true
  }
 
  /**
   * Profile page "restart the walkthrough": every panel shows again, from now.
   * Rethrows so the caller can report a failure.
   */
  async function reset() {
    apply(undefined)
    pausedForSession.value = false
    loaded.value = true
    await save()
  }
 
  return {
    seenSteps,
    snoozedUntil,
    dismissed,
    loaded,
    pausedForSession,
    load,
    hydrationToken,
    hydrate,
    canShow,
    isSeen,
    markSeen,
    snooze,
    dismiss,
    pauseForSession,
    reset
  }
})