@next-box/i18n 0.0.2-alpha-3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +126 -0
  3. package/dist/cjs/index.cjs +2 -0
  4. package/dist/cjs/index.cjs.map +1 -0
  5. package/dist/cjs/macros.cjs +2 -0
  6. package/dist/cjs/macros.cjs.map +1 -0
  7. package/dist/esm/index.mjs +2 -0
  8. package/dist/esm/index.mjs.map +1 -0
  9. package/dist/production.analysis.txt +16 -0
  10. package/dist/types/cjs/components/I18nProvider.d.cts +28 -0
  11. package/dist/types/cjs/components/I18nProvider.d.cts.map +1 -0
  12. package/dist/types/cjs/components/Md.d.cts +10 -0
  13. package/dist/types/cjs/components/Md.d.cts.map +1 -0
  14. package/dist/types/cjs/helpers/injectVariables.d.cts +2 -0
  15. package/dist/types/cjs/helpers/injectVariables.d.cts.map +1 -0
  16. package/dist/types/cjs/index.d.cts +5 -0
  17. package/dist/types/cjs/index.d.cts.map +1 -0
  18. package/dist/types/cjs/macros.d.cts +2 -0
  19. package/dist/types/cjs/macros.d.cts.map +1 -0
  20. package/dist/types/cjs/main.d.cts +3 -0
  21. package/dist/types/cjs/main.d.cts.map +1 -0
  22. package/dist/types/cjs/types.d.cts +8 -0
  23. package/dist/types/cjs/types.d.cts.map +1 -0
  24. package/dist/types/esm/components/I18nProvider.d.ts +28 -0
  25. package/dist/types/esm/components/I18nProvider.d.ts.map +1 -0
  26. package/dist/types/esm/components/Md.d.ts +10 -0
  27. package/dist/types/esm/components/Md.d.ts.map +1 -0
  28. package/dist/types/esm/helpers/injectVariables.d.ts +2 -0
  29. package/dist/types/esm/helpers/injectVariables.d.ts.map +1 -0
  30. package/dist/types/esm/index.d.ts +5 -0
  31. package/dist/types/esm/index.d.ts.map +1 -0
  32. package/dist/types/esm/macros.d.ts +2 -0
  33. package/dist/types/esm/macros.d.ts.map +1 -0
  34. package/dist/types/esm/main.d.ts +3 -0
  35. package/dist/types/esm/main.d.ts.map +1 -0
  36. package/dist/types/esm/types.d.ts +8 -0
  37. package/dist/types/esm/types.d.ts.map +1 -0
  38. package/dist/types/tsconfig.build.tsbuildinfo +1 -0
  39. package/package.json +70 -0
  40. package/rollup.config.mjs +17 -0
  41. package/src/__testUtils__/content.md +11 -0
  42. package/src/components/I18nProvider.tsx +24 -0
  43. package/src/components/Md.test.tsx +72 -0
  44. package/src/components/Md.tsx +39 -0
  45. package/src/helpers/injectVariables.ts +17 -0
  46. package/src/index.ts +4 -0
  47. package/src/macros.test.ts +35 -0
  48. package/src/macros.ts +15 -0
  49. package/src/main.test.ts +111 -0
  50. package/src/main.ts +23 -0
  51. package/src/types.ts +19 -0
  52. package/tsconfig.build.json +10 -0
  53. package/tsconfig.json +7 -0
