Skip to content

Commit

Permalink
Merge pull request #589 from VitNode/feat/create_lang_when_create_nav…
Browse files Browse the repository at this point in the history
…_plugin

feat: Create langs code when user creating nav for plugin
  • Loading branch information
aXenDeveloper authored Nov 27, 2024
2 parents 3df0602 + 1d0176c commit c4b4fec
Show file tree
Hide file tree
Showing 25 changed files with 202 additions and 59 deletions.
3 changes: 3 additions & 0 deletions apps/frontend/public/sw.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
'use strict';

self.addEventListener('install', () => {});
2 changes: 1 addition & 1 deletion apps/frontend/src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@ import { createMiddleware } from 'vitnode-frontend/middleware';
export default createMiddleware();

export const config = {
matcher: '/((?!_next|robots.txt|sitemap.xml|sitemap).*)',
matcher: '/((?!_next|robots.txt|sitemap.xml|sitemap|sw.js).*)',
};
6 changes: 2 additions & 4 deletions apps/frontend/src/plugins/welcome/langs/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,7 @@
},
"admin_welcome": {
"nav": {
"title": "Welcome",
"test": "Test",
"test_testchild": "Test Child"
"title": "Welcome"
}
}
}
}
8 changes: 7 additions & 1 deletion apps/frontend/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@
"@/*": ["./src/*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
"public/sw.js"
],
"exclude": ["node_modules"]
}
20 changes: 20 additions & 0 deletions bump-version.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,26 @@ function logError(error) {
recursive: true,
});

// Copy public in frontend to create-vitnode-app
const createVitnodeAppPublicPath = path.join(
WORKSPACE,
'packages',
'create-vitnode-app',
'templates',
'basic',
'apps',
'frontend',
'public',
);
const frontendPublicPath = path.join(WORKSPACE, 'apps', 'frontend', 'public');
if (!fs.existsSync(createVitnodeAppPublicPath)) {
fs.mkdirSync(createVitnodeAppPublicPath, { recursive: true });
}

fs.cpSync(frontendPublicPath, createVitnodeAppPublicPath, {
recursive: true,
});

if (process.argv[2] === '--without-bump-version') {
exitSuccess('Folders & Files copied!');
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import {
NotFoundException,
} from '@nestjs/common';
import { existsSync } from 'fs';
import { readFile, writeFile } from 'fs/promises';
import { readdir, readFile, writeFile } from 'fs/promises';
import { join } from 'path';
import { ParentNavAuthAdminObj } from 'vitnode-shared/admin/auth.dto';
import { ConfigPlugin } from 'vitnode-shared/admin/plugin.dto';
import { CreateNavPluginsAdminBody } from 'vitnode-shared/admin/plugins/nav.dto';
Expand Down Expand Up @@ -62,6 +63,30 @@ export class CreateNavPluginsAdminService extends HelpersAdminNavPluginsService
});
}

const langPathFolder = ABSOLUTE_PATHS.plugin({
code: plugin_code,
}).frontend.languages;
// Get all files
const langs = await readdir(langPathFolder);
await Promise.all(
langs.map(async lang => {
const langFilePath = join(langPathFolder, lang);
if (!langFilePath.endsWith('.json')) return;

const langFile = JSON.parse(await readFile(langFilePath, 'utf8'));
const langCode = parent_code ? `${parent_code}_${code}` : code;
langFile[`admin_${plugin_code}`] = {
...langFile[`admin_${plugin_code}`],
nav: {
...langFile[`admin_${plugin_code}`].nav,
[langCode]: `admin_${plugin_code}.nav.${langCode}`,
},
};

await writeFile(langFilePath, JSON.stringify(langFile, null, 2));
}),
);

await writeFile(pathConfig, JSON.stringify(config, null, 2));

