← 返回学习路线

SYSTEM

D34 前端:素材面板 + 选中一键收藏 + 插入正文

QuillAgent文档6. D34 前端:素材面板 + 选中一键收藏 + 插入正文growth
src/content/notes/growth/D34-前端:素材面板-选中一键收藏-插入正文.md

6. D34 前端:素材面板 + 选中一键收藏 + 插入正文

6.1 代码

electron/src/api/material.ts(新建)

import http from './http';

export interface Material {
    id: number; genre: string; kind: string; content: string;
    source: string; createdAt: string; updatedAt: string;
}

export const materialApi = {
    list: (genre?: string) =>
        http.get<Material[]>('/api/materials', { params: { genre } }).then(r => r.data.data),
    create: (m: Partial<Material>) => http.post<Material>('/api/materials', m).then(r => r.data.data),
    update: (id: number, m: Partial<Material>) =>
        http.put<Material>(`/api/materials/${id}`, m).then(r => r.data.data),
    remove: (id: number) => http.delete(`/api/materials/${id}`),
};

electron/src/components/MaterialPanel.vue(新建,抽屉;支持预填内容用于”选中收藏”,见 props)

<template>
  <el-drawer v-model="visible" title="素材收藏" size="480px">
    <div class="mt-actions">
      <el-select v-model="genreFilter" size="small" style="width: 140px" @change="reload">
        <el-option label="全部" value="" />
        <el-option v-for="g in GENRES" :key="g" :label="LABELS[g]" :value="g" />
      </el-select>
      <el-button type="primary" size="small" @click="openDialog()">收藏素材</el-button>
    </div>

    <el-card v-for="m in materials" :key="m.id" class="mt-card" shadow="never">
      <div class="mt-head">
        <el-tag size="small">{{ LABELS[m.genre] }}</el-tag>
        <el-tag size="small" type="info">{{ KIND_LABELS[m.kind] ?? m.kind }}</el-tag>
        <span v-if="m.source" class="mt-source">{{ m.source }}</span>
      </div>
      <p class="mt-content">{{ m.content }}</p>
      <div class="mt-foot">
        <el-button link type="primary" size="small" @click="insert(m.content)">插入正文</el-button>
        <el-button link size="small" @click="openDialog(m)">编辑</el-button>
        <el-popconfirm title="删除该素材?" @confirm="onDelete(m.id)">
          <template #reference><el-button link type="danger" size="small">删除</el-button></template>
        </el-popconfirm>
      </div>
    </el-card>
    <el-empty v-if="!materials.length" description="暂无素材" :image-size="60" />

    <el-dialog v-model="dialogOpen" :title="form.id ? '编辑素材' : '收藏素材'" width="420px">
      <el-form label-width="70px">
        <el-form-item label="文体">
          <el-select v-model="form.genre">
            <el-option v-for="g in GENRES" :key="g" :label="LABELS[g]" :value="g" />
          </el-select>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="form.kind">
            <el-option label="金句" value="QUOTE" />
            <el-option label="案例" value="CASE" />
            <el-option label="专业表述" value="PHRASE" />
          </el-select>
        </el-form-item>
        <el-form-item label="内容">
          <el-input v-model="form.content" type="textarea" :rows="6" maxlength="5000" show-word-limit />
        </el-form-item>
        <el-form-item label="来源">
          <el-input v-model="form.source" maxlength="200" placeholder="来源/备忘,可选" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogOpen = false">取消</el-button>
        <el-button type="primary" @click="saveDialog">保存</el-button>
      </template>
    </el-dialog>
  </el-drawer>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { useEditorStore } from '../stores/editor';
import { materialApi, type Material } from '../api/material';

const props = defineProps<{
    /** 打开面板时可预填的素材内容("选中收藏"场景由写作页注入) */
    presetContent?: string;
}>();
const visible = defineModel<boolean>({ required: true });
const editorStore = useEditorStore();

const GENRES = ['NOVEL', 'MEDIA', 'OFFICIAL', 'CUSTOM'];
const LABELS: Record<string, string> = { NOVEL: '网文', MEDIA: '自媒体', OFFICIAL: '公文', CUSTOM: '自定义' };
const KIND_LABELS: Record<string, string> = { QUOTE: '金句', CASE: '案例', PHRASE: '专业表述' };

