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

Use default calculated i18n keys #1848

Merged
merged 2 commits into from
Dec 10, 2021
Merged
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: 43 additions & 14 deletions packages/core/src/i18n/i18nUtil.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,60 @@
import { ErrorObject } from 'ajv';
import { UISchemaElement } from '../models';
import { getControlPath } from '../reducers';
import { formatErrorMessage } from '../util';
import { i18nJsonSchema, ErrorTranslator, Translator } from './i18nTypes';

export const getI18nKeyPrefixBySchema = (
schema: i18nJsonSchema | undefined,
uischema: UISchemaElement | undefined
): string | undefined => {
return uischema?.options?.i18n ?? schema?.i18n ?? undefined;
};

/**
* Transforms a given path to a prefix which can be used for i18n keys.
* Returns 'root' for empty paths and removes array indices
*/
export const transformPathToI18nPrefix = (path: string) => {
return (
path
?.split('.')
.filter(segment => !/^\d+$/.test(segment))
.join('.') || 'root'
);
};

export const getI18nKeyPrefix = (
schema: i18nJsonSchema | undefined,
uischema: UISchemaElement | undefined,
path: string | undefined
): string | undefined => {
return (
getI18nKeyPrefixBySchema(schema, uischema) ??
transformPathToI18nPrefix(path)
);
};

export const getI18nKey = (
schema: i18nJsonSchema | undefined,
uischema: UISchemaElement | undefined,
path: string | undefined,
key: string
): string | undefined => {
if (uischema?.options?.i18n) {
return `${uischema.options.i18n}.${key}`;
}
if (schema?.i18n) {
return `${schema.i18n}.${key}`;
}
return undefined;
return `${getI18nKeyPrefix(schema, uischema, path)}.${key}`;
};

export const defaultTranslator: Translator = (_id: string, defaultMessage: string | undefined) => defaultMessage;