return {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { ABSOLUTE_PATHS } from '@/app.module';
import { Injectable, NotFoundException } from '@nestjs/common';
import { existsSync } from 'fs';
import { readFile, writeFile } from 'fs/promises';
import { readdir, readFile, writeFile } from 'fs/promises';
import { join } from 'path';
import { ConfigPlugin } from 'vitnode-shared/admin/plugin.dto';
import { DeleteNavPluginsAdminBody } from 'vitnode-shared/admin/plugins/nav.dto';

Expand Down Expand Up @@ -44,6 +45,27 @@ export class DeleteNavPluginsAdminService {
config.nav = config.nav.filter(nav => nav.code !== code);
}

// Delete lang from json
const langPathFolder = ABSOLUTE_PATHS.plugin({
code: plugin_code,
}).frontend.languages;
const langs = await readdir(langPathFolder);
await Promise.all(
langs.map(async lang => {
const langFilePath = join(langPathFolder, lang);
if (!langFilePath.endsWith('.json')) return;

const langFile = JSON.parse(await readFile(langFilePath, 'utf8'));
const langCode = parent_code ? `${parent_code}_${code}` : code;

if (langFile[`admin_${plugin_code}`]?.nav?.[langCode]) {
delete langFile[`admin_${plugin_code}`].nav[langCode];

await writeFile(langFilePath, JSON.stringify(langFile, null, 2));
}
}),
);

await writeFile(pathConfig, JSON.stringify(config, null, 2));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import {
NotFoundException,
} from '@nestjs/common';
import { existsSync } from 'fs';
import { readFile, writeFile } from 'fs/promises';
import { readdir, readFile, writeFile } from 'fs/promises';
import { join } from 'path';
import { ParentNavAuthAdminObj } from 'vitnode-shared/admin/auth.dto';
import { ConfigPlugin } from 'vitnode-shared/admin/plugin.dto';
import { CreateNavPluginsAdminBody } from 'vitnode-shared/admin/plugins/nav.dto';
Expand Down Expand Up @@ -62,6 +63,30 @@ export class EditNavPluginsAdminService {
};
}

// Edit lang from json
const langPathFolder = ABSOLUTE_PATHS.plugin({
code: plugin_code,
}).frontend.languages;
const langs = await readdir(langPathFolder);
await Promise.all(
langs.map(async lang => {
const langFilePath = join(langPathFolder, lang);
if (!langFilePath.endsWith('.json')) return;

const langFile = JSON.parse(await readFile(langFilePath, 'utf8'));
const langPreviousCode = parent_code
? `${parent_code}_${previous_code}`
: previous_code;
const langCode = parent_code ? `${parent_code}_${code}` : code;
const prevValue =
langFile[`admin_${plugin_code}`].nav[langPreviousCode];
delete langFile[`admin_${plugin_code}`].nav[langPreviousCode];
langFile[`admin_${plugin_code}`].nav[langCode] = prevValue;

await writeFile(langFilePath, JSON.stringify(langFile, null, 2));
}),
);

await writeFile(pathConfig, JSON.stringify(config, null, 2));

