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 16 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 .eslintrc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ rules:
semi:
- error
- always
"@typescript-eslint/no-explicit-any": off
ins0 marked this conversation as resolved.
Show resolved Hide resolved
"@typescript-eslint/no-unused-vars":
- error
- varsIgnorePattern: "[iI]gnored"
Expand Down
3,999 changes: 2,115 additions & 1,884 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" }
89 changes: 89 additions & 0 deletions packages/components/dev/viteI18nPlugin.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
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",
{} as any,
])) 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",
"",
{} as any,
])) 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" },
});
}
});
});
119 changes: 119 additions & 0 deletions packages/components/dev/viteI18nPlugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
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(".", ".")})$`,
ins0 marked this conversation as resolved.
Show resolved Hide resolved
);

const getImportPathInfos = (
id: string,
stripModuleId: boolean = false,
):
| {
directory: string;
filePath: string;
fileName: string;
languageKey: string;
matches: true;
}
| {
directory: string;
filePath: string;
fileName: string;
languageKey: string;
matches: false;
} => {
ins0 marked this conversation as resolved.
Show resolved Hide resolved
let idToMatch = id;
if (stripModuleId) {
idToMatch = idToMatch.replace(moduleId, "");
}
ins0 marked this conversation as resolved.
Show resolved Hide resolved
const matches = idToMatch.match(importPathInfosRegEx);
if (matches) {
return {
directory: matches[1],
filePath: idToMatch,
languageKey: matches[3],
fileName: matches[2],
matches: true,
};
}

return {
directory: "",
filePath: "",
languageKey: "",
fileName: "",
matches: false,
};
ins0 marked this conversation as resolved.
Show resolved Hide resolved
};

const generateComponentIntlContent = (importPath: string): string => {
const langObject: string[] = [];
const { languageKey, filePath, directory } = getImportPathInfos(importPath);
ins0 marked this conversation as resolved.
Show resolved Hide resolved

if (languageKey !== "*") {
ins0 marked this conversation as resolved.
Show resolved Hide resolved
const fileContent = fs.readFileSync(filePath, "utf8");
langObject.push(`"${languageKey}":${fileContent}`);
} else {
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}`);
});
}

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

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

if (matches) {
return {
code: generateComponentIntlContent(filePath),
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)}`,
ins0 marked this conversation as resolved.
Show resolved Hide resolved
};
}
},
} as Plugin;
17 changes: 10 additions & 7 deletions packages/components/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,31 +24,34 @@
"dependencies": {
"@mittwald/flow-design-tokens": "workspace:*",
"clsx": "^2.0.0",
"react-aria": "^3.30.0",
"react-aria-components": "^1.0.0-rc.0"
},
"devDependencies": {
"@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",
"postcss-nesting": "^12.0.1",
"prop-types": "^15.8.1",
"react": "^18.2.0",
"react-dom": "^18.2.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
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"example": "Beispiasasddel"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"example": "Example"
}
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