Skip to content

Commit

Permalink
feat(frontend): Add i18n without routing
Browse files Browse the repository at this point in the history
  • Loading branch information
aXenDeveloper committed Sep 16, 2024
1 parent e242d2c commit f3d0a11
Show file tree
Hide file tree
Showing 38 changed files with 88 additions and 60 deletions.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
// ! DO NOT TOUCH THIS FILE!!! IT IS GENERATED BY VITNODE-CLI

import React from 'react';
import {
DefaultPage,
Expand All @@ -13,7 +11,7 @@ export default function Page(props: DefaultPageProps) {
return (
<DefaultPage
pathToDefaultPage={async plugin =>
import(`../../../plugins/${plugin}/templates/default-page`)
import(`@/plugins/${plugin}/templates/default-page`)
}
{...props}
/>
Expand Down
7 changes: 0 additions & 7 deletions apps/frontend/src/app/[locale]/error.tsx

This file was deleted.

14 changes: 0 additions & 14 deletions apps/frontend/src/app/[locale]/layout.tsx

This file was deleted.

File renamed without changes.
File renamed without changes.
19 changes: 13 additions & 6 deletions apps/frontend/src/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
export default async function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return children;
import { GeistSans } from 'geist/font/sans';
import {
generateMetadataRootLayout,
RootLayout,
RootLayoutProps,
} from 'vitnode-frontend/views/layout/root-layout';

import './global.css';

export const generateMetadata = generateMetadataRootLayout;

export default function Layout(props: RootLayoutProps) {
return <RootLayout className={GeistSans.className} {...props} />;
}
8 changes: 0 additions & 8 deletions apps/frontend/src/app/not-found.tsx

This file was deleted.

6 changes: 4 additions & 2 deletions apps/frontend/src/i18n.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { getRequestConfig } from 'next-intl/server';
import { i18nConfig } from 'vitnode-frontend/i18n';

export default getRequestConfig(async args => {
export default getRequestConfig(async () => {
const locale = 'en';

const config = await i18nConfig({
...args,
locale,
pathsToMessagesFromPlugins: async ({ plugin, locale }) => {
return import(`./plugins/${plugin}/langs/${locale}.json`);
},
Expand Down
6 changes: 1 addition & 5 deletions apps/frontend/src/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
import createMiddleware from 'vitnode-frontend/middleware';

export default createMiddleware();

export const config = {
matcher: '/((?!_next/static|_next/image|robots.txt|sitemap.xml|sitemap).*)',
};
export default createMiddleware({});
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { getRequestConfig } from 'next-intl/server';
import { i18nConfig } from 'vitnode-frontend/i18n';

export default getRequestConfig(async ({ locale }) => {
const config = await i18nConfig({
locale,
pathsToMessagesFromPlugins: async ({ plugin, locale }) => {
return import(`./plugins/${plugin}/langs/${locale}.json`);
},
});

return config;
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import createMiddleware from 'vitnode-frontend/middleware';

export default createMiddleware({
isLocalePathRoute: true,
});

export const config = {
matcher: '/((?!_next/static|_next/image|robots.txt|sitemap.xml|sitemap).*)',
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import createMiddleware from 'vitnode-frontend/middleware';

export default createMiddleware({});
2 changes: 1 addition & 1 deletion packages/frontend/next.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ dotenv.config({
path: join(process.cwd(), '..', '..', '.env'),
});

const withNextIntl = createNextIntlPlugin();
const withNextIntl = createNextIntlPlugin('./src/i18n.ts');

const nextConfig = (config: NextConfig): NextConfig => {
const ENVS = {
Expand Down
3 changes: 1 addition & 2 deletions packages/frontend/src/hooks/core/sign/in/mutation-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
Core_Sessions__Sign_InMutation,
Core_Sessions__Sign_InMutationVariables,
} from '@/graphql/mutations/sessions/core_sessions__sign_in.generated';
import { redirect } from '@/navigation';

import { revalidatePath } from 'next/cache';

Check warning on line 10 in packages/frontend/src/hooks/core/sign/in/mutation-api.ts

View workflow job for this annotation

GitHub Actions / linting

Extra spacing between "@/graphql/mutations/sessions/core_sessions__sign_in.generated" and "next/cache" imports

export const mutationApi = async (
Expand All @@ -27,5 +27,4 @@ export const mutationApi = async (
}

revalidatePath(variables.admin ? '/admin' : '/', 'layout');
redirect(variables.admin ? '/admin/core/dashboard' : '/');
};
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ import React from 'react';
import * as z from 'zod';

import { mutationApi } from './mutation-api';
import { useRouter } from '@/navigation';

Check warning on line 5 in packages/frontend/src/hooks/core/sign/in/use-sign-in-admin-view.ts

View workflow job for this annotation

GitHub Actions / linting

Expected "@/navigation" (external) to come before "./mutation-api" (sibling)

export const useSignInAdminView = () => {
const [error, setError] = React.useState<string>('');
const { push } = useRouter();

const formSchema = z.object({
email: z.string().min(1),
Expand All @@ -16,7 +18,11 @@ export const useSignInAdminView = () => {
const mutation = await mutationApi({ ...values, admin: true });
if (mutation?.error) {
setError(mutation.error);

return;
}

push('/admin/core/dashboard');
};

return {
Expand Down
6 changes: 6 additions & 0 deletions packages/frontend/src/hooks/core/sign/in/use-sign-in-view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ import React from 'react';
import * as z from 'zod';

import { mutationApi } from './mutation-api';
import { useRouter } from '@/navigation';

Check warning on line 5 in packages/frontend/src/hooks/core/sign/in/use-sign-in-view.ts

View workflow job for this annotation

GitHub Actions / linting

Expected "@/navigation" (external) to come before "./mutation-api" (sibling)

export const useSignInView = () => {
const [error, setError] = React.useState('');
const { push } = useRouter();

const formSchema = z.object({
email: z.string().email().default(''),
Expand All @@ -17,7 +19,11 @@ export const useSignInView = () => {
const mutation = await mutationApi(values);
if (mutation?.error) {
setError(mutation.error);

return;
}

push('/');
};

return {
Expand Down
2 changes: 0 additions & 2 deletions packages/frontend/src/hooks/core/sign/out/mutation-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import {
Core_Sessions__Sign_OutMutation,
Core_Sessions__Sign_OutMutationVariables,
} from '@/graphql/mutations/sessions/core_sessions__sign_out.generated';
import { redirect } from '@/navigation';
import { revalidatePath } from 'next/cache';

export const mutationApi = async () => {
Expand All @@ -24,5 +23,4 @@ export const mutationApi = async () => {
}

revalidatePath('/', 'page');
redirect('/');
};
6 changes: 3 additions & 3 deletions packages/frontend/src/i18n.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { notFound } from 'next/navigation';
import { IntlConfig } from 'next-intl';

import { fetcher } from './graphql/fetcher';
Expand All @@ -20,7 +19,7 @@ export const i18nConfig = async ({
locale: string;
plugin: string;
}) => Promise<{ default: unknown }>;
}): Promise<Omit<IntlConfig, 'locale'>> => {
}): Promise<IntlConfig> => {
let plugins: string[] = [];
try {
const {
Expand All @@ -33,7 +32,7 @@ export const i18nConfig = async ({
});

if (!languages.find(lang => lang.code === locale)) {
notFound();
plugins = ['core', 'admin'];
}

plugins = pluginsFromServer;
Expand All @@ -58,6 +57,7 @@ export const i18nConfig = async ({
);

return {
locale,
messages: {
...messagesFormApps.reduce(
(acc, messages) => ({ ...acc, ...messages }),
Expand Down
18 changes: 14 additions & 4 deletions packages/frontend/src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import {
Core_Middleware__ShowQuery,
Core_Middleware__ShowQueryVariables,
} from './graphql/queries/core_middleware__show.generated';
import { join } from 'path';

Check warning on line 10 in packages/frontend/src/middleware.ts

View workflow job for this annotation

GitHub Actions / linting

Expected "path" (builtin) to come before "./graphql/queries/core_middleware__show.generated" (sibling)

Check warning on line 10 in packages/frontend/src/middleware.ts

View workflow job for this annotation

GitHub Actions / linting

'join' is defined but never used
import { existsSync } from 'fs';

Check warning on line 11 in packages/frontend/src/middleware.ts

View workflow job for this annotation

GitHub Actions / linting

Expected "fs" to come before "path"

Check warning on line 11 in packages/frontend/src/middleware.ts

View workflow job for this annotation

GitHub Actions / linting

'existsSync' is defined but never used

const getI18n = async () => {
try {
Expand Down Expand Up @@ -55,11 +57,14 @@ const removeLocaleFromUrl = (urlPath: string, locales: string[]): string => {
return `/${parts.join('/')}`;
};

export default function createMiddleware() {
export default function createMiddleware({
isLocalePathRoute,
}: {
isLocalePathRoute?: boolean;
}) {
return async function middleware(request: NextRequest) {
const i18n = await getI18n();
const handleI18nRouting = createIntlMiddleware(i18n);
const response = handleI18nRouting(request);

const pathname = removeLocaleFromUrl(
request.nextUrl.pathname,
i18n.locales,
Expand Down Expand Up @@ -94,6 +99,11 @@ export default function createMiddleware() {
return NextResponse.redirect(new URL('/admin', request.url));
}

return response;
if (isLocalePathRoute) {
const handleI18nRouting = createIntlMiddleware(i18n);
const response = handleI18nRouting(request);

return response;
}
};
}
16 changes: 13 additions & 3 deletions packages/frontend/src/views/layout/root-layout.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Metadata } from 'next';
import { NextIntlClientProvider } from 'next-intl';
import { getMessages } from 'next-intl/server';
import { getLocale, getMessages } from 'next-intl/server';
import React from 'react';

import { getGlobalData } from '../../graphql/get-global-data';
Expand All @@ -19,8 +19,13 @@ interface Props extends RootLayoutProps {
}

export const generateMetadataRootLayout = async ({
params: { locale },
params: { locale: localeFromParams },
}: RootLayoutProps): Promise<Metadata> => {
let locale = localeFromParams;
if (!locale) {
locale = await getLocale();
}

const metadata: Metadata = {
manifest: `${CONFIG.backend_public_url}/assets/${locale}/manifest.webmanifest`,
icons: {
Expand Down Expand Up @@ -51,9 +56,14 @@ export const generateMetadataRootLayout = async ({

export const RootLayout = async ({
children,
params: { locale },
params: { locale: localeFromParams },
className,
}: Props) => {
let locale = localeFromParams;
if (!locale) {
locale = await getLocale();
}

const messages = await getMessages({ locale });

try {
Expand Down

0 comments on commit f3d0a11

Please sign in to comment.