Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: universal environment #832

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 55 additions & 2 deletions lib/locale.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,41 @@
* SPDX-License-Identifier: GPL-3.0-or-later
*/

declare global {
// eslint-disable-next-line camelcase, no-var
var _nc_l10n_locale: string | undefined
// eslint-disable-next-line camelcase, no-var
var _nc_l10n_language: string | undefined
}
Comment on lines +6 to +11
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will make it available also in exported typings.
Should probably be moved to a globals.d.ts file


/**
* Returns the user's locale
* @example 'de_DE'
*/
export function getLocale(): string {
return document.documentElement.dataset.locale || 'en'
// Web-browser runtime
if (typeof document !== 'undefined' && document.documentElement.dataset.locale) {
return document.documentElement.dataset.locale
}

// Node.js runtime
if ('_nc_l10n_locale' in globalThis && globalThis._nc_l10n_locale) {
return globalThis._nc_l10n_locale
}

// Fallback to English
return 'en'
Comment on lines +23 to +29
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

globalThis always works in all contexts.

Suggested change
// Node.js runtime
if ('_nc_l10n_locale' in globalThis && globalThis._nc_l10n_locale) {
return globalThis._nc_l10n_locale
}
// Fallback to English
return 'en'
return globalThis._nc_l10n_locale ?? 'en'

}

/**
* Set the user's locale
* @param locale - The locale to set
*/
export function setLocale(locale: string): void {
if (typeof document !== 'undefined') {
document.documentElement.lang = locale
}
globalThis._nc_l10n_locale = locale
}

/**
Expand All @@ -20,9 +50,32 @@ export function getCanonicalLocale(): string {

/**
* Returns the user's language
* @example 'de-DE'
*/
export function getLanguage(): string {
return document.documentElement.lang || 'en'
// Web-browser runtime
if (typeof document !== 'undefined' && document.documentElement.lang) {
return document.documentElement.lang
}

// Node.js runtime
if ('_nc_l10n_language' in globalThis && globalThis._nc_l10n_language) {
return globalThis._nc_l10n_language
}

// Fallback to English
return 'en'
Comment on lines +61 to +67
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here

Suggested change
// Node.js runtime
if ('_nc_l10n_language' in globalThis && globalThis._nc_l10n_language) {
return globalThis._nc_l10n_language
}
// Fallback to English
return 'en'
return globalThis._nc_l10n_language ?? 'en'

}

/**
* Set the user's language
* @param language - The language to set
*/
export function setLanguage(language: string): void {
if (typeof document !== 'undefined') {
document.documentElement.lang = language
}
globalThis._nc_l10n_language = language
}

/**
Expand Down
24 changes: 12 additions & 12 deletions lib/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export interface NextcloudWindowWithRegistry extends Nextcloud.v27.WindowWithGlo
_oc_l10n_registry_plural_functions?: Record<string, PluralFunction>
}

declare const window: NextcloudWindowWithRegistry
declare const globalThis: NextcloudWindowWithRegistry

interface AppTranslations {
translations: Translations
Expand All @@ -59,8 +59,8 @@ interface AppTranslations {
*/
export function hasAppTranslations(appId: string) {
return (
window._oc_l10n_registry_translations?.[appId] !== undefined
&& window._oc_l10n_registry_plural_functions?.[appId] !== undefined
globalThis._oc_l10n_registry_translations?.[appId] !== undefined
&& globalThis._oc_l10n_registry_plural_functions?.[appId] !== undefined
)
}

