Improve client routing logic

This commit is contained in:
Andrew Kingston 2022-06-17 10:09:27 +01:00
parent aeacc4e59f
commit e048d00fc8
1 changed files with 28 additions and 25 deletions

View File

@ -47,23 +47,19 @@
// Handle no matching route // Handle no matching route
$: { $: {
if (dataLoaded && $routeStore.routerLoaded && !$routeStore.activeRoute) { if (dataLoaded && $routeStore.routerLoaded && !$routeStore.activeRoute) {
if ($authStore) { if ($screenStore.screens.length) {
// There is a logged in user, so handle them // If we have some available screens, find the best route to push the
if ($screenStore.screens.length) { // user to initially
// Find the best route to push the user to initially const route = getBestRoute($screenStore.screens)
const route = getBestRoute( permissionError = false
$authStore, routeStore.actions.navigate(route)
$screenStore.screens, } else if ($authStore) {
$devToolsStore.role // If the user is logged in but has no screens, they don't have
) // permission to use the app
permissionError = false permissionError = true
routeStore.actions.navigate(route)
} else {
// No screens likely means the user has no permissions to view this app
permissionError = true
}
} else { } else {
// The user is not logged in, redirect them to login // If they have no screens and are not logged in, it probably means
// they should log in to gain access
const returnUrl = `${window.location.pathname}${window.location.hash}` const returnUrl = `${window.location.pathname}${window.location.hash}`
CookieUtils.setCookie(Constants.Cookies.ReturnUrl, returnUrl) CookieUtils.setCookie(Constants.Cookies.ReturnUrl, returnUrl)
window.location = "/builder/auth/login" window.location = "/builder/auth/login"
@ -71,20 +67,27 @@
} }
} }
const getBestRoute = (user, screens) => { // Assigns a rank to a potential screen route, preferring home screens
// Rank all screens, preferring all home screens // and higher roles
const rankScreen = screen => { const rankScreen = screen => {
const roleId = screen.routing.roleId const roleId = screen.routing.roleId
let rank = RoleUtils.getRolePriority(roleId) let rank = RoleUtils.getRolePriority(roleId)
if (screen.routing.homeScreen) { if (screen.routing.homeScreen) {
rank += 100 rank += 100
}
return rank
} }
return rank
}
// Determines the best route to push the user to initially from a set of
// available screens
const getBestRoute = screens => {
// Enrich and rank all screens, preferring all home screens
const enrichedScreens = screens?.map(screen => ({ const enrichedScreens = screens?.map(screen => ({
...screen, ...screen,
rank: rankScreen(screen), rank: rankScreen(screen),
})) }))
// Sort ranked screens
const rankedScreens = enrichedScreens?.sort((a, b) => { const rankedScreens = enrichedScreens?.sort((a, b) => {
// First sort by rank // First sort by rank
if (a.rank !== b.rank) { if (a.rank !== b.rank) {