Skip to content

Commit

Permalink
feat: add SEO TDK support to template
Browse files Browse the repository at this point in the history
  • Loading branch information
zjy365 committed Aug 30, 2024
1 parent d58375e commit 6fe30a7
Show file tree
Hide file tree
Showing 6 changed files with 221 additions and 117 deletions.
2 changes: 1 addition & 1 deletion frontend/.lintstagedrc
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"**/src/**/*.{js,jsx,ts,tsx}": ["prettier --write", "eslint --fix", "eslint"],
"**/src/**/*.{js,jsx,ts,tsx}": ["prettier --write"],
"**/src/**/*.{json,css,scss,md}": ["prettier --write"]
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse<
kubeconfig: await authSession(req.headers)
});
user_namespace = namespace;
} catch (error) {
console.log(error, 'Unauthorized allowed');
}
} catch (error) {}

const { code, message, dataSource, templateYaml, TemplateEnvs, appYaml } =
await GetTemplateByName({
Expand Down
188 changes: 130 additions & 58 deletions frontend/providers/template/src/pages/deploy/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,7 @@ import { useSearchStore } from '@/store/search';
import type { QueryType, YamlItemType } from '@/types';
import { ApplicationType, TemplateSourceType } from '@/types/app';
import { serviceSideProps } from '@/utils/i18n';
import {
generateYamlList,
parseTemplateString,
} from '@/utils/json-yaml';
import { generateYamlList, parseTemplateString } from '@/utils/json-yaml';
import { compareFirstLanguages, deepSearch, useCopyData } from '@/utils/tools';
import { Box, Flex, Icon, Text } from '@chakra-ui/react';
import { useQuery } from '@tanstack/react-query';
Expand All @@ -26,11 +23,22 @@ import { useForm } from 'react-hook-form';
import Form from './components/Form';
import ReadMe from './components/ReadMe';
import { getTemplateInputDefaultValues, getTemplateValues } from '@/utils/template';
import Head from 'next/head';

const ErrorModal = dynamic(() => import('./components/ErrorModal'));
const Header = dynamic(() => import('./components/Header'), { ssr: false });

export default function EditApp({ appName }: { appName?: string }) {
export default function EditApp({
appName,
metaData
}: {
appName?: string;
metaData: {
title: string;
keywords: string;
description: string;
};
}) {
const { t, i18n } = useTranslation();
const { toast } = useToast();
const router = useRouter();
Expand Down Expand Up @@ -70,37 +78,45 @@ export default function EditApp({ appName }: { appName?: string }) {
return val;
}, [screenWidth]);

const generateYamlData = useCallback((templateSource: TemplateSourceType, inputs: Record<string, string>): YamlItemType[] => {
if (!templateSource) return [];
const app_name = templateSource?.source?.defaults?.app_name?.value;
const { defaults, defaultInputs } = getTemplateValues(templateSource);
const data = {
...platformEnvs,
...templateSource?.source,
inputs: {
...defaultInputs,
...inputs
},
defaults: defaults,
};
const generateStr = parseTemplateString(templateSource.appYaml, data);
return generateYamlList(generateStr, app_name);
}, [platformEnvs])
const generateYamlData = useCallback(
(templateSource: TemplateSourceType, inputs: Record<string, string>): YamlItemType[] => {
if (!templateSource) return [];
const app_name = templateSource?.source?.defaults?.app_name?.value;
const { defaults, defaultInputs } = getTemplateValues(templateSource);
const data = {
...platformEnvs,
...templateSource?.source,
inputs: {
...defaultInputs,
...inputs
},
defaults: defaults
};
const generateStr = parseTemplateString(templateSource.appYaml, data);
return generateYamlList(generateStr, app_name);
},
[platformEnvs]
);

const formOnchangeDebounce = useCallback(debounce((inputs: Record<string, string>) => {
try {
if (!templateSource) return;
const list = generateYamlData(templateSource, inputs)
setYamlList(list);
} catch (error) {
console.log(error);
}
}, 500), [templateSource, generateYamlData]);
const formOnchangeDebounce = useCallback(
debounce((inputs: Record<string, string>) => {
try {
if (!templateSource) return;
const list = generateYamlData(templateSource, inputs);
setYamlList(list);
} catch (error) {
console.log(error);
}
}, 500),
[templateSource, generateYamlData]
);

const getCachedValue = (): {
cachedKey: string,
[key: string]: any
} | undefined => {
const getCachedValue = ():
| {
cachedKey: string;
[key: string]: any;
}
| undefined => {
if (!cached) return undefined;
const cachedValue = JSON.parse(cached);
return cachedValue?.cachedKey === templateName ? cachedValue : undefined;
Expand All @@ -124,36 +140,58 @@ export default function EditApp({ appName }: { appName?: string }) {
setIsLoading(true);
try {
if (!insideCloud) {
setIsLoading(false);
setCached(JSON.stringify({ ...formHook.getValues(), cachedKey: templateName }));
const _name = encodeURIComponent(`?templateName=${templateName}&sealos_inside=true`);
const _domain = platformEnvs?.SEALOS_CLOUD_DOMAIN;
const href = `https://${_domain}/?openapp=system-template${_name}`;
return window.open(href, '_self');
handleOutside();
} else {
await handleInside();
}
const yamls = yamlList.map((item) => item.value);

await postDeployApp(yamls, 'create');

toast({
title: t(applySuccess),
status: 'success'
});

deleteCached();
setAppType(ApplicationType.MyApp);
router.push({
pathname: '/instance',
query: {
instanceName: detailName
}
});
} catch (error) {
setErrorMessage(JSON.stringify(error));
}
setIsLoading(false);
};

const handleOutside = () => {
setCached(JSON.stringify({ ...formHook.getValues(), cachedKey: templateName }));

const params = new URLSearchParams();
['k', 's', 'bd_vid'].forEach((param) => {
const value = router.query[param];
if (typeof value === 'string') {
params.append(param, value);
}
});

const queryString = params.toString();

const baseUrl = `https://${platformEnvs?.SEALOS_CLOUD_DOMAIN}/`;
const encodedTemplateQuery = encodeURIComponent(
`templateName=${templateName}&sealos_inside=true`
);
const templateQuery = `openapp=system-template?${encodedTemplateQuery}`;
const href = `${baseUrl}${
queryString ? `?${queryString}&${templateQuery}` : `?${templateQuery}`
}`;

window.open(href, '_self');
};

const handleInside = async () => {
const yamls = yamlList.map((item) => item.value);
await postDeployApp(yamls, 'create');

toast({
title: t(applySuccess),
status: 'success'
});

deleteCached();
setAppType(ApplicationType.MyApp);
router.push({
pathname: '/instance',
query: { instanceName: detailName }
});
};

const submitError = async () => {
await formHook.trigger();
toast({
Expand Down Expand Up @@ -230,6 +268,15 @@ export default function EditApp({ appName }: { appName?: string }) {
borderRadius={'12px'}
background={'linear-gradient(180deg, #FFF 0%, rgba(255, 255, 255, 0.70) 100%)'}
>
<Head>
<title>{`${metaData.title}${
i18n.language === 'en'
? 'Deployment and installation tutorial - Sealos'
: '部署和安装教程 - Sealos'
}`}</title>
<meta name="keywords" content={metaData.keywords} />
<meta name="description" content={metaData.description} />
</Head>
<Flex
zIndex={99}
position={'sticky'}
Expand Down Expand Up @@ -304,7 +351,12 @@ export default function EditApp({ appName }: { appName?: string }) {
applyCb={() => formHook.handleSubmit(openConfirm(submitSuccess), submitError)()}
/>
<Flex w="100%" mt="32px" flexDirection="column">
<Form formHook={formHook} pxVal={pxVal} formSource={templateSource!} platformEnvs={platformEnvs!} />
<Form
formHook={formHook}
pxVal={pxVal}
formSource={templateSource!}
platformEnvs={platformEnvs!}
/>
{/* <Yaml yamlList={yamlList} pxVal={pxVal}></Yaml> */}
<ReadMe templateDetail={data?.templateYaml!} />
</Flex>
Expand Down Expand Up @@ -332,9 +384,29 @@ export async function getServerSideProps(content: any) {

const appName = content?.query?.templateName || '';

const baseurl = `http://${process.env.HOSTNAME || 'localhost'}:${process.env.PORT || 3000}`;

let metaData = {
title: `${appName}部署和安装教程 - Sealos`,
keywords: '',
description: ''
};

try {
const templateSource: { data: TemplateSourceType } = await (
await fetch(`${baseurl}/api/getTemplateSource?templateName=${appName}`)
).json();
metaData = {
title: templateSource?.data.templateYaml.spec.title,
keywords: templateSource?.data.templateYaml.spec.description,
description: templateSource?.data.templateYaml.spec.description
};
} catch (error) {}

return {
props: {
appName,
metaData,
...(await serviceSideProps(content))
}
};
Expand Down
Loading

0 comments on commit 6fe30a7

Please sign in to comment.