feat:【ele】【ai】write 的代码迁移

This commit is contained in:
YunaiV
2025-10-26 14:00:30 +08:00
parent 82917f88a5
commit 98d69fbee9
6 changed files with 768 additions and 0 deletions

View File

@@ -0,0 +1,88 @@
<script lang="ts" setup>
import type { AiWriteApi } from '#/api/ai/write';
import { nextTick, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { WriteExample } from '@vben/constants';
import { ElMessage as message } from 'element-plus';
import { writeStream } from '#/api/ai/write';
import Left from './modules/left.vue';
import Right from './modules/right.vue';
const writeResult = ref(''); // 写作结果
const isWriting = ref(false); // 是否正在写作中
const abortController = ref<AbortController>(); // // 写作进行中 abort 控制器(控制 stream 写作)
const rightRef = ref<InstanceType<typeof Right>>(); // 写作面板
/** 停止 stream 生成 */
function handleStopStream() {
abortController.value?.abort();
isWriting.value = false;
}
/** 提交写作 */
function handleSubmit(data: Partial<AiWriteApi.Write>) {
abortController.value = new AbortController();
writeResult.value = '';
isWriting.value = true;
writeStream({
data,
onMessage: async (res: any) => {
const { code, data, msg } = JSON.parse(res.data);
if (code !== 0) {
message.error(`写作异常! ${msg}`);
handleStopStream();
return;
}
writeResult.value = writeResult.value + data;
// 滚动到底部
await nextTick();
rightRef.value?.scrollToBottom();
},
ctrl: abortController.value,
onClose: handleStopStream,
onError: (error: any) => {
console.error('写作异常', error);
handleStopStream();
// 需要抛出异常,禁止重试
throw error;
},
});
}
/** 点击示例触发 */
function handleExampleClick(type: keyof typeof WriteExample) {
writeResult.value = WriteExample[type].data;
}
/** 点击重置的时候清空写作的结果*/
function handleReset() {
writeResult.value = '';
}
</script>
<template>
<Page auto-content-height>
<div class="absolute bottom-0 left-0 right-0 top-0 m-4 flex">
<Left
:is-writing="isWriting"
class="mr-4 h-full rounded-lg"
@submit="handleSubmit"
@reset="handleReset"
@example="handleExampleClick"
/>
<Right
:is-writing="isWriting"
@stop-stream="handleStopStream"
ref="rightRef"
class="flex-grow"
v-model:content="writeResult"
/>
</div>
</Page>
</template>

View File

@@ -0,0 +1,244 @@
<script setup lang="ts">
import type { AiWriteApi } from '#/api/ai/write';
import { ref } from 'vue';
import { AiWriteTypeEnum, DICT_TYPE, WriteExample } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { IconifyIcon } from '@vben/icons';
import { createReusableTemplate } from '@vueuse/core';
import { ElButton as Button, ElMessage as message } from 'element-plus';
import Tag from './tag.vue';
type TabType = AiWriteApi.Write['type'];
defineProps<{
isWriting: boolean;
}>();
const emit = defineEmits<{
(e: 'example', param: 'reply' | 'write'): void;
(e: 'reset'): void;
(e: 'submit', params: Partial<AiWriteApi.Write>): void;
}>();
function omit(obj: Record<string, any>, keysToOmit: string[]) {
const result: Record<string, any> = {};
for (const key in obj) {
if (!keysToOmit.includes(key)) {
result[key] = obj[key];
}
}
return result;
}
/** 点击示例的时候,将定义好的文章作为示例展示出来 */
function example(type: 'reply' | 'write') {
formData.value = {
...initData,
...omit(WriteExample[type], ['data']),
};
emit('example', type);
}
/** 重置,将表单值作为初选值 */
function reset() {
formData.value = { ...initData };
emit('reset');
}
const selectedTab = ref<TabType>(AiWriteTypeEnum.WRITING);
const tabs: {
text: string;
value: TabType;
}[] = [
{ text: '撰写', value: AiWriteTypeEnum.WRITING },
{ text: '回复', value: AiWriteTypeEnum.REPLY },
];
const [DefineTab, ReuseTab] = createReusableTemplate<{
active?: boolean;
itemClick: () => void;
text: string;
}>();
const [DefineLabel, ReuseLabel] = createReusableTemplate<{
class?: string;
hint?: string;
hintClick?: () => void;
label: string;
}>();
const initData: AiWriteApi.Write = {
type: 1,
prompt: '',
originalContent: '',
tone: 1,
language: 1,
length: 1,
format: 1,
};
const formData = ref<AiWriteApi.Write>({ ...initData });
const recordFormData = {} as Record<AiWriteTypeEnum, AiWriteApi.Write>; // 用来记录切换之前所填写的数据,切换的时候给赋值回来
/** 切换 tab */
function handleSwitchTab(value: TabType) {
if (value !== selectedTab.value) {
// 保存之前的久数据
recordFormData[selectedTab.value] = formData.value;
selectedTab.value = value;
// 将之前的旧数据赋值回来
formData.value = { ...initData, ...recordFormData[value] };
}
}
/** 提交写作 */
function handleSubmit() {
if (
selectedTab.value === AiWriteTypeEnum.REPLY &&
!formData.value.originalContent
) {
message.warning('请输入原文');
return;
}
if (!formData.value.prompt) {
message.warning(`请输入${selectedTab.value === 1 ? '写作' : '回复'}内容`);
return;
}
emit('submit', {
// 撰写的时候没有 originalContent 字段
...(selectedTab.value === 1
? omit(formData.value, ['originalContent'])
: formData.value),
// 使用选中 tab 值覆盖当前的 type 类型
type: selectedTab.value,
});
}
</script>
<template>
<DefineTab v-slot="{ active, text, itemClick }">
<span
:class="
active ? 'bg-primary-600 text-white shadow-md' : 'hover:bg-primary-200'
"
class="relative z-10 inline-block w-1/2 cursor-pointer rounded-full text-center leading-7 hover:text-black"
@click="itemClick"
>
{{ text }}
</span>
</DefineTab>
<!-- 定义 label 组件长度/格式/语气/语言等 -->
<DefineLabel v-slot="{ label, hint, hintClick }">
<h3 class="mb-3 mt-5 flex items-center justify-between text-sm">
<span>{{ label }}</span>
<span
v-if="hint"
class="text-primary-500 flex cursor-pointer select-none items-center text-xs"
@click="hintClick"
>
<IconifyIcon icon="lucide:circle-help" />
{{ hint }}
</span>
</h3>
</DefineLabel>
<div class="flex flex-col" v-bind="$attrs">
<div class="bg-card flex w-full justify-center pt-2">
<div class="bg-card z-10 w-72 rounded-full p-1">
<div
:class="
selectedTab === AiWriteTypeEnum.REPLY &&
'after:translate-x-[100%] after:transform'
"
class="after:bg-card relative flex items-center after:absolute after:left-0 after:top-0 after:block after:h-7 after:w-1/2 after:rounded-full after:transition-transform after:content-['']"
>
<ReuseTab
v-for="tab in tabs"
:key="tab.value"
:active="tab.value === selectedTab"
:item-click="() => handleSwitchTab(tab.value)"
:text="tab.text"
class="relative z-20"
/>
</div>
</div>
</div>
<div
class="bg-card box-border h-full w-96 flex-grow overflow-y-auto px-7 pb-2 lg:block"
>
<div>
<template v-if="selectedTab === AiWriteTypeEnum.WRITING">
<ReuseLabel
:hint-click="() => example('write')"
hint="示例"
label="写作内容"
/>
<el-input
v-model="formData.prompt"
type="textarea"
:maxlength="500"
:rows="5"
placeholder="请输入写作内容"
show-word-limit
/>
</template>
<template v-else>
<ReuseLabel
:hint-click="() => example('reply')"
hint="示例"
label="原文"
/>
<el-input
v-model="formData.originalContent"
type="textarea"
:maxlength="500"
:rows="5"
placeholder="请输入原文"
show-word-limit
/>
<ReuseLabel label="回复内容" />
<el-input
v-model="formData.prompt"
type="textarea"
:maxlength="500"
:rows="5"
placeholder="请输入回复内容"
show-word-limit
/>
</template>
<ReuseLabel label="长度" />
<Tag
v-model="formData.length"
:tags="getDictOptions(DICT_TYPE.AI_WRITE_LENGTH, 'number')"
/>
<ReuseLabel label="格式" />
<Tag
v-model="formData.format"
:tags="getDictOptions(DICT_TYPE.AI_WRITE_FORMAT, 'number')"
/>
<ReuseLabel label="语气" />
<Tag
v-model="formData.tone"
:tags="getDictOptions(DICT_TYPE.AI_WRITE_TONE, 'number')"
/>
<ReuseLabel label="语言" />
<Tag
v-model="formData.language"
:tags="getDictOptions(DICT_TYPE.AI_WRITE_LANGUAGE, 'number')"
/>
<div class="mt-3 flex items-center justify-center">
<Button :disabled="isWriting" class="mr-2" @click="reset">
重置
</Button>
<Button type="primary" :loading="isWriting" @click="handleSubmit">
生成
</Button>
</div>
</div>
</div>
</div>
</template>

View File

@@ -0,0 +1,142 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { IconifyIcon } from '@vben/icons';
import { useClipboard } from '@vueuse/core';
import { ElButton as Button, ElCard as Card, ElMessage as message } from 'element-plus';
const props = defineProps({
content: {
type: String,
default: '',
}, // 生成的结果
isWriting: {
type: Boolean,
default: false,
}, // 是否正在生成文章
});
const emits = defineEmits(['update:content', 'stopStream']);
const { copied, copy } = useClipboard();
/** 通过计算属性,双向绑定,更改生成的内容,考虑到用户想要更改生成文章的情况 */
const compContent = computed({
get() {
return props.content;
},
set(val) {
emits('update:content', val);
},
});
/** 滚动 */
const contentRef = ref<HTMLDivElement>();
defineExpose({
scrollToBottom() {
contentRef.value?.scrollTo(0, contentRef.value?.scrollHeight);
},
});
/** 点击复制的时候复制内容 */
const showCopy = computed(() => props.content && !props.isWriting); // 是否展示复制按钮,在生成内容完成的时候展示
function copyContent() {
copy(props.content);
}
/** 复制成功的时候 copied.value 为 true */
watch(copied, (val) => {
if (val) {
message.success('复制成功');
}
});
</script>
<template>
<Card class="flex h-full flex-col">
<template #header>
<h3 class="m-0 flex shrink-0 items-center justify-between px-7">
<span>预览</span>
<Button
type="primary"
v-show="showCopy"
@click="copyContent"
size="small"
>
<IconifyIcon icon="lucide:copy" />
复制
</Button>
</h3>
</template>
<div
ref="contentRef"
class="hide-scroll-bar box-border h-full overflow-y-auto"
>
<div
class="bg-card relative box-border min-h-full w-full flex-grow p-2 sm:p-5"
>
<Button
v-show="isWriting"
class="absolute bottom-1 left-1/2 z-40 flex -translate-x-1/2 sm:bottom-2"
@click="emits('stopStream')"
size="small"
>
<template #icon>
<div class="flex items-center justify-center">
<IconifyIcon icon="lucide:ban" />
</div>
</template>
终止生成
</Button>
<el-input
id="inputId"
v-model="compContent"
type="textarea"
:autosize="{ minRows: 4, maxRows: 25 }"
placeholder="生成的内容……"
/>
</div>
</div>
</Card>
</template>
<style lang="scss" scoped>
// 定义一个 mixin 替代 extend
@mixin hide-scroll-bar {
-ms-overflow-style: none;
scrollbar-width: none;
&::-webkit-scrollbar {
width: 0;
height: 0;
}
}
.hide-scroll-bar {
@include hide-scroll-bar;
}
.my-card {
:deep(.el-card__body) {
box-sizing: border-box;
flex-grow: 1;
padding: 0;
overflow-y: auto;
@include hide-scroll-bar;
}
}
// markmap 的 tool 样式覆盖
:deep(.markmap) {
width: 100%;
}
:deep(.mm-toolbar-brand) {
display: none;
}
:deep(.mm-toolbar) {
display: flex;
flex-direction: row;
}
</style>

View File

@@ -0,0 +1,33 @@
<!-- 标签选项 -->
<script setup lang="ts">
const props = withDefaults(
defineProps<{
[k: string]: any;
modelValue: string;
tags?: { label: string; value: string }[];
}>(),
{
tags: () => [],
},
);
const emits = defineEmits<{
(e: 'update:modelValue', value: string): void;
}>();
</script>
<template>
<div class="flex flex-wrap gap-2">
<span
v-for="tag in props.tags"
:key="tag.value"
class="bg-card border-card-100 mb-2 cursor-pointer rounded border-2 border-solid px-1 text-xs leading-6"
:class="
modelValue === tag.value && '!border-primary-500 !text-primary-500'
"
@click="emits('update:modelValue', tag.value)"
>
{{ tag.label }}
</span>
</div>
</template>

View File

@@ -0,0 +1,171 @@
import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { SystemUserApi } from '#/api/system/user';
import { DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { getSimpleUserList } from '#/api/system/user';
import { getRangePickerDefaultProps } from '#/utils';
/** 关联数据 */
let userList: SystemUserApi.User[] = [];
getSimpleUserList().then((data) => (userList = data));
/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'userId',
label: '用户编号',
component: 'ApiSelect',
componentProps: {
api: getSimpleUserList,
labelField: 'nickname',
valueField: 'id',
placeholder: '请选择用户',
allowClear: true,
},
},
{
fieldName: 'type',
label: '写作类型',
component: 'Select',
componentProps: {
allowClear: true,
placeholder: '请选择写作类型',
options: getDictOptions(DICT_TYPE.AI_WRITE_TYPE, 'number'),
},
},
{
fieldName: 'platform',
label: '平台',
component: 'Select',
componentProps: {
allowClear: true,
placeholder: '请选择平台',
options: getDictOptions(DICT_TYPE.AI_PLATFORM, 'string'),
},
},
{
fieldName: 'createTime',
label: '创建时间',
component: 'RangePicker',
componentProps: {
...getRangePickerDefaultProps(),
allowClear: true,
},
},
];
}
/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions['columns'] {
return [
{
field: 'id',
title: '编号',
minWidth: 180,
fixed: 'left',
},
{
minWidth: 180,
title: '用户',
field: 'userId',
formatter: ({ cellValue }) => {
return userList.find((user) => user.id === cellValue)?.nickname || '-';
},
},
{
field: 'type',
title: '写作类型',
minWidth: 120,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.AI_WRITE_TYPE },
},
},
{
field: 'platform',
title: '平台',
minWidth: 120,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.AI_WRITE_TYPE },
},
},
{
field: 'model',
title: '模型',
minWidth: 180,
},
{
field: 'prompt',
title: '生成内容提示',
minWidth: 180,
},
{
field: 'generatedContent',
title: '生成的内容',
minWidth: 180,
},
{
field: 'originalContent',
title: '原文',
minWidth: 180,
},
{
field: 'length',
title: '长度',
minWidth: 120,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.AI_WRITE_LENGTH },
},
},
{
field: 'format',
title: '格式',
minWidth: 120,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.AI_WRITE_FORMAT },
},
},
{
field: 'tone',
title: '语气',
minWidth: 120,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.AI_WRITE_TONE },
},
},
{
field: 'language',
title: '语言',
minWidth: 120,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.AI_WRITE_LANGUAGE },
},
},
{
field: 'createTime',
title: '创建时间',
minWidth: 180,
formatter: 'formatDateTime',
},
{
field: 'errorMessage',
title: '错误信息',
minWidth: 180,
},
{
title: '操作',
width: 130,
fixed: 'right',
slots: { default: 'actions' },
},
];
}

