Skip to content

Commit

Permalink
Change the locale dynamically by adding &i18n-locale to URL (opensear…
Browse files Browse the repository at this point in the history
…ch-project#7686)

* Change the locale dynamically by adding &i18n-locale to URL

The main issue was the inability to dynamically change the locale in OpenSearch
Dashboards. Currently we need to update config file and i18nrc.json.

This PR allows  users to switch to a different locale (e.g., from English to Chinese)
by appending or modifying the 'i18n-locale' parameter in the URL.

* getAndUpdateLocaleInUrl: If a non-default locale is found, this function reconstructs
the URL with the locale parameter in the correct position.
* updated the ScopedHistory class, allowing it to detect locale changes and trigger reloads
as necessary.
* modify the i18nMixin, which sets up the i18n system during server startup, to register
all available translation files during server startup, not just the current locale.
* update the uiRenderMixin to accept requests for any registered locale and dynamically
load and cache translations for requested locales.

Signed-off-by: Anan Zhuang <ananzh@amazon.com>

* fix PR comments

Signed-off-by: Anan Zhuang <ananzh@amazon.com>

* fix comments 2

Signed-off-by: Anan Zhuang <ananzh@amazon.com>

* fix tests

Signed-off-by: Anan Zhuang <ananzh@amazon.com>

* Changeset file for PR opensearch-project#7686 created/updated

---------

Signed-off-by: Anan Zhuang <ananzh@amazon.com>
Co-authored-by: opensearch-changeset-bot[bot] <154024398+opensearch-changeset-bot[bot]@users.noreply.github.com>
  • Loading branch information
ananzh and opensearch-changeset-bot[bot] authored Aug 15, 2024
1 parent 97ddd8a commit 21b8a2f
Show file tree
Hide file tree
Showing 14 changed files with 586 additions and 40 deletions.
2 changes: 2 additions & 0 deletions changelogs/fragments/7686.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
feat:
- Change the locale dynamically by adding &i18n-locale to URL ([#7686](https://github.com/opensearch-project/OpenSearch-Dashboards/pull/7686))
34 changes: 33 additions & 1 deletion packages/osd-i18n/src/core/i18n.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -899,8 +899,17 @@ describe('I18n engine', () => {

describe('load', () => {
let mockFetch: jest.SpyInstance;
let originalWindow: any;

beforeEach(() => {
mockFetch = jest.spyOn(global as any, 'fetch').mockImplementation();
originalWindow = global.window;
global.window = { ...originalWindow };
});

afterEach(() => {
global.window = originalWindow;
delete (window as any).__i18nWarning; // Clear the warning after each test
});

test('fails if server returns >= 300 status code', async () => {
Expand Down Expand Up @@ -928,7 +937,7 @@ describe('I18n engine', () => {

mockFetch.mockResolvedValue({
status: 200,
json: jest.fn().mockResolvedValue(translations),
json: jest.fn().mockResolvedValue({ translations }),
});

await expect(i18n.load('some-url')).resolves.toBeUndefined();
Expand All @@ -938,5 +947,28 @@ describe('I18n engine', () => {

expect(i18n.getTranslation()).toEqual(translations);
});

test('sets warning on window when present in response', async () => {
const warning = { title: 'Warning', text: 'This is a warning' };
mockFetch.mockResolvedValue({
status: 200,
json: jest.fn().mockResolvedValue({ translations: { locale: 'en' }, warning }),
});

await i18n.load('some-url');

expect((window as any).__i18nWarning).toEqual(warning);
});

test('does not set warning on window when not present in response', async () => {
mockFetch.mockResolvedValue({
status: 200,
json: jest.fn().mockResolvedValue({ translations: { locale: 'en' } }),
});

await i18n.load('some-url');

expect((window as any).__i18nWarning).toBeUndefined();
});
});
});
9 changes: 8 additions & 1 deletion packages/osd-i18n/src/core/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -261,5 +261,12 @@ export async function load(translationsUrl: string) {
throw new Error(`Translations request failed with status code: ${response.status}`);
}

init(await response.json());
const data = await response.json();

if (data.warning) {
// Store the warning to be displayed after core system setup
(window as any).__i18nWarning = data.warning;
}

init(data.translations);
}
60 changes: 60 additions & 0 deletions src/core/public/application/scoped_history.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,23 @@

import { ScopedHistory } from './scoped_history';
import { createMemoryHistory } from 'history';
import { getLocaleInUrl } from '../locale_helper';
import { i18n } from '@osd/i18n';

jest.mock('../locale_helper', () => ({
getLocaleInUrl: jest.fn(),
}));

jest.mock('@osd/i18n', () => ({
i18n: {
getLocale: jest.fn(),
},
}));

describe('ScopedHistory', () => {
beforeEach(() => {
(getLocaleInUrl as jest.Mock).mockReturnValue('en');
});
describe('construction', () => {
it('succeeds if current location matches basePath', () => {
const gh = createMemoryHistory();
Expand Down Expand Up @@ -358,4 +373,49 @@ describe('ScopedHistory', () => {
expect(gh.length).toBe(4);
});
});

describe('locale handling', () => {
let originalLocation: Location;

beforeEach(() => {
originalLocation = window.location;
delete (window as any).location;
window.location = { href: 'http://localhost/app/wow', reload: jest.fn() } as any;
(i18n.getLocale as jest.Mock).mockReturnValue('en');
});

afterEach(() => {
window.location = originalLocation;
jest.resetAllMocks();
});

it('reloads the page when locale changes', () => {
const gh = createMemoryHistory();
gh.push('/app/wow');
const h = new ScopedHistory(gh, '/app/wow');
// Use the 'h' variable to trigger the listener
h.push('/new-page');

// Mock getLocaleInUrl to return a different locale
(getLocaleInUrl as jest.Mock).mockReturnValue('fr');

// Simulate navigation
gh.push('/app/wow/new-page');

expect(window.location.reload).toHaveBeenCalled();
});

it('does not reload the page when locale changes', () => {
const gh = createMemoryHistory();
gh.push('/app/wow');

// Mock getLocaleInUrl to return a different locale
(getLocaleInUrl as jest.Mock).mockReturnValue('en');

// Simulate navigation
gh.push('/app/wow/new-page');

expect(window.location.reload).not.toHaveBeenCalled();
});
});
});
11 changes: 11 additions & 0 deletions src/core/public/application/scoped_history.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ import {
Href,
Action,
} from 'history';
import { i18n } from '@osd/i18n';
import { getLocaleInUrl } from '../locale_helper';

/**
* A wrapper around a `History` instance that is scoped to a particular base path of the history stack. Behaves
Expand Down Expand Up @@ -307,6 +309,7 @@ export class ScopedHistory<HistoryLocationState = unknown>
* state. Also forwards events to child listeners with the base path stripped from the location.
*/
private setupHistoryListener() {
const currentLocale = i18n.getLocale() || 'en';
const unlisten = this.parentHistory.listen((location, action) => {
// If the user navigates outside the scope of this basePath, tear it down.
if (!location.pathname.startsWith(this.basePath)) {
Expand All @@ -315,6 +318,14 @@ export class ScopedHistory<HistoryLocationState = unknown>
return;
}

const localeValue = getLocaleInUrl(window.location.href);

if (localeValue !== currentLocale) {
// Force a full page reload
window.location.reload();
return;
}

/**
* Track location keys using the same algorithm the browser uses internally.
* - On PUSH, remove all items that came after the current location and append the new location.
Expand Down
50 changes: 50 additions & 0 deletions src/core/public/locale_helper.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/

import { getLocaleInUrl } from './locale_helper';

describe('getLocaleInUrl', () => {
beforeEach(() => {
// Clear any warnings before each test
delete (window as any).__localeWarning;
});

it('should return the locale from a valid query string', () => {
const url = 'http://localhost:5603/app/home?locale=en-US';
expect(getLocaleInUrl(url)).toBe('en-US');
});

it('should return the locale from a valid hash query string', () => {
const url = 'http://localhost:5603/app/home#/?locale=fr-FR';
expect(getLocaleInUrl(url)).toBe('fr-FR');
});

it('should return en for a URL without locale', () => {
const url = 'http://localhost:5603/app/home';
expect(getLocaleInUrl(url)).toBe('en');
});

it('should return en and set a warning for an invalid locale format in hash', () => {
const url = 'http://localhost:5603/app/home#/&locale=de-DE';
expect(getLocaleInUrl(url)).toBe('en');
expect((window as any).__localeWarning).toBeDefined();
expect((window as any).__localeWarning.title).toBe('Invalid URL Format');
});

it('should return en for an empty locale value', () => {
const url = 'http://localhost:5603/app/home?locale=';
expect(getLocaleInUrl(url)).toBe('en');
});

it('should handle URLs with other query parameters', () => {
const url = 'http://localhost:5603/app/home?param1=value1&locale=ja-JP&param2=value2';
expect(getLocaleInUrl(url)).toBe('ja-JP');
});

it('should handle URLs with other hash parameters', () => {
const url = 'http://localhost:5603/app/home#/route?param1=value1&locale=zh-CN&param2=value2';
expect(getLocaleInUrl(url)).toBe('zh-CN');
});
});
68 changes: 68 additions & 0 deletions src/core/public/locale_helper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/

/**
* Extracts the locale value from a given URL.
*
* This function looks for the 'locale' parameter in either the main query string
* or in the hash part of the URL. It supports two valid formats:
* 1. As a regular query parameter: "?locale=xx-XX"
* 2. In the hash with a proper query string: "#/?locale=xx-XX"
*
* If an invalid format is detected, it sets a warning message on the window object.
*
* @param url - The URL to extract the locale from
* @returns The locale value if found and valid, or null otherwise
*/
export function getLocaleInUrl(url: string): string | null {
let urlObject: URL;
// Attempt to parse the URL, return null if invalid
try {
urlObject = new URL(url, window.location.origin);
} catch (error) {
setInvalidUrlWarning();
return null;
}

let localeValue: string | null = null;

// Check for locale in the main query string
if (urlObject.searchParams.has('locale')) {
localeValue = urlObject.searchParams.get('locale');
}
// Check for locale in the hash, but only if it's in proper query string format
else if (urlObject.hash.includes('?')) {
const hashParams = new URLSearchParams(urlObject.hash.split('?')[1]);
if (hashParams.has('locale')) {
localeValue = hashParams.get('locale');
}
}

// Check for non standard query format:
if (localeValue === null && url.includes('&locale=')) {
setInvalidUrlWithLocaleWarning();
return 'en';
}

// Return the locale value if found, or 'en' if not found
return localeValue && localeValue.trim() !== '' ? localeValue : 'en';
}

function setInvalidUrlWarning(): void {
(window as any).__localeWarning = {
title: 'Invalid URL Format',
text: 'The provided URL is not in a valid format.',
};
}

function setInvalidUrlWithLocaleWarning(): void {
(window as any).__localeWarning = {
title: 'Invalid URL Format',
text:
'The locale parameter is not in a valid URL format. ' +
'Use either "?locale=xx-XX" in the main URL or "#/?locale=xx-XX" in the hash. ' +
'For example: "yourapp.com/page?locale=en-US" or "yourapp.com/page#/?locale=en-US".',
};
}
28 changes: 16 additions & 12 deletions src/core/public/osd_bootstrap.test.mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,18 +31,6 @@
import { applicationServiceMock } from './application/application_service.mock';
import { fatalErrorsServiceMock } from './fatal_errors/fatal_errors_service.mock';
export const fatalErrorMock = fatalErrorsServiceMock.createSetupContract();
export const coreSystemMock = {
setup: jest.fn().mockResolvedValue({
fatalErrors: fatalErrorMock,
}),
start: jest.fn().mockResolvedValue({
application: applicationServiceMock.createInternalStartContract(),
}),
};
jest.doMock('./core_system', () => ({
CoreSystem: jest.fn().mockImplementation(() => coreSystemMock),
}));

export const apmSystem = {
setup: jest.fn().mockResolvedValue(undefined),
start: jest.fn().mockResolvedValue(undefined),
Expand All @@ -53,9 +41,25 @@ jest.doMock('./apm_system', () => ({
}));

export const i18nLoad = jest.fn().mockResolvedValue(undefined);
export const i18nSetLocale = jest.fn();
jest.doMock('@osd/i18n', () => ({
i18n: {
...jest.requireActual('@osd/i18n').i18n,
load: i18nLoad,
setLocale: i18nSetLocale,
},
}));

export const coreSystemMock = {
setup: jest.fn().mockResolvedValue({
fatalErrors: fatalErrorMock,
}),
start: jest.fn().mockResolvedValue({
application: applicationServiceMock.createInternalStartContract(),
}),
};
jest.doMock('./core_system', () => ({
CoreSystem: jest.fn().mockImplementation(() => coreSystemMock),
}));

export const consoleWarnMock = jest.spyOn(console, 'warn').mockImplementation(() => {});
Loading

0 comments on commit 21b8a2f

Please sign in to comment.