export const defaultErrorTranslator: ErrorTranslator = (error, t, uischema) => {
// check whether there is a special keyword message
const keyInSchemas = getI18nKey(
const i18nKey = getI18nKey(
error.parentSchema,
uischema,
getControlPath(error),
`error.${error.keyword}`
);
const specializedKeywordMessage = keyInSchemas && t(keyInSchemas, undefined);
const specializedKeywordMessage = t(i18nKey, undefined);
if (specializedKeywordMessage !== undefined) {
return specializedKeywordMessage;
}
Expand All @@ -44,7 +72,7 @@ export const defaultErrorTranslator: ErrorTranslator = (error, t, uischema) => {
}

// rewrite required property messages (if they were not customized) as we place them next to the respective input
if (error.keyword === 'required') {
if (error.keyword === 'required' && error.message?.startsWith('must have required property')) {
return t('is a required property', 'is a required property');
}

Expand All @@ -53,19 +81,20 @@ export const defaultErrorTranslator: ErrorTranslator = (error, t, uischema) => {

/**
* Returns the determined error message for the given errors.
* All errors must correspond to the given schema and uischema.
* All errors must correspond to the given schema, uischema or path.
*/
export const getCombinedErrorMessage = (
errors: ErrorObject[],
et: ErrorTranslator,
t: Translator,
schema?: i18nJsonSchema,
uischema?: UISchemaElement
uischema?: UISchemaElement,
path?: string
) => {
if (errors.length > 0 && t) {
// check whether there is a special message which overwrites all others
const keyInSchemas = getI18nKey(schema, uischema, 'error.custom');
const specializedErrorMessage = keyInSchemas && t(keyInSchemas, undefined);
const customErrorKey = getI18nKey(schema, uischema, path, 'error.custom');
const specializedErrorMessage = t(customErrorKey, undefined);
if (specializedErrorMessage !== undefined) {
return specializedErrorMessage;
}
Expand Down
20 changes: 0 additions & 20 deletions packages/core/src/reducers/reducers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,7 @@ import { ControlElement, UISchemaElement } from '../models';
import {
coreReducer,
errorAt,
errorsAt,
getControlPath,
JsonFormsCore,
subErrorsAt,
ValidationMode
} from './core';
import { defaultDataReducer } from './default-data';
import { rendererReducer } from './renderers';
Expand All @@ -40,7 +36,6 @@ import {
findMatchingUISchema,
JsonFormsUISchemaRegistryEntry,
uischemaRegistryReducer,
UISchemaTester
} from './uischemas';
import {
fetchErrorTranslator,
Expand All @@ -57,19 +52,6 @@ import get from 'lodash/get';
import { fetchTranslator } from '.';
import { ErrorTranslator, Translator } from '../i18n';

export {
rendererReducer,
cellReducer,
coreReducer,
i18nReducer,
configReducer,
UISchemaTester,
uischemaRegistryReducer,
findMatchingUISchema,
JsonFormsUISchemaRegistryEntry
};
export { JsonFormsCore, ValidationMode };

export const jsonFormsReducerConfig = {
core: coreReducer,
renderers: rendererReducer,
Expand Down Expand Up @@ -128,8 +110,6 @@ export const getErrorAt = (instancePath: string, schema: JsonSchema) => (
return errorAt(instancePath, schema)(state.jsonforms.core);
};

export { errorsAt, getControlPath };

export const getSubErrorsAt = (instancePath: string, schema: JsonSchema) => (
state: JsonFormsState
) => subErrorsAt(instancePath, schema)(state.jsonforms.core);
Expand Down
8 changes: 4 additions & 4 deletions packages/core/src/util/cell.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ import {
} from './renderer';
import { JsonFormsState } from '../store';
import { JsonSchema } from '../models';
import { i18nJsonSchema } from '..';
import { getI18nKeyPrefix } from '../i18n';

export { JsonFormsCellRendererRegistryEntry };

Expand Down Expand Up @@ -202,14 +202,14 @@ export const defaultMapStateToEnumCellProps = (
enumToEnumOptionMapper(
e,
getTranslator()(state),
props.uischema?.options?.i18n ?? (props.schema as i18nJsonSchema).i18n
getI18nKeyPrefix(props.schema, props.uischema, props.path)
)
) ||
(props.schema.const && [
enumToEnumOptionMapper(
props.schema.const,
getTranslator()(state),
props.uischema?.options?.i18n ?? (props.schema as i18nJsonSchema).i18n
getI18nKeyPrefix(props.schema, props.uischema, props.path)
)
]);
return {
Expand All @@ -235,7 +235,7 @@ export const mapStateToOneOfEnumCellProps = (
oneOfToEnumOptionMapper(
oneOfSubSchema,
getTranslator()(state),
props.uischema?.options?.i18n
getI18nKeyPrefix(props.schema, props.uischema, props.path)
)
);
return {
Expand Down
29 changes: 14 additions & 15 deletions packages/core/src/util/renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,7 @@ import { isVisible } from './runtime';
import { CoreActions, update } from '../actions';
import { ErrorObject } from 'ajv';
import { JsonFormsState } from '../store';
import { getCombinedErrorMessage, getI18nKey, i18nJsonSchema, Translator } from '../i18n';

export { JsonFormsRendererRegistryEntry, JsonFormsCellRendererRegistryEntry };
import { getCombinedErrorMessage, getI18nKey, getI18nKeyPrefix, Translator } from '../i18n';

const isRequired = (
schema: JsonSchema,
Expand Down Expand Up @@ -195,7 +193,7 @@ export const enumToEnumOptionMapper = (
export const oneOfToEnumOptionMapper = (
e: any,
t?: Translator,
uiSchemaI18nKey?: string
fallbackI18nKey?: string
): EnumOption => {
let label =
e.title ??
Expand All @@ -204,8 +202,8 @@ export const oneOfToEnumOptionMapper = (
// prefer schema keys as they can be more specialized
if (e.i18n) {
label = t(e.i18n, label);
} else if (uiSchemaI18nKey) {
label = t(`${uiSchemaI18nKey}.${label}`, label);
} else if (fallbackI18nKey) {
label = t(`${fallbackI18nKey}.${label}`, label);
} else {
label = t(label, label);
}
Expand Down Expand Up @@ -464,9 +462,9 @@ export const mapStateToControlProps = (
const schema = resolvedSchema ?? rootSchema;
const t = getTranslator()(state);
const te = getErrorTranslator()(state);
const i18nLabel = t(getI18nKey(schema, uischema, 'label') ?? label, label);
const i18nDescription = t(getI18nKey(schema, uischema, 'description') ?? description, description);
const i18nErrorMessage = getCombinedErrorMessage(errors, te, t, schema, uischema);
const i18nLabel = t(getI18nKey(schema, uischema, path, 'label'), label);
const i18nDescription = t(getI18nKey(schema, uischema, path, 'description'), description);
const i18nErrorMessage = getCombinedErrorMessage(errors, te, t, schema, uischema, path);

return {
data,
Expand Down Expand Up @@ -518,14 +516,14 @@ export const mapStateToEnumControlProps = (
enumToEnumOptionMapper(
e,
getTranslator()(state),
props.uischema?.options?.i18n ?? (props.schema as i18nJsonSchema).i18n
getI18nKeyPrefix(props.schema, props.uischema, props.path)
)
) ||
(props.schema.const && [
enumToEnumOptionMapper(
props.schema.const,
getTranslator()(state),
props.uischema?.options?.i18n ?? (props.schema as i18nJsonSchema).i18n
getI18nKeyPrefix(props.schema, props.uischema, props.path)
)
]);
return {
Expand All @@ -551,7 +549,7 @@ export const mapStateToOneOfEnumControlProps = (
oneOfToEnumOptionMapper(
oneOfSubSchema,
getTranslator()(state),
props.uischema?.options?.i18n
getI18nKeyPrefix(props.schema, props.uischema, props.path)
)
);
return {
Expand Down Expand Up @@ -579,14 +577,14 @@ export const mapStateToMultiEnumControlProps = (
oneOfToEnumOptionMapper(
oneOfSubSchema,
state.jsonforms.i18n?.translate,
props.uischema?.options?.i18n
getI18nKeyPrefix(props.schema, props.uischema, props.path)
)
)) ||
items?.enum?.map(e =>
enumToEnumOptionMapper(
e,
state.jsonforms.i18n?.translate,
props.uischema?.options?.i18n ?? (props.schema as i18nJsonSchema).i18n
getI18nKeyPrefix(props.schema, props.uischema, props.path)
)
);
return {
Expand Down Expand Up @@ -923,7 +921,7 @@ export interface StatePropsOfCombinator extends OwnPropsOfControl {
data: any;
}

const mapStateToCombinatorRendererProps = (
export const mapStateToCombinatorRendererProps = (
state: JsonFormsState,
ownProps: OwnPropsOfControl,
keyword: CombinatorKeyword
Expand Down Expand Up @@ -1052,6 +1050,7 @@ export const mapStateToArrayLayoutProps = (
getErrorTranslator()(state),
getTranslator()(state),
undefined,
undefined,
undefined
);

Expand Down
48 changes: 48 additions & 0 deletions packages/core/test/i18n/i18nUtil.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
The MIT License

Copyright (c) 2017-2021 EclipseSource Munich
https://github.com/eclipsesource/jsonforms

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import test from 'ava';

import { transformPathToI18nPrefix } from '../../src';

test('transformPathToI18nPrefix returns root when empty', t => {
t.is(transformPathToI18nPrefix(''), 'root');
});

test('transformPathToI18nPrefix does not modify non-array paths', t => {
t.is(transformPathToI18nPrefix('foo'), 'foo');
t.is(transformPathToI18nPrefix('foo.bar'), 'foo.bar');
t.is(transformPathToI18nPrefix('bar3.foo2'), 'bar3.foo2');
});

test('transformPathToI18nPrefix removes array indices', t => {
t.is(transformPathToI18nPrefix('foo.2.bar'), 'foo.bar');
t.is(transformPathToI18nPrefix('foo.234324234.bar'), 'foo.bar');
t.is(transformPathToI18nPrefix('foo.0.bar'), 'foo.bar');
t.is(transformPathToI18nPrefix('foo.0.bar.1.foobar'), 'foo.bar.foobar');
t.is(transformPathToI18nPrefix('3.foobar'), 'foobar');
t.is(transformPathToI18nPrefix('foobar.3'), 'foobar');
t.is(transformPathToI18nPrefix('foo1.23.b2ar3.1.5.foo'), 'foo1.b2ar3.foo');
t.is(transformPathToI18nPrefix('3'), 'root');
});
5 changes: 2 additions & 3 deletions packages/core/test/reducers/core.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
import test from 'ava';
import Ajv from 'ajv';
import { coreReducer } from '../../src/reducers';
import { init, update, updateErrors } from '../../src/actions';
import { init, setSchema, setValidationMode, update, updateCore, updateErrors } from '../../src/actions';
import { JsonSchema } from '../../src/models/jsonSchema';
import {
errorAt,
Expand All @@ -34,9 +34,8 @@ import {
subErrorsAt
} from '../../src/reducers/core';

import { createAjv, updateCore } from '../../src';
import { setSchema, setValidationMode } from '../../lib';
import { cloneDeep } from 'lodash';
import { createAjv } from '../../src/util/validator';

test('core reducer should support v7', t => {
const schema: JsonSchema = {
Expand Down
Loading