const genreFilter = ref('');
const materials = ref<Material[]>([]);
const dialogOpen = ref(false);
const form = reactive<Partial<Material>>({});

async function reload() {
    materials.value = await materialApi.list(genreFilter.value || undefined);
}

/** 面板打开:若有预填内容(选中收藏),自动弹出收藏对话框 */
function onOpen() {
    reload().then(() => {
        if (props.presetContent) openDialog();
    });
}

function openDialog(m?: Material) {
    form.id = m?.id; form.genre = m?.genre ?? 'NOVEL'; form.kind = m?.kind ?? 'QUOTE';
    form.content = m?.content ?? props.presetContent ?? '';
    form.source = m?.source ?? '';
    dialogOpen.value = true;
}

async function saveDialog() {
    if (!form.content?.trim()) { ElMessage.warning('素材内容不能为空'); return; }
    if (form.id) await materialApi.update(form.id, form);
    else await materialApi.create(form);
    dialogOpen.value = false;
    await reload();
    ElMessage.success('已收藏');
}

async function onDelete(id: number) {
    await materialApi.remove(id);
    await reload();
}

/** 插入光标处:原样粘贴 content(纯文本),TipTap 事务进撤销栈 */
function insert(text: string) {
    const ed = editorStore.editor;
    if (!ed) return;
    ed.chain().focus().insertContent(text).run();
    ElMessage.success('已插入光标处');
}
</script>

<style scoped>
.mt-actions { display: flex; justify-content: space-between; margin-bottom: 12px; }
.mt-card { margin-bottom: 10px; }
.mt-head { display: flex; align-items: center; gap: 6px; margin-bottom: 6px; }
.mt-source { font-size: 12px; color: var(--el-text-color-placeholder); }
.mt-content { font-size: 13px; line-height: 1.7; margin: 0 0 8px; }
.mt-foot { display: flex; gap: 4px; }
</style>

写作页集成(WritingView.vue):工具栏追加三个入口 + 「选中收藏」动作:

<el-button icon="List" @click="outlineOpen = true">大纲</el-button>
<el-button icon="MagicStick" @click="inspireOpen = true">灵感</el-button>
<el-button icon="Collection" @click="materialOpen = true">素材</el-button>
<el-button icon="Folder" @click="templateOpen = true">模板</el-button>
<!-- 抽屉区 -->
<OutlinePanel v-model="outlineOpen" />
<InspirePanel v-model="inspireOpen" />
<MaterialPanel v-model="materialOpen" :preset-content="pendingMaterial" />
<TemplatePanel v-model="templateOpen" />
import { ref } from 'vue';
import OutlinePanel from '../components/OutlinePanel.vue';
import InspirePanel from '../components/InspirePanel.vue';
import MaterialPanel from '../components/MaterialPanel.vue';
import TemplatePanel from '../components/TemplatePanel.vue';
import { useEditorStore } from '../stores/editor';

const editorStore = useEditorStore();
const outlineOpen = ref(false);
const inspireOpen = ref(false);
const materialOpen = ref(false);
const templateOpen = ref(false);
const pendingMaterial = ref<string | undefined>(undefined);

/** 选中文本一键收藏:取选区纯文本预填素材面板 */
function collectSelection() {
    const ed = editorStore.editor;
    if (!ed) return;
    const { from, to } = ed.state.selection;
    if (to <= from) { ElMessage.warning('请先选中要收藏的文字'); return; }
    pendingMaterial.value = ed.state.doc.textBetween(from, to);
    materialOpen.value = true;
}

工具栏可加 @click="collectSelection" 的【📌 收藏选中】按钮(有选区才可用,与 W3 quick 的 hasSelection 同判断)。 拖拽插入说明:v1.0 以”点击插入”为主;面板卡片可加 draggable + dragstart 存文本、编辑器 drop 拦截 insertText 作为增强(大纲拖拽排序已明确裁剪,素材拖拽同理可选做,不阻塞验收)。