feat: 代码生成预览

pull/69/head
puhui999 2025-04-08 12:15:57 +08:00
parent b376524980
commit 0b450aafa2
4 changed files with 140 additions and 68 deletions

View File

@ -43,6 +43,7 @@
"@vueuse/core": "catalog:", "@vueuse/core": "catalog:",
"ant-design-vue": "catalog:", "ant-design-vue": "catalog:",
"dayjs": "catalog:", "dayjs": "catalog:",
"highlight.js": "^11.11.1",
"pinia": "catalog:", "pinia": "catalog:",
"vue": "catalog:", "vue": "catalog:",
"vue-codemirror": "^6.1.1", "vue-codemirror": "^6.1.1",

View File

@ -46,19 +46,6 @@ export function useImportTableFormSchema(): VbenFormSchema[] {
]; ];
} }
/** 预览代码模态框 */
export function usePreviewFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'content',
component: 'Textarea',
componentProps: {
readonly: true,
},
},
];
}
/** 列表的搜索表单 */ /** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] { export function useGridFormSchema(): VbenFormSchema[] {
return [ return [

View File

@ -5,8 +5,8 @@ import type { InfraDataSourceConfigApi } from '#/api/infra/data-source-config';
import { DocAlert } from '#/components/doc-alert'; import { DocAlert } from '#/components/doc-alert';
// import ImportTable from './modules/import-table.vue'; // import ImportTable from './modules/import-table.vue';
// import PreviewCode from './modules/preview-code.vue'; import PreviewCode from './modules/preview-code.vue';
import { Page } from '@vben/common-ui'; import { Page, useVbenModal } from '@vben/common-ui';
import { Plus } from '@vben/icons'; import { Plus } from '@vben/icons';
import { Button, message } from 'ant-design-vue'; import { Button, message } from 'ant-design-vue';
@ -28,10 +28,11 @@ const dataSourceConfigList = ref<InfraDataSourceConfigApi.InfraDataSourceConfig[
// destroyOnClose: true, // destroyOnClose: true,
// }); // });
// //
// const [PreviewModal, previewModalApi] = useVbenModal({
// connectedComponent: PreviewCode, const [PreviewModal, previewModalApi] = useVbenModal({
// destroyOnClose: true, connectedComponent: PreviewCode,
// }); destroyOnClose: true,
});
/** 刷新表格 */ /** 刷新表格 */
function onRefresh() { function onRefresh() {
@ -45,7 +46,7 @@ function onImport() {
/** 预览代码 */ /** 预览代码 */
function onPreview(row: InfraCodegenApi.CodegenTable) { function onPreview(row: InfraCodegenApi.CodegenTable) {
// previewModalApi.setData(row.id).open(); previewModalApi.setData(row).open();
} }
/** 编辑表格 */ /** 编辑表格 */
@ -191,7 +192,7 @@ initDataSourceConfig();
<DocAlert title="单元测试" url="https://doc.iocoder.cn/unit-test/" /> <DocAlert title="单元测试" url="https://doc.iocoder.cn/unit-test/" />
<!-- <ImportModal @success="onRefresh" />--> <!-- <ImportModal @success="onRefresh" />-->
<!-- <PreviewModal />--> <PreviewModal />
<Grid table-title=""> <Grid table-title="">
<template #toolbar-tools> <template #toolbar-tools>
<Button type="primary" @click="onImport" v-access:code="['infra:codegen:create']"> <Button type="primary" @click="onImport" v-access:code="['infra:codegen:create']">

View File

@ -2,12 +2,11 @@
import type { InfraCodegenApi } from '#/api/infra/codegen'; import type { InfraCodegenApi } from '#/api/infra/codegen';
import { useVbenModal } from '@vben/common-ui'; import { useVbenModal } from '@vben/common-ui';
import { CopyOutlined } from '@vben/icons'; import { Copy } from '@vben/icons';
import { message, Tree } from 'ant-design-vue'; import { Button, message, Tree } from 'ant-design-vue';
import { useVbenForm } from '#/adapter/form';
import { previewCodegen } from '#/api/infra/codegen'; import { previewCodegen } from '#/api/infra/codegen';
import { ref } from 'vue'; import { computed, h, ref } from 'vue';
import { useClipboard } from '@vueuse/core'; import { useClipboard } from '@vueuse/core';
import hljs from 'highlight.js/lib/core'; import hljs from 'highlight.js/lib/core';
@ -17,10 +16,7 @@ import sql from 'highlight.js/lib/languages/sql';
import typescript from 'highlight.js/lib/languages/typescript'; import typescript from 'highlight.js/lib/languages/typescript';
import xml from 'highlight.js/lib/languages/xml'; import xml from 'highlight.js/lib/languages/xml';
import { usePreviewFormSchema } from '../data'; /** 注册代码高亮语言 */
import 'highlight.js/styles/github.css';
hljs.registerLanguage('java', java); hljs.registerLanguage('java', java);
hljs.registerLanguage('xml', xml); hljs.registerLanguage('xml', xml);
hljs.registerLanguage('html', xml); hljs.registerLanguage('html', xml);
@ -29,7 +25,7 @@ hljs.registerLanguage('javascript', javascript);
hljs.registerLanguage('sql', sql); hljs.registerLanguage('sql', sql);
hljs.registerLanguage('typescript', typescript); hljs.registerLanguage('typescript', typescript);
// /** 文件树类型 */
interface FileNode { interface FileNode {
key: string; key: string;
title: string; title: string;
@ -38,27 +34,30 @@ interface FileNode {
children?: FileNode[]; children?: FileNode[];
} }
/** 组件状态 */
const loading = ref(false); const loading = ref(false);
const fileTree = ref<FileNode[]>([]); const fileTree = ref<FileNode[]>([]);
const previewFiles = ref<InfraCodegenApi.CodegenPreview[]>([]); const previewFiles = ref<InfraCodegenApi.CodegenPreview[]>([]);
const activeKey = ref<string>(''); const activeKey = ref<string>('');
const highlightedCode = ref<string>(''); const highlightedCode = ref<string>('');
// /** 当前活动文件的语言 */
const [Form, formApi] = useVbenForm({ const activeLanguage = computed(() => {
schema: usePreviewFormSchema(), return activeKey.value.split('.').pop() || '';
showActionButtonGroup: false,
}); });
// /** 复制代码 */
const copyCode = async () => { const copyCode = async () => {
const { copy } = useClipboard(); const { copy } = useClipboard();
await copy(highlightedCode.value); const file = previewFiles.value.find((item) => item.filePath === activeKey.value);
message.success('复制成功'); if (file) {
await copy(file.code);
message.success('复制成功');
}
}; };
// /** 文件节点点击事件 */
const handleNodeClick = (selectedKeys: string[], e: any) => { const handleNodeClick = (_: any[], e: any) => {
if (e.node.isLeaf) { if (e.node.isLeaf) {
activeKey.value = e.node.key; activeKey.value = e.node.key;
const file = previewFiles.value.find((item) => item.filePath === activeKey.value); const file = previewFiles.value.find((item) => item.filePath === activeKey.value);
@ -69,12 +68,11 @@ const handleNodeClick = (selectedKeys: string[], e: any) => {
} catch { } catch {
highlightedCode.value = file.code; highlightedCode.value = file.code;
} }
formApi.setFieldValue('content', file.code);
} }
} }
}; };
// /** 处理文件树 */
const handleFiles = (data: InfraCodegenApi.CodegenPreview[]): FileNode[] => { const handleFiles = (data: InfraCodegenApi.CodegenPreview[]): FileNode[] => {
const exists: Record<string, boolean> = {}; const exists: Record<string, boolean> = {};
const files: FileNode[] = []; const files: FileNode[] = [];
@ -97,7 +95,7 @@ const handleFiles = (data: InfraCodegenApi.CodegenPreview[]): FileNode[] => {
let packagePath = ''; let packagePath = '';
i++; i++;
while (i < paths.length) { while (i < paths.length) {
const nextPath = paths[i]; const nextPath = paths[i] || '';
if (['controller', 'convert', 'dal', 'dataobject', 'enums', 'mysql', 'service', 'vo'].includes(nextPath)) { if (['controller', 'convert', 'dal', 'dataobject', 'enums', 'mysql', 'service', 'vo'].includes(nextPath)) {
break; break;
} }
@ -118,7 +116,7 @@ const handleFiles = (data: InfraCodegenApi.CodegenPreview[]): FileNode[] => {
// //
for (let i = 0; i < newPaths.length; i++) { for (let i = 0; i < newPaths.length; i++) {
const oldFullPath = fullPath; const oldFullPath = fullPath;
fullPath = fullPath.length === 0 ? newPaths[i] : `${fullPath.replaceAll('.', '/')}/${newPaths[i]}`; fullPath = fullPath.length === 0 ? newPaths[i] || '' : `${fullPath.replaceAll('.', '/')}/${newPaths[i]}`;
if (exists[fullPath]) { if (exists[fullPath]) {
continue; continue;
@ -127,14 +125,14 @@ const handleFiles = (data: InfraCodegenApi.CodegenPreview[]): FileNode[] => {
exists[fullPath] = true; exists[fullPath] = true;
files.push({ files.push({
key: fullPath, key: fullPath,
title: newPaths[i], title: newPaths[i] || '',
parentKey: oldFullPath || '/', parentKey: oldFullPath || '/',
isLeaf: i === newPaths.length - 1, isLeaf: i === newPaths.length - 1,
}); });
} }
} }
// /** 构建树形结构 */
const buildTree = (parentKey: string): FileNode[] => { const buildTree = (parentKey: string): FileNode[] => {
return files return files
.filter((file) => file.parentKey === parentKey) .filter((file) => file.parentKey === parentKey)
@ -147,9 +145,10 @@ const handleFiles = (data: InfraCodegenApi.CodegenPreview[]): FileNode[] => {
return buildTree('/'); return buildTree('/');
}; };
// /** 模态框实例 */
const [Modal, modalApi] = useVbenModal({ const [Modal, modalApi] = useVbenModal({
footer: false, footer: false,
class: 'w-3/5',
async onOpenChange(isOpen: boolean) { async onOpenChange(isOpen: boolean) {
if (!isOpen) { if (!isOpen) {
previewFiles.value = []; previewFiles.value = [];
@ -159,27 +158,26 @@ const [Modal, modalApi] = useVbenModal({
return; return;
} }
// ID const row = modalApi.getData<InfraCodegenApi.CodegenTable>();
const id = modalApi.getData<number>(); if (!row) return;
if (!id) return;
// //
loading.value = true; loading.value = true;
try { try {
const data = await previewCodegen(id); const data = await previewCodegen(row.id);
previewFiles.value = data; previewFiles.value = data;
fileTree.value = handleFiles(data); fileTree.value = handleFiles(data);
// //
if (data.length > 0) { if (data.length > 0) {
activeKey.value = data[0].filePath; activeKey.value = data[0]?.filePath || '';
const lang = data[0].filePath.split('.').pop() || ''; const lang = activeKey.value.split('.').pop() || '';
const code = data[0]?.code || '';
try { try {
highlightedCode.value = hljs.highlight(data[0].code, { language: lang }).value; highlightedCode.value = hljs.highlight(code, { language: lang }).value;
} catch { } catch {
highlightedCode.value = data[0].code; highlightedCode.value = code;
} }
formApi.setFieldValue('content', data[0].code);
} }
} finally { } finally {
loading.value = false; loading.value = false;
@ -190,22 +188,23 @@ const [Modal, modalApi] = useVbenModal({
<template> <template>
<Modal title="代码预览"> <Modal title="代码预览">
<div class="flex h-[70vh]" v-loading="loading"> <div class="h-1/1 flex" v-loading="loading">
<!-- 文件树 --> <!-- 文件树 -->
<div class="w-1/3 border-r pr-4"> <div class="w-1/3 border-r border-gray-200 pr-4 dark:border-gray-700">
<Tree :selected-keys="[activeKey]" :tree-data="fileTree" @select="handleNodeClick" /> <Tree :selected-keys="[activeKey]" :tree-data="fileTree" @select="handleNodeClick" />
</div> </div>
<!-- 代码预览 --> <!-- 代码预览 -->
<div class="w-2/3 pl-4"> <div class="w-2/3 pl-4">
<div class="mb-2 flex justify-between"> <div class="mb-2 flex justify-between">
<div class="text-lg font-medium">{{ activeKey.split('/').pop() }}</div> <div class="text-lg font-medium dark:text-gray-200">
<a-button type="primary" @click="copyCode"> {{ activeKey.split('/').pop() }}
<CopyOutlined class="mr-1" /> <span class="ml-2 text-xs text-gray-500 dark:text-gray-400">({{ activeLanguage }})</span>
复制代码 </div>
</a-button> <Button type="primary" ghost @click="copyCode" :icon="h(Copy)"> 复制代码 </Button>
</div> </div>
<div class="h-[calc(100%-40px)] overflow-auto"> <div class="h-[calc(100%-40px)] overflow-auto">
<pre><code v-html="highlightedCode" class="hljs"></code></pre> <pre class="overflow-auto rounded-md bg-gray-50 p-4 text-gray-800 dark:bg-gray-800 dark:text-gray-200">
<code v-html="highlightedCode" class="code-highlight"></code></pre>
</div> </div>
</div> </div>
</div> </div>
@ -213,10 +212,94 @@ const [Modal, modalApi] = useVbenModal({
</template> </template>
<style scoped> <style scoped>
.hljs { /* 代码高亮样式 - 支持暗黑模式 */
padding: 16px; :deep(.code-highlight) {
overflow: auto; background: transparent;
background-color: #f8f8f8; }
border-radius: 4px;
/* 关键字 */
:deep(.hljs-keyword) {
@apply text-purple-600 dark:text-purple-400;
}
/* 字符串 */
:deep(.hljs-string) {
@apply text-green-600 dark:text-green-400;
}
/* 注释 */
:deep(.hljs-comment) {
@apply text-gray-500 dark:text-gray-400;
}
/* 函数 */
:deep(.hljs-function) {
@apply text-blue-600 dark:text-blue-400;
}
/* 数字 */
:deep(.hljs-number) {
@apply text-orange-600 dark:text-orange-400;
}
/* 类 */
:deep(.hljs-class) {
@apply text-yellow-600 dark:text-yellow-400;
}
/* 标题/函数名 */
:deep(.hljs-title) {
@apply font-bold text-blue-600 dark:text-blue-400;
}
/* 参数 */
:deep(.hljs-params) {
@apply text-gray-700 dark:text-gray-300;
}
/* 内置对象 */
:deep(.hljs-built_in) {
@apply text-teal-600 dark:text-teal-400;
}
/* HTML标签 */
:deep(.hljs-tag) {
@apply text-blue-600 dark:text-blue-400;
}
/* 属性 */
:deep(.hljs-attribute),
:deep(.hljs-attr) {
@apply text-green-600 dark:text-green-400;
}
/* 字面量 */
:deep(.hljs-literal) {
@apply text-purple-600 dark:text-purple-400;
}
/* 元信息 */
:deep(.hljs-meta) {
@apply text-gray-500 dark:text-gray-400;
}
/* 选择器标签 */
:deep(.hljs-selector-tag) {
@apply text-blue-600 dark:text-blue-400;
}
/* XML/HTML名称 */
:deep(.hljs-name) {
@apply text-blue-600 dark:text-blue-400;
}
/* 变量 */
:deep(.hljs-variable) {
@apply text-orange-600 dark:text-orange-400;
}
/* 属性 */
:deep(.hljs-property) {
@apply text-red-600 dark:text-red-400;
} }
</style> </style>