Skip to content

Commit

Permalink
fix: Make language stable
Browse files Browse the repository at this point in the history
  • Loading branch information
stepan662 committed Mar 14, 2022
1 parent 8cbc219 commit cd96ee8
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 17 deletions.
13 changes: 13 additions & 0 deletions packages/core/src/Properties.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,19 @@ describe('Properties', () => {
expect(properties.currentLanguage).toEqual('cs');
});

test('language is stored locally and detected only once', () => {
const languageGetter = jest.spyOn(window.navigator, 'language', 'get');
languageGetter.mockReturnValue('cs');
Storage.prototype.getItem = jest.fn();
properties.config = new TolgeeConfig({
availableLanguages: ['cs', 'en'],
});
expect(properties.currentLanguage).toEqual('cs');
expect(properties.currentLanguage).toEqual('cs');

expect(languageGetter).toBeCalledTimes(1);
});

test('available languages derrived from staticData', () => {
const languageGetter = jest.spyOn(window.navigator, 'language', 'get');
languageGetter.mockReturnValue('cs');
Expand Down
38 changes: 21 additions & 17 deletions packages/core/src/Properties.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,25 +15,11 @@ export class Properties {
return this.config.forceLanguage;
}

if (this._currentLanguage) {
return this._currentLanguage;
if (!this._currentLanguage) {
this._currentLanguage = this.getInitialLanguage();
}

if (this.config.enableLanguageStore) {
const storedLanguage = this.getStoredLanguage();
if (storedLanguage) {
return storedLanguage;
}
}

if (this.config.enableLanguageDetection) {
const detectedLanguage = this.getLanguageByNavigator();
if (detectedLanguage) {
return detectedLanguage;
}
}

return this.config.defaultLanguage;
return this._currentLanguage;
}

set currentLanguage(language: string) {
Expand Down Expand Up @@ -63,6 +49,24 @@ export class Properties {
);
}

private getInitialLanguage() {
if (this.config.enableLanguageStore) {
const storedLanguage = this.getStoredLanguage();
if (storedLanguage) {
return storedLanguage;
}
}

if (this.config.enableLanguageDetection) {
const detectedLanguage = this.getLanguageByNavigator();
if (detectedLanguage) {
return detectedLanguage;
}
}

return this.config.defaultLanguage;
}

private getStoredLanguage() {
if (typeof localStorage !== 'undefined') {
const storedLanguage = localStorage.getItem(
Expand Down

0 comments on commit cd96ee8

Please sign in to comment.