@@ -0,0 +1,72 @@
1
+ /**
2
+ * @jest-environment jsdom
3
+ */
4
+ import { render } from '@testing-library/react';
5
+ import { type ReactNode } from 'react';
6
+ import { I18nProvider } from '#components/I18nProvider.tsx';
7
+ import { type ComponentMapper } from '#types.js';
8
+ import { Md } from './Md.tsx';
9
+
10
+ type ComponentProps = {
11
+ children: ReactNode;
12
+ };
13
+
14
+ const componentMapper: ComponentMapper = {
15
+ CustomComponent: ({ children }: ComponentProps) => <div data-display-name="CustomComponent">{children}</div>,
16
+ p: ({ children }: ComponentProps) => <p data-disaplay-name="p">{children}</p>,
17
+ };
18
+
19
+ describe('MarkdownToJsx', () => {
20
+ it('should render the expected components', () => {
21
+ const Wrapper = ({ children }: ComponentProps) => (
22
+ <I18nProvider componentMapper={componentMapper}>{children}</I18nProvider>
23
+ );
24
+
25
+ const { container } = render(<Md>{'<CustomComponent><p>content</p></CustomComponent>'}</Md>, { wrapper: Wrapper });
26
+
27
+ expect(container).toMatchInlineSnapshot(`
28
+ <div>
29
+ <div
30
+ data-display-name="CustomComponent"
31
+ >
32
+ <p
33
+ data-disaplay-name="p"
34
+ >
35
+ content
36
+ </p>
37
+ </div>
38
+ </div>
39
+ `);
40
+ });
41
+
42
+ describe('when the markdown as template variables', () => {
43
+ it('should render the expected components with template variables injected', () => {
44
+ const Wrapper = ({ children }: ComponentProps) => (
45
+ <I18nProvider componentMapper={componentMapper}>{children}</I18nProvider>
46
+ );
47
+
48
+ const { container } = render(
49
+ <Md variables={{ adjective: 'great' }}>
50
+ {"<CustomComponent><p>{'Have a {{adjective}} day'}</p></CustomComponent>"}
51
+ </Md>,
52
+ {
53
+ wrapper: Wrapper,
54
+ },
55
+ );
56
+
57
+ expect(container).toMatchInlineSnapshot(`
58
+ <div>
59
+ <div
60
+ data-display-name="CustomComponent"
61
+ >
62
+ <p
63
+ data-disaplay-name="p"
64
+ >
65
+ {'Have a great day'}
66
+ </p>
67
+ </div>
68
+ </div>
69
+ `);
70
+ });
71
+ });
72
+ });
@@ -0,0 +1,39 @@
1
+ import MarkdownToJsx from 'markdown-to-jsx';
2
+ import { type ComponentProps, type JSX, useContext } from 'react';
3
+ import { I18nContext } from '#components/I18nProvider.tsx';
4
+ import { injectVariables } from '#helpers/injectVariables.ts';
5
+ import { type ComponentMapper } from '#types.ts';
6
+
7
+ export type MdProps = {
8
+ // The markdown to convert into JSX.
9
+ children: string;
10
+ // An object of key/value pairs, with the key being the
11
+ // name of the html tag that maps to supported markdown or
12
+ // the name of a React component, and the value being a
13
+ // React component. This prop is designed as an override
14
+ // for the componentMapper passed into the I18nProvider.
15
+ componentMapper?: ComponentMapper;
16
+ // An object of key/value pairs for content with template variables.
17
+ variables?: Record<string, string | number>;
18
+ } & Omit<ComponentProps<typeof MarkdownToJsx>['options'], 'overrides'>;
19
+
20
+ export const Md = ({
21
+ children,
22
+ componentMapper: componentMapperOverrides,
23
+ variables,
24
+ ...markdownToJsxOptionOverrides
25
+ }: MdProps): JSX.Element => {
26
+ const { componentMapper, ...markdownToJsxOptions } = useContext(I18nContext);
27
+
28
+ return (
29
+ <MarkdownToJsx
30
+ options={{
31
+ overrides: { ...componentMapper, ...componentMapperOverrides },
32
+ ...markdownToJsxOptions,
33
+ ...markdownToJsxOptionOverrides,
34
+ }}
35
+ >
36
+ {injectVariables(children, variables)}
37
+ </MarkdownToJsx>
38
+ );
39
+ };
@@ -0,0 +1,17 @@
1
+ const extractTemplateVariables = /{{[^\s{}]+}}/g;
2
+ const extractVarName = /{{ *([^ }]*) *}}/;
3
+
4
+ export const injectVariables = (markdown: string, variables?: Record<string, string | number>): string =>
5
+ variables
6
+ ? // @ts-expect-error lib config needs updating
7
+ markdown.replaceAll(extractTemplateVariables, (match: string) => {
8
+ const varName = match.replace(extractVarName, '$1');
9
+ const replacementValue = variables[varName];
10
+
11
+ if (replacementValue) {
12
+ return replacementValue;
13
+ }
14
+
15
+ throw new Error(`Markdown contains un-replaced variable '${varName}'`);
16
+ })
17
+ : markdown;
package/src/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ export * from './components/I18nProvider.tsx';
2
+ export * from './components/Md.tsx';
3
+ export * from './main.ts';
4
+ export * from './types.ts';
@@ -0,0 +1,35 @@
1
+ import { md } from '#macros.ts';
2
+
3
+ describe('md', () => {
4
+ describe('when a valid path is provided', () => {
5
+ it('should return the markdown content in the file the path resolves to', () => {
6
+ const content = md('./packages/i18n/src/__testUtils__/content.md');
7
+
8
+ expect(content).toMatchInlineSnapshot(`
9
+ "# Page title
10
+
11
+ ## Section title
12
+
13
+ ### Section subtitle
14
+
15
+ > Inset text
16
+
17
+ This is a paragraph.
18
+
19
+ For more info, see [this link](http://localhost)"
20
+ `);
21
+ });
22
+ });
23
+
24
+ describe('when no path is not provided', () => {
25
+ it('should throw the expected error', () => {
26
+ expect(() => md('')).toThrow('Tagged template expected a path, but received none');
27
+ });
28
+ });
29
+
30
+ describe('when a valid path is not provided', () => {
31
+ it('should throw the expected error', () => {
32
+ expect(() => md('./packages/i18n/src/__testUtils__/no-content.md')).toThrow();
33
+ });
34
+ });
35
+ });
package/src/macros.ts ADDED
@@ -0,0 +1,15 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+
4
+ export const md = <P extends string>(path: P): P => {
5
+ if (!path) {
6
+ throw new Error('Tagged template expected a path, but received none');
7
+ }
8
+
9
+ const fullPath = resolve(process.cwd(), path);
10
+ // @ts-expect-error `md` function runs and build time and its return value
11
+ // replaces the `md` invocation. We are forcing the return type to be the
12
+ // input type to aid type inference when using `createI18n` and its
13
+ // `tt` content resolvers.
14
+ return readFileSync(fullPath, { encoding: 'utf8' }).trim();
15
+ };
@@ -0,0 +1,111 @@
1
+ import { createI18n } from './main.ts';
2
+
3
+ const content = {
4
+ alpha: 'alpha',
5
+ bravo: 'bravo',
6
+ charlie: 'charlie is a {{adjective}} boy',
7
+ delta: 'delta',
8
+ echo: {
9
+ foxtrot: 'foxtrot',
10
+ golf: [
11
+ {
12
+ hotel: {
13
+ india: 'india',
14
+ julia: 'julia is a {{adjective}} {{activity}}',
15
+ },
16
+ },
17
+ ],
18
+ },
19
+ } as const;
20
+
21
+ describe('createI18n', () => {
22
+ it('should return an instance of the i18n reader', () => {
23
+ expect(createI18n(content)).toEqual({
24
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
25
+ t: expect.any(Function),
26
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
27
+ tt: expect.any(Function),
28
+ });
29
+ });
30
+ });
31
+
32
+ describe('tt', () => {
33
+ describe('when a key path does not resolves to a value', () => {
34
+ it('should throw the expected error', () => {
35
+ const { tt } = createI18n(content);
36
+ // @ts-expect-error intentional to test runtime behaviour
37
+ expect(() => tt('zebra')).toThrow('Path "zebra" did not resolve to a value');
38
+ });
39
+ });
40
+
41
+ describe('when a key path resolves to a value', () => {
42
+ it('should return the value', () => {
43
+ const { tt } = createI18n(content);
44
+ expect(tt('alpha')).toBe('alpha');
45
+ });
46
+ });
47
+
48
+ describe('when a nested key path resolves to a value', () => {
49
+ it('should return the value', () => {
50
+ const { tt } = createI18n(content);
51
+ expect(tt('echo.golf.0.hotel.india')).toBe('india');
52
+ });
53
+ });
54
+
55
+ describe('when the value has a template variable and variables are passed in', () => {
56
+ it('should return the value with the variable injected into the value', () => {
57
+ const { tt } = createI18n(content);
58
+ expect(tt('charlie', { adjective: 'good' })).toBe('charlie is a good boy');
59
+ });
60
+ });
61
+
62
+ describe('when the value has multiple template variable and variables are passed in', () => {
63
+ it('should return the value with the variable injected into the value', () => {
64
+ const { tt } = createI18n(content);
65
+
66
+ expect(tt('echo.golf.0.hotel.julia', { activity: 'gymnast', adjective: 'great' })).toBe(
67
+ 'julia is a great gymnast',
68
+ );
69
+ });
70
+ });
71
+ });
72
+
73
+ describe('t', () => {
74
+ describe('when a key path does not resolves to a value', () => {
75
+ it('should return undefined', () => {
76
+ const { t } = createI18n(content);
77
+ expect(t('zebra')).toBeUndefined();
78
+ });
79
+ });
80
+
81
+ describe('when a key path resolves to a value', () => {
82
+ it('should return the value', () => {
83
+ const { t } = createI18n(content);
84
+ expect(t('alpha')).toBe('alpha');
85
+ });
86
+ });
87
+
88
+ describe('when a nested key path resolves to a value', () => {
89
+ it('should return the value', () => {
90
+ const { t } = createI18n(content);
91
+ expect(t('echo.golf.0.hotel.india')).toBe('india');
92
+ });
93
+ });
94
+
95
+ describe('when the value has a template variable and variables are passed in', () => {
96
+ it('should return the value with the variable injected into the value', () => {
97
+ const { t } = createI18n(content);
98
+ expect(t('charlie', { adjective: 'good' })).toBe('charlie is a good boy');
99
+ });
100
+ });
101
+
102
+ describe('when the value has multiple template variable and variables are passed in', () => {
103
+ it('should return the value with the variable injected into the value', () => {
104
+ const { t } = createI18n(content);
105
+
106
+ expect(t('echo.golf.0.hotel.julia', { activity: 'gymnast', adjective: 'great' })).toBe(
107
+ 'julia is a great gymnast',
108
+ );
109
+ });
110
+ });
111
+ });
package/src/main.ts ADDED
@@ -0,0 +1,23 @@
1
+ import { type AnyRecord, type Path, createConfigReader } from 'zcb';
2
+ import { type CreateI18nResult } from '#types.ts';
3
+
4
+ export const createI18n = <U extends object>(i18n: U): CreateI18nResult<U> => {
5
+ const reader = createConfigReader<U>(i18n);
6
+
7
+ return {
8
+ // @ts-expect-error intentionally ignoring the type checking here as
9
+ // function is supposed to be untyped.
10
+ t: (key: string, variables?: AnyRecord): string | undefined => reader.read(key, variables),
11
+ tt: <P extends Path<U>>(path: P, variables?: AnyRecord) => {
12
+ const result = reader.read(path, variables);
13
+
14
+ // This can resolve to a falsy value at runtime
15
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
16
+ if (!result) {
17
+ throw new Error(`Path "${String(path)}" did not resolve to a value`);
18
+ }
19
+
20
+ return result;
21
+ },
22
+ };
23
+ };
package/src/types.ts ADDED
@@ -0,0 +1,19 @@
1
+ import { type ComponentType } from 'react';
2
+ import { type AnyRecord, type ConfigReader } from 'zcb';
3
+
4
+ // Need to keep as generic as possible.
5
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
6
+ export type ComponentMapper = Record<string, ComponentType<any>>;
7
+
8
+ export type CreateI18nResult<U extends object> = {
9
+ // Untyped content lookup. Function takes a string and returns the
10
+ // value that path resolves in the i18n object passed into createI18n.
11
+ // If the function resolves no value, then it returns undefined.
12
+ t: (key: string, variables?: AnyRecord) => string | undefined;
13
+ // A typed content lookup. Function takes a string that is type-checked
14
+ // against all the possible paths in the i18n object passed into
15
+ // createI18n. The value that path resolves to can be previewed through
16
+ // IDE's inbuilt Typescript type preview. If the function resolves no
17
+ // value, then it throws an error.
18
+ tt: ConfigReader<U>['read'];
19
+ };
@@ -0,0 +1,10 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "outDir": "dist/types/esm",
5
+ "rootDir": "src"
6
+ },
7
+ "exclude": [
8
+ "**/*.test.*"
9
+ ]
10
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "extends": ["@repodog/ts-config/index.json", "@repodog/ts-config/build.json"],
3
+ "include": [
4
+ "src/**/*"
5
+ ],
6
+ "references": []
7
+ }