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:
2026-04-18 00:47:57 +08:00
parent 614ca4a2ea
commit 3ef0807456
32 changed files with 2414 additions and 3518 deletions
@@ -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("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;");
}
</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>&#123;&#123;{{ variable.key || variable.id }}&#125;&#125;</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;
+11
View File
@@ -190,7 +190,18 @@ const enUS = {
publishPackage: "Publish",
archivePackage: "Archive",
createPrompt: "Create prompt",
activatePrompt: "Go live",
archivePrompt: "Take offline",
platformHint: "Platform",
platformHintDefault: "General",
status: {
draft: "Draft",
active: "Live",
archived: "Offline",
},
editor: {
basicInfo: "Basic info",
saveMeta: "Save basic info",
saveDraft: "Save draft",
publish: "Publish",
preview: "Preview form",
+13 -2
View File
@@ -168,7 +168,7 @@ const zhCN = {
},
empty: "暂无已上架的订阅包",
subscribers: "{count} 个订阅租户",
prompts: "{count} 个 Prompt",
prompts: "{count} 个提示词",
},
package: {
subscribe: "申请订阅",
@@ -189,8 +189,19 @@ const zhCN = {
editPackage: "编辑包",
publishPackage: "发布",
archivePackage: "归档",
createPrompt: "新增 Prompt",
createPrompt: "新增提示词",
activatePrompt: "上线",
archivePrompt: "下线",
platformHint: "平台",
platformHintDefault: "通用",
status: {
draft: "草稿",
active: "已上线",
archived: "已下线",
},
editor: {
basicInfo: "基本信息",
saveMeta: "保存基本信息",
saveDraft: "保存草稿",
publish: "发布",
preview: "预览表单",
+21 -12
View File
@@ -33,12 +33,11 @@ import type {
KolAssistTask,
KolPackageSummary,
KolPackageDetail,
PublishKolPromptRequest,
KolSubscription,
KolSubscriptionPromptCard,
KolProfile,
KolPromptDetail,
KolPromptRevision,
KolSaveDraftRequest,
KolSubscriptionPromptSchema,
KolGenerateRequest,
KolGenerateResponse,
@@ -323,15 +322,27 @@ export const kolManageApi = {
deletePrompt(id: number) {
return apiClient.remove<null>(`/api/tenant/kol/manage/prompts/${id}`);
},
saveDraft(promptId: number, body: KolSaveDraftRequest) {
return apiClient.post<KolPromptRevision, KolSaveDraftRequest>(
`/api/tenant/kol/manage/prompts/${promptId}/draft`,
savePrompt(promptId: number, body: PublishKolPromptRequest) {
return apiClient.post<KolPromptDetail, PublishKolPromptRequest>(
`/api/tenant/kol/manage/prompts/${promptId}/save`,
body,
);
},
publishPrompt(promptId: number) {
return apiClient.post<{ ok: boolean }, Record<string, never>>(
publishPrompt(promptId: number, body: PublishKolPromptRequest) {
return apiClient.post<KolPromptDetail, PublishKolPromptRequest>(
`/api/tenant/kol/manage/prompts/${promptId}/publish`,
body,
);
},
activatePrompt(promptId: number) {
return apiClient.put<KolPromptDetail, Record<string, never>>(
`/api/tenant/kol/manage/prompts/${promptId}/activate`,
{},
);
},
archivePrompt(promptId: number) {
return apiClient.put<KolPromptDetail, Record<string, never>>(
`/api/tenant/kol/manage/prompts/${promptId}/archive`,
{},
);
},
@@ -348,7 +359,7 @@ export const kolManageApi = {
export const kolMarketplaceApi = {
list(params: { industry?: string; keyword?: string; limit?: number; offset?: number }) {
return apiClient.get<KolPackageSummary[]>("/api/tenant/kol/marketplace", { params });
return apiClient.get<KolPackageSummary[]>("/api/tenant/kol/marketplace/packages", { params });
},
detail(id: number) {
return apiClient.get<KolPackageDetail>(`/api/tenant/kol/marketplace/packages/${id}`);
@@ -360,12 +371,10 @@ export const kolMarketplaceApi = {
);
},
mySubscriptions() {
return apiClient.get<KolSubscription[]>("/api/tenant/kol/marketplace/my-subscriptions");
return apiClient.get<KolSubscription[]>("/api/tenant/kol/subscriptions");
},
mySubscriptionPrompts() {
return apiClient.get<KolSubscriptionPromptCard[]>(
"/api/tenant/kol/marketplace/my-subscription-prompts",
);
return apiClient.get<KolSubscriptionPromptCard[]>("/api/tenant/kol/subscription-prompts");
},
};
+113
View File
@@ -0,0 +1,113 @@
import type { KolVariableDefinition, KolVariableType } from "@geo/shared-types";
import { newVariableId } from "./kol-variable-id";
const KOL_PLACEHOLDER_RE = /\{\{\s*([^{}]+?)\s*\}\}/g;
function normalizePlaceholderKey(value: string): string {
return value.trim();
}
function normalizeVariableType(type?: KolVariableType): KolVariableType {
switch (type) {
case "textarea":
case "select":
case "number":
case "checkbox":
return type;
case "input":
default:
return "input";
}
}
export function buildKolPlaceholderToken(key: string): string {
return `{{${normalizePlaceholderKey(key)}}}`;
}
export function extractKolPlaceholderKeys(content: string): string[] {
const text = String(content ?? "");
const seen = new Set<string>();
const keys: string[] = [];
for (const match of text.matchAll(KOL_PLACEHOLDER_RE)) {
const key = normalizePlaceholderKey(match[1] ?? "");
if (!key || seen.has(key)) {
continue;
}
seen.add(key);
keys.push(key);
}
return keys;
}
export function findKolPlaceholderKeyAtPosition(content: string, position: number): string | null {
const text = String(content ?? "");
if (!text || position < 0) {
return null;
}
for (const match of text.matchAll(KOL_PLACEHOLDER_RE)) {
const token = match[0] ?? "";
const start = match.index ?? -1;
const end = start + token.length;
if (start < 0) {
continue;
}
if (position >= start && position <= end) {
return normalizePlaceholderKey(match[1] ?? "");
}
}
return null;
}
export function createKolVariableDefinition(
key: string,
overrides: Partial<KolVariableDefinition> = {},
): KolVariableDefinition {
const normalizedKey = normalizePlaceholderKey(key);
return {
id: overrides.id?.trim() || newVariableId(),
key: normalizedKey,
label: overrides.label?.trim() || normalizedKey,
type: normalizeVariableType(overrides.type),
required: overrides.required ?? true,
placeholder: overrides.placeholder,
options: overrides.options,
};
}
export function syncKolVariablesWithContent(
content: string,
variables: KolVariableDefinition[],
): KolVariableDefinition[] {
const keys = extractKolPlaceholderKeys(content);
const byKey = new Map<string, KolVariableDefinition>();
for (const variable of variables) {
const key = normalizePlaceholderKey(variable.key || variable.label || "");
if (!key || byKey.has(key)) {
continue;
}
byKey.set(
key,
createKolVariableDefinition(key, {
...variable,
key,
label: variable.label?.trim() || key,
}),
);
}
return keys.map((key) => {
const existing = byKey.get(key);
if (existing) {
return existing;
}
return createKolVariableDefinition(key);
});
}
@@ -0,0 +1,15 @@
export interface KolPlatformOption {
label: string;
value: string;
}
export function buildKolPlatformOptions(defaultLabel: string): KolPlatformOption[] {
return [
{ label: defaultLabel, value: "通用" },
{ label: "小红书", value: "xiaohongshu" },
{ label: "微信", value: "wechat" },
{ label: "豆包", value: "doubao" },
{ label: "DeepSeek", value: "deepseek" },
{ label: "ChatGPT", value: "chatgpt" },
];
}
+8 -11
View File
@@ -5,7 +5,6 @@ import { message } from "ant-design-vue";
import { computed, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useRoute, useRouter } from "vue-router";
import { MilkdownProvider } from "@milkdown/vue";
import ArticleEditorCanvas from "@/components/ArticleEditorCanvas.vue";
import CoverPickerModal from "@/components/CoverPickerModal.vue";
@@ -379,16 +378,14 @@ function serializePlatformSelection(platformIds: string[]): string {
/>
<div class="article-editor-view__layout">
<section class="article-editor-view__main">
<MilkdownProvider>
<ArticleEditorCanvas
:key="String(articleId)"
:article-id="articleId"
v-model:title="title"
v-model="markdown"
:disabled="editorLocked"
:upload-image="uploadEditorImage"
/>
</MilkdownProvider>
<ArticleEditorCanvas
:key="String(articleId)"
:article-id="articleId"
v-model:title="title"
v-model="markdown"
:disabled="editorLocked"
:upload-image="uploadEditorImage"
/>
</section>
<aside class="article-editor-view__rail">
+6 -2
View File
@@ -22,6 +22,10 @@ const schemaQuery = useQuery({
const values = ref<Record<string, any>>({});
function fieldKey(key?: string | null, id?: string): string {
return key?.trim() || id || "";
}
// Initialize values from schema
watch(
() => schemaQuery.data.value,
@@ -29,7 +33,7 @@ watch(
if (schema?.schema_json?.variables) {
const newValues: Record<string, any> = {};
schema.schema_json.variables.forEach((v) => {
newValues[v.key] = v.type === "checkbox" ? [] : undefined;
newValues[fieldKey(v.key, v.id)] = v.type === "checkbox" ? [] : undefined;
});
values.value = newValues;
}
@@ -59,7 +63,7 @@ function handleSubmit() {
const missingLabels: string[] = [];
schema.schema_json.variables.forEach((v) => {
if (v.required && !values.value[v.key]) {
if (v.required && !values.value[fieldKey(v.key, v.id)]) {
missingLabels.push(v.label);
}
});
+215 -123
View File
@@ -6,12 +6,13 @@ import { message, Modal } from "ant-design-vue";
import {
PlusOutlined,
EditOutlined,
PlayCircleOutlined,
PauseCircleOutlined,
CloudUploadOutlined,
InboxOutlined,
DeleteOutlined,
} from "@ant-design/icons-vue";
import PageHero from "@/components/PageHero.vue";
import KolPackageFormModal from "@/components/kol/KolPackageFormModal.vue";
import KolPromptFormModal from "@/components/kol/KolPromptFormModal.vue";
import KolPromptEditor from "@/components/kol/KolPromptEditor.vue";
@@ -26,8 +27,8 @@ const selectedPackageId = ref<number | null>(null);
const packageModalOpen = ref(false);
const editingPackage = ref<KolPackageSummary | null>(null);
const promptModalOpen = ref(false);
const editorDrawerOpen = ref(false);
const editingPromptId = ref<number | null>(null);
const togglingPromptId = ref<number | null>(null);
const { data: packages, isPending: packagesPending } = useQuery({
queryKey: ["kol", "packages"],
@@ -77,11 +78,12 @@ const archivePackageMutation = useMutation({
const deletePackageMutation = useMutation({
mutationFn: (id: number) => kolManageApi.deletePackage(id),
onSuccess: () => {
onSuccess: (_, id) => {
message.success(t("common.delete") + "成功");
queryClient.invalidateQueries({ queryKey: ["kol", "packages"] });
if (selectedPackageId.value === selectedPackageId.value) {
if (selectedPackageId.value === id) {
selectedPackageId.value = null;
editingPromptId.value = null;
}
},
});
@@ -97,6 +99,31 @@ const createPromptMutation = useMutation({
},
onError: (error) => message.error(formatError(error)),
});
const togglePromptStatusMutation = useMutation({
mutationFn: (data: { id: number; nextStatus: "active" | "archived" }) =>
data.nextStatus === "active"
? kolManageApi.activatePrompt(data.id)
: kolManageApi.archivePrompt(data.id),
onMutate: (variables) => {
togglingPromptId.value = variables.id;
},
onSuccess: (_, variables) => {
message.success(
t(variables.nextStatus === "active" ? "kol.manage.activatePrompt" : "kol.manage.archivePrompt") + "成功"
);
void queryClient.invalidateQueries({ queryKey: ["kol", "packages"] });
void queryClient.invalidateQueries({
queryKey: ["kol", "packages", selectedPackageId.value, "prompts"],
});
void queryClient.invalidateQueries({ queryKey: ["kol", "prompt", variables.id] });
},
onError: (error) => message.error(formatError(error)),
onSettled: () => {
togglingPromptId.value = null;
},
});
const packageInitialValue = computed<Partial<CreateKolPackageRequest> | undefined>(() => {
if (!editingPackage.value) return undefined;
return {
@@ -135,130 +162,172 @@ function handleDeletePackage(id: number) {
});
}
function handleSelectPackage(packageId: number) {
selectedPackageId.value = packageId;
editingPromptId.value = null;
}
function handleOpenEditor(promptId: number) {
editingPromptId.value = promptId;
editorDrawerOpen.value = true;
}
function handleCloseEditor() {
editingPromptId.value = null;
}
function promptStatusLabel(status: 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-manage-view">
<PageHero
:title="t('kol.manage.title')"
:description="t('route.tracking.description')"
/>
<div class="manage-content">
...
<KolPackageFormModal
v-model:open="packageModalOpen"
:initial-value="packageInitialValue"
@submit="handlePackageSubmit"
/>
<a-button type="primary" size="small" @click="handleCreatePackage">
<template #icon><PlusOutlined /></template>
{{ t('kol.manage.createPackage') }}
</a-button>
</div>
<a-list
class="package-list"
:loading="packagesPending"
:data-source="packages"
size="small"
>
<template #renderItem="{ item }">
<a-list-item
:class="{ 'is-selected': selectedPackageId === item.id }"
@click="selectedPackageId = item.id"
>
<div class="package-item-content">
<div class="package-name">{{ item.name }}</div>
<div class="package-meta">
<a-tag :color="item.status === 'published' ? 'green' : 'orange'" size="small">
{{ item.status }}
</a-tag>
<span>{{ item.prompt_count }} Prompts</span>
</div>
</div>
<template #actions>
<a-dropdown>
<a class="ant-dropdown-link" @click.prevent>...</a>
<template #overlay>
<a-menu>
<a-menu-item @click="handleEditPackage(item)">
<EditOutlined /> {{ t('common.edit') }}
</a-menu-item>
<a-menu-item
v-if="item.status !== 'published'"
@click="publishPackageMutation.mutate(item.id)"
>
<CloudUploadOutlined /> {{ t('kol.manage.publishPackage') }}
</a-menu-item>
<a-menu-item
v-if="item.status === 'published'"
@click="archivePackageMutation.mutate(item.id)"
>
<InboxOutlined /> {{ t('kol.manage.archivePackage') }}
</a-menu-item>
<a-menu-divider />
<a-menu-item danger @click="handleDeletePackage(item.id)">
<DeleteOutlined /> {{ t('common.delete') }}
</a-menu-item>
</a-menu>
</template>
</a-dropdown>
</template>
</a-list-item>
</template>
</a-list>
<div v-if="editingPromptId" class="manage-content manage-content--editor">
<div class="fullscreen-editor">
<KolPromptEditor :prompt-id="editingPromptId" @back="handleCloseEditor" />
</div>
<!-- Right Column: Prompts -->
<div class="prompt-column">
<template v-if="selectedPackageId">
</div>
<div v-else class="manage-content">
<div class="package-column">
<div class="column-header">
<h3>Prompts</h3>
<a-button type="primary" size="small" @click="promptModalOpen = true">
<h3>订阅包</h3>
<a-button type="primary" size="small" @click="handleCreatePackage">
<template #icon><PlusOutlined /></template>
{{ t('kol.manage.createPrompt') }}
{{ t('kol.manage.createPackage') }}
</a-button>
</div>
<a-table
:columns="[
{ title: t('common.title'), dataIndex: 'name', key: 'name' },
{ title: 'Platform', dataIndex: 'platform_hint', key: 'platform_hint' },
{ title: t('common.status'), dataIndex: 'status', key: 'status' },
{ title: t('common.actions'), key: 'actions', align: 'right' },
]"
:data-source="prompts"
:loading="promptsPending"
<a-list
class="package-list"
:loading="packagesPending"
:data-source="packages"
size="small"
:pagination="false"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'platform_hint'">
<a-tag color="blue">{{ record.platform_hint || '通用' }}</a-tag>
</template>
<template v-else-if="column.key === 'status'">
<a-tag :color="record.status === 'active' ? 'green' : 'orange'">
{{ record.status }}
</a-tag>
</template>
<template v-else-if="column.key === 'actions'">
<a-button type="link" size="small" @click="handleOpenEditor(record.id)">
{{ t('common.edit') }}
</a-button>
</template>
<template #renderItem="{ item }">
<a-list-item
:class="{ 'is-selected': selectedPackageId === item.id }"
@click="handleSelectPackage(item.id)"
>
<div class="package-item-content">
<div class="package-name">{{ item.name }}</div>
<div class="package-meta">
<a-tag :color="item.status === 'published' ? 'green' : 'orange'" size="small">
{{ item.status }}
</a-tag>
<span>{{ item.prompt_count }} 提示词</span>
</div>
</div>
<template #actions>
<a-dropdown>
<a class="ant-dropdown-link" @click.prevent>...</a>
<template #overlay>
<a-menu>
<a-menu-item @click="handleEditPackage(item)">
<EditOutlined /> {{ t('common.edit') }}
</a-menu-item>
<a-menu-item
v-if="item.status !== 'published'"
@click="publishPackageMutation.mutate(item.id)"
>
<CloudUploadOutlined /> {{ t('kol.manage.publishPackage') }}
</a-menu-item>
<a-menu-item
v-if="item.status === 'published'"
@click="archivePackageMutation.mutate(item.id)"
>
<InboxOutlined /> {{ t('kol.manage.archivePackage') }}
</a-menu-item>
<a-menu-divider />
<a-menu-item danger @click="handleDeletePackage(item.id)">
<DeleteOutlined /> {{ t('common.delete') }}
</a-menu-item>
</a-menu>
</template>
</a-dropdown>
</template>
</a-list-item>
</template>
</a-table>
</template>
<div v-else class="empty-prompts">
<a-empty description="请选择左侧订阅包以查看 Prompt" />
</a-list>
</div>
<!-- Right Column: Prompts -->
<div class="prompt-column">
<template v-if="selectedPackageId">
<div class="column-header">
<h3>提示词</h3>
<a-button type="primary" size="small" @click="promptModalOpen = true">
<template #icon><PlusOutlined /></template>
{{ t('kol.manage.createPrompt') }}
</a-button>
</div>
<a-table
:columns="[
{ title: t('common.title'), dataIndex: 'name', key: 'name' },
{ title: t('tracking.columns.platform'), dataIndex: 'platform_hint', key: 'platform_hint' },
{ title: t('common.status'), dataIndex: 'status', key: 'status' },
{ title: t('common.actions'), key: 'actions', align: 'right', width: 112 },
]"
:data-source="prompts"
:loading="promptsPending"
size="small"
:pagination="false"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'platform_hint'">
<a-tag color="blue">{{ record.platform_hint || '通用' }}</a-tag>
</template>
<template v-else-if="column.key === 'status'">
<a-tag :color="record.status === 'active' ? 'green' : record.status === 'archived' ? 'orange' : 'default'">
{{ promptStatusLabel(record.status) }}
</a-tag>
</template>
<template v-else-if="column.key === 'actions'">
<div class="table-actions-row">
<a-tooltip :title="t('common.edit')">
<a-button
type="text"
shape="circle"
size="small"
class="action-btn action-edit"
@click="handleOpenEditor(record.id)"
>
<EditOutlined />
</a-button>
</a-tooltip>
<a-tooltip
:title="record.status === 'active' ? t('kol.manage.archivePrompt') : t('kol.manage.activatePrompt')"
>
<a-button
type="text"
shape="circle"
size="small"
:class="[
'action-btn',
record.status === 'active' ? 'action-disable' : 'action-enable',
]"
:loading="togglePromptStatusMutation.isPending.value && togglingPromptId === record.id"
@click="togglePromptStatusMutation.mutate({
id: record.id,
nextStatus: record.status === 'active' ? 'archived' : 'active',
})"
>
<PauseCircleOutlined v-if="record.status === 'active'" />
<PlayCircleOutlined v-else />
</a-button>
</a-tooltip>
</div>
</template>
</template>
</a-table>
</template>
<div v-else class="empty-prompts">
<a-empty description="请选择左侧订阅包以查看提示词" />
</div>
</div>
</div>
</div>
<KolPackageFormModal
v-model:open="packageModalOpen"
@@ -271,16 +340,6 @@ function handleOpenEditor(promptId: number) {
:package-id="selectedPackageId || 0"
@submit="createPromptMutation.mutate"
/>
<a-drawer
v-model:open="editorDrawerOpen"
width="90vw"
:closable="true"
:destroy-on-close="true"
class="editor-drawer"
>
<KolPromptEditor v-if="editingPromptId" :prompt-id="editingPromptId" />
</a-drawer>
</div>
</template>
@@ -291,13 +350,23 @@ function handleOpenEditor(promptId: number) {
height: calc(100vh - 64px);
}
.fullscreen-editor {
flex: 1;
min-height: 0;
border-radius: 12px;
overflow: hidden;
}
.manage-content--editor {
padding: 16px;
}
.manage-content {
flex: 1;
display: flex;
overflow: hidden;
padding: 16px;
gap: 16px;
background: #f5f5f5;
}
.package-column {
@@ -314,6 +383,7 @@ function handleOpenEditor(promptId: number) {
border-radius: 8px;
display: flex;
flex-direction: column;
min-width: 0;
}
.column-header {
@@ -372,7 +442,29 @@ function handleOpenEditor(promptId: number) {
justify-content: center;
}
.editor-drawer :deep(.ant-drawer-body) {
padding: 0;
.prompt-editor-panel {
flex: 1;
min-height: 0;
}
.table-actions-row {
display: inline-flex;
align-items: center;
gap: 4px;
}
.action-edit.ant-btn:hover:not(:disabled) {
color: #52c41a;
background: #f6ffed;
}
.action-enable.ant-btn:hover:not(:disabled) {
color: #1677ff;
background: #e6f4ff;
}
.action-disable.ant-btn:hover:not(:disabled) {
color: #fa8c16;
background: #fff7e6;
}
</style>