Expand All @@ -76,15 +76,15 @@ export function registerAppTranslations(
translations: Translations,
pluralFunction: PluralFunction,
) {
window._oc_l10n_registry_translations = Object.assign(
window._oc_l10n_registry_translations || {},
globalThis._oc_l10n_registry_translations = Object.assign(
globalThis._oc_l10n_registry_translations || {},
{
[appId]: Object.assign(window._oc_l10n_registry_translations?.[appId] || {}, translations),
[appId]: Object.assign(globalThis._oc_l10n_registry_translations?.[appId] || {}, translations),
},
)

window._oc_l10n_registry_plural_functions = Object.assign(
window._oc_l10n_registry_plural_functions || {},
globalThis._oc_l10n_registry_plural_functions = Object.assign(
globalThis._oc_l10n_registry_plural_functions || {},
{
[appId]: pluralFunction,
},
Expand All @@ -97,8 +97,8 @@ export function registerAppTranslations(
* @param {string} appId the app id
*/
export function unregisterAppTranslations(appId: string) {
delete window._oc_l10n_registry_translations?.[appId]
delete window._oc_l10n_registry_plural_functions?.[appId]
delete globalThis._oc_l10n_registry_translations?.[appId]
delete globalThis._oc_l10n_registry_plural_functions?.[appId]
}

/**
Expand All @@ -109,7 +109,7 @@ export function unregisterAppTranslations(appId: string) {
*/
export function getAppTranslations(appId: string): AppTranslations {
return {
translations: window._oc_l10n_registry_translations?.[appId] ?? {},
pluralFunction: window._oc_l10n_registry_plural_functions?.[appId] ?? ((number: number) => number),
translations: globalThis._oc_l10n_registry_translations?.[appId] ?? {},
pluralFunction: globalThis._oc_l10n_registry_plural_functions?.[appId] ?? ((number: number) => number),
}
}
57 changes: 19 additions & 38 deletions lib/translation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,13 @@
* SPDX-License-Identifier: GPL-3.0-or-later
*/
import type { Translations } from './registry'
import { getLanguage, getLocale } from './locale'
import { getLanguage } from './locale'
import {
getAppTranslations,
hasAppTranslations,
registerAppTranslations,
unregisterAppTranslations,
} from './registry'
import { generateFilePath } from '@nextcloud/router'

import DOMPurify from 'dompurify'
import escapeHTML from 'escape-html'
Expand Down Expand Up @@ -154,47 +153,29 @@ export function translatePlural(
* the translations are loaded
* @return {Promise} promise
*/
export function loadTranslations(appName: string, callback: (...args: []) => unknown) {
interface TranslationBundle {
translations: Translations
pluralForm: string
}

if (hasAppTranslations(appName) || getLocale() === 'en') {
export async function loadTranslations(appName: string, callback: (...args: []) => unknown) {
if (hasAppTranslations(appName) || getLanguage() === 'en') {
return Promise.resolve().then(callback)
}

const url = generateFilePath(appName, 'l10n', getLocale() + '.json')
const { generateFilePath } = await import('@nextcloud/router')
const url = generateFilePath(appName, 'l10n', getLanguage() + '.json')

const promise = new Promise<TranslationBundle>((resolve, reject) => {
const request = new XMLHttpRequest()
request.open('GET', url, true)
request.onerror = () => {
reject(new Error(request.statusText || 'Network error'))
}
request.onload = () => {
if (request.status >= 200 && request.status < 300) {
try {
const bundle = JSON.parse(request.responseText)
if (typeof bundle.translations === 'object') resolve(bundle)
} catch (error) {
// error is probably a SyntaxError due to invalid response text, this is handled by next line
}
reject(new Error('Invalid content of translation bundle'))
} else {
reject(new Error(request.statusText))
}
const response = await fetch(url)
if (!response.ok) {
throw new Error(response.statusText || 'Network error')
}
try {
const bundle = await response.json()
if (typeof bundle.translations === 'object') {
register(appName, bundle.translations)
return Promise.resolve(bundle).then(callback)
}
request.send()
})

// load JSON translation bundle per AJAX
return promise
.then((result) => {
register(appName, result.translations)
return result
})
.then(callback)
throw new Error('Invalid content of translation bundle')
Comment on lines +170 to +174
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I personally prefer error handling instead of success handling

		if (typeof bundle.translations !== 'object') {
			throw new Error('Invalid content of translation bundle')
		}

		register(appName, bundle.translations)
		return callback(bundle)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I only wanted to change XHR with fetch here, without changing anything else

} catch {
// Error is probably a SyntaxError due to invalid response, this is handled by the next line
Comment on lines +175 to +176
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will remove useful information for debugging, instead "duplicate here"

Suggested change
} catch {
// Error is probably a SyntaxError due to invalid response, this is handled by the next line
} catch (error) {
throw new Error('Invalid content of translation bundle', { cause: error })

}
throw new Error('Invalid content of translation bundle')
}

/**
Expand Down
Loading
Loading