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 i18n support #24

Merged
merged 25 commits into from
Dec 8, 2023
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
3,993 changes: 2,112 additions & 1,881 deletions .pnp.cjs

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
"pre-commit": "yarn lint"
},
"devDependencies": {
"@eslint/js": "^8.55.0",
"@types/eslint__js": "^8",
"@typescript-eslint/eslint-plugin": "^6.13.2",
"@typescript-eslint/parser": "^6.13.2",
"concurrently": "^8.2.2",
Expand Down
1 change: 1 addition & 0 deletions packages/components/dev/test/locales/bar.locale.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{ "bar": "baz" }
1 change: 1 addition & 0 deletions packages/components/dev/test/locales/foo.locale.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{ "foo": "bar" }
95 changes: 95 additions & 0 deletions packages/components/dev/viteI18nPlugin.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import plugin from "./viteI18nPlugin";
import { expect } from "@jest/globals";
import path from "path";
import type {
PartialResolvedId,
PluginContext,
TransformPluginContext,
SourceDescription,
} from "rollup";

describe("vite i18n plugin", () => {
mfal marked this conversation as resolved.
Show resolved Hide resolved
it("resolve will return correct id", async () => {
if (plugin.resolveId && typeof plugin.resolveId === "function") {
const resolve = (await plugin.resolveId.apply({} as PluginContext, [
"./locales/*.locale.json",
"./foo/foo.ts",
{
isEntry: false,
attributes: {},
},
])) as PartialResolvedId;

expect(resolve).toBeDefined();
expect(typeof resolve).toBe("object");
expect(resolve.id.startsWith("\x00.locale.json@")).toBeTruthy();
expect(resolve.id.endsWith("/foo/locales/*.locale.json")).toBeTruthy();
}
});

it("resolve will return nothing when importer is not known", async () => {
if (plugin.resolveId && typeof plugin.resolveId === "function") {
const resolve = (await plugin.resolveId.apply({} as PluginContext, [
"./locales/*.locale.json",
"",
{
isEntry: false,
attributes: {},
},
])) as PartialResolvedId;

expect(resolve).toBeUndefined();
}
});

it("test multi intl files will be generated", () => {
if (plugin.load && typeof plugin.load === "function") {
const load = plugin.load.apply({} as PluginContext, [
path.join(__dirname, "test", "locales", "*.locale.json"),
]) as SourceDescription;

expect(JSON.parse(load.code)).toMatchObject({
bar: { bar: "baz" },
foo: { foo: "bar" },
});
}
});

it("test single intl files will be generated", () => {
if (plugin.load && typeof plugin.load === "function") {
const load = plugin.load.apply({} as PluginContext, [
path.join(__dirname, "test", "locales", "bar.locale.json"),
]) as SourceDescription;

expect(JSON.parse(load.code)).toMatchObject({
bar: { bar: "baz" },
});
}
});

it("test multi intl files will be transformed", () => {
if (plugin.transform && typeof plugin.transform === "function") {
const transform = plugin.transform.apply({} as TransformPluginContext, [
"",
path.join(__dirname, "test", "locales", "*.locale.json"),
]) as SourceDescription;

expect(JSON.parse(transform.code)).toMatchObject({
bar: { bar: "baz" },
foo: { foo: "bar" },
});
}
});

it("test single intl files will be transformed", () => {
if (plugin.load && typeof plugin.load === "function") {
const load = plugin.load.apply({} as PluginContext, [
path.join(__dirname, "test", "locales", "bar.locale.json"),
]) as SourceDescription;

expect(JSON.parse(load.code)).toMatchObject({
bar: { bar: "baz" },
});
}
});
});
113 changes: 113 additions & 0 deletions packages/components/dev/viteI18nPlugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import { Plugin } from "vite";
import path from "path";
import * as fs from "fs";
import type { SourceDescription } from "rollup";

const moduleSuffix = ".locale.json";
const moduleId = `\x00${moduleSuffix}@`;
mfal marked this conversation as resolved.
Show resolved Hide resolved
const localeDirectory = "locales";
const importPathInfosRegEx = new RegExp(
`^(.+/${localeDirectory})/((.+)${moduleSuffix.replaceAll(".", "\\.")})$`,
);

interface ImportPathData {
directory: string;
filePath: string;
fileName: string;
languageKey: string;
}

type ImportPathInfos =
| ({ matches: true } & ImportPathData)
| ({ matches: false } & Partial<ImportPathData>);

const getImportPathInfos = (
id: string,
stripModuleId: boolean = false,
): ImportPathInfos => {
const idToMatch = stripModuleId ? id.replace(moduleId, "") : id;
const matches = idToMatch.match(importPathInfosRegEx);
if (matches) {
return {
directory: matches[1],
filePath: idToMatch,
languageKey: matches[3],
fileName: matches[2],
matches: true,
};
}

return {
matches: false,
};
};

const generateComponentIntlContent = (
importPathInfos: ImportPathInfos,
): string => {
const langObject: string[] = [];
const { matches, languageKey, filePath, directory } = importPathInfos;

if (matches) {
if (languageKey === "*") {
fs.readdirSync(directory).forEach((file) => {
const filePath = path.join(directory, file);
const { languageKey } = getImportPathInfos(filePath);

const fileContent = fs.readFileSync(filePath, "utf8");
langObject.push(`"${languageKey}":${fileContent}`);
});
} else {
const fileContent = fs.readFileSync(filePath, "utf8");
langObject.push(`"${languageKey}":${fileContent}`);
}
}

return `{${langObject.join(",")}}`;
};

const generateSourceResponse = (id: string): SourceDescription | undefined => {
const pathInfo = getImportPathInfos(id, true);

if (pathInfo.matches) {
return {
code: generateComponentIntlContent(pathInfo),
map: null,
};
}
};

export default {
name: "handle-i18n-import",
enforce: "pre",
handleHotUpdate: async ({ file, server }) => {
const { matches, filePath, directory } = getImportPathInfos(file);

if (matches) {
[
moduleId + path.join(directory, `*${moduleSuffix}`),
moduleId + filePath,
].forEach((id) => {
const module = server.moduleGraph.getModuleById(id);
if (module) {
server.moduleGraph.invalidateModule(module);
}
});

server.ws.send({
type: "full-reload",
});
}
},
transform: (_, id) => generateSourceResponse(id),
load: (id) => generateSourceResponse(id),
resolveId: (id, source) => {
const { matches, filePath } = getImportPathInfos(id);

if (matches && source) {
return {
id: moduleId + path.resolve(path.dirname(source), filePath),
};
}
},
} as Plugin;
17 changes: 10 additions & 7 deletions packages/components/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,24 +28,26 @@
"@mittwald/flow-design-tokens": "workspace:*",
"clsx": "^2.0.0",
"html-react-parser": "^5.0.7",
"react-aria": "^3.30.0",
"react-aria-components": "^1.0.0-rc.0"
},
"devDependencies": {
"@fortawesome/free-regular-svg-icons": "^6.5.1",
"@jest/globals": "^29.7.0",
"@nx/storybook": "^17.1.3",
"@storybook/addon-essentials": "^7.6.3",
"@storybook/addon-interactions": "^7.6.3",
"@storybook/addon-links": "^7.6.3",
"@storybook/addon-essentials": "^7.6.4",
"@storybook/addon-interactions": "^7.6.4",
"@storybook/addon-links": "^7.6.4",
"@storybook/addon-onboarding": "^1.0.9",
"@storybook/blocks": "^7.6.3",
"@storybook/react": "^7.6.3",
"@storybook/react-vite": "^7.6.3",
"@storybook/blocks": "^7.6.4",
"@storybook/react": "^7.6.4",
"@storybook/react-vite": "^7.6.4",
"@storybook/testing-library": "^0.2.2",
"@types/jest": "^29.5.11",
"@types/prop-types": "^15.7.11",
"@types/react": "^18.2.42",
"@types/react-dom": "^18.2.17",
"@types/rollup": "^0.54.0",
"jest": "^29.7.0",
"postcss": "^8.4.32",
"postcss-nested-import": "^1.3.0",
Expand All @@ -54,7 +56,8 @@
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-element-to-jsx-string": "^15.0.0",
"storybook": "^7.6.3",
"rollup": "^4.6.1",
"storybook": "^7.6.4",
"ts-jest": "^29.1.1",
"typescript": "^5.3.2",
"typescript-plugin-css-modules": "^5.0.2",
Expand Down
2 changes: 1 addition & 1 deletion packages/components/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"paths": {
"@/*": ["packages/components/src/*"]
},
"plugins": [{ "name": "typescript-plugin-css-modules" }]
"plugins": [{ "name": "typescript-plugin-css-modules" }],
},
"extends": "../../tsconfig.json",
"include": ["types.d.ts", "**/*.ts", "**/*.tsx"]
Expand Down
8 changes: 8 additions & 0 deletions packages/components/types.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
/// <reference types="vite/client" />

declare module "*.module.css" {
const classes: { [key: string]: string };
export default classes;
}

declare module "*.locale.json" {
import { LocalizedStrings } from "react-aria";
const langFile: LocalizedStrings;
export default langFile;
}
5 changes: 4 additions & 1 deletion packages/components/vite.config.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import { defineConfig } from "vite";
import postcssNesting from "postcss-nesting";
import { cssModuleClassNameGenerator } from "./dev/cssModuleClassNameGenerator";
import path from "path";
import viteI18nPlugin from "./dev/viteI18nPlugin";

export default defineConfig({
plugins: [viteI18nPlugin],
resolve: {
alias: {
"@/": "/src/",
"@": path.resolve(__dirname, "/src"),
},
},
css: {
Expand Down
Loading