16005: Open collection and project in new tab feature added
[arvados-workbench2.git] / src / common / redirect-to.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { Config } from './config';
6
7 const REDIRECT_TO_KEY = 'redirectTo';
8 export const REDIRECT_TO_APPLY_TO_PATH = 'redirectToApplyToPath';
9
10 export const storeRedirects = () => {
11     let redirectUrl;
12     const { location: { href }, localStorage } = window;
13     const applyToPath = href.indexOf(REDIRECT_TO_APPLY_TO_PATH) > -1;
14
15     if (href.indexOf(REDIRECT_TO_KEY) > -1) {
16         redirectUrl = href.split(`${REDIRECT_TO_KEY}=`)[1];
17     }
18
19     if (localStorage && redirectUrl) {
20         localStorage.setItem(REDIRECT_TO_KEY, redirectUrl);
21
22         if (applyToPath) {
23             localStorage.setItem(REDIRECT_TO_APPLY_TO_PATH, 'true');
24         }
25     }
26 };
27
28 export const handleRedirects = (token: string, config: Config) => {
29     const { localStorage } = window;
30     const { keepWebServiceUrl } = config;
31
32     if (localStorage && localStorage.getItem(REDIRECT_TO_KEY)) {
33         const redirectUrl = localStorage.getItem(REDIRECT_TO_KEY);
34         localStorage.removeItem(REDIRECT_TO_KEY);
35         const applyToPath = localStorage.getItem(REDIRECT_TO_APPLY_TO_PATH);
36
37         if (redirectUrl) {
38             if (applyToPath === 'true') {
39                 localStorage.removeItem(REDIRECT_TO_APPLY_TO_PATH);
40                 setTimeout(() => {
41                     window.location.pathname = redirectUrl;
42                 }, 0);
43             } else {
44                 const sep = redirectUrl.indexOf("?") > -1 ? "&" : "?";
45                 window.location.href = `${keepWebServiceUrl}${redirectUrl}${sep}api_token=${token}`;
46             }
47         }
48     }
49 };