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 14 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
148 changes: 146 additions & 2 deletions fluent-react/src/localization.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
import { FluentBundle, FluentVariable } from "@fluent/bundle";
import { mapBundleSync } from "@fluent/sequence";
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";

// Match the opening angle bracket (<) in HTML tags, and HTML entities like
// &amp;, &#0038;, &#x0026;.
const reMarkup = /<|&#?\w+;/;

/*
* `ReactLocalization` handles translation formatting and fallback.
Expand Down Expand Up @@ -38,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 @@ -73,6 +79,144 @@ export class ReactLocalization {
return fallback || id;
}

getElement(
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>;
},
Copy link
Member

Choose a reason for hiding this comment

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

I'm not really sure about this. In <Localized/> passing each of these in as props makes sense, but here it feels like we're putting different things into the same basket -- esp. as this is so close to the shape of the getString() args argument.

My first instinct would be to separate vars from the other two, but maybe calling this something other than args could also help?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Oh heh, good eye. I'd actually argue that renaming getStrings second argument to vars would be more appropriate, since the Fluent docs also call them variables, but I can understand that changing the name of an existing API might not be desirable.

I could name it something like props? Because they're basically analogous to <Localized>'s props, although it could also be confusing, given that they're not React props. Or how about params?

Copy link
Member

Choose a reason for hiding this comment

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

I'm ok with changing the internal name of the getSrting() argument to vars, because it only impacts the documentation.

props and params aren't really better, and both come with their own sets of baggage.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

eemeli marked this conversation as resolved.
Show resolved Hide resolved
): ReactElement {
const bundle = this.getBundle(id);
if (bundle === null) {
if (!id) {
this.reportError(
new Error("No string id was provided when localizing a component.")
);
} else if (this.areBundlesEmpty()) {
this.reportError(
new Error(
"Attempting to get a localized element when no localization bundles are " +
"present."
)
);
} else {
this.reportError(
new Error(
`The id "${id}" did not match any messages in the localization ` +
"bundles."
)
);
}

return createElement(Fragment, null, componentToRender);
}

// this.getBundle makes the bundle.hasMessage check which ensures that
// bundle.getMessage returns an existing message.
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const msg = bundle.getMessage(id)!;

let errors: Array<Error> = [];

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
// explicitly allowed by the developer.
if (args?.attrs && msg.attributes) {
localizedProps = {};
errors = [];
for (const [name, allowed] of Object.entries(args?.attrs)) {
if (allowed && name in msg.attributes) {
localizedProps[name] = bundle.formatPattern(
msg.attributes[name],
args?.vars,
errors
);
}
}
for (let error of errors) {
this.reportError(error);
}
}

// If the component to render is a known void element, explicitly dismiss the
// message value and do not pass it to cloneElement in order to avoid the
// "void element tags must neither have `children` nor use
// `dangerouslySetInnerHTML`" error.
if (typeof componentToRender.type === "string" && componentToRender.type in voidElementTags) {
return cloneElement(componentToRender, localizedProps);
}

// If the message has a null value, we're only interested in its attributes.
// Do not pass the null value to cloneElement as it would nuke all children
// of the wrapped component.
if (msg.value === null) {
return cloneElement(componentToRender, localizedProps);
}

errors = [];
const messageValue = bundle.formatPattern(msg.value, args?.vars, errors);
for (let error of errors) {
this.reportError(error);
}

// If the message value doesn't contain any markup nor any HTML entities,
// insert it as the only child of the component to render.
if (!reMarkup.test(messageValue) || this.parseMarkup === null) {
return cloneElement(componentToRender, localizedProps, messageValue);
}

let elemsLower: Map<string, ReactElement>;
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);
}
}

// If the message contains markup, parse it and try to match the children
// found in the translation with the args passed to this function.
const translationNodes = this.parseMarkup(messageValue);
const translatedChildren = translationNodes.map(({ nodeName, textContent }) => {
if (nodeName === "#text") {
return textContent;
}

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

// If the child is not expected just take its textContent.
if (!sourceChild) {
return textContent;
}

// If the element passed in the elems prop is a known void element,
// explicitly dismiss any textContent which might have accidentally been
// defined in the translation to prevent the "void element tags must not
// have children" error.
if (
typeof sourceChild.type === "string" &&
sourceChild.type in voidElementTags
) {
return sourceChild;
}

// TODO Protect contents of elements wrapped in <Localized>
// https://github.com/projectfluent/fluent.js/issues/184
// TODO Control localizable attributes on elements passed as props
// https://github.com/projectfluent/fluent.js/issues/185
return cloneElement(sourceChild, undefined, textContent);
});

return cloneElement(componentToRender, localizedProps, ...translatedChildren);
}

// XXX Control this via a prop passed to the LocalizationProvider.
// See https://github.com/projectfluent/fluent.js/issues/411.
reportError(error: Error): void {
Expand Down