View File

@@ -0,0 +1,90 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { AiWriteApi } from '#/api/ai/write';
import { DocAlert, Page } from '@vben/common-ui';
import { ElMessage as message } from 'element-plus';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteWrite, getWritePage } from '#/api/ai/write';
import { $t } from '#/locales';
import { useGridColumns, useGridFormSchema } from './data';
/** 刷新表格 */
function handleRefresh() {
gridApi.query();
}
/** 删除 */
async function handleDelete(row: AiWriteApi.AiWritePageReq) {
const hideLoading = message.loading({
message: $t('ui.actionMessage.deleting', [row.id]),
duration: 0,
});
try {
await deleteWrite(row.id as number);
message.success($t('ui.actionMessage.deleteSuccess', [row.id]));
handleRefresh();
} finally {
hideLoading();
}
}
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useGridFormSchema(),
},
gridOptions: {
columns: useGridColumns(),
height: 'auto',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await getWritePage({
pageNo: page.currentPage,
pageSize: page.pageSize,
...formValues,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<AiWriteApi.AiWritePageReq>,
});
</script>
<template>
<Page auto-content-height>
<template #doc>
<DocAlert title="AI 写作助手" url="https://doc.iocoder.cn/ai/write/" />
</template>
<Grid table-title="写作管理列表">
<template #actions="{ row }">
<TableAction
:actions="[
{
label: $t('common.delete'),
type: 'danger',
link: true,
icon: ACTION_ICON.DELETE,
auth: ['ai:write:delete'],
popConfirm: {
title: $t('ui.actionMessage.deleteConfirm', [row.id]),
confirm: handleDelete.bind(null, row),
},
},
]"
/>
</template>
</Grid>
</Page>
</template>