fix: Enhance Kol Variable Rendering and Management
- Updated the regex for placeholder matching to support more flexible key formats. - Refactored variable storage to allow both ID and key lookups in rendering. - Improved schema validation to check for duplicate keys and enforce non-empty keys. - Added new utility functions for variable value lookup and display name generation. - Enhanced tests to cover new key-based variable scenarios. - Refactored KolPrompt repository to simplify prompt storage and management, including the removal of obsolete revision handling. - Introduced new API endpoints for saving, activating, and archiving prompts. - Added new utility functions for handling Kol placeholders and platform options in the admin web. - Implemented database migrations to simplify prompt storage structure and ensure data integrity.
This commit is contained in:
@@ -52,8 +52,16 @@ import { callCommand, replaceAll } from "@milkdown/kit/utils";
|
||||
import { Crepe, CrepeFeature } from "@milkdown/crepe";
|
||||
import "@milkdown/crepe/theme/common/style.css";
|
||||
import "@milkdown/crepe/theme/frame.css";
|
||||
import { Milkdown, useEditor, useInstance } from "@milkdown/vue";
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue";
|
||||
import {
|
||||
computed,
|
||||
nextTick,
|
||||
onBeforeUnmount,
|
||||
onMounted,
|
||||
ref,
|
||||
shallowRef,
|
||||
watch,
|
||||
type ComponentPublicInstance,
|
||||
} from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
|
||||
import EditorActionMenu from "@/components/editor-common/EditorActionMenu.vue";
|
||||
@@ -88,8 +96,11 @@ const emit = defineEmits<{
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const crepeRef = ref<Crepe | null>(null);
|
||||
const crepeRef = shallowRef<Crepe | null>(null);
|
||||
const syncingExternalMarkdown = ref(false);
|
||||
const editorRootRef = ref<HTMLElement | null>(null);
|
||||
const editorRef = shallowRef<MilkdownEditorInstance | null>(null);
|
||||
const loading = ref(true);
|
||||
const surfaceRef = ref<HTMLElement | null>(null);
|
||||
const tablePickerRef = ref<HTMLElement | null>(null);
|
||||
|
||||
@@ -197,6 +208,8 @@ type SelectedImageSnapshot = {
|
||||
align: RichImageAlign;
|
||||
};
|
||||
|
||||
type MilkdownEditorInstance = Awaited<ReturnType<Crepe["create"]>>;
|
||||
|
||||
function createDefaultTableContextMenuState(): TableContextMenuState {
|
||||
return {
|
||||
open: false,
|
||||
@@ -248,7 +261,7 @@ function createDefaultAiOptimizePanelState(): AiOptimizePanelState {
|
||||
};
|
||||
}
|
||||
|
||||
const { loading } = useEditor((root) => {
|
||||
function createCrepe(root: HTMLElement): Crepe {
|
||||
const crepe = new Crepe({
|
||||
root,
|
||||
defaultValue: props.modelValue || "",
|
||||
@@ -298,10 +311,13 @@ const { loading } = useEditor((root) => {
|
||||
|
||||
crepeRef.value = crepe;
|
||||
return crepe;
|
||||
});
|
||||
}
|
||||
|
||||
const [instanceLoading, getEditor] = useInstance();
|
||||
const editorDisabled = computed(() => props.disabled || instanceLoading.value || loading.value);
|
||||
function getEditor(): MilkdownEditorInstance | null {
|
||||
return editorRef.value;
|
||||
}
|
||||
|
||||
const editorDisabled = computed(() => props.disabled || loading.value);
|
||||
const tablePickerOpen = ref(false);
|
||||
const imagePickerOpen = ref(false);
|
||||
const imagePickerAction = ref<ImagePickerAction>("insert");
|
||||
@@ -528,9 +544,9 @@ watch(
|
||||
);
|
||||
|
||||
watch(
|
||||
[() => props.modelValue, loading, instanceLoading],
|
||||
([value, editorLoading, currentInstanceLoading]) => {
|
||||
if (editorLoading || currentInstanceLoading) {
|
||||
[() => props.modelValue, loading],
|
||||
([value, editorLoading]) => {
|
||||
if (editorLoading) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -539,6 +555,26 @@ watch(
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
async function mountEditor(): Promise<void> {
|
||||
const root = editorRootRef.value;
|
||||
if (!root || crepeRef.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
loading.value = true;
|
||||
|
||||
const crepe = createCrepe(root);
|
||||
|
||||
try {
|
||||
editorRef.value = await crepe.create();
|
||||
} catch (error) {
|
||||
crepeRef.value = null;
|
||||
console.error(error);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
stopAiOptimizeGeneration();
|
||||
if (selectedImageSyncFrame) {
|
||||
@@ -549,6 +585,8 @@ onBeforeUnmount(() => {
|
||||
window.removeEventListener("pointerdown", handleWindowPointerDown);
|
||||
window.removeEventListener("resize", handleWindowResize);
|
||||
window.removeEventListener("keydown", handleWindowKeydown);
|
||||
editorRef.value = null;
|
||||
void crepeRef.value?.destroy().catch(console.error);
|
||||
crepeRef.value = null;
|
||||
});
|
||||
|
||||
@@ -556,6 +594,7 @@ onMounted(() => {
|
||||
window.addEventListener("pointerdown", handleWindowPointerDown);
|
||||
window.addEventListener("resize", handleWindowResize);
|
||||
window.addEventListener("keydown", handleWindowKeydown);
|
||||
void mountEditor();
|
||||
});
|
||||
|
||||
function runCommand(command: { key: unknown }, payload?: unknown): void {
|
||||
@@ -680,6 +719,18 @@ function closeTablePicker(): void {
|
||||
tablePickerOpen.value = false;
|
||||
}
|
||||
|
||||
function assignTablePickerRef(element: Element | ComponentPublicInstance | null): void {
|
||||
tablePickerRef.value = element instanceof HTMLElement ? element : null;
|
||||
}
|
||||
|
||||
function assignSurfaceRef(element: Element | ComponentPublicInstance | null): void {
|
||||
surfaceRef.value = element instanceof HTMLElement ? element : null;
|
||||
}
|
||||
|
||||
function assignEditorRootRef(element: Element | ComponentPublicInstance | null): void {
|
||||
editorRootRef.value = element instanceof HTMLElement ? element : null;
|
||||
}
|
||||
|
||||
function closeTableContextMenu(): void {
|
||||
tableContextMenu.value = createDefaultTableContextMenuState();
|
||||
}
|
||||
@@ -1830,7 +1881,7 @@ function runTableContextAction(action: TableContextMenuAction): void {
|
||||
<template #icon><OrderedListOutlined /></template>
|
||||
</a-button>
|
||||
|
||||
<div ref="tablePickerRef" class="article-editor-canvas__table-trigger">
|
||||
<div :ref="assignTablePickerRef" class="article-editor-canvas__table-trigger">
|
||||
<a-button
|
||||
size="small"
|
||||
type="text"
|
||||
@@ -1861,7 +1912,7 @@ function runTableContextAction(action: TableContextMenuAction): void {
|
||||
</div>
|
||||
|
||||
<div
|
||||
ref="surfaceRef"
|
||||
:ref="assignSurfaceRef"
|
||||
class="article-editor-canvas__surface"
|
||||
@contextmenu.capture="handleEditorContextMenu"
|
||||
@dragstart.capture="handleEditorDragStart"
|
||||
@@ -1881,7 +1932,7 @@ function runTableContextAction(action: TableContextMenuAction): void {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Milkdown />
|
||||
<div :ref="assignEditorRootRef" data-milkdown-root></div>
|
||||
|
||||
<EditorSelectionFrame
|
||||
v-if="selectedImage.open"
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useQuery } from "@tanstack/vue-query";
|
||||
import { computed, ref, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { imagesApi } from "@/lib/api";
|
||||
import { formatBytes } from "@/lib/display";
|
||||
import { formatBytes, formatPercentage } from "@/lib/display";
|
||||
import type { ImageAssetItem } from "@geo/shared-types";
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
@@ -139,7 +139,7 @@ function getSelectPopupContainer(triggerNode: HTMLElement) {
|
||||
<span>{{ t("images.storageUsage") }}: {{ t("images.storageUsageDetail", {
|
||||
used: formatBytes(storageUsage.used_bytes),
|
||||
total: formatBytes(storageUsage.quota_bytes),
|
||||
percent: storageUsage.used_pct
|
||||
percent: formatPercentage(storageUsage.used_pct)
|
||||
}) }}</span>
|
||||
</div>
|
||||
<a-progress
|
||||
|
||||
@@ -25,8 +25,12 @@ function updateField(key: string, value: any) {
|
||||
}
|
||||
|
||||
const selectOptions = (variable: KolVariableDefinition) => {
|
||||
return (variable.options || []).map(opt => ({ label: opt, value: opt }));
|
||||
return (variable.options || []).map((opt) => ({ label: opt, value: opt }));
|
||||
};
|
||||
|
||||
function fieldKey(variable: KolVariableDefinition): string {
|
||||
return variable.key?.trim() || variable.id;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -39,44 +43,44 @@ const selectOptions = (variable: KolVariableDefinition) => {
|
||||
>
|
||||
<template v-if="variable.type === 'input'">
|
||||
<a-input
|
||||
:value="modelValue[variable.key]"
|
||||
:value="modelValue[fieldKey(variable)]"
|
||||
:placeholder="variable.placeholder || t('common.inputPlease')"
|
||||
@update:value="(val: string) => updateField(variable.key, val)"
|
||||
@update:value="(val: string) => updateField(fieldKey(variable), val)"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<template v-else-if="variable.type === 'textarea'">
|
||||
<a-textarea
|
||||
:value="modelValue[variable.key]"
|
||||
:value="modelValue[fieldKey(variable)]"
|
||||
:placeholder="variable.placeholder || t('common.inputPlease')"
|
||||
:rows="4"
|
||||
@update:value="(val: string) => updateField(variable.key, val)"
|
||||
@update:value="(val: string) => updateField(fieldKey(variable), val)"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<template v-else-if="variable.type === 'select'">
|
||||
<a-select
|
||||
:value="modelValue[variable.key]"
|
||||
:value="modelValue[fieldKey(variable)]"
|
||||
:placeholder="variable.placeholder || t('common.selectPlease')"
|
||||
:options="selectOptions(variable)"
|
||||
@update:value="(val: string) => updateField(variable.key, val)"
|
||||
@update:value="(val: string) => updateField(fieldKey(variable), val)"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<template v-else-if="variable.type === 'number'">
|
||||
<a-input-number
|
||||
:value="modelValue[variable.key]"
|
||||
:value="modelValue[fieldKey(variable)]"
|
||||
:placeholder="variable.placeholder"
|
||||
style="width: 100%"
|
||||
@update:value="(val: number) => updateField(variable.key, val)"
|
||||
@update:value="(val: number) => updateField(fieldKey(variable), val)"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<template v-else-if="variable.type === 'checkbox'">
|
||||
<a-checkbox-group
|
||||
:value="modelValue[variable.key] || []"
|
||||
:value="modelValue[fieldKey(variable)] || []"
|
||||
:options="selectOptions(variable)"
|
||||
@update:value="(val: string[]) => updateField(variable.key, val)"
|
||||
@update:value="(val: string[]) => updateField(fieldKey(variable), val)"
|
||||
/>
|
||||
</template>
|
||||
</a-form-item>
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue";
|
||||
import { computed, h, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { ExperimentOutlined, ThunderboltOutlined, LoadingOutlined } from "@ant-design/icons-vue";
|
||||
import type { KolVariableDefinition, KolVariableType } from "@geo/shared-types";
|
||||
import { newVariableId } from "@/lib/kol-variable-id";
|
||||
import { Modal } from "ant-design-vue";
|
||||
|
||||
import {
|
||||
buildKolPlaceholderToken,
|
||||
createKolVariableDefinition,
|
||||
findKolPlaceholderKeyAtPosition,
|
||||
} from "@/lib/kol-placeholders";
|
||||
|
||||
const props = defineProps<{
|
||||
content: string;
|
||||
variables: KolVariableDefinition[];
|
||||
@@ -17,17 +22,46 @@ const emit = defineEmits<{
|
||||
(e: "update:variables", value: KolVariableDefinition[]): void;
|
||||
(e: "ai-generate", description: string): void;
|
||||
(e: "ai-optimize"): void;
|
||||
(e: "focus-variable", key: string): void;
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const aiDescription = ref("");
|
||||
const textareaRef = ref<HTMLTextAreaElement | null>(null);
|
||||
const highlightRef = ref<HTMLDivElement | null>(null);
|
||||
|
||||
const editorPlaceholder = "在这里输入提示词内容,可以使用 {{变量名}} 引用左侧定义的变量";
|
||||
const highlightTokenRE = /\{\{\s*([^{}]+?)\s*\}\}/g;
|
||||
|
||||
const highlightedContent = computed(() => {
|
||||
const text = props.content ?? "";
|
||||
if (!text) {
|
||||
return `<span class="editor-placeholder">${escapeHtml(editorPlaceholder)}</span>`;
|
||||
}
|
||||
|
||||
let html = "";
|
||||
let lastIndex = 0;
|
||||
|
||||
for (const match of text.matchAll(highlightTokenRE)) {
|
||||
const matchIndex = match.index ?? 0;
|
||||
const token = match[0] ?? "";
|
||||
|
||||
html += escapeHtml(text.slice(lastIndex, matchIndex));
|
||||
html += `<span class="token-highlight">${escapeHtml(token)}</span>`;
|
||||
lastIndex = matchIndex + token.length;
|
||||
}
|
||||
|
||||
html += escapeHtml(text.slice(lastIndex));
|
||||
return html;
|
||||
});
|
||||
|
||||
function onDrop(event: DragEvent) {
|
||||
event.preventDefault();
|
||||
const type = event.dataTransfer?.getData("application/kol-variable-type") as KolVariableType;
|
||||
if (!type) return;
|
||||
|
||||
const labelValue = ref("");
|
||||
|
||||
Modal.confirm({
|
||||
title: t("kol.manage.variable.label"),
|
||||
content: () => {
|
||||
@@ -35,34 +69,29 @@ function onDrop(event: DragEvent) {
|
||||
h("input", {
|
||||
class: "ant-input",
|
||||
placeholder: t("common.inputPlease"),
|
||||
value: labelValue.value,
|
||||
onInput: (e: Event) => {
|
||||
(Modal.confirm as any).labelValue = (e.target as HTMLInputElement).value;
|
||||
labelValue.value = (e.target as HTMLInputElement).value;
|
||||
},
|
||||
}),
|
||||
]);
|
||||
},
|
||||
onOk: () => {
|
||||
const label = (Modal.confirm as any).labelValue || t(`kol.manage.variable.${type}`);
|
||||
const id = newVariableId();
|
||||
const key = label;
|
||||
|
||||
const newVar: KolVariableDefinition = {
|
||||
id,
|
||||
key,
|
||||
label,
|
||||
type,
|
||||
required: true,
|
||||
};
|
||||
const key = labelValue.value.trim() || t(`kol.manage.variable.${type}`);
|
||||
const existingVariable = props.variables.find((variable) => variable.key === key);
|
||||
|
||||
emit("update:variables", [...props.variables, newVar]);
|
||||
insertToken(`{{${key}}}`);
|
||||
if (!existingVariable) {
|
||||
const newVar: KolVariableDefinition = createKolVariableDefinition(key, {
|
||||
type,
|
||||
});
|
||||
emit("update:variables", [...props.variables, newVar]);
|
||||
}
|
||||
|
||||
insertToken(buildKolPlaceholderToken(key));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Helper to use 'h' since we are in script setup
|
||||
import { h } from "vue";
|
||||
|
||||
function insertToken(token: string) {
|
||||
if (!textareaRef.value) return;
|
||||
|
||||
@@ -78,6 +107,7 @@ function insertToken(token: string) {
|
||||
setTimeout(() => {
|
||||
el.focus();
|
||||
el.setSelectionRange(start + token.length, start + token.length);
|
||||
syncScroll();
|
||||
}, 0);
|
||||
}
|
||||
|
||||
@@ -85,6 +115,45 @@ function handleAiGenerate() {
|
||||
if (!aiDescription.value.trim()) return;
|
||||
emit("ai-generate", aiDescription.value);
|
||||
}
|
||||
|
||||
function handleContentInput(event: Event) {
|
||||
emit("update:content", (event.target as HTMLTextAreaElement).value);
|
||||
syncScroll();
|
||||
}
|
||||
|
||||
function handleCaretInteraction() {
|
||||
if (!textareaRef.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
const textarea = textareaRef.value;
|
||||
if (!textarea) {
|
||||
return;
|
||||
}
|
||||
|
||||
const key = findKolPlaceholderKeyAtPosition(props.content, textarea.selectionStart ?? -1);
|
||||
if (key) {
|
||||
emit("focus-variable", key);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function syncScroll() {
|
||||
if (!textareaRef.value || !highlightRef.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
highlightRef.value.scrollTop = textareaRef.value.scrollTop;
|
||||
highlightRef.value.scrollLeft = textareaRef.value.scrollLeft;
|
||||
}
|
||||
|
||||
function escapeHtml(value: string): string {
|
||||
return value
|
||||
.replaceAll("&", "&")
|
||||
.replaceAll("<", "<")
|
||||
.replaceAll(">", ">");
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -126,12 +195,21 @@ function handleAiGenerate() {
|
||||
<span>AI 正在思考中...</span>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
ref="highlightRef"
|
||||
class="prompt-highlight"
|
||||
aria-hidden="true"
|
||||
v-html="highlightedContent"
|
||||
></div>
|
||||
<textarea
|
||||
ref="textareaRef"
|
||||
class="prompt-textarea"
|
||||
:value="content"
|
||||
@input="e => emit('update:content', (e.target as HTMLTextAreaElement).value)"
|
||||
placeholder="在这里输入提示词内容,可以使用 {{变量名}} 引用左侧定义的变量"
|
||||
:placeholder="editorPlaceholder"
|
||||
@input="handleContentInput"
|
||||
@mouseup="handleCaretInteraction"
|
||||
@keyup="handleCaretInteraction"
|
||||
@scroll="syncScroll"
|
||||
></textarea>
|
||||
</div>
|
||||
</div>
|
||||
@@ -166,21 +244,50 @@ function handleAiGenerate() {
|
||||
flex: 1;
|
||||
position: relative;
|
||||
display: flex;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.prompt-highlight {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
overflow: auto;
|
||||
padding: 24px;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
font-family: inherit;
|
||||
font-size: 16px;
|
||||
line-height: 1.6;
|
||||
color: #262626;
|
||||
pointer-events: none;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.prompt-textarea {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
flex: 1;
|
||||
border: none;
|
||||
resize: none;
|
||||
padding: 24px;
|
||||
background: transparent;
|
||||
font-family: inherit;
|
||||
font-size: 16px;
|
||||
line-height: 1.6;
|
||||
outline: none;
|
||||
color: #262626;
|
||||
color: transparent;
|
||||
caret-color: #262626;
|
||||
}
|
||||
|
||||
.prompt-textarea::placeholder {
|
||||
color: transparent;
|
||||
}
|
||||
|
||||
.prompt-highlight :deep(.token-highlight) {
|
||||
color: #eb2f96;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.prompt-highlight :deep(.editor-placeholder) {
|
||||
color: #bfbfbf;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,22 +1,28 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from "vue";
|
||||
import { computed, nextTick, reactive, ref, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/vue-query";
|
||||
import { message } from "ant-design-vue";
|
||||
import { SaveOutlined, SendOutlined, EyeOutlined } from "@ant-design/icons-vue";
|
||||
import { LeftOutlined, SaveOutlined, SendOutlined, EyeOutlined } from "@ant-design/icons-vue";
|
||||
|
||||
import KolVariablePanel from "./KolVariablePanel.vue";
|
||||
import KolVariableConfig from "./KolVariableConfig.vue";
|
||||
import KolPromptEditArea from "./KolPromptEditArea.vue";
|
||||
import KolDynamicForm from "./KolDynamicForm.vue";
|
||||
import { kolManageApi } from "@/lib/api";
|
||||
import type { KolVariableDefinition, KolSchemaJson } from "@geo/shared-types";
|
||||
import type { KolVariableDefinition } from "@geo/shared-types";
|
||||
import { formatError } from "@/lib/errors";
|
||||
import { buildKolPlatformOptions } from "@/lib/kol-platform-options";
|
||||
import { syncKolVariablesWithContent } from "@/lib/kol-placeholders";
|
||||
|
||||
const props = defineProps<{
|
||||
promptId: number;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
back: [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
@@ -25,16 +31,32 @@ const variables = ref<KolVariableDefinition[]>([]);
|
||||
const previewOpen = ref(false);
|
||||
const previewValues = ref<Record<string, any>>({});
|
||||
const aiTaskId = ref<string | null>(null);
|
||||
const variableConfigRef = ref<{ focusVariable: (key: string) => void } | null>(null);
|
||||
const metadataForm = reactive({
|
||||
name: "",
|
||||
platform_hint: "通用",
|
||||
});
|
||||
|
||||
const { data: promptDetail, isPending } = useQuery({
|
||||
const { data: promptDetail } = useQuery({
|
||||
queryKey: computed(() => ["kol", "prompt", props.promptId]),
|
||||
queryFn: () => kolManageApi.getPrompt(props.promptId),
|
||||
});
|
||||
|
||||
const platformOptions = computed(() => {
|
||||
const options = buildKolPlatformOptions(t("kol.manage.platformHintDefault"));
|
||||
const currentValue = metadataForm.platform_hint.trim();
|
||||
if (currentValue && !options.some((option) => option.value === currentValue)) {
|
||||
return [{ label: currentValue, value: currentValue }, ...options];
|
||||
}
|
||||
return options;
|
||||
});
|
||||
|
||||
watch(
|
||||
() => promptDetail.value,
|
||||
(detail) => {
|
||||
if (detail) {
|
||||
metadataForm.name = detail.name;
|
||||
metadataForm.platform_hint = detail.platform_hint || "通用";
|
||||
content.value = detail.latest_prompt_content ?? "";
|
||||
variables.value = detail.latest_schema_json?.variables ?? [];
|
||||
}
|
||||
@@ -42,27 +64,24 @@ watch(
|
||||
{ immediate: true }
|
||||
);
|
||||
|
||||
const saveDraftMutation = useMutation({
|
||||
mutationFn: (data: { content: string; variables: KolVariableDefinition[] }) =>
|
||||
kolManageApi.saveDraft(props.promptId, {
|
||||
content: data.content,
|
||||
schema: { variables: data.variables },
|
||||
card_config: {},
|
||||
}),
|
||||
const publishMutation = useMutation({
|
||||
mutationFn: (payload: ReturnType<typeof buildPromptPayload>) =>
|
||||
kolManageApi.publishPrompt(props.promptId, payload),
|
||||
onSuccess: () => {
|
||||
message.success(t("common.save") + "成功");
|
||||
queryClient.invalidateQueries({ queryKey: ["kol", "prompt", props.promptId] });
|
||||
message.success(t("kol.manage.editor.publish") + "成功");
|
||||
invalidatePromptQueries();
|
||||
},
|
||||
onError: (error) => {
|
||||
message.error(formatError(error));
|
||||
},
|
||||
});
|
||||
|
||||
const publishMutation = useMutation({
|
||||
mutationFn: () => kolManageApi.publishPrompt(props.promptId),
|
||||
const saveMutation = useMutation({
|
||||
mutationFn: (payload: ReturnType<typeof buildPromptPayload>) =>
|
||||
kolManageApi.savePrompt(props.promptId, payload),
|
||||
onSuccess: () => {
|
||||
message.success(t("kol.manage.editor.publish") + "成功");
|
||||
queryClient.invalidateQueries({ queryKey: ["kol", "prompt", props.promptId] });
|
||||
message.success(t("common.save") + "成功");
|
||||
invalidatePromptQueries();
|
||||
},
|
||||
onError: (error) => {
|
||||
message.error(formatError(error));
|
||||
@@ -84,7 +103,7 @@ watch(
|
||||
(task) => {
|
||||
if (task?.status === "completed" && task.result) {
|
||||
content.value = task.result.content;
|
||||
variables.value = task.result.schema.variables;
|
||||
variables.value = syncKolVariablesWithContent(task.result.content, task.result.schema.variables);
|
||||
aiTaskId.value = null;
|
||||
message.success("AI 处理完成");
|
||||
} else if (task?.status === "failed") {
|
||||
@@ -109,10 +128,11 @@ async function handleAiGenerate(description: string) {
|
||||
|
||||
async function handleAiOptimize() {
|
||||
try {
|
||||
const syncedVariables = syncVariablesFromContent();
|
||||
const res = await kolManageApi.submitAssist({
|
||||
mode: "optimize",
|
||||
current_content: content.value,
|
||||
schema: { variables: variables.value },
|
||||
schema: { variables: syncedVariables },
|
||||
prompt_id: props.promptId,
|
||||
});
|
||||
aiTaskId.value = res.task_id;
|
||||
@@ -121,34 +141,126 @@ async function handleAiOptimize() {
|
||||
}
|
||||
}
|
||||
|
||||
function buildPromptPayload(nextVariables: KolVariableDefinition[] = variables.value) {
|
||||
return {
|
||||
name: metadataForm.name.trim(),
|
||||
platform_hint: metadataForm.platform_hint,
|
||||
sort_order: promptDetail.value?.sort_order,
|
||||
content: content.value,
|
||||
schema: { variables: nextVariables },
|
||||
card_config: {},
|
||||
};
|
||||
}
|
||||
|
||||
function syncVariablesFromContent(): KolVariableDefinition[] {
|
||||
const syncedVariables = syncKolVariablesWithContent(content.value, variables.value);
|
||||
variables.value = syncedVariables;
|
||||
return syncedVariables;
|
||||
}
|
||||
|
||||
function buildPreviewValues(nextVariables: KolVariableDefinition[]): Record<string, any> {
|
||||
const nextValues: Record<string, any> = {};
|
||||
|
||||
nextVariables.forEach((variable) => {
|
||||
const fieldKey = variable.key?.trim() || variable.id;
|
||||
nextValues[fieldKey] = variable.type === "checkbox" ? [] : undefined;
|
||||
});
|
||||
|
||||
return nextValues;
|
||||
}
|
||||
|
||||
function invalidatePromptQueries() {
|
||||
void queryClient.invalidateQueries({ queryKey: ["kol", "prompt", props.promptId] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["kol", "packages"] });
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: ["kol", "packages", promptDetail.value?.package_id, "prompts"],
|
||||
});
|
||||
}
|
||||
|
||||
function validateBeforeSubmit(): boolean {
|
||||
if (!metadataForm.name.trim()) {
|
||||
message.warning(t("common.inputPlease") + t("common.title"));
|
||||
return false;
|
||||
}
|
||||
if (!content.value.trim()) {
|
||||
message.warning("请输入提示词内容");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleSave() {
|
||||
saveDraftMutation.mutate({ content: content.value, variables: variables.value });
|
||||
const syncedVariables = syncVariablesFromContent();
|
||||
if (!validateBeforeSubmit()) {
|
||||
return;
|
||||
}
|
||||
saveMutation.mutate(buildPromptPayload(syncedVariables));
|
||||
}
|
||||
|
||||
function handlePublish() {
|
||||
publishMutation.mutate();
|
||||
const syncedVariables = syncVariablesFromContent();
|
||||
if (!validateBeforeSubmit()) {
|
||||
return;
|
||||
}
|
||||
publishMutation.mutate(buildPromptPayload(syncedVariables));
|
||||
}
|
||||
|
||||
function handlePreview() {
|
||||
previewValues.value = {};
|
||||
const syncedVariables = syncVariablesFromContent();
|
||||
previewValues.value = buildPreviewValues(syncedVariables);
|
||||
previewOpen.value = true;
|
||||
}
|
||||
|
||||
async function handleFocusVariable(key: string) {
|
||||
syncVariablesFromContent();
|
||||
await nextTick();
|
||||
variableConfigRef.value?.focusVariable(key);
|
||||
}
|
||||
|
||||
function getSelectPopupContainer(triggerNode: HTMLElement) {
|
||||
return triggerNode.parentElement ?? triggerNode;
|
||||
}
|
||||
|
||||
function statusTagColor(status?: string): string {
|
||||
if (status === "active") return "green";
|
||||
if (status === "archived") return "orange";
|
||||
return "default";
|
||||
}
|
||||
|
||||
function statusLabel(status?: string): string {
|
||||
if (status === "active") return t("kol.manage.status.active");
|
||||
if (status === "archived") return t("kol.manage.status.archived");
|
||||
return t("kol.manage.status.draft");
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="kol-prompt-editor">
|
||||
<div class="editor-topbar">
|
||||
<button class="back-btn" type="button" @click="emit('back')">
|
||||
<LeftOutlined />
|
||||
<span>{{ t("common.back") }}</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="editor-header">
|
||||
<div class="header-title">
|
||||
<span class="prompt-name">{{ promptDetail?.name || 'Loading...' }}</span>
|
||||
<div class="title-row">
|
||||
<span class="prompt-name">{{ metadataForm.name || promptDetail?.name || t("common.loading") }}</span>
|
||||
<a-tag v-if="promptDetail" :color="statusTagColor(promptDetail.status)">
|
||||
{{ statusLabel(promptDetail.status) }}
|
||||
</a-tag>
|
||||
</div>
|
||||
<span class="prompt-subtitle">{{ t("kol.manage.editor.basicInfo") }}</span>
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<a-button @click="handlePreview">
|
||||
<template #icon><EyeOutlined /></template>
|
||||
{{ t('kol.manage.editor.preview') }}
|
||||
</a-button>
|
||||
<a-button :loading="saveDraftMutation.isPending.value" @click="handleSave">
|
||||
<a-button :loading="saveMutation.isPending.value" @click="handleSave">
|
||||
<template #icon><SaveOutlined /></template>
|
||||
{{ t('kol.manage.editor.saveDraft') }}
|
||||
{{ t('common.save') }}
|
||||
</a-button>
|
||||
<a-button type="primary" :loading="publishMutation.isPending.value" @click="handlePublish">
|
||||
<template #icon><SendOutlined /></template>
|
||||
@@ -157,6 +269,28 @@ function handlePreview() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="editor-meta-card">
|
||||
<div class="editor-section-title">{{ t("kol.manage.editor.basicInfo") }}</div>
|
||||
<a-form layout="vertical" class="editor-meta-form">
|
||||
<a-form-item :label="t('common.title')" required>
|
||||
<a-input
|
||||
v-model:value="metadataForm.name"
|
||||
:placeholder="t('common.inputPlease') + t('common.title')"
|
||||
/>
|
||||
</a-form-item>
|
||||
|
||||
<a-form-item :label="t('kol.manage.platformHint')">
|
||||
<a-select
|
||||
v-model:value="metadataForm.platform_hint"
|
||||
:options="platformOptions"
|
||||
option-filter-prop="label"
|
||||
show-search
|
||||
:get-popup-container="getSelectPopupContainer"
|
||||
/>
|
||||
</a-form-item>
|
||||
</a-form>
|
||||
</div>
|
||||
|
||||
<div class="editor-body">
|
||||
<KolVariablePanel />
|
||||
<KolPromptEditArea
|
||||
@@ -165,8 +299,12 @@ function handlePreview() {
|
||||
:ai-task-id="aiTaskId"
|
||||
@ai-generate="handleAiGenerate"
|
||||
@ai-optimize="handleAiOptimize"
|
||||
@focus-variable="handleFocusVariable"
|
||||
/>
|
||||
<KolVariableConfig
|
||||
ref="variableConfigRef"
|
||||
v-model:variables="variables"
|
||||
/>
|
||||
<KolVariableConfig v-model:variables="variables" />
|
||||
</div>
|
||||
|
||||
<a-modal
|
||||
@@ -190,30 +328,133 @@ function handlePreview() {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.editor-topbar {
|
||||
padding: 12px 16px;
|
||||
}
|
||||
|
||||
.back-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: #111827;
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.back-btn :deep(.anticon) {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 999px;
|
||||
background: rgba(255, 255, 255, 0.82);
|
||||
border: 1px solid rgba(144, 157, 181, 0.24);
|
||||
}
|
||||
|
||||
.editor-header {
|
||||
height: 56px;
|
||||
padding: 0 16px;
|
||||
border-bottom: 1px solid #f0f0f0;
|
||||
margin: 0 16px;
|
||||
padding: 16px 20px;
|
||||
border: 1px solid #f0f0f0;
|
||||
border-radius: 16px;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.header-title {
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.title-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.prompt-name {
|
||||
font-size: 16px;
|
||||
font-weight: 500;
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
color: #111827;
|
||||
}
|
||||
|
||||
.prompt-subtitle {
|
||||
font-size: 13px;
|
||||
color: #667085;
|
||||
}
|
||||
|
||||
.header-actions {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.editor-meta-card {
|
||||
margin: 12px 16px 0;
|
||||
padding: 16px 20px 4px;
|
||||
border: 1px solid #f0f0f0;
|
||||
border-radius: 16px;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.editor-section-title {
|
||||
margin: 0 0 16px;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: #111827;
|
||||
}
|
||||
|
||||
.editor-meta-form {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(240px, 1.4fr) minmax(200px, 1fr);
|
||||
gap: 16px;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.editor-body {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
overflow: hidden;
|
||||
margin: 12px 16px 16px;
|
||||
border: 1px solid #f0f0f0;
|
||||
border-radius: 16px;
|
||||
background: #f0f0f0;
|
||||
}
|
||||
|
||||
@media (max-width: 1200px) {
|
||||
.editor-meta-form {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.editor-header {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.header-actions {
|
||||
width: 100%;
|
||||
justify-content: flex-start;
|
||||
}
|
||||
|
||||
.editor-meta-form {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.editor-body {
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
<script setup lang="ts">
|
||||
import { reactive, watch } from "vue";
|
||||
import { computed, reactive, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import type { CreateKolPromptRequest } from "@geo/shared-types";
|
||||
import { buildKolPlatformOptions } from "@/lib/kol-platform-options";
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean;
|
||||
@@ -20,12 +21,7 @@ const formState = reactive<CreateKolPromptRequest>({
|
||||
platform_hint: "通用",
|
||||
});
|
||||
|
||||
const platformOptions = [
|
||||
{ label: "通用", value: "通用" },
|
||||
{ label: "豆包", value: "豆包" },
|
||||
{ label: "DeepSeek", value: "DeepSeek" },
|
||||
{ label: "ChatGPT", value: "ChatGPT" },
|
||||
];
|
||||
const platformOptions = computed(() => buildKolPlatformOptions(t("kol.manage.platformHintDefault")));
|
||||
|
||||
watch(
|
||||
() => props.open,
|
||||
@@ -46,6 +42,10 @@ function handleOk() {
|
||||
function handleCancel() {
|
||||
emit("update:open", false);
|
||||
}
|
||||
|
||||
function getSelectPopupContainer(triggerNode: HTMLElement) {
|
||||
return triggerNode.parentElement ?? triggerNode;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -60,10 +60,13 @@ function handleCancel() {
|
||||
<a-input v-model:value="formState.name" :placeholder="t('common.inputPlease')" />
|
||||
</a-form-item>
|
||||
|
||||
<a-form-item label="Platform Hint">
|
||||
<a-form-item :label="t('kol.manage.platformHint')">
|
||||
<a-select
|
||||
v-model:value="formState.platform_hint"
|
||||
:options="platformOptions"
|
||||
option-filter-prop="label"
|
||||
show-search
|
||||
:get-popup-container="getSelectPopupContainer"
|
||||
@change="(val: string) => formState.platform_hint = val"
|
||||
/>
|
||||
</a-form-item>
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
<script setup lang="ts">
|
||||
import { CloseOutlined } from "@ant-design/icons-vue";
|
||||
import type { KolVariableDefinition } from "@geo/shared-types";
|
||||
import { Tag } from "ant-design-vue";
|
||||
import type { ComponentPublicInstance } from "vue";
|
||||
import { nextTick, ref } from "vue";
|
||||
import { CloseOutlined, DownOutlined } from "@ant-design/icons-vue";
|
||||
import type { KolVariableDefinition, KolVariableType } from "@geo/shared-types";
|
||||
import { useI18n } from "vue-i18n";
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -13,17 +14,22 @@ const emit = defineEmits<{
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const panelRef = ref<HTMLDivElement | null>(null);
|
||||
const activeVariableKey = ref<string>("");
|
||||
let activeHighlightTimer: number | null = null;
|
||||
const cardRefs = new Map<string, HTMLElement>();
|
||||
|
||||
const componentTypes: Array<{ type: KolVariableType }> = [
|
||||
{ type: "input" },
|
||||
{ type: "textarea" },
|
||||
{ type: "select" },
|
||||
{ type: "number" },
|
||||
{ type: "checkbox" },
|
||||
];
|
||||
|
||||
function updateVariable(index: number, updates: Partial<KolVariableDefinition>) {
|
||||
const newVariables = [...props.variables];
|
||||
const oldVar = newVariables[index];
|
||||
|
||||
// If label is updated and matches key (default behavior), update key too
|
||||
if (updates.label !== undefined && oldVar.label === oldVar.key) {
|
||||
updates.key = updates.label;
|
||||
}
|
||||
|
||||
newVariables[index] = { ...oldVar, ...updates };
|
||||
newVariables[index] = { ...newVariables[index], ...updates };
|
||||
emit("update:variables", newVariables);
|
||||
}
|
||||
|
||||
@@ -34,19 +40,103 @@ function removeVariable(index: number) {
|
||||
}
|
||||
|
||||
function handleOptionsChange(index: number, value: string) {
|
||||
const options = value.split(",").map(s => s.trim()).filter(Boolean);
|
||||
const options = value
|
||||
.split(",")
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean);
|
||||
updateVariable(index, { options });
|
||||
}
|
||||
|
||||
function handleTypeChange(index: number, type: KolVariableType) {
|
||||
updateVariable(index, { type });
|
||||
}
|
||||
|
||||
function setCardRef(key: string, el: Element | ComponentPublicInstance | null) {
|
||||
const element =
|
||||
el instanceof HTMLElement
|
||||
? el
|
||||
: el && "$el" in el && el.$el instanceof HTMLElement
|
||||
? el.$el
|
||||
: null;
|
||||
|
||||
if (element) {
|
||||
cardRefs.set(key, element);
|
||||
return;
|
||||
}
|
||||
cardRefs.delete(key);
|
||||
}
|
||||
|
||||
async function focusVariable(key: string) {
|
||||
activeVariableKey.value = key;
|
||||
|
||||
if (activeHighlightTimer !== null) {
|
||||
window.clearTimeout(activeHighlightTimer);
|
||||
}
|
||||
activeHighlightTimer = window.setTimeout(() => {
|
||||
if (activeVariableKey.value === key) {
|
||||
activeVariableKey.value = "";
|
||||
}
|
||||
activeHighlightTimer = null;
|
||||
}, 1800);
|
||||
|
||||
await nextTick();
|
||||
|
||||
const card = cardRefs.get(key);
|
||||
const panel = panelRef.value;
|
||||
if (!card || !panel) {
|
||||
return;
|
||||
}
|
||||
|
||||
const targetTop = Math.max(card.offsetTop - 16, 0);
|
||||
panel.scrollTo({
|
||||
top: targetTop,
|
||||
behavior: "smooth",
|
||||
});
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
const input = card.querySelector("input");
|
||||
if (input instanceof HTMLInputElement) {
|
||||
input.focus();
|
||||
input.select();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
defineExpose({
|
||||
focusVariable,
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="kol-variable-config">
|
||||
<div ref="panelRef" class="kol-variable-config">
|
||||
<div v-if="variables.length === 0" class="empty-state">
|
||||
{{ t('common.noData') }}
|
||||
</div>
|
||||
<div v-for="(variable, index) in variables" :key="variable.id" class="variable-card">
|
||||
<div
|
||||
v-for="(variable, index) in variables"
|
||||
:key="variable.id"
|
||||
:ref="(el) => setCardRef(variable.key || variable.id, el)"
|
||||
class="variable-card"
|
||||
:class="{ 'variable-card--active': activeVariableKey === (variable.key || variable.id) }"
|
||||
>
|
||||
<div class="card-header">
|
||||
<Tag color="blue">{{ t(`kol.manage.variable.${variable.type}`) }}</Tag>
|
||||
<a-dropdown :trigger="['click']">
|
||||
<button type="button" class="type-trigger">
|
||||
<span>{{ t(`kol.manage.variable.${variable.type}`) }}</span>
|
||||
<DownOutlined />
|
||||
</button>
|
||||
<template #overlay>
|
||||
<a-menu>
|
||||
<a-menu-item
|
||||
v-for="item in componentTypes"
|
||||
:key="item.type"
|
||||
@click="handleTypeChange(index, item.type)"
|
||||
>
|
||||
{{ t(`kol.manage.variable.${item.type}`) }}
|
||||
</a-menu-item>
|
||||
</a-menu>
|
||||
</template>
|
||||
</a-dropdown>
|
||||
<div class="header-actions">
|
||||
<a-button type="text" size="small" @click="removeVariable(index)">
|
||||
<template #icon><CloseOutlined /></template>
|
||||
@@ -92,7 +182,7 @@ function handleOptionsChange(index: number, value: string) {
|
||||
</div>
|
||||
|
||||
<div class="token-display">
|
||||
<code>{{ `{{${variable.key}}}` }}</code>
|
||||
<code>{{{{ variable.key || variable.id }}}}</code>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -121,6 +211,13 @@ function handleOptionsChange(index: number, value: string) {
|
||||
border: 1px solid #f0f0f0;
|
||||
border-radius: 4px;
|
||||
background: #fafafa;
|
||||
transition: border-color 0.25s ease, box-shadow 0.25s ease, background 0.25s ease;
|
||||
}
|
||||
|
||||
.variable-card--active {
|
||||
border-color: #ff85c0;
|
||||
background: #fff7fb;
|
||||
box-shadow: 0 0 0 3px rgba(235, 47, 150, 0.12);
|
||||
}
|
||||
|
||||
.card-header {
|
||||
@@ -131,6 +228,26 @@ function handleOptionsChange(index: number, value: string) {
|
||||
border-bottom: 1px solid #f0f0f0;
|
||||
}
|
||||
|
||||
.type-trigger {
|
||||
appearance: none;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 2px 10px;
|
||||
border: 1px solid #91caff;
|
||||
border-radius: 999px;
|
||||
background: #f0f7ff;
|
||||
color: #1677ff;
|
||||
font-size: 12px;
|
||||
line-height: 20px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.type-trigger:hover {
|
||||
border-color: #69b1ff;
|
||||
background: #e6f4ff;
|
||||
}
|
||||
|
||||
.card-body {
|
||||
padding: 12px;
|
||||
display: flex;
|
||||
|
||||
Reference in New Issue
Block a user