*/
import * as theme from '../../src/main/js/app/theme';
import ThemeContext from '../../src/main/js/components/theme';
-import SonarUiCommonInitializer, { DEFAULT_LOCALE } from '../../src/main/js/helpers/init';
const content = document.createElement('div');
content.id = 'content';
const baseUrl = '';
(window as any).baseUrl = baseUrl;
-SonarUiCommonInitializer.setLocale(DEFAULT_LOCALE)
- .setMessages({})
- .setUrlContext(baseUrl);
// Hack : override the default value of the context used for theme by emotion
// This allows tests to get the theme value without specifiying a theme provider
import { Link } from 'react-router';
import { DropdownOverlay } from '../../../components/controls/Dropdown';
import { translate } from '../../../helpers/l10n';
-import { getBaseUrl } from '../../../helpers/urls';
+import { getBaseUrl } from '../../../helpers/system';
import { SuggestionsContext } from './SuggestionsContext';
interface Props {
import { connect } from 'react-redux';
import { Link } from 'react-router';
import { translate } from '../../../../helpers/l10n';
-import { getBaseUrl } from '../../../../helpers/urls';
+import { getBaseUrl } from '../../../../helpers/system';
import { getGlobalSettingValue, Store } from '../../../../store/rootReducer';
interface StateProps {
import { Router, withRouter } from '../../../../components/hoc/withRouter';
import Avatar from '../../../../components/ui/Avatar';
import { translate } from '../../../../helpers/l10n';
-import { getBaseUrl } from '../../../../helpers/urls';
+import { getBaseUrl } from '../../../../helpers/system';
import { isLoggedIn } from '../../../../helpers/users';
import { rawSizes } from '../../../theme';
import ContextNavBar from '../../../../components/ui/ContextNavBar';
import NavBarTabs from '../../../../components/ui/NavBarTabs';
import { translate } from '../../../../helpers/l10n';
-import { getBaseUrl } from '../../../../helpers/urls';
+import { getBaseUrl } from '../../../../helpers/system';
import { AdminPageExtension } from '../../../../types/extension';
import { PendingPluginResult } from '../../../../types/plugins';
import { rawSizes } from '../../../theme';
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import { installExtensionsHandler, installWebAnalyticsHandler } from '../helpers/extensionsHandler';
-import SonarUiCommonInitializer from '../helpers/init';
import { loadL10nBundle } from '../helpers/l10n';
import { parseJSON, request } from '../helpers/request';
import { getBaseUrl, getSystemStatus } from '../helpers/system';
import './styles/sonar.css';
-SonarUiCommonInitializer.setUrlContext(getBaseUrl());
-
installWebAnalyticsHandler();
if (isMainApp()) {
import * as React from 'react';
import { Link } from 'react-router';
import { translate } from '../../../helpers/l10n';
-import { getBaseUrl } from '../../../helpers/urls';
+import { getBaseUrl } from '../../../helpers/system';
const scanners = [
{
import { getIdentityProviders } from '../../../api/users';
import { colors } from '../../../app/theme';
import { getTextColor } from '../../../helpers/colors';
-import { getBaseUrl } from '../../../helpers/urls';
+import { getBaseUrl } from '../../../helpers/system';
export interface UserExternalIdentityProps {
user: T.LoggedInUser;
import SearchBox from '../../../components/controls/SearchBox';
import DeferredSpinner from '../../../components/ui/DeferredSpinner';
import { translate } from '../../../helpers/l10n';
-import { getBaseUrl } from '../../../helpers/urls';
+import { getBaseUrl } from '../../../helpers/system';
import { AzureProject, AzureRepository } from '../../../types/alm-integration';
import { AlmKeys, AlmSettingsInstance } from '../../../types/alm-settings';
import AzurePersonalAccessTokenForm from './AzurePersonalAccessTokenForm';
*/
import * as React from 'react';
import { translate } from '../../../helpers/l10n';
-import { getBaseUrl } from '../../../helpers/urls';
+import { getBaseUrl } from '../../../helpers/system';
import { BitbucketCloudRepository } from '../../../types/alm-integration';
import { AlmKeys, AlmSettingsInstance } from '../../../types/alm-settings';
import BitbucketCloudSearchForm from './BitbucketCloudSearchForm';
import { Button } from '../../../components/controls/buttons';
import DeferredSpinner from '../../../components/ui/DeferredSpinner';
import { translate } from '../../../helpers/l10n';
-import { getBaseUrl } from '../../../helpers/urls';
+import { getBaseUrl } from '../../../helpers/system';
import {
BitbucketProject,
BitbucketProjectRepositories,
import ChevronsIcon from '../../../components/icons/ChevronsIcon';
import { Alert } from '../../../components/ui/Alert';
import { translate, translateWithParameters } from '../../../helpers/l10n';
-import { getBaseUrl } from '../../../helpers/urls';
+import { getBaseUrl } from '../../../helpers/system';
import { AlmKeys } from '../../../types/alm-settings';
import { CreateProjectModes } from './types';
*/
import * as React from 'react';
import { translate } from '../../../helpers/l10n';
-import { getBaseUrl } from '../../../helpers/urls';
+import { getBaseUrl } from '../../../helpers/system';
import { GitlabProject } from '../../../types/alm-integration';
import { AlmKeys, AlmSettingsInstance } from '../../../types/alm-settings';
import CreateProjectPageHeader from './CreateProjectPageHeader';
import { Alert } from '../../../components/ui/Alert';
import DeferredSpinner from '../../../components/ui/DeferredSpinner';
import { translate } from '../../../helpers/l10n';
-import { getBaseUrl } from '../../../helpers/urls';
+import { getBaseUrl } from '../../../helpers/system';
import { AlmKeys, AlmSettingsInstance } from '../../../types/alm-settings';
interface Props {
import DateFromNow from '../../../components/intl/DateFromNow';
import TimeFormatter from '../../../components/intl/TimeFormatter';
import { translate } from '../../../helpers/l10n';
-import { isSonarCloud } from '../../../helpers/system';
-import { getBaseUrl, getReturnUrl } from '../../../helpers/urls';
+import { getBaseUrl, isSonarCloud } from '../../../helpers/system';
+import { getReturnUrl } from '../../../helpers/urls';
import '../styles.css';
interface Props {
import { Link } from 'react-router';
import { getBranchLikeQuery } from '../../../helpers/branch-like';
import { translate } from '../../../helpers/l10n';
-import { getBaseUrl } from '../../../helpers/urls';
+import { getBaseUrl } from '../../../helpers/system';
import { Branch } from '../../../types/branch-like';
import { ComponentQualifier } from '../../../types/component';
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
-import SonarUiCommonInitializer from '../../../helpers/init';
+import { resetMessages } from '../../../helpers/l10n';
import { isSonarCloud } from '../../../helpers/system';
import { convertToPermissionDefinitions } from '../utils';
jest.mock('../../../helpers/system', () => ({ isSonarCloud: jest.fn() }));
afterEach(() => {
- SonarUiCommonInitializer.setMessages({});
+ resetMessages({});
});
describe('convertToPermissionDefinitions', () => {
it('should convert and translate a permission definition', () => {
(isSonarCloud as jest.Mock).mockImplementation(() => false);
- SonarUiCommonInitializer.setMessages({
+ resetMessages({
'global_permissions.admin': 'Administer System'
});
it('should convert and translate a permission definition for SonarCloud', () => {
(isSonarCloud as jest.Mock).mockImplementation(() => true);
- SonarUiCommonInitializer.setMessages({
+ resetMessages({
'global_permissions.admin': 'Administer System',
'global_permissions.admin.sonarcloud': 'Administer Organization'
});
it('should fallback to basic message when SonarCloud version does not exist', () => {
(isSonarCloud as jest.Mock).mockImplementation(() => true);
- SonarUiCommonInitializer.setMessages({
+ resetMessages({
'global_permissions.admin': 'Administer System'
});
import { Link } from 'react-router';
import ChevronsIcon from '../../../components/icons/ChevronsIcon';
import { translate } from '../../../helpers/l10n';
-import { getBaseUrl } from '../../../helpers/urls';
+import { getBaseUrl } from '../../../helpers/system';
import { AlmKeys } from '../../../types/alm-settings';
export interface ProjectCreationMenuItemProps {
import { click } from '../../../helpers/testUtils';
import Header, { Props } from '../Header';
-jest.mock('../../../helpers/system', () => ({ isSonarCloud: jest.fn().mockReturnValue(false) }));
+jest.mock('../../../helpers/system', () => ({
+ getReactDomContainerSelector: jest.fn(() => '#content'),
+ isSonarCloud: jest.fn().mockReturnValue(false)
+}));
it('renders', () => {
expect(shallowRender()).toMatchSnapshot('default');
import * as React from 'react';
import { Link } from 'react-router';
import { translate } from '../../../helpers/l10n';
-import { getBaseUrl } from '../../../helpers/urls';
+import { getBaseUrl } from '../../../helpers/system';
export interface EmptyHotspotsPageProps {
filtered: boolean;
import { SubmitButton } from '../../../components/controls/buttons';
import DeferredSpinner from '../../../components/ui/DeferredSpinner';
import { translate } from '../../../helpers/l10n';
-import { getBaseUrl } from '../../../helpers/urls';
+import { getBaseUrl } from '../../../helpers/system';
import './LoginForm.css';
interface Props {
import GlobalMessagesContainer from '../../../app/components/GlobalMessagesContainer';
import RecentHistory from '../../../app/components/RecentHistory';
import { translate } from '../../../helpers/l10n';
-import { getBaseUrl } from '../../../helpers/urls';
+import { getBaseUrl } from '../../../helpers/system';
import { doLogout } from '../../../store/rootActions';
interface Props {
import HelpTooltip from '../../../components/controls/HelpTooltip';
import IdentityProviderLink from '../../../components/controls/IdentityProviderLink';
import { translateWithParameters } from '../../../helpers/l10n';
-import { getBaseUrl } from '../../../helpers/urls';
+import { getBaseUrl } from '../../../helpers/system';
import './OAuthProviders.css';
interface Props {
import * as React from 'react';
import { getCookie } from '../../../helpers/cookies';
import { translate } from '../../../helpers/l10n';
-import { getBaseUrl } from '../../../helpers/urls';
+import { getBaseUrl } from '../../../helpers/system';
export default function Unauthorized() {
const message = decodeURIComponent(getCookie('AUTHENTICATION-ERROR') || '');
import * as React from 'react';
import BoxedTabs from '../../../../components/controls/BoxedTabs';
import { translate } from '../../../../helpers/l10n';
-import { getBaseUrl } from '../../../../helpers/urls';
+import { getBaseUrl } from '../../../../helpers/system';
import {
AlmKeys,
AlmSettingsBindingDefinitions,
import Dropdown from '../../../components/controls/Dropdown';
import DropdownIcon from '../../../components/icons/DropdownIcon';
import { translate } from '../../../helpers/l10n';
-import { getBaseUrl } from '../../../helpers/urls';
+import { getBaseUrl } from '../../../helpers/system';
import { getFileNameSuffix } from '../utils';
import ChangeLogLevelForm from './ChangeLogLevelForm';
import * as React from 'react';
import { colors } from '../../../app/theme';
import { getTextColor } from '../../../helpers/colors';
-import { getBaseUrl } from '../../../helpers/urls';
+import { getBaseUrl } from '../../../helpers/system';
export interface Props {
identityProvider?: T.IdentityProvider;
import { formatMeasure } from '../../helpers/measures';
import { collapsedDirFromPath, fileFromPath } from '../../helpers/path';
import { omitNil } from '../../helpers/request';
+import { getBaseUrl } from '../../helpers/system';
import {
- getBaseUrl,
getBranchLikeUrl,
getCodeUrl,
getComponentIssuesUrl,
import * as React from 'react';
import DeferredSpinner from '../../components/ui/DeferredSpinner';
import { translate } from '../../helpers/l10n';
-import { getBaseUrl } from '../../helpers/urls';
+import { getBaseUrl } from '../../helpers/system';
import { GraphType, MeasureHistory, Serie } from '../../types/project-activity';
import GraphHistory from './GraphHistory';
import './styles.css';
import * as classNames from 'classnames';
import * as React from 'react';
import { isDarkColor } from '../../helpers/colors';
-import { getBaseUrl } from '../../helpers/urls';
+import { getBaseUrl } from '../../helpers/system';
import './IdentityProviderLink.css';
interface Props {
import * as classNames from 'classnames';
import * as React from 'react';
import * as ReactModal from 'react-modal';
-import { getReactDomContainerSelector } from '../../helpers/init';
+import { getReactDomContainerSelector } from '../../helpers/system';
import './Modal.css';
ReactModal.setAppElement(getReactDomContainerSelector());
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import * as React from 'react';
-import { getBaseUrl } from '../../helpers/urls';
+import { getBaseUrl } from '../../helpers/system';
export default function DocImg(props: React.ImgHTMLAttributes<HTMLImageElement>) {
const { alt, src, ...other } = props;
*/
import * as React from 'react';
import { Alert } from '../components/ui/Alert';
-import { IS_SSR } from '../helpers/init';
+import { IS_SSR } from '../helpers/browser';
import { translate } from '../helpers/l10n';
import { requestTryAndRepeatUntil } from '../helpers/request';
import * as React from 'react';
import EllipsisIcon from '../../components/icons/EllipsisIcon';
import { translate } from '../../helpers/l10n';
-import { getBaseUrl } from '../../helpers/urls';
+import { getBaseUrl } from '../../helpers/system';
import { AlmKeys, AlmSettingsInstance, ProjectAlmBindingResponse } from '../../types/alm-settings';
import AzurePipelinesTutorial from './azure-pipelines/AzurePipelinesTutorial';
import BitbucketPipelinesTutorial from './bitbucket-pipelines/BitbucketPipelinesTutorial';
*/
import * as React from 'react';
import { translate } from '../../../helpers/l10n';
-import { getBaseUrl } from '../../../helpers/urls';
+import { getBaseUrl } from '../../../helpers/system';
import { AlmKeys } from '../../../types/alm-settings';
import { withAppState } from '../../hoc/withAppState';
import SentenceWithHighlights from './SentenceWithHighlights';
import * as React from 'react';
import { FormattedMessage } from 'react-intl';
import { translate } from '../../../../helpers/l10n';
-import { getBaseUrl } from '../../../../helpers/urls';
+import { getBaseUrl } from '../../../../helpers/system';
import { OSs } from '../../types';
export interface DownloadBuildWrapperProps {
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2021 SonarSource SA
- * mailto:info AT sonarsource DOT com
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-/* eslint-disable no-console */
-import Initializer, {
- DEFAULT_LOCALE,
- DEFAULT_MESSAGES,
- getLocale,
- getMessages,
- getReactDomContainerSelector,
- getUrlContext
-} from '../init';
-
-const originalConsoleWarn = console.warn;
-console.warn = jest.fn();
-
-beforeEach(() => {
- (console.warn as jest.Mock).mockClear();
-});
-
-afterAll(() => {
- Initializer.setLocale('en')
- .setMessages({})
- .setUrlContext('');
- // @ts-ignore: initialize everything to undefined, not possible by respecting types
- Initializer.setReactDomContainer(undefined);
- console.warn = originalConsoleWarn;
-});
-
-it('should throw when trying to get a value without initializing first', () => {
- // @ts-ignore: initialize react dom container to undefined, not possible by respecting types
- Initializer.setLocale(undefined)
- .setMessages(undefined)
- .setUrlContext(undefined);
-
- expect(getLocale()).toBe(DEFAULT_LOCALE);
- expect(console.warn).toHaveBeenLastCalledWith(
- expect.stringContaining('L10n locale is not initialized')
- );
-
- expect(getMessages()).toBe(DEFAULT_MESSAGES);
- expect(console.warn).toHaveBeenLastCalledWith(
- expect.stringContaining('L10n messages are not initialized')
- );
-
- expect(getUrlContext).toThrowErrorMatchingInlineSnapshot(
- `"sonar-ui-common init: web context needs to be initialized by Initializer.setUrlContext before being used"`
- );
-});
-
-it('should return the initialized values', () => {
- const locale = 'ru';
- const messages = { any: 'Any' };
- const urlContext = '/context';
- const reactDomContainerSelector = '#custom';
-
- Initializer.setLocale(locale)
- .setMessages(messages)
- .setUrlContext(urlContext)
- .setReactDomContainer(reactDomContainerSelector);
-
- expect(getLocale()).toBe(locale);
- expect(getMessages()).toBe(messages);
- expect(getUrlContext()).toBe(urlContext);
- expect(getReactDomContainerSelector()).toBe(reactDomContainerSelector);
- expect(console.warn).not.toBeCalled();
-});
-
-it('should have a default react dom container selector without warning', () => {
- // @ts-ignore: initialize react dom container to undefined, not possible by respecting types
- Initializer.setReactDomContainer(undefined);
-
- expect(getReactDomContainerSelector()).toBe('#content');
- expect(console.warn).not.toBeCalled();
-});
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
-import * as reactIntl from 'react-intl';
import { fetchL10nBundle } from '../../api/l10n';
-import SonarUiCommonInitializer, { getMessages } from '../init';
import {
getLocalizedCategoryMetricName,
getLocalizedMetricDomain,
getLocalizedMetricName,
+ getMessages,
getShortMonthName,
getShortWeekDayName,
getWeekDayName,
hasMessage,
loadL10nBundle,
+ resetMessages,
translate,
translateWithParameters
} from '../l10n';
expect.objectContaining({ locale: cachedBundle.locale, messages: cachedBundle.messages })
);
});
-
- it('should init react-intl & sonar-ui-common', async () => {
- jest.spyOn(SonarUiCommonInitializer, 'setLocale');
- jest.spyOn(SonarUiCommonInitializer, 'setMessages');
- jest.spyOn(reactIntl, 'addLocaleData');
-
- await loadL10nBundle();
-
- expect(SonarUiCommonInitializer.setLocale).toHaveBeenCalledWith('de');
- expect(SonarUiCommonInitializer.setMessages).toHaveBeenCalledWith({ test_message: 'test' });
- expect(reactIntl.addLocaleData).toHaveBeenCalled();
- });
});
const originalMessages = getMessages();
const MSG = 'my_message';
afterEach(() => {
- SonarUiCommonInitializer.setMessages(originalMessages);
+ resetMessages(originalMessages);
});
describe('translate', () => {
it('should translate simple message', () => {
- SonarUiCommonInitializer.setMessages({ my_key: MSG });
+ resetMessages({ my_key: MSG });
expect(translate('my_key')).toBe(MSG);
});
it('should translate message with composite key', () => {
- SonarUiCommonInitializer.setMessages({ 'my.composite.message': MSG });
+ resetMessages({ 'my.composite.message': MSG });
expect(translate('my', 'composite', 'message')).toBe(MSG);
expect(translate('my.composite', 'message')).toBe(MSG);
expect(translate('my', 'composite.message')).toBe(MSG);
describe('translateWithParameters', () => {
it('should translate message with one parameter in the beginning', () => {
- SonarUiCommonInitializer.setMessages({ x_apples: '{0} apples' });
+ resetMessages({ x_apples: '{0} apples' });
expect(translateWithParameters('x_apples', 5)).toBe('5 apples');
});
it('should translate message with one parameter in the middle', () => {
- SonarUiCommonInitializer.setMessages({ x_apples: 'I have {0} apples' });
+ resetMessages({ x_apples: 'I have {0} apples' });
expect(translateWithParameters('x_apples', 5)).toBe('I have 5 apples');
});
it('should translate message with one parameter in the end', () => {
- SonarUiCommonInitializer.setMessages({ x_apples: 'Apples: {0}' });
+ resetMessages({ x_apples: 'Apples: {0}' });
expect(translateWithParameters('x_apples', 5)).toBe('Apples: 5');
});
it('should translate message with several parameters', () => {
- SonarUiCommonInitializer.setMessages({
+ resetMessages({
x_apples: '{0}: I have {2} apples in my {1} baskets - {3}'
});
expect(translateWithParameters('x_apples', 1, 2, 3, 4)).toBe(
});
it('should not be affected by replacement pattern XSS vulnerability of String.replace', () => {
- SonarUiCommonInitializer.setMessages({ x_apples: 'I have {0} apples' });
+ resetMessages({ x_apples: 'I have {0} apples' });
expect(translateWithParameters('x_apples', '$`')).toBe('I have $` apples');
});
describe('hasMessage', () => {
it('should return that the message exists', () => {
- SonarUiCommonInitializer.setMessages({ foo: 'Foo', 'foo.bar': 'Foo Bar' });
+ resetMessages({ foo: 'Foo', 'foo.bar': 'Foo Bar' });
expect(hasMessage('foo')).toBe(true);
expect(hasMessage('foo', 'bar')).toBe(true);
});
const metric = { key: 'new_code', name: 'new_code_metric_name' };
it('should return the metric name translation', () => {
- SonarUiCommonInitializer.setMessages({ 'metric.new_code.name': 'metric.new_code.name_t' });
+ resetMessages({ 'metric.new_code.name': 'metric.new_code.name_t' });
expect(getLocalizedMetricName(metric)).toBe('metric.new_code.name_t');
});
it('should return the metric short name', () => {
- SonarUiCommonInitializer.setMessages({
+ resetMessages({
'metric.new_code.short_name': 'metric.new_code.short_name_t'
});
expect(getLocalizedMetricName(metric, true)).toBe('metric.new_code.short_name_t');
});
it('should fallback on name if short name is absent', () => {
- SonarUiCommonInitializer.setMessages({ 'metric.new_code.name': 'metric.new_code.name_t' });
+ resetMessages({ 'metric.new_code.name': 'metric.new_code.name_t' });
expect(getLocalizedMetricName(metric, true)).toBe('metric.new_code.name_t');
});
describe('getLocalizedCategoryMetricName', () => {
it('should return metric category name translation', () => {
- SonarUiCommonInitializer.setMessages({
+ resetMessages({
'metric.new_code.extra_short_name': 'metric.new_code.extra_short_name_t'
});
expect(getLocalizedCategoryMetricName({ key: 'new_code' })).toBe(
});
it('should fallback on metric name if extra_short_name is absent', () => {
- SonarUiCommonInitializer.setMessages({ 'metric.new_code.name': 'metric.new_code.name_t' });
+ resetMessages({ 'metric.new_code.name': 'metric.new_code.name_t' });
expect(getLocalizedCategoryMetricName({ key: 'new_code' })).toBe('metric.new_code.name_t');
});
});
describe('getLocalizedMetricDomain', () => {
it('should return metric domain name translation', () => {
- SonarUiCommonInitializer.setMessages({ 'metric_domain.domain': 'metric_domain.domain_t' });
+ resetMessages({ 'metric_domain.domain': 'metric_domain.domain_t' });
expect(getLocalizedMetricDomain('domain')).toBe('metric_domain.domain_t');
});
describe('getShortMonthName', () => {
it('should properly translation months', () => {
- SonarUiCommonInitializer.setMessages({ Jan: 'Jan_t' });
+ resetMessages({ Jan: 'Jan_t' });
expect(getShortMonthName(0)).toBe('Jan_t');
});
});
describe('getWeekDayName', () => {
it('should properly translation weekday', () => {
- SonarUiCommonInitializer.setMessages({ Sunday: 'Sunday_t' });
+ resetMessages({ Sunday: 'Sunday_t' });
expect(getWeekDayName(0)).toBe('Sunday_t');
});
});
describe('getShortWeekDayName', () => {
it('should properly translation short weekday', () => {
- SonarUiCommonInitializer.setMessages({ Sun: 'Sun_t' });
+ resetMessages({ Sun: 'Sun_t' });
expect(getShortWeekDayName(0)).toBe('Sun_t');
});
});
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
-import SonarUiCommonInitializer from '../init';
+import { resetMessages } from '../l10n';
import {
enhanceConditionWithMeasure,
formatMeasure,
const ONE_DAY = HOURS_IN_DAY * ONE_HOUR;
beforeAll(() => {
- SonarUiCommonInitializer.setMessages({
+ resetMessages({
'work_duration.x_days': '{0}d',
'work_duration.x_hours': '{0}h',
'work_duration.x_minutes': '{0}min',
});
afterAll(() => {
- SonarUiCommonInitializer.setMessages({});
+ resetMessages({});
});
describe('#formatMeasure()', () => {
import { AlmKeys } from '../../types/alm-settings';
import { ComponentQualifier } from '../../types/component';
import { IssueType } from '../../types/issues';
-import SonarUICommonInitializer from '../init';
import {
convertGithubApiUrlToLink,
getComponentDrilldownUrl,
});
});
-afterEach(() => {
- SonarUICommonInitializer.setUrlContext('');
-});
-
describe('#getPathUrlAsString', () => {
it('should return component url', () => {
expect(
getPathUrlAsString({ pathname: '/dashboard', query: { id: COMPLEX_COMPONENT_KEY } })
).toBe('/dashboard?id=' + COMPLEX_COMPONENT_KEY_ENCODED);
});
-
- it('should take baseUrl into account', () => {
- SonarUICommonInitializer.setUrlContext('/context');
- expect(
- getPathUrlAsString({ pathname: '/dashboard', query: { id: COMPLEX_COMPONENT_KEY } })
- ).toBe('/context/dashboard?id=' + COMPLEX_COMPONENT_KEY_ENCODED);
- });
});
describe('#getReturnUrl', () => {
*/
import { EnhancedWindow } from '../types/browser';
+export const IS_SSR = typeof window === 'undefined';
+
export function getEnhancedWindow() {
return (window as unknown) as EnhancedWindow;
}
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
-import { getBaseUrl } from '../helpers/urls';
+import { getBaseUrl } from '../helpers/system';
import { getExtensionFromCache } from './extensionsHandler';
let librariesExposed = false;
*/
import { createHistory, History } from 'history';
import { useRouterHistory } from 'react-router';
-import { getUrlContext } from './init';
+import { getBaseUrl } from './system';
let history: History;
function ensureHistory() {
// eslint-disable-next-line react-hooks/rules-of-hooks
history = useRouterHistory(createHistory)({
- basename: getUrlContext()
+ basename: getBaseUrl()
});
return history;
}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2021 SonarSource SA
- * mailto:info AT sonarsource DOT com
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-import { Messages } from './l10n';
-
-let urlContext: string | undefined; // Is the base path (web context) in SQ
-let messages: Messages | undefined;
-let locale: string | undefined;
-let reactDomContainerSelector: string | undefined; // CSS selector of the DOM node where the React App is attached
-
-export const IS_SSR = typeof window === 'undefined';
-export const DEFAULT_LOCALE = 'en';
-export const DEFAULT_MESSAGES = {
- // eslint-disable-next-line camelcase
- default_error_message: 'The request cannot be processed. Try again later.'
-};
-const LOGGER_PREFIX = 'sonar-ui-common init:';
-
-export default {
- setUrlContext(newUrlContext?: string) {
- urlContext = newUrlContext;
- return this;
- },
- setLocale(newLocale: string) {
- locale = newLocale;
- return this;
- },
- setMessages(newMessages?: Messages) {
- messages = newMessages;
- return this;
- },
- setReactDomContainer(nodeSelector: string) {
- reactDomContainerSelector = nodeSelector;
- return this;
- }
-};
-
-export function getMessages() {
- if (typeof messages === 'undefined') {
- logWarning('L10n messages are not initialized. Use default messages.');
- return DEFAULT_MESSAGES;
- }
- return messages;
-}
-
-export function getLocale() {
- if (typeof locale === 'undefined') {
- logWarning('L10n locale is not initialized. Use default locale.');
- return DEFAULT_LOCALE;
- }
- return locale;
-}
-
-export function getReactDomContainerSelector() {
- return reactDomContainerSelector || '#content';
-}
-
-export function getUrlContext() {
- if (typeof urlContext === 'undefined') {
- throw new Error(
- `${LOGGER_PREFIX} web context needs to be initialized by Initializer.setUrlContext before being used`
- );
- }
- return urlContext;
-}
-
-function logWarning(message: string) {
- if (process.env.NODE_ENV !== 'production') {
- // eslint-disable-next-line no-console
- console.warn(`${LOGGER_PREFIX} ${message}`);
- }
-}
import { fetchL10nBundle } from '../api/l10n';
import { L10nBundle, L10nBundleRequestParams } from '../types/l10n';
import { toNotSoISOString } from './dates';
-import SonarUiCommonInitializer, { DEFAULT_LOCALE, getLocale, getMessages } from './init';
import { get as loadFromLocalStorage, save as saveInLocalStorage } from './storage';
export type Messages = T.Dict<string>;
+export const DEFAULT_LOCALE = 'en';
+export const DEFAULT_MESSAGES = {
+ // eslint-disable-next-line camelcase
+ default_error_message: 'The request cannot be processed. Try again later.'
+};
+
+let allMessages: Messages = {};
+let locale: string | undefined;
+
export function translate(...keys: string[]): string {
const messageKey = keys.join('.');
const l10nMessages = getMessages();
return getMessages()[messageKey] != null;
}
+export function getMessages() {
+ if (typeof allMessages === 'undefined') {
+ logWarning('L10n messages are not initialized. Use default messages.');
+ return DEFAULT_MESSAGES;
+ }
+ return allMessages;
+}
+
+export function resetMessages(newMessages: Messages) {
+ allMessages = newMessages;
+}
+
export function getLocalizedMetricName(
metric: { key: string; name?: string },
short = false
}
export function getCurrentLocale() {
- return getLocale();
+ return locale;
+}
+
+export function resetCurrentLocale(newLocale: string) {
+ locale = newLocale;
}
export function getShortMonthName(index: number) {
messages: {}
}));
- SonarUiCommonInitializer.setLocale(bundle.locale).setMessages(bundle.messages);
+ resetCurrentLocale(bundle.locale);
+ resetMessages(bundle.messages);
+
// No need to load english (default) bundle, it's coming with react-intl
if (bundle.locale !== DEFAULT_LOCALE) {
const [intlBundle, intl] = await Promise.all([
effectiveLocale: cachedBundle.locale || browserLocale || DEFAULT_LOCALE,
messages: cachedBundle.messages ?? {}
};
- } else {
- throw new Error(`Unexpected status code: ${response.status}`);
}
+ throw new Error(`Unexpected status code: ${response.status}`);
});
const bundle = {
function saveL10nBundleToLocalStorage(bundle: L10nBundle) {
saveInLocalStorage(L10N_BUNDLE_LS_KEY, JSON.stringify(bundle));
}
+
+function logWarning(message: string) {
+ if (process.env.NODE_ENV !== 'production') {
+ // eslint-disable-next-line no-console
+ console.warn(message);
+ }
+}
import { isNil, omitBy } from 'lodash';
import { stringify } from 'querystring';
import { getCookie } from './cookies';
-import { getUrlContext } from './init';
import { translate } from './l10n';
+import { getBaseUrl } from './system';
export function getCSRFTokenName(): string {
return 'X-XSRF-TOKEN';
submit(): Promise<Response> {
const { url, options } = this.getSubmitData({ ...getCSRFToken() });
- return window.fetch(getUrlContext() + url, options);
+ return window.fetch(getBaseUrl() + url, options);
}
setMethod(method: string): Request {
export function isSonarCloud() {
return getInstance() === InstanceType.SonarCloud;
}
+
+export function getReactDomContainerSelector() {
+ return '#content';
+}
import { GraphType } from '../types/project-activity';
import { SecurityStandard } from '../types/security';
import { getBranchLikeQuery, isBranch, isMainBranch, isPullRequest } from './branch-like';
-import { getUrlContext, IS_SSR } from './init';
+import { IS_SSR } from './browser';
+import { getBaseUrl } from './system';
export interface Location {
pathname: string;
return url.replace(/\/$/, '');
}
-export function getBaseUrl(): string {
- return getUrlContext();
-}
-
export function getHostUrl(): string {
if (IS_SSR) {
throw new Error('No host url available on server side.');