← 返回学习路线

SYSTEM

D31 大纲生成(后端端点 + 前端大纲树)

QuillAgent文档3. D31 大纲生成(后端端点 + 前端大纲树)growth
src/content/notes/growth/D31-大纲生成-后端端点-前端大纲树.md

3. D31 大纲生成(后端端点 + 前端大纲树)

3.1 后端:POST /api/ai/outline(SSE)

AiController.java 追加(import 补 java.util.List、jakarta.validation.constraints.NotEmpty):

    /** 大纲生成(D31):零散关键点 → 严格 ##/### 层级 Markdown 大纲 */
    @PostMapping(value = "/outline", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter outline(@Valid @RequestBody OutlineRequest req) {
        String genre = normalizeGenre(req.genre());
        String system = promptService.styleSystem(genre) + "\n" + promptService.outlineSystem();
        // 关键点来自用户输入(可能粘贴),包 <key_points> 边界声明防注入
        String user = "<key_points>\n" + String.join("\n", req.keyPoints()) + "\n</key_points>";
        return streamService.stream(req.modelConfig(), system, user);
    }

    public record OutlineRequest(
            @NotBlank(message = "genre 不能为空") String genre,
            @NotEmpty(message = "keyPoints 不能为空") @Size(max = 20, message = "关键点最多 20 条")
            List<@Size(max = 200, message = "单条关键点过长") String> keyPoints,
            @NotNull(message = "modelConfig 不能为空") @Valid ModelConfig modelConfig) {
    }

3.2 前端:OutlinePanel.vue(生成 + 解析树 + 锚点跳转)

<template>
  <el-drawer v-model="visible" title="大纲生成" size="460px">
    <el-input v-model="keyPoints" type="textarea" :rows="5"
              placeholder="关键点,每行一个:&#10;穿越到修仙大陆&#10;主角是废材身份&#10;金手指:识宝能力" />
    <el-button type="primary" style="margin-top: 10px" :loading="busy" @click="generate">
      生成大纲
    </el-button>

    <div v-if="raw" class="ol-raw">{{ raw }}<span v-if="busy" class="cursor">▍</span></div>

    <div v-if="tree.length" class="ol-tree">
      <div v-for="(n, i) in tree" :key="i" class="ol-node" :class="'lv' + n.level">
        <span class="ol-dot">{{ n.level === 2 ? '●' : '○' }}</span>
        <span class="ol-title" @click="jump(n)">{{ n.title }}</span>
        <span v-if="n.note" class="ol-note">{{ n.note }}</span>
      </div>
    </div>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { useEditorStore } from '../stores/editor';
import { loadModelSettings } from '../stores/settings';
import { streamAi } from '../api/ai';

const visible = defineModel<boolean>({ required: true });
const editorStore = useEditorStore();

const keyPoints = ref('');
const busy = ref(false);
const raw = ref('');
const tree = ref<Array<{ level: 2 | 3; title: string; note: string }>>([]);

async function generate() {
    const points = keyPoints.value.split('\n').map(s => s.trim()).filter(Boolean);
    if (!points.length) { ElMessage.warning('请先输入关键点(每行一个)'); return; }
    raw.value = '';
    tree.value = [];
    busy.value = true;
    await streamAi('/api/ai/outline', {
        genre: editorStore.genre, keyPoints: points.slice(0, 20), modelConfig: loadModelSettings(),
    }, {
        onToken(t) { raw.value += t; },
        onComplete() {
            tree.value = parseOutline(raw.value);   // 解析容错:非标题行归入上级备注
            busy.value = false;
        },
        onError(e) { ElMessage.error(e.message); busy.value = false; },
    });
}

/** 解析 Markdown 大纲:## → 2 级、### → 3 级;其余行归入上一节点 note */
function parseOutline(md: string) {
    const nodes: Array<{ level: 2 | 3; title: string; note: string }> = [];
    for (const line of md.split('\n')) {
        const m = /^(#{2,3})\s+(.+)$/.exec(line.trim());
        if (m) {
            nodes.push({ level: (m[1].length as 2 | 3), title: m[2].trim(), note: '' });
        } else if (nodes.length && line.trim()) {
            const last = nodes[nodes.length - 1];
            last.note = last.note ? last.note + ';' + line.trim() : line.trim();
        }
    }
    return nodes;
}

/** 锚点跳转:在正文中定位同文本标题块并选中;找不到则追加到文末(TipTap 事务可撤销) */
function jump(n: { level: 2 | 3; title: string }) {
    const ed = editorStore.editor;
    if (!ed) return;
    let hit = false;
    ed.state.doc.descendants((node, pos) => {
        if (hit || !node.isTextblock) return false;
        if ((node.textContent ?? '').trim() === n.title) {
            ed.commands.setTextSelection({ from: pos, to: pos + node.nodeSize - 1 });
            ed.commands.scrollIntoView();
            hit = true;
            return false;
        }
        return true;
    });
    if (!hit) {
        // 写作前大纲:正文尚无该标题 → 追加为标题段落(进撤销栈)
        const tag = n.level === 2 ? 'h2' : 'h3';
        ed.chain().focus('end').insertContent({ type: 'heading', attrs: { level: n.level }, content: [{ type: 'text', text: n.title }] }).run();
        ElMessage.success('正文未找到该标题,已追加到文末');
    }
}
</script>

<style scoped>
.ol-raw { font-size: 12px; color: var(--el-text-color-secondary); margin-top: 10px; white-space: pre-wrap; }
.ol-tree { margin-top: 14px; }
.ol-node { display: flex; align-items: baseline; gap: 6px; padding: 3px 0; }
.ol-node.lv2 .ol-title { font-weight: 600; }
.ol-node.lv3 { padding-left: 18px; }
.ol-dot { font-size: 10px; color: var(--el-text-color-placeholder); }
.ol-title { cursor: pointer; color: var(--el-color-primary); }
.ol-title:hover { text-decoration: underline; }
.ol-note { font-size: 12px; color: var(--el-text-color-placeholder); }
.cursor { animation: blink 1s step-end infinite; }
@keyframes blink { 50% { opacity: 0; } }
</style>

说明:层级解析与”非标题行归入上级”即 04 计划 D31 的容错要求;大纲拖拽排序为降级项,v1.0 纯展示 + 跳转。