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

Add getFragment method to ReactLocalization #595

Merged
merged 19 commits into from
Oct 27, 2022
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
70 changes: 10 additions & 60 deletions fluent-react/src/localization.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { FluentBundle, FluentVariable } from "@fluent/bundle";
import { mapBundleSync } from "@fluent/sequence";
import { Fragment, ReactElement, createElement, isValidElement, ReactFragment, cloneElement, ReactNode } from "react";
import { Fragment, ReactElement, createElement, isValidElement, cloneElement } from "react";
import { CachedSyncIterable } from "cached-iterable";
import { createParseMarkup, MarkupParser } from "./markup.js";
import voidElementTags from "../vendor/voidElementTags.js";
Expand Down Expand Up @@ -44,15 +44,15 @@ export class ReactLocalization {

getString(
id: string,
args?: Record<string, FluentVariable> | null,
vars?: Record<string, FluentVariable> | null,
fallback?: string
): string {
const bundle = this.getBundle(id);
if (bundle) {
const msg = bundle.getMessage(id);
if (msg && msg.value) {
let errors: Array<Error> = [];
let value = bundle.formatPattern(msg.value, args, errors);
let value = bundle.formatPattern(msg.value, vars, errors);
for (let error of errors) {
this.reportError(error);
}
Expand All @@ -79,44 +79,15 @@ export class ReactLocalization {
return fallback || id;
}

getFragment(
id: string,
args?: {
vars?: Record<string, FluentVariable>,
elems?: Record<string, ReactElement>,
},
fallback?: string
): ReactFragment {
return this.getElement(createElement(Fragment, null, fallback || id), id, args);
}

getElement(
component: ReactNode | Array<ReactNode>,
componentToRender: ReactElement,
eemeli marked this conversation as resolved.
Show resolved Hide resolved
id: string,
args?: {
vars?: Record<string, FluentVariable>,
elems?: Record<string, ReactElement>,
attrs?: Record<string, boolean>;
},
): ReactElement {
let componentToRender: ReactNode | null;

// Validate that the child element isn't an array that contains multiple
// elements.
if (Array.isArray(component)) {
if (component.length > 1) {
throw new Error(
"Expected to receive a single React node element to inject a localized string into."
);
}

// If it's an array with zero or one element, we can directly get the first
// one.
componentToRender = component[0];
} else {
componentToRender = component ?? null;
}

const bundle = this.getBundle(id);
if (bundle === null) {
if (!id) {
Expand Down Expand Up @@ -149,22 +120,6 @@ export class ReactLocalization {

let errors: Array<Error> = [];

// Check if the component to render is a valid element -- if not, then
// it's either null or a simple fallback string. No need to localize the
// attributes.
if (!isValidElement(componentToRender)) {
if (msg.value) {
// Replace the fallback string with the message value;
let value = bundle.formatPattern(msg.value, args?.vars, errors);
for (let error of errors) {
this.reportError(error);
}
return createElement(Fragment, null, value);
}

return createElement(Fragment, null, componentToRender);
}

let localizedProps: Record<string, string> | undefined;
// The default is to forbid all message attributes. If the attrs prop exists
// on the Localized instance, only set message attributes which have been
Expand Down Expand Up @@ -217,6 +172,10 @@ export class ReactLocalization {
if (args?.elems) {
elemsLower = new Map();
for (let [name, elem] of Object.entries(args?.elems)) {
// Ignore elems which are not valid React elements.
if (!isValidElement(elem)) {
continue;
}
elemsLower.set(name.toLowerCase(), elem);
}
}
Expand All @@ -230,19 +189,10 @@ export class ReactLocalization {
}

const childName = nodeName.toLowerCase();
const sourceChild = elemsLower?.get(childName);

// If the child is not expected just take its textContent.
if (
!elemsLower ||
!Object.prototype.hasOwnProperty.call(elemsLower, childName)
) {
return textContent;
}

const sourceChild = elemsLower.get(childName);

// Ignore elems which are not valid React elements.
if (!isValidElement(sourceChild)) {
if (!sourceChild) {
return textContent;
}

Expand Down
38 changes: 36 additions & 2 deletions fluent-react/src/localized.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
import React, {
isValidElement,
Vinnl marked this conversation as resolved.
Show resolved Hide resolved
ReactElement,
ReactNode,
useContext,
Expand Down Expand Up @@ -45,7 +46,40 @@ export function Localized(props: LocalizedProps): ReactElement {
);
}

return l10n.getElement(children, id, { attrs, vars, elems });
let componentToRender: ReactNode | null;

// Validate that the child element isn't an array that contains multiple
// elements.
if (Array.isArray(children)) {
if (children.length > 1) {
throw new Error(
"Expected to receive a single React element to localize."
);
}

// If it's an array with zero or one element, we can directly get the first
// one.
componentToRender = children[0];
} else {
componentToRender = children ?? null;
}
eemeli marked this conversation as resolved.
Show resolved Hide resolved

// Check if the component to render is a valid element -- if not, then
// it's either null or a simple fallback string. No need to localize the
// attributes or replace.
if (!isValidElement(componentToRender)) {
return React.createElement(
React.Fragment,
null,
l10n.getString(
id,
vars,
typeof componentToRender === "string" ? componentToRender : undefined,
),
);
}

return l10n.getElement(componentToRender, id, { attrs, vars, elems });
}

export default Localized;
4 changes: 2 additions & 2 deletions fluent-react/test/localized_render.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -557,7 +557,7 @@ foo = Message
expect(renderer.toJSON()).toMatchInlineSnapshot(`"Message"`);
});

test("render without a fallback and no message returns nothing", () => {
test("render without a fallback and no message returns the message ID", () => {
jest.spyOn(console, "warn").mockImplementation(() => {});
const bundle = new FluentBundle();

Expand All @@ -567,7 +567,7 @@ foo = Message
</LocalizationProvider>
);

expect(renderer.toJSON()).toMatchInlineSnapshot(`null`);
expect(renderer.toJSON()).toMatchInlineSnapshot(`"foo"`);
expect(console.warn.mock.calls).toMatchInlineSnapshot(`
Array [
Array [
Expand Down
2 changes: 1 addition & 1 deletion fluent-react/test/use_localization.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ function DummyComponent() {
return (
<div>
<p>{l10n.getString("foo")}</p>
<p>{l10n.getFragment("bar", { elems: { elem: <b/> } })}</p>
<p>{l10n.getElement(<></>, "bar", { elems: { elem: <b/> } })}</p>
{l10n.getElement(<p/>, "bar", { elems: { elem: <i/> }, attrs: { "title": true } })}
</div>
);
Expand Down