All files / src/composables usePermissionsRefresh.ts

100% Statements 13/13
100% Branches 6/6
100% Functions 4/4
100% Lines 11/11

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        2x                   11x 11x     5x 3x 2x       11x 11x       6x 6x     11x    
import { useAuthStore } from '@/stores/auth'
import { useFlowsStore } from '@/stores/flows'
 
/** Memberships older than this are reloaded when the tab comes back */
export const PERMISSIONS_STALE_AFTER_MS = 5 * 60 * 1000
 
/**
 * Safety net for the pushed `permissionsChanged` (see useMessagesSocket.ts),
 * which a dropped WebSocket connection can miss, and for role edits that push
 * nothing (a role's permissions changed): when the tab comes back to the
 * foreground, memberships loaded more than 5 minutes ago are reloaded in the
 * background — at most one call per 5 minutes, never blocking the UI.
 */
export function usePermissionsRefresh() {
  const authStore = useAuthStore()
  const flowsStore = useFlowsStore()
 
  function onForeground() {
    if (document.visibilityState !== 'visible' || !authStore.isAuthenticated) return
    if (Date.now() - flowsStore.myFlowsLoadedAt < PERMISSIONS_STALE_AFTER_MS) return
    void flowsStore.refreshMyFlows()
  }
 
  function start() {
    document.addEventListener('visibilitychange', onForeground)
    window.addEventListener('focus', onForeground)
  }
 
  function stop() {
    document.removeEventListener('visibilitychange', onForeground)
    window.removeEventListener('focus', onForeground)
  }
 
  return { start, stop }
}