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

[WIP] Attempted conversion of i18n package #12201

Closed
wants to merge 1 commit into from
Closed
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
1 change: 1 addition & 0 deletions packages/i18n/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
},
"main": "dist/index.js",
"module": "dist-module/index.js",
"types": "dist-types/index.d.ts",
"source": "src/index.js",
"publishConfig": {
"access": "public"
Expand Down
30 changes: 23 additions & 7 deletions packages/i18n/src/i18n.js → packages/i18n/src/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,17 @@
*/
import Tannin from 'tannin';

/**
* Internal dependencies
*/
import type { LocaleDataWrapper } from './types';

const TEXT_DOMAIN = 'web-stories';

const tannin = new Tannin({
[TEXT_DOMAIN]: {
'': {
plural_forms(n) {
plural_forms(n: number) {
return n === 1 ? 0 : 1;
},
},
Expand All @@ -34,9 +39,9 @@ const tannin = new Tannin({
/**
* Merge locale data into the Tannin instance.
*
* @param {Object} data Locale data.
* @param {LocaleDataWrapper} data Locale data.
*/
export function setLocaleData(data) {
export function setLocaleData(data: LocaleDataWrapper) {
const translations =
data.locale_data['web-stories'] || data.locale_data.messages;
tannin.data[TEXT_DOMAIN] = {
Expand All @@ -56,7 +61,7 @@ export function setLocaleData(data) {
* @param {string} [domain] Text domain. Unique identifier for retrieving translated strings.
* @return {string} Translated text.
*/
export function __(text, domain = TEXT_DOMAIN) {
export function __(text: string, domain = TEXT_DOMAIN) {
return tannin.dcnpgettext(domain, undefined, text);
}

Expand All @@ -68,7 +73,7 @@ export function __(text, domain = TEXT_DOMAIN) {
* @param {string} [domain] Text domain. Unique identifier for retrieving translated strings.
* @return {string} Translated text.
*/
export function _x(text, context, domain = TEXT_DOMAIN) {
export function _x(text: string, context: string, domain = TEXT_DOMAIN) {
return tannin.dcnpgettext(domain, context, text);
}

Expand All @@ -81,7 +86,12 @@ export function _x(text, context, domain = TEXT_DOMAIN) {
* @param {string} [domain] Text domain. Unique identifier for retrieving translated strings.
* @return {string} Translated text.
*/
export function _n(singular, plural, number, domain = TEXT_DOMAIN) {
export function _n(
singular: string,
plural: string,
number: number,
domain = TEXT_DOMAIN
) {
return tannin.dcnpgettext(domain, undefined, singular, plural, number);
}

Expand All @@ -95,6 +105,12 @@ export function _n(singular, plural, number, domain = TEXT_DOMAIN) {
* @param {string} [domain] Text domain. Unique identifier for retrieving translated strings.
* @return {string} Translated text.
*/
export function _nx(singular, plural, number, context, domain = TEXT_DOMAIN) {
export function _nx(
singular: string,
plural: string,
number: number,
context: string,
domain = TEXT_DOMAIN
) {
return tannin.dcnpgettext(domain, context, singular, plural, number);
}
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import { __ } from './i18n';
* @param {Array.<string>} options The options that will be joined with the `or` conjunction.
* @return {string} Localized list items.
*/
function translateToExclusiveList(options) {
function translateToExclusiveList(options: Array<string>) {
switch (options.length) {
case 0:
return '';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import { __ } from './i18n';
* @param {Array.<string>} options The options that will be joined with the `and` conjunction.
* @return {string} Localized list items.
*/
function translateToInclusiveList(options) {
function translateToInclusiveList(options: Array<string>) {
switch (options.length) {
case 0:
return '';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ import {
Fragment,
} from '@googleforcreators/react';
import PropTypes from 'prop-types';
import type React from 'react';

/**
* Internal dependencies
*/
import type { Mapping } from './types';

/** @typedef {import('react').ReactNode} ReactNode */
/** @typedef {import('react').ReactElement} ReactElement */
Expand Down Expand Up @@ -52,18 +58,22 @@ const VOID_ELEMENTS = [
* @param {?Object.<string, ReactElement>} mapping Map of tag names to React components.
* @return {ReactNode} Transformed node.
*/
export function transformNode(node, mapping = {}) {
const { childNodes, localName, nodeType, textContent } = node;
export function transformNode(
node: ChildNode,
mapping: Mapping = {}
): React.ReactNode {
const { firstChild, nodeType, textContent } = node;
if (Node.TEXT_NODE === nodeType) {
return textContent;
}

const children = node.hasChildNodes()
? [...childNodes].map((child) => transform(child, mapping))
: null;
Comment on lines -61 to -63
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 am pretty sure this old code is wrong, no? It loops over all the child nodes and transforms each, but transformNode transform both the given node and all its following siblings, so this old code duplicates a lot of nodes, no?

Well, at least the type system told me that the children variable had type ReactNode[][], which definitely seemed wrong.

const children = node.hasChildNodes() ? transform(firstChild, mapping) : null;

if (localName in mapping) {
return cloneElement(mapping[localName], null, children);
if ('localName' in node) {
const { localName } = node as Element;
if (localName in mapping) {
return cloneElement(mapping[localName], undefined, children);
Copy link
Contributor Author

Choose a reason for hiding this comment

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

For the life of me, I can't figure out how to get TS to accept the type of this one? I tried everything, but I can't match the types to any of the overloads available. And similarly for createElement and its overloads a few lines below.

}
}

return createElement(localName, null, children);
Expand All @@ -77,17 +87,21 @@ export function transformNode(node, mapping = {}) {
* @param {?Object.<string, ReactElement>} mapping Map of tag names to React components.
* @return {ReactNode[]} List of transformed nodes.
*/
function transform(node, mapping = {}) {
const result = [];

do {
function transform(node: ChildNode | null, mapping: Mapping = {}) {
const result: Array<React.ReactNode> = [];
while (node) {
result.push(transformNode(node, mapping));
node = node.nextSibling;
} while (node !== null);
}

return result;
}

interface TranslateWithMarkupProps {
mapping: Mapping;
children: string;
}

/**
* Component to facilitate translation of strings containing markup.
*
Expand All @@ -99,10 +113,13 @@ function transform(node, mapping = {}) {
* @see https://github.com/googleforcreators/web-stories-wp/issues/1578
* @param {Object} props Component props.
* @param {?Object.<string, ReactElement>} props.mapping Map of tag names to React components.
* @param {ReactNode[]|string} props.children Children / string to parse.
* @param {string} props.children Children / string to parse.
* @return {ReactNode[]} Transformed children.
*/
function TranslateWithMarkup({ mapping = {}, children }) {
function TranslateWithMarkup({
mapping = {},
children,
}: TranslateWithMarkupProps) {
//Ensure all Object keys are lowercase as the DOMParser converts tag names to lowercase.
mapping = Object.fromEntries(
Object.entries(mapping).map(([k, v]) => [k.toLowerCase(), v])
Expand Down
33 changes: 33 additions & 0 deletions packages/i18n/src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

type DomainMetadata = {
domain: string;
lang: string;
plural_forms: string | (() => string);
};

type Translation = [string, string];

type LocaleDomain = Record<string, DomainMetadata | Translation>;

type LocaleData = Record<string, LocaleDomain>;

export type LocaleDataWrapper = {
locale_data: LocaleData;
};

export type Mapping = Record<string, React.ReactElement>;
9 changes: 9 additions & 0 deletions packages/i18n/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "../../tsconfig.shared.json",
"compilerOptions": {
"rootDir": "src",
"declarationDir": "dist-types"
},
"references": [{ "path": "../react" }],
"include": ["src/**/*"]
}