Files
threshold-ui/ui/desktop/app/routes/application.js
T
2024-09-17 16:36:47 -07:00

107 lines
3.0 KiB
JavaScript

/**
* Copyright (c) HashiCorp, Inc.
* SPDX-License-Identifier: BUSL-1.1
*/
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
import { action } from '@ember/object';
import { A } from '@ember/array';
import { getOwner } from '@ember/application';
import { notifyError } from 'core/decorators/notify';
export default class ApplicationRoute extends Route {
// =services
@service session;
@service clusterUrl;
@service ipc;
@service intl;
// =attributes
/**
* @type {string}
*/
routeIfUnauthenticated = 'index';
/**
* Check that the clusterUrl specified in the renderer matches the clusterUrl
* reported by the main process. If they differ, update the main process
* clusterUrl so that the renderer's CSP can be rewritten to allow requests.
*/
@notifyError(({ message }) => message, { catch: true })
async beforeModel() {
this.intl.setLocale(['en-us']);
await this.session.setup();
const theme = this.session.get('data.theme');
this.toggleTheme(theme);
await this.clusterUrl.updateClusterUrl();
// Add token to cache daemon after a successful authentication restoration
if (this.session.isAuthenticated) {
const sessionData = this.session.data?.authenticated;
await this.ipc.invoke('addTokenToDaemons', {
tokenId: sessionData?.id,
token: sessionData?.token,
});
}
}
/**
* Add window frame config on controller.
*/
async setupController(controller) {
controller.set('hasMacOSChrome', await this.ipc.invoke('hasMacOSChrome'));
controller.set(
'showWindowActions',
await this.ipc.invoke('showWindowActions'),
);
}
// =actions
/**
* Invalidates the session if a 401 error occurs and returns false to
* prevent further error handling.
* Returns true in all other cases, allowing error handling to occur (such
* as displaying the `error.hbs` template, if one exists).
* @param {Error} e
*/
@action
error(e) {
const isUnauthenticated = A(e?.errors)?.[0]?.isUnauthenticated;
if (isUnauthenticated) {
this.session.invalidate();
return false;
}
return true;
}
/**
* Applies the specified color theme to the root ember element.
* @param {string} theme - "light", "dark", or nullish (system default)
*/
@action
toggleTheme(theme) {
const rootElementSelector = getOwner(this).rootElement;
const rootEl = getOwner(this)
.lookup('service:-document')
.querySelector(rootElementSelector);
this.session.set('data.theme', theme);
switch (theme) {
case 'light':
rootEl.classList.add('rose-theme-light');
rootEl.classList.remove('rose-theme-dark');
break;
case 'dark':
rootEl.classList.add('rose-theme-dark');
rootEl.classList.remove('rose-theme-light');
break;
default:
rootEl.classList.remove('rose-theme-dark');
rootEl.classList.remove('rose-theme-light');
}
}
}