mirror of
https://github.com/gristlabs/grist-core.git
synced 2026-03-02 04:09:24 +00:00
(core) updates from grist-core
This commit is contained in:
@@ -1,5 +1,7 @@
|
||||
import {getGristConfig} from 'app/common/urlUtils';
|
||||
import {DomContents} from 'grainjs';
|
||||
import i18next from 'i18next';
|
||||
import {G} from 'grainjs/dist/cjs/lib/browserGlobals';
|
||||
|
||||
export async function setupLocale() {
|
||||
const now = Date.now();
|
||||
@@ -15,7 +17,7 @@ export async function setupLocale() {
|
||||
}
|
||||
}
|
||||
|
||||
const ns = getGristConfig().namespaces ?? ['core'];
|
||||
const ns = getGristConfig().namespaces ?? ['client'];
|
||||
// Initialize localization plugin
|
||||
try {
|
||||
// We don't await this promise, as it is resolved synchronously due to initImmediate: false.
|
||||
@@ -28,13 +30,13 @@ export async function setupLocale() {
|
||||
initImmediate: false,
|
||||
// Read language from navigator object.
|
||||
lng,
|
||||
// By default we use core namespace.
|
||||
defaultNS: 'core',
|
||||
// By default we use client namespace.
|
||||
defaultNS: 'client',
|
||||
// Read namespaces that are supported by the server.
|
||||
// TODO: this can be converted to a dynamic list of namespaces, for async components.
|
||||
// for now just import all what server offers.
|
||||
// We can fallback to core namespace for any addons.
|
||||
fallbackNS: 'core',
|
||||
// We can fallback to client namespace for any addons.
|
||||
fallbackNS: 'client',
|
||||
ns,
|
||||
supportedLngs
|
||||
}).catch((err: any) => {
|
||||
@@ -68,14 +70,52 @@ export async function setupLocale() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the translation of the given key, using the given options.
|
||||
* Resolves the translation of the given key using the given options.
|
||||
*/
|
||||
export function t(key: string, args?: any): string {
|
||||
if (!i18next.exists(key)) {
|
||||
export function tString(key: string, args?: any, instance = i18next): string {
|
||||
if (!instance.exists(key, args || undefined)) {
|
||||
const error = new Error(`Missing translation for key: ${key} and language: ${i18next.language}`);
|
||||
reportError(error);
|
||||
}
|
||||
return i18next.t(key, args);
|
||||
return instance.t(key, args);
|
||||
}
|
||||
|
||||
// We will try to infer result from the arguments passed to `t` function.
|
||||
// For plain objects we expect string as a result. If any property doesn't look as a plain value
|
||||
// we assume that it might be a dom node and the result is DomContents.
|
||||
type InferResult<T> = T extends Record<string, string | number | boolean>|undefined|null ? string : DomContents;
|
||||
|
||||
/**
|
||||
* Resolves the translation of the given key and substitutes. Supports dom elements interpolation.
|
||||
*/
|
||||
export function t<T extends Record<string, any>>(key: string, args?: T|null, instance = i18next): InferResult<T> {
|
||||
if (!instance.exists(key, args || undefined)) {
|
||||
const error = new Error(`Missing translation for key: ${key} and language: ${i18next.language}`);
|
||||
reportError(error);
|
||||
}
|
||||
// If there are any DomElements in args, handle it with missingInterpolationHandler.
|
||||
const domElements = !args ? [] : Object.entries(args).filter(([_, value]) => isLikeDomContents(value));
|
||||
if (!args || !domElements.length) {
|
||||
return instance.t(key, args || undefined) as any;
|
||||
} else {
|
||||
// Make a copy of the arguments, and remove any dom elements from it. It will instruct
|
||||
// i18next library to use `missingInterpolationHandler` handler.
|
||||
const copy = {...args};
|
||||
domElements.forEach(([prop]) => delete copy[prop]);
|
||||
|
||||
// Passing `missingInterpolationHandler` will allow as to resolve all missing keys
|
||||
// and replace them with a marker.
|
||||
const result: string = instance.t(key, {...copy, missingInterpolationHandler});
|
||||
|
||||
// Now replace all markers with dom elements passed as arguments.
|
||||
const parts = result.split(/(\[\[\[[^\]]+?\]\]\])/);
|
||||
for (let i = 1; i < parts.length; i += 2) { // Every second element is our dom element.
|
||||
const propName = parts[i].substring(3, parts[i].length - 3);
|
||||
const domElement = args[propName] ?? `{{${propName}}}`; // If the prop is not there, simulate default behavior.
|
||||
parts[i] = domElement;
|
||||
}
|
||||
return parts.filter(p => p !== '') as any; // Remove empty parts.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -84,3 +124,27 @@ export function t(key: string, args?: any): string {
|
||||
export function hasTranslation(key: string) {
|
||||
return i18next.exists(key);
|
||||
}
|
||||
|
||||
function missingInterpolationHandler(key: string, value: any) {
|
||||
return `[[[${value[1]}]]]`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Very naive detection if an element has DomContents type.
|
||||
*/
|
||||
function isLikeDomContents(value: any): boolean {
|
||||
// As null and undefined are valid DomContents values, we don't treat them as such.
|
||||
if (value === null || value === undefined) { return false; }
|
||||
return value instanceof G.Node || // Node
|
||||
(Array.isArray(value) && isLikeDomContents(value[0])) || // DomComputed
|
||||
typeof value === 'function'; // DomMethod
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to create scoped t function.
|
||||
*/
|
||||
export function makeT(scope: string) {
|
||||
return function<T extends Record<string, any>>(key: string, args?: T|null, instance = i18next) {
|
||||
return t(`${scope}.${key}`, args, instance);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
import {theme, vars} from 'app/client/ui2018/cssVars';
|
||||
import {makeT} from 'app/client/lib/localization';
|
||||
import {icon} from 'app/client/ui2018/icons';
|
||||
import {dom, DomElementArg, Observable, styled} from "grainjs";
|
||||
import {t} from 'app/client/lib/localization';
|
||||
|
||||
const translate = makeT(`AddNewButton`);
|
||||
|
||||
export function addNewButton(isOpen: Observable<boolean> | boolean = true, ...args: DomElementArg[]) {
|
||||
return cssAddNewButton(
|
||||
cssAddNewButton.cls('-open', isOpen),
|
||||
// Setting spacing as flex items allows them to shrink faster when there isn't enough space.
|
||||
cssLeftMargin(),
|
||||
cssAddText(t('AddNew')),
|
||||
cssAddText(translate('AddNew')),
|
||||
dom('div', {style: 'flex: 1 1 16px'}),
|
||||
cssPlusButton(cssPlusIcon('Plus')),
|
||||
dom('div', {style: 'flex: 0 1 16px'}),
|
||||
|
||||
@@ -29,11 +29,13 @@ import {Document, Workspace} from 'app/common/UserAPI';
|
||||
import {computed, Computed, dom, DomArg, DomContents, IDisposableOwner,
|
||||
makeTestId, observable, Observable} from 'grainjs';
|
||||
import {buildTemplateDocs} from 'app/client/ui/TemplateDocs';
|
||||
import {t} from 'app/client/lib/localization';
|
||||
import {makeT} from 'app/client/lib/localization';
|
||||
import {localStorageBoolObs} from 'app/client/lib/localStorageObs';
|
||||
import {bigBasicButton} from 'app/client/ui2018/buttons';
|
||||
import sortBy = require('lodash/sortBy');
|
||||
|
||||
const translate = makeT(`DocMenu`);
|
||||
|
||||
const testId = makeTestId('test-dm-');
|
||||
|
||||
/**
|
||||
@@ -105,10 +107,10 @@ function createLoadedDocMenu(owner: IDisposableOwner, home: HomeModel) {
|
||||
null :
|
||||
css.docListHeader(
|
||||
(
|
||||
page === 'all' ? t('AllDocuments') :
|
||||
page === 'all' ? translate('AllDocuments') :
|
||||
page === 'templates' ?
|
||||
dom.domComputed(use => use(home.featuredTemplates).length > 0, (hasFeaturedTemplates) =>
|
||||
hasFeaturedTemplates ? t('MoreExamplesAndTemplates') : t('ExamplesAndTemplates')
|
||||
hasFeaturedTemplates ? translate('MoreExamplesAndTemplates') : translate('ExamplesAndTemplates')
|
||||
) :
|
||||
page === 'trash' ? 'Trash' :
|
||||
workspace && [css.docHeaderIcon('Folder'), workspaceName(home.app, workspace)]
|
||||
@@ -268,7 +270,7 @@ function buildOtherSites(home: HomeModel) {
|
||||
return css.otherSitesBlock(
|
||||
dom.autoDispose(hideOtherSitesObs),
|
||||
css.otherSitesHeader(
|
||||
t('OtherSites'),
|
||||
translate('OtherSites'),
|
||||
dom.domComputed(hideOtherSitesObs, (collapsed) =>
|
||||
collapsed ? css.otherSitesHeaderIcon('Expand') : css.otherSitesHeaderIcon('Collapse')
|
||||
),
|
||||
@@ -280,7 +282,7 @@ function buildOtherSites(home: HomeModel) {
|
||||
const siteName = home.app.currentOrgName;
|
||||
return [
|
||||
dom('div',
|
||||
t('OtherSitesWelcome', { siteName, context: personal ? 'personal' : '' }),
|
||||
translate('OtherSitesWelcome', { siteName, context: personal ? 'personal' : '' }),
|
||||
testId('other-sites-message')
|
||||
),
|
||||
css.otherSitesButtons(
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {t} from 'app/client/lib/localization';
|
||||
import {makeT} from 'app/client/lib/localization';
|
||||
import {getLoginOrSignupUrl, urlState} from 'app/client/models/gristUrlState';
|
||||
import {HomeModel} from 'app/client/models/HomeModel';
|
||||
import {productPill} from 'app/client/ui/AppHeader';
|
||||
@@ -14,6 +14,7 @@ import {FullUser} from 'app/common/LoginSessionAPI';
|
||||
import * as roles from 'app/common/roles';
|
||||
import {Computed, dom, DomContents, styled} from 'grainjs';
|
||||
|
||||
const translate = makeT('HomeIntro');
|
||||
|
||||
export function buildHomeIntro(homeModel: HomeModel): DomContents {
|
||||
const isViewer = homeModel.app.currentOrg?.access === roles.VIEWER;
|
||||
@@ -102,7 +103,7 @@ function makePersonalIntro(homeModel: HomeModel, user: FullUser) {
|
||||
css.docListHeader(`Welcome to Grist, ${user.name}!`, testId('welcome-title')),
|
||||
cssIntroLine('Get started by creating your first Grist document.'),
|
||||
(shouldHideUiElement('helpCenter') ? null :
|
||||
cssIntroLine('Visit our ', helpCenterLink(), ' to learn more.',
|
||||
cssIntroLine(translate('VisitHelpCenter', { link: helpCenterLink() }),
|
||||
testId('welcome-text'))
|
||||
),
|
||||
makeCreateButtons(homeModel),
|
||||
@@ -110,12 +111,12 @@ function makePersonalIntro(homeModel: HomeModel, user: FullUser) {
|
||||
}
|
||||
|
||||
function makeAnonIntro(homeModel: HomeModel) {
|
||||
const signUp = cssLink({href: getLoginOrSignupUrl()}, t('SignUp'));
|
||||
const signUp = cssLink({href: getLoginOrSignupUrl()}, translate('SignUp'));
|
||||
return [
|
||||
css.docListHeader(t('Welcome'), testId('welcome-title')),
|
||||
css.docListHeader(translate('Welcome'), testId('welcome-title')),
|
||||
cssIntroLine('Get started by exploring templates, or creating your first Grist document.'),
|
||||
cssIntroLine(signUp, ' to save your work.',
|
||||
(shouldHideUiElement('helpCenter') ? null : [' Visit our ', helpCenterLink(), ' to learn more.']),
|
||||
cssIntroLine(signUp, ' to save your work. ',
|
||||
(shouldHideUiElement('helpCenter') ? null : translate('VisitHelpCenter', { link: helpCenterLink() })),
|
||||
testId('welcome-text')),
|
||||
makeCreateButtons(homeModel),
|
||||
];
|
||||
|
||||
@@ -12,6 +12,8 @@ import jsesc from 'jsesc';
|
||||
import * as handlebars from 'handlebars';
|
||||
import * as path from 'path';
|
||||
|
||||
const translate = (req: express.Request, key: string, args?: any) => req.t(`sendAppPage.${key}`, args);
|
||||
|
||||
export interface ISendAppPageOptions {
|
||||
path: string; // Ignored if .content is present (set to "" for clarity).
|
||||
content?: string;
|
||||
@@ -155,7 +157,7 @@ function configuredPageTitleSuffix() {
|
||||
*/
|
||||
function getPageTitle(req: express.Request, config: GristLoadConfig): string {
|
||||
const maybeDoc = getDocFromConfig(config);
|
||||
if (!maybeDoc) { return req.t('Loading') + "..."; }
|
||||
if (!maybeDoc) { return translate(req, 'sendAppPage.Loading') + "..."; }
|
||||
|
||||
return handlebars.Utils.escapeExpression(maybeDoc.name);
|
||||
}
|
||||
|
||||
@@ -26,8 +26,8 @@ export function setupLocale(appRoot: string): i18n {
|
||||
supportedNamespaces.add(namespace);
|
||||
return lang;
|
||||
}).filter((lang) => lang));
|
||||
if (!supportedLngs.has('en') || !supportedNamespaces.has('core')) {
|
||||
throw new Error("Missing core English language file");
|
||||
if (!supportedLngs.has('en') || !supportedNamespaces.has('server')) {
|
||||
throw new Error("Missing server English language file");
|
||||
}
|
||||
// Initialize localization filesystem plugin that will read the locale files from the localeDir.
|
||||
instance.use(i18fsBackend);
|
||||
@@ -40,7 +40,7 @@ export function setupLocale(appRoot: string): i18n {
|
||||
initImmediate: false,
|
||||
preload: [...supportedLngs],
|
||||
supportedLngs: [...supportedLngs],
|
||||
defaultNS: 'core',
|
||||
defaultNS: 'server',
|
||||
ns: [...supportedNamespaces],
|
||||
fallbackLng: 'en',
|
||||
backend: {
|
||||
@@ -71,5 +71,5 @@ export function readLoadedNamespaces(instance?: i18n): readonly string[] {
|
||||
if (Array.isArray(instance?.options.ns)) {
|
||||
return instance.options.ns;
|
||||
}
|
||||
return instance?.options.ns ? [instance.options.ns as string] : ['core'];
|
||||
return instance?.options.ns ? [instance.options.ns as string] : ['server'];
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user