From 14177cfadedb9e98e22674407c1c6bc4460790e7 Mon Sep 17 00:00:00 2001 From: Dave Lockhart Date: Mon, 18 Nov 2024 16:02:54 -0500 Subject: [PATCH] make things work with static resources --- lib/localize.js | 15 +++++++++++---- test/localize.test.js | 22 ++++++++++++++++++++++ 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/lib/localize.js b/lib/localize.js index 317c368..8e92f12 100644 --- a/lib/localize.js +++ b/lib/localize.js @@ -156,10 +156,8 @@ export const getLocalizeClass = (superclass = class {}) => class LocalizeClass e } if (Object.prototype.hasOwnProperty.call(this, 'getLocalizeResources') || Object.prototype.hasOwnProperty.call(this, 'resources')) { const possibleLanguages = this._generatePossibleLanguages(config); - if (config?.importFunc) { - const resourcesPromise = this.getLocalizeResources(possibleLanguages, config); - resourcesLoadedPromises.push(resourcesPromise); - } + const resourcesPromise = this.getLocalizeResources(possibleLanguages, config); + resourcesLoadedPromises.push(resourcesPromise); if (config?.loadCommon) { resourcesLoadedPromises.push(this.getLocalizeResources(possibleLanguages, { importFunc: async(lang) => { @@ -177,6 +175,8 @@ export const getLocalizeClass = (superclass = class {}) => class LocalizeClass e static async _getLocalizeResources(langs, { importFunc, osloCollection, useBrowserLangs }) { + if (importFunc === undefined) return; + // in dev, don't request unsupported langpacks if (!importFunc.toString().includes('switch') && !useBrowserLangs) { langs = langs.filter(lang => supportedLangpacks.includes(lang)); @@ -219,6 +219,13 @@ export const getLocalizeClass = (superclass = class {}) => class LocalizeClass e const allResources = {}; const resolvedLocales = new Set(); + + localizeResources.forEach((entry, index) => { + if (entry === undefined) { + localizeResources.splice(index, 1); + } + }); + for (const { language, resources } of localizeResources) { for (const [name, value] of Object.entries(resources)) { allResources[name] = { language, value }; diff --git a/test/localize.test.js b/test/localize.test.js index b4382b1..3aea21a 100644 --- a/test/localize.test.js +++ b/test/localize.test.js @@ -71,6 +71,28 @@ describe('Localize', () => { expect(localizer.localize.resources).to.deep.equal(localizer2.localize.resources); }); + it('should handle static resources with no importFunc', async() => { + class StaticLocalizer extends Localize { + static async getLocalizeResources(langs) { + for (let i = 0; i < langs.length; i++) { + if (resources[langs[i]]) { + return { + language: langs[i], + resources: resources[langs[i]] + }; + } + } + } + constructor() { + super({}); + } + } + const staticLocalizer = new StaticLocalizer(); + await staticLocalizer.ready; + const localized = staticLocalizer.localize('basic', { employerName: 'D2L' }); + expect(localized).to.equal('D2L is my employer'); + }); + describe('onResourcesChange', () => { it('runs when the document locale changes', async() => {