Skip to content

Commit

Permalink
Lock profile when user leaves app on Ionic platform
Browse files Browse the repository at this point in the history
  • Loading branch information
lubej committed May 14, 2024
1 parent cdc95f9 commit fcea203
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 2 deletions.
1 change: 1 addition & 0 deletions .changelog/1933.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Lock profile when user leaves app on Ionic platform
24 changes: 22 additions & 2 deletions src/app/components/Ionic/IonicProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
import { createContext, FC, PropsWithChildren, useEffect } from 'react'
import { createContext, FC, PropsWithChildren, useEffect, useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import { Capacitor } from '@capacitor/core'
import { App } from '@capacitor/app'
import { useDispatch } from 'react-redux'
import { persistActions } from '../../state/persist'
import { deltaMsToLockProfile } from '../../../ionicConfig'

const IonicContext = createContext<undefined>(undefined)

const IonicContextProvider: FC<PropsWithChildren> = ({ children }) => {
const dispatch = useDispatch()
const navigate = useNavigate()
const lockTimestamp = useRef<number>()

useEffect(() => {
/**
Expand All @@ -21,10 +26,25 @@ const IonicContextProvider: FC<PropsWithChildren> = ({ children }) => {
}
})

// TODO: appStateChange triggers on the web platform as well, using visibilitychange listener, consider reusing the code(downside @capacitor/app dependency on web & extension)
const appStateChangeListenerHandle = App.addListener('appStateChange', ({ isActive }) => {
const shouldLock = lockTimestamp.current && Date.now() - lockTimestamp.current > deltaMsToLockProfile
if (isActive && shouldLock) {
dispatch(persistActions.lockAsync())
} else if (isActive && !shouldLock) {
lockTimestamp.current = undefined
}

if (!isActive) {
lockTimestamp.current = Date.now()
}
})

return () => {
backButtonListenerHandle.remove()
appStateChangeListenerHandle.remove()
}
}, [navigate])
}, [dispatch, navigate])

return <IonicContext.Provider value={undefined}>{children}</IonicContext.Provider>
}
Expand Down
6 changes: 6 additions & 0 deletions src/ionicConfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/**
* Represents the duration in milliseconds to lock a profile.
*
* @type {number}
*/
export const deltaMsToLockProfile = 30 * 1000

0 comments on commit fcea203

Please sign in to comment.