return {
Expand Down
2 changes: 1 addition & 1 deletion packages/backend/src/helpers/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ export const DEFAULT_CONFIG_DATA: ConfigType = {
authorization: {
force_login: false,
lock_register: false,
require_confirm_email: true,
require_confirm_email: false,
},
},
langs: [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@
"@/*": ["./src/*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
"public/sw.js"
],
"exclude": ["node_modules"]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import React from 'react';

export const DevPluginAdminContext = React.createContext({
pluginCode: '',
});

export const useDevPluginAdmin = () => {
const hook = React.useContext(DevPluginAdminContext);

if (!hook) {
throw new Error(
'useDevPluginAdmin must be used inside dev plugin views in AdminCP!',
);
}

return hook;
};
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ import { Metadata } from 'next';
import { getTranslations } from 'next-intl/server';
import React from 'react';

import { getPluginDataAdmin } from './query-api';
import { TabsDevPluginAdmin } from './tabs';
import { getPluginDataAdmin } from '../query-api';
import { TabsDevPluginAdmin } from '../tabs';
import { WrapperDevPluginAdminLayout } from './wrapper';

interface Props {
children: React.ReactNode;
Expand Down Expand Up @@ -48,7 +49,7 @@ export const DevPluginAdminLayout = async ({ code, children }: Props) => {
]);

return (
<>
<WrapperDevPluginAdminLayout pluginCode={code}>
<HeaderContent
desc={
<div>
Expand Down Expand Up @@ -90,6 +91,6 @@ export const DevPluginAdminLayout = async ({ code, children }: Props) => {
<TabsDevPluginAdmin code={code} />

<Card className="p-6">{children}</Card>
</>
</WrapperDevPluginAdminLayout>
);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
'use client';

import { DevPluginAdminContext } from '../hooks/use-dev-plugin';

export const WrapperDevPluginAdminLayout = ({
children,
pluginCode,
}: {
children: React.ReactNode;
pluginCode: string;
}) => {
return (
<DevPluginAdminContext.Provider value={{ pluginCode }}>
{children}
</DevPluginAdminContext.Provider>
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@

import { DragAndDropSortableList } from '@/components/drag&drop/sortable-list/list';
import { TextAndIconsAsideAdmin } from '@/views/admin/layout/sidebar/sidebar';
import { useParams } from 'next/navigation';
import { useTranslations } from 'next-intl';
import React from 'react';
import { toast } from 'sonner';
import { ParentNavAuthAdminObj } from 'vitnode-shared/admin/auth.dto';

import { useDevPluginAdmin } from '../hooks/use-dev-plugin';
import { mutationChangePositionApi } from './hooks/mutation-change-position-api';
import { ItemContentNavDevPluginAdmin } from './item/item';

Expand All @@ -19,7 +19,7 @@ export const ContentNavDevPluginAdmin = ({
textsAndIcons: TextAndIconsAsideAdmin[];
}) => {
const t = useTranslations('core.global.errors');
const { code } = useParams();
const { pluginCode } = useDevPluginAdmin();

return (
<DragAndDropSortableList
Expand All @@ -45,12 +45,10 @@ export const ContentNavDevPluginAdmin = ({
}))}
maxDepth={1}
onDragEnd={async moveTo => {
if (!code) return;

try {
await mutationChangePositionApi({
code: moveTo.id.toString(),
plugin_code: Array.isArray(code) ? code[0] : code,
plugin_code: pluginCode,
index_to_move: moveTo.indexToMove,
parent_code: moveTo.parentId?.toString(),
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { useDialog } from '@/components/ui/dialog';
import { zodTag } from '@/helpers/zod';
import { useParams } from 'next/navigation';
import { useTranslations } from 'next-intl';
import { UseFormReturn } from 'react-hook-form';
import { toast } from 'sonner';
import * as z from 'zod';

import { useDevPluginAdmin } from '../../../hooks/use-dev-plugin';
import { CreateEditNavDevPluginAdmin } from '../create-edit';
import { createMutationApi } from './create-mutation-api';
import { editMutationApi } from './edit-mutation-api';
Expand All @@ -21,7 +21,7 @@ export const useCreateNavPluginAdmin = ({
const t = useTranslations('admin.core.plugins.dev.nav');
const tCore = useTranslations('core.global.errors');
const { setOpen } = useDialog();
const { code } = useParams();
const { pluginCode } = useDevPluginAdmin();

const formSchema = z.object({
code: z
Expand Down Expand Up @@ -50,22 +50,22 @@ export const useCreateNavPluginAdmin = ({
values: z.infer<typeof formSchema>,
form: UseFormReturn<z.infer<typeof formSchema>>,
) => {
if (!code) return;
if (!pluginCode) return;

try {
if (data) {
await editMutationApi({
...values,
previous_code: data.code,
plugin_code: Array.isArray(code) ? code[0] : code,
plugin_code: pluginCode,
parent_code:
values.parent_code === 'null' ? undefined : values.parent_code,
keywords: (values.keywords ?? []).map(keyword => keyword.value),
});
} else {
await createMutationApi({
...values,
plugin_code: Array.isArray(code) ? code[0] : code,
plugin_code: pluginCode,
parent_code:
values.parent_code === 'null' ? undefined : values.parent_code,
keywords: (values.keywords ?? []).map(keyword => keyword.value),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { useAlertDialog } from '@/components/ui/alert-dialog';
import { useParams } from 'next/navigation';
import { useTranslations } from 'next-intl';
import { toast } from 'sonner';

import { useDevPluginAdmin } from '../../../../../hooks/use-dev-plugin';
import { ContentDeleteActionTableNavDevPluginAdmin } from '../content';
import { mutationApi } from './mutation-api';

Expand All @@ -13,11 +13,9 @@ export const useDeleteNavPluginAdmin = ({
const t = useTranslations('admin.core.plugins.dev.nav.delete');
const tCore = useTranslations('core.global.errors');
const { setOpen } = useAlertDialog();
const { code: pluginCode } = useParams();
const { pluginCode } = useDevPluginAdmin();

const onSubmit = async () => {
if (!pluginCode) return;

try {
await mutationApi({
code,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { TextAndIconsAsideAdmin } from '@/views/admin/layout/sidebar/sidebar';
import { useParams } from 'next/navigation';
import { useTranslations } from 'next-intl';
import { ParentNavAuthAdminObj } from 'vitnode-shared/admin/auth.dto';

import { useDevPluginAdmin } from '../../hooks/use-dev-plugin';
import { ActionsTableNavDevPluginAdmin } from './actions/actions';

export const ItemContentNavDevPluginAdmin = ({
Expand All @@ -16,7 +16,7 @@ export const ItemContentNavDevPluginAdmin = ({
parentId?: string;
textsAndIcons: TextAndIconsAsideAdmin[];
}) => {
const { code: pluginCode } = useParams();
const { pluginCode } = useDevPluginAdmin();
const tAdmin = useTranslations('admin.core.plugins.dev.nav');
const langKey = parentId ? `${parentId}_${data.code}` : data.code;
const textAndIcon = textsAndIcons.find(item => item.id === langKey);
Expand Down
Loading

0 comments on commit c4b4fec

Please sign in to comment.