frontend: add the paper list, document view, and paragraph editor

The 论文 menu now carries the papers themselves, read from a pinia store, so a
paper opens straight from the rail; every page that changes the list reloads
that store, and a filter box appears once there are more than six.

PapersView is the library — search, create, edit, open, single and batch
delete. PaperDetailView is the writing surface: it renders the server's
document verbatim, with an edit button beside every paragraph (written or not,
because content only ever enters a paper through the editor), citation markers
numbered in reading order to match the 参考文献 list, and a 切换模板 dialog that
previews the impact before re-shaping the document.

The paragraph editor shows one paragraph as the paper will read it — every
sentence on its own line, in sort order, each editable, each able to carry
citations — and writes the paragraph back whole. Whitespace-only lines are
dropped on save; a citation with an empty 引用内容 is refused; and 所属段落
moves the paragraph to another position, appended after what is already there.
This commit is contained in:
2026-09-18 17:29:16 +08:00
parent 06d7e922bd
commit 4d749b3592
13 changed files with 2813 additions and 57 deletions
@@ -0,0 +1,267 @@
<script setup lang="ts">
/**
* Create / edit dialog for a paper's metadata.
*
* The template select is the important field: a paper's whole structure comes
* from its template, so this is the one choice that decides what the writing
* view will look like. It is therefore required — except when no template
* exists yet at all, in which case demanding one would make creating a paper
* impossible and the paper can be given a structure later.
*
* Keywords are edited as tags but stored as the canonical comma-separated
* string the API writes, so the same value round-trips through either side.
*/
import { computed, reactive, ref, watch } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { errorMessage } from '@/api/client'
import {
createPaper,
getPaper,
updatePaper,
PAPER_STATUS_OPTIONS,
type PaperDetail,
type PaperListItem,
type PaperStatus,
} from '@/api/papers'
import { fetchAllTemplates, type TemplateListItem } from '@/api/templates'
import { splitKeywords } from '@/utils/format'
const props = defineProps<{
/** Visibility, used with `v-model`. */
modelValue: boolean
/** The paper being edited, or `null` to create a new one. */
paper: PaperListItem | null
}>()
const emit = defineEmits<{
'update:modelValue': [value: boolean]
/** Emitted after a successful write, with the stored paper. */
saved: [paper: PaperDetail]
}>()
const visible = computed({
get: () => props.modelValue,
set: (value: boolean) => emit('update:modelValue', value),
})
const formRef = ref<FormInstance>()
const loading = ref(false)
const saving = ref(false)
const templates = ref<TemplateListItem[]>([])
const form = reactive({
title: '',
template_id: null as number | null,
abstract: '',
author: '',
status: 'draft' as PaperStatus,
keywords: [] as string[],
target_journal: '',
})
/** A template is required as soon as there is one to choose. */
const rules = computed<FormRules>(() => ({
title: [{ required: true, message: '请填写论文标题', trigger: 'blur' }],
template_id: templates.value.length
? [{ required: true, message: '请选择论文模板', trigger: 'change' }]
: [],
}))
const title = computed(() => (props.paper ? '编辑论文信息' : '新建论文'))
watch(
() => props.modelValue,
async (open) => {
if (!open) return
formRef.value?.clearValidate()
form.title = props.paper?.title ?? ''
form.template_id = props.paper?.template_id ?? null
form.abstract = ''
form.author = props.paper?.author ?? ''
form.status = props.paper?.status ?? 'draft'
form.keywords = splitKeywords(props.paper?.keywords)
form.target_journal = props.paper?.target_journal ?? ''
loading.value = true
try {
templates.value = await fetchAllTemplates()
// A new paper starts on the most recently edited template — the one the
// writer was last working on is usually the one they want again.
if (!props.paper && form.template_id == null && templates.value.length) {
form.template_id = templates.value[0]!.id
}
if (props.paper) {
const detail = await getPaper(props.paper.id)
form.title = detail.title
form.template_id = detail.template_id
form.abstract = detail.abstract ?? ''
form.author = detail.author ?? ''
form.status = detail.status
form.keywords = splitKeywords(detail.keywords)
form.target_journal = detail.target_journal ?? ''
}
} catch (error) {
ElMessage.error(errorMessage(error))
} finally {
loading.value = false
}
},
)
async function submit(): Promise<void> {
const valid = await formRef.value?.validate().catch(() => false)
if (!valid) return
saving.value = true
try {
const payload = {
title: form.title.trim(),
template_id: form.template_id,
abstract: form.abstract.trim() || null,
author: form.author.trim() || null,
status: form.status,
keywords: form.keywords.length ? form.keywords.join(', ') : null,
target_journal: form.target_journal.trim() || null,
}
// `template_id` travels even when it is null: clearing a template is a
// real change, and PATCH would otherwise read the key as "not sent".
const saved = props.paper
? await updatePaper(props.paper.id, payload)
: await createPaper(payload)
ElMessage.success(props.paper ? '论文已更新' : '论文已创建')
emit('saved', saved)
visible.value = false
} catch (error) {
ElMessage.error(errorMessage(error))
} finally {
saving.value = false
}
}
</script>
<template>
<el-dialog
v-model="visible"
:title="title"
width="min(680px, 94vw)"
:close-on-click-modal="false"
append-to-body
>
<el-form ref="formRef" v-loading="loading" :model="form" :rules="rules" label-width="96px">
<el-form-item label="论文标题" prop="title">
<el-input v-model="form.title" placeholder="如 基于结构化模板的论文写作工具" maxlength="255" clearable />
</el-form-item>
<el-form-item label="所用模板" prop="template_id">
<!-- Only settable at creation time. Changing the template of a paper
that already has content re-shapes the whole document, so it goes
through the paper view's 切换模板 dialog, which previews the
impact first. -->
<el-select
v-model="form.template_id"
placeholder="选择论文模板"
clearable
:disabled="Boolean(paper)"
class="full"
>
<el-option
v-for="template in templates"
:key="template.id"
:value="template.id"
:label="template.name"
>
<span>{{ template.name }}</span>
<span class="option-hint">{{ template.field_count }} 段</span>
</el-option>
</el-select>
<div v-if="templates.length === 0" class="field-hint">
还没有模板,可以先创建论文,之后在
<RouterLink to="/templates/list">模板列表</RouterLink> 里建好再切换。
</div>
<div v-else-if="paper" class="field-hint">
切换模板会改变正文结构,请回到论文页面点「切换模板」,那里会先说明影响。
</div>
<div v-else class="field-hint">
正文的结构完全来自这个模板:每个段落字段对应论文里的一个段落。
</div>
</el-form-item>
<el-form-item label="作者">
<el-input v-model="form.author" placeholder="如 张三、李四" maxlength="255" clearable />
</el-form-item>
<el-form-item label="状态">
<el-radio-group v-model="form.status">
<el-radio-button
v-for="option in PAPER_STATUS_OPTIONS"
:key="option.value"
:value="option.value"
>
{{ option.label }}
</el-radio-button>
</el-radio-group>
</el-form-item>
<el-form-item label="关键词">
<el-select
v-model="form.keywords"
multiple
filterable
allow-create
default-first-option
:reserve-keyword="false"
placeholder="输入后回车添加,如 结构化写作"
class="full"
>
<el-option v-for="word in form.keywords" :key="word" :value="word" :label="word" />
</el-select>
</el-form-item>
<el-form-item label="目标期刊">
<el-input v-model="form.target_journal" placeholder="如 情报学报" maxlength="255" clearable />
</el-form-item>
<el-form-item label="摘要">
<el-input
v-model="form.abstract"
type="textarea"
:rows="3"
placeholder="论文摘要,可稍后再写"
/>
</el-form-item>
</el-form>
<template #footer>
<el-button @click="visible = false">取消</el-button>
<el-button type="primary" :loading="saving" @click="submit">
{{ paper ? '保存修改' : '创建论文' }}
</el-button>
</template>
</el-dialog>
</template>
<style scoped>
.full {
width: 100%;
}
.option-hint {
float: right;
color: var(--el-text-color-placeholder);
font-size: 12px;
}
.field-hint {
width: 100%;
margin-top: 4px;
font-size: 12px;
color: var(--el-text-color-secondary);
line-height: 1.6;
}
</style>
@@ -0,0 +1,250 @@
<script setup lang="ts">
/**
* One paragraph of a paper, as the reader sees it.
*
* Two things about this component carry the feature's contracts:
*
* 1. **The structure is never skipped.** A paragraph with no sentences still
* renders its heading and a quiet placeholder, because the paper's shape
* comes from its template and an unwritten paragraph is still a paragraph.
* 2. **A paragraph is reassembled from its sentences.** They are printed in
* `sort` order, one after another, with no separator added — Chinese
* sentences already end in punctuation, and inserting anything between them
* would show up in the text.
*
* A sentence that quotes something gets a superscript marker numbered by the
* paper's citation list, so the marker and the 参考文献 entry cannot disagree.
*/
import { computed } from 'vue'
import { Edit } from '@element-plus/icons-vue'
import type { PaperParagraph } from '@/api/papers'
import { PARAGRAPH_UNSET_LABEL, levelIndent } from '@/utils/format'
const props = defineProps<{
paragraph: PaperParagraph
/** Citation id -> the number shown in the text, assigned by reading order. */
citationIndex: Record<number, number>
}>()
defineEmits<{ edit: [paragraph: PaperParagraph] }>()
/** The heading's own typography, read from the template's field. */
const headingStyle = computed(() => {
const style: Record<string, string> = {}
if (props.paragraph.font_size != null) style.fontSize = `${props.paragraph.font_size}pt`
if (props.paragraph.font_color) style.color = props.paragraph.font_color
return style
})
/** Indentation follows the field's level, exactly as the template outline does. */
const headingIndent = computed(() => levelIndent(props.paragraph.level))
/** Whether anything has actually been written here. */
const hasContent = computed(() =>
props.paragraph.sentences.some(
(sentence) => sentence.content.trim().length > 0 || sentence.citations.length > 0,
),
)
/** Anchor id, so a citation can point back at the paragraph it came from. */
const anchor = computed(() => `paragraph-${props.paragraph.paper_template_filed_sort}`)
</script>
<template>
<section :id="anchor" class="paragraph" :class="{ 'is-unset': !paragraph.matched }">
<header class="paragraph-head">
<h3 class="paragraph-title" :style="{ paddingLeft: headingIndent }">
<span class="paragraph-sort" :title="`sort = ${paragraph.paper_template_filed_sort}`">
{{ paragraph.paper_template_filed_sort }}
</span>
<span v-if="paragraph.name" class="paragraph-name" :style="headingStyle">
{{ paragraph.name }}
</span>
<span v-else class="paragraph-name paragraph-name--unset" :style="headingStyle">
{{ PARAGRAPH_UNSET_LABEL }}
</span>
</h3>
<div class="paragraph-actions">
<el-tag v-if="!paragraph.matched" size="small" type="warning" effect="plain">
模板无此段
</el-tag>
<span v-else class="paragraph-count">{{ paragraph.sentences.length }} 句</span>
<!-- The edit button sits beside every paragraph, written or not. -->
<el-button
size="small"
type="primary"
plain
:icon="Edit"
@click="$emit('edit', paragraph)"
>
编辑
</el-button>
</div>
</header>
<p v-if="hasContent" class="paragraph-body">
<template v-for="sentence in paragraph.sentences" :key="sentence.id">
<span class="sentence">{{ sentence.content }}</span>
<el-tooltip
v-for="citation in sentence.citations"
:key="citation.id"
placement="top"
:show-after="120"
>
<template #content>
<div class="cite-tip">
<div class="cite-tip-head">
[{{ citationIndex[citation.id] ?? '?' }}]
<span v-if="citation.reference_id">引用 #{{ citation.reference_id }}</span>
<span v-else class="cite-tip-unlinked">未关联引用 id</span>
</div>
<div class="cite-tip-quote">{{ citation.quote }}</div>
</div>
</template>
<sup class="cite-mark">{{ citationIndex[citation.id] ?? '?' }}</sup>
</el-tooltip>
</template>
</p>
<p v-else class="paragraph-empty">(本段暂无内容)</p>
</section>
</template>
<style scoped>
.paragraph {
padding: 14px 16px;
border-radius: 8px;
border: 1px solid transparent;
transition: background-color 0.15s ease, border-color 0.15s ease;
}
.paragraph + .paragraph {
border-top: 1px solid var(--el-border-color-lighter);
border-top-left-radius: 0;
border-top-right-radius: 0;
}
.paragraph:hover {
background-color: var(--el-fill-color-lighter);
}
.paragraph.is-unset {
background-color: var(--el-color-warning-light-9);
}
.paragraph.is-unset:hover {
background-color: var(--el-color-warning-light-8);
}
.paragraph-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.paragraph-title {
display: flex;
align-items: baseline;
gap: 8px;
margin: 0;
min-width: 0;
font-weight: 600;
line-height: 1.6;
}
/* The position the paragraph occupies in the document. Shown because it is
what a sentence is addressed by, and what survives a template switch. */
.paragraph-sort {
flex: 0 0 auto;
min-width: 24px;
padding: 0 6px;
font-size: 11px;
font-weight: 400;
font-variant-numeric: tabular-nums;
text-align: center;
color: var(--el-text-color-secondary);
background-color: var(--el-fill-color);
border-radius: 4px;
}
.paragraph-name {
min-width: 0;
overflow-wrap: anywhere;
}
.paragraph-name--unset {
color: var(--el-color-warning);
font-style: italic;
}
.paragraph-actions {
display: flex;
align-items: center;
gap: 8px;
flex: 0 0 auto;
}
.paragraph-count {
font-size: 12px;
color: var(--el-text-color-placeholder);
}
.paragraph-body {
margin: 8px 0 0;
/* Body text is set at a readable size rather than at the heading's: a
template's font size describes its headings, not its prose. */
font-size: 15px;
line-height: 2;
color: var(--el-text-color-primary);
text-align: justify;
/* The two-character indent a Chinese manuscript expects. */
text-indent: 2em;
overflow-wrap: anywhere;
}
.sentence {
white-space: pre-wrap;
}
.cite-mark {
margin: 0 1px;
padding: 0 2px;
font-size: 11px;
color: var(--el-color-primary);
cursor: help;
vertical-align: super;
line-height: 0;
}
.paragraph-empty {
margin: 8px 0 0;
font-size: 13px;
color: var(--el-text-color-placeholder);
font-style: italic;
}
.cite-tip {
max-width: 320px;
}
.cite-tip-head {
display: flex;
align-items: center;
gap: 8px;
font-weight: 600;
}
.cite-tip-unlinked {
font-weight: 400;
opacity: 0.7;
}
.cite-tip-quote {
margin-top: 4px;
line-height: 1.6;
}
</style>
@@ -0,0 +1,576 @@
<script setup lang="ts">
/**
* The paragraph editor — the writer's unit of work.
*
* It shows one paragraph the way the paper will read it: every sentence of the
* paragraph on its own line, in `sort` order, each one editable, each one able
* to carry citations. Saving writes the paragraph back whole, so what is on
* screen and what is stored cannot drift apart.
*
* Three rules are stated in the UI because they are the ones a writer would
* otherwise have to guess:
*
* * **order comes from `sort`, not from the screen.** Rows are displayed in
* ascending `sort`, so editing a number moves the line — which is the point:
* the paragraph is reassembled from these numbers, and nothing else.
* * **a citation must quote something.** A citation with an empty 引用内容 is
* refused here (and by the API), because a bare id is not usable in a text.
* * **whitespace-only lines are dropped on save.** Adding a line and leaving it
* blank is a normal way to type, not a request for an empty sentence.
*
* The optional 「所属段落」 select moves the whole paragraph to another position,
* appending after whatever that paragraph already holds. That is the manual
* form of what switching the paper's template does by itself.
*/
import { computed, reactive, ref, watch } from 'vue'
import { ArrowDown, ArrowUp, Delete, Plus, Refresh } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { errorMessage } from '@/api/client'
import {
getParagraph,
replaceParagraph,
type PaperDocument,
type PaperParagraph,
type SentenceInput,
} from '@/api/papers'
import { PARAGRAPH_UNSET_LABEL, foldWhitespace } from '@/utils/format'
const props = defineProps<{
/** Visibility, used with `v-model`. */
modelValue: boolean
paperId: number
/** The paragraph being edited, identified by the position it occupies. */
fieldSort: number | null
/** Every paragraph of the document, for the 「所属段落」 select. */
paragraphs: PaperParagraph[]
}>()
const emit = defineEmits<{
'update:modelValue': [value: boolean]
/** Emitted with the refreshed document after a successful write. */
saved: [document: PaperDocument]
}>()
/** One citation line in the editor. */
interface CitationDraft {
/** Local identity for `v-for`; not sent to the server. */
key: number
reference_id: number | null
quote: string
}
/** One sentence line in the editor. `sort` is always set — see the template. */
interface SentenceDraft {
key: number
sort: number
content: string
citations: CitationDraft[]
}
const visible = computed({
get: () => props.modelValue,
set: (value: boolean) => emit('update:modelValue', value),
})
const loading = ref(false)
const saving = ref(false)
const heading = ref<PaperParagraph | null>(null)
const rows = ref<SentenceDraft[]>([])
const targetSort = ref<number | null>(null)
/** Keys only ever count up, so reopening the dialog cannot collide with itself. */
let nextKey = 1
/** The paragraph as the reader will meet it: ascending `sort`, ties by insertion. */
const orderedRows = computed(() =>
[...rows.value].sort((a, b) => a.sort - b.sort || a.key - b.key),
)
/** Where the paragraph sits now, and where it could go. */
const currentSort = computed(() => props.fieldSort ?? 0)
const moveOptions = computed(() =>
[...props.paragraphs]
.sort((a, b) => a.paper_template_filed_sort - b.paper_template_filed_sort)
.map((paragraph) => ({
value: paragraph.paper_template_filed_sort,
label: `#${paragraph.paper_template_filed_sort} · ${
paragraph.name ?? PARAGRAPH_UNSET_LABEL
}`,
count: paragraph.sentences.length,
})),
)
/** The target paragraph, when the writer has chosen a different one. */
const moveTarget = computed(() => {
if (targetSort.value == null || targetSort.value === currentSort.value) return null
return (
props.paragraphs.find(
(paragraph) => paragraph.paper_template_filed_sort === targetSort.value,
) ?? null
)
})
watch(
() => props.modelValue,
async (open) => {
if (!open || props.fieldSort == null) return
rows.value = []
heading.value = null
targetSort.value = props.fieldSort
loading.value = true
try {
// Read the paragraph from the server rather than from the caller's copy:
// the editor must never write back a stale version of the paragraph.
const detail = await getParagraph(props.paperId, props.fieldSort)
heading.value = detail.paragraph
rows.value = detail.paragraph.sentences.map((sentence) => ({
key: nextKey++,
sort: sentence.sort,
content: sentence.content,
citations: sentence.citations.map((citation) => ({
key: nextKey++,
reference_id: citation.reference_id,
quote: citation.quote,
})),
}))
} catch (error) {
ElMessage.error(errorMessage(error))
visible.value = false
} finally {
loading.value = false
}
},
)
/** The next free sort, so an added line lands at the end. */
function nextSort(): number {
return rows.value.reduce((max, row) => Math.max(max, row.sort), 0) + 1
}
function addSentence(): void {
rows.value.push({ key: nextKey++, sort: nextSort(), content: '', citations: [] })
}
function removeSentence(key: number): void {
rows.value = rows.value.filter((row) => row.key !== key)
}
function addCitation(row: SentenceDraft): void {
row.citations.push({ key: nextKey++, reference_id: null, quote: '' })
}
function removeCitation(row: SentenceDraft, key: number): void {
row.citations = row.citations.filter((citation) => citation.key !== key)
}
/**
* Move a line one step, by swapping `sort` with its neighbour.
*
* Only the two values involved change, so a deliberately sparse numbering
* (10, 20, 30) survives a nudge. Equal values would sit still after a plain
* swap, so in that case the moving row is nudged past its neighbour instead.
*/
function swapOrder(index: number, delta: number): void {
const ordered = orderedRows.value
const target = index + delta
if (target < 0 || target >= ordered.length) return
const moving = ordered[index]!
const other = ordered[target]!
const movingSort = moving.sort
if (movingSort === other.sort) {
moving.sort = delta < 0 ? other.sort - 1 : other.sort + 1
return
}
moving.sort = other.sort
other.sort = movingSort
}
/** Renumber the lines 1..N in the order they are displayed. */
function autoNumber(): void {
orderedRows.value.forEach((row, index) => {
row.sort = index + 1
})
}
/** The first reason the paragraph cannot be saved, or `null`. */
function firstProblem(): string | null {
for (const [index, row] of orderedRows.value.entries()) {
if (row.content.trim() && !Number.isFinite(row.sort)) {
return `第 ${index + 1} 句的 sort 无效`
}
for (const citation of row.citations) {
if (citation.reference_id != null && citation.reference_id < 1) {
return `第 ${index + 1} 句的引用 id 必须是正整数`
}
// The one hard rule: a citation must say what it quotes.
if (!citation.quote.trim()) {
return `第 ${index + 1} 句的引用内容不能为空(引用必须写明引用的内容)`
}
}
}
return null
}
async function submit(): Promise<void> {
if (props.fieldSort == null) return
const problem = firstProblem()
if (problem) {
ElMessage.warning(problem)
return
}
// Whitespace-only lines are dropped: a line the writer added and left blank
// carries nothing, and keeping it would put an empty sentence in the paper.
const sentences: SentenceInput[] = orderedRows.value
.filter(
(row) =>
row.content.trim().length > 0 ||
row.citations.some((citation) => citation.quote.trim().length > 0),
)
.map((row) => ({
sort: row.sort,
content: foldWhitespace(row.content),
citations: row.citations
.filter((citation) => citation.quote.trim().length > 0)
.map((citation) => ({
reference_id: citation.reference_id ?? null,
quote: citation.quote.trim(),
})),
}))
saving.value = true
try {
const document_ = await replaceParagraph(props.paperId, props.fieldSort, {
sentences,
target_sort:
targetSort.value != null && targetSort.value !== props.fieldSort
? targetSort.value
: null,
})
ElMessage.success(
targetSort.value !== props.fieldSort ? '段落已保存并移动到新位置' : '段落已保存',
)
emit('saved', document_)
visible.value = false
} catch (error) {
ElMessage.error(errorMessage(error))
} finally {
saving.value = false
}
}
</script>
<template>
<el-dialog
v-model="visible"
width="min(860px, 94vw)"
top="6vh"
:close-on-click-modal="false"
append-to-body
destroy-on-close
>
<template #header>
<div class="dialog-header">
<span class="dialog-title">编辑段落</span>
<span v-if="heading" class="dialog-subject">
<span v-if="heading.name">{{ heading.name }}</span>
<span v-else class="unset">{{ PARAGRAPH_UNSET_LABEL }}</span>
<el-tag size="small" effect="plain" type="info">
sort = {{ heading.paper_template_filed_sort }}
</el-tag>
</span>
</div>
</template>
<div v-loading="loading" class="editor">
<el-alert
v-if="heading && !heading.matched"
type="warning"
:closable="false"
show-icon
title="当前模板在这个位置上没有段落"
description="内容会照常保存和显示,标题显示为「未设定」。切回原来的模板,标题就会恢复。"
/>
<div class="editor-meta">
<span class="meta-label">所属段落</span>
<el-select v-model="targetSort" size="small" class="meta-select">
<el-option
v-for="option in moveOptions"
:key="option.value"
:value="option.value"
:label="option.label"
>
<span>{{ option.label }}</span>
<span class="option-hint">
{{ option.value === currentSort ? '当前' : `${option.count} 句` }}
</span>
</el-option>
</el-select>
<span class="meta-hint">
换段落会把这一段整体搬过去,追加到目标段落已有句子之后。
</span>
</div>
<el-alert
v-if="moveTarget"
type="warning"
:closable="false"
show-icon
:title="`目标段落「${moveTarget.name ?? PARAGRAPH_UNSET_LABEL}」已有 ${moveTarget.sentences.length} 句`"
description="本段的句子会追加在它们之后。"
/>
<div class="editor-toolbar">
<span class="toolbar-title">共 {{ orderedRows.length }} 句</span>
<span class="toolbar-hint">按 sort 升序拼成这个段落</span>
<div class="toolbar-spacer" />
<el-button size="small" :icon="Refresh" :disabled="!orderedRows.length" @click="autoNumber">
自动编号
</el-button>
<el-button size="small" type="primary" plain :icon="Plus" @click="addSentence">
新增一句
</el-button>
</div>
<div class="rows">
<el-empty
v-if="orderedRows.length === 0"
:image-size="60"
description="这一段还没有内容,点「新增一句」开始写"
/>
<article v-for="(row, index) in orderedRows" :key="row.key" class="row">
<header class="row-head">
<span class="row-index">第 {{ index + 1 }} 句</span>
<el-input-number
v-model="row.sort"
size="small"
controls-position="right"
:min="-9999"
:max="9999"
class="sort-input"
/>
<div class="toolbar-spacer" />
<el-button
link
:icon="ArrowUp"
title="上移"
:disabled="index === 0"
@click="swapOrder(index, -1)"
/>
<el-button
link
:icon="ArrowDown"
title="下移"
:disabled="index === orderedRows.length - 1"
@click="swapOrder(index, 1)"
/>
<el-button link type="danger" :icon="Delete" title="删除这一句" @click="removeSentence(row.key)" />
</header>
<el-input
v-model="row.content"
type="textarea"
:autosize="{ minRows: 1, maxRows: 6 }"
placeholder="这一句的内容(只留空白的句子保存时会删除)"
/>
<div class="citations">
<div v-for="citation in row.citations" :key="citation.key" class="citation">
<el-input-number
v-model="citation.reference_id"
size="small"
controls-position="right"
:min="1"
:max="999999"
placeholder="引用 id"
class="cite-id"
/>
<el-input
v-model="citation.quote"
size="small"
type="textarea"
:autosize="{ minRows: 1, maxRows: 4 }"
placeholder="引用内容(必填)"
class="cite-quote"
/>
<el-button
link
type="danger"
:icon="Delete"
title="删除这条引用"
@click="removeCitation(row, citation.key)"
/>
</div>
<el-button link type="primary" :icon="Plus" @click="addCitation(row)">
添加引用
</el-button>
</div>
</article>
</div>
</div>
<template #footer>
<span class="footer-hint">空段落会保留结构,在正文里显示为空白。</span>
<el-button @click="visible = false">取消</el-button>
<el-button type="primary" :loading="saving" @click="submit">保存段落</el-button>
</template>
</el-dialog>
</template>
<style scoped>
.dialog-header {
display: flex;
align-items: baseline;
gap: 12px;
min-width: 0;
}
.dialog-title {
font-size: 16px;
font-weight: 600;
}
.dialog-subject {
display: inline-flex;
align-items: center;
gap: 8px;
color: var(--el-text-color-regular);
font-size: 13px;
}
.unset {
color: var(--el-color-warning);
font-style: italic;
}
.editor {
display: flex;
flex-direction: column;
gap: 12px;
min-height: 200px;
}
.editor-meta {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.meta-label {
font-size: 13px;
color: var(--el-text-color-regular);
}
.meta-select {
width: 240px;
}
.meta-hint {
font-size: 12px;
color: var(--el-text-color-secondary);
}
.option-hint {
float: right;
color: var(--el-text-color-placeholder);
font-size: 12px;
}
.editor-toolbar {
display: flex;
align-items: center;
gap: 10px;
}
.toolbar-title {
font-size: 13px;
font-weight: 600;
}
.toolbar-hint {
font-size: 12px;
color: var(--el-text-color-secondary);
}
.toolbar-spacer {
flex: 1 1 auto;
min-width: 0;
}
.rows {
display: flex;
flex-direction: column;
gap: 10px;
max-height: 52vh;
overflow-y: auto;
scrollbar-width: thin;
padding-right: 4px;
}
.row {
display: flex;
flex-direction: column;
gap: 8px;
padding: 10px 12px;
border: 1px solid var(--el-border-color);
border-radius: 8px;
background-color: var(--el-fill-color-blank);
}
.row-head {
display: flex;
align-items: center;
gap: 8px;
}
.row-index {
font-size: 12px;
color: var(--el-text-color-secondary);
}
.sort-input {
width: 104px;
}
.citations {
display: flex;
flex-direction: column;
gap: 6px;
padding-left: 12px;
border-left: 2px solid var(--el-border-color-lighter);
}
.citation {
display: flex;
align-items: flex-start;
gap: 8px;
}
.cite-id {
width: 130px;
flex: 0 0 auto;
}
.cite-quote {
flex: 1 1 auto;
}
.footer-hint {
float: left;
font-size: 12px;
color: var(--el-text-color-secondary);
line-height: 32px;
}
</style>
@@ -0,0 +1,262 @@
<script setup lang="ts">
/**
* Switch the template a paper is written against.
*
* This is the risky edit in the feature — it re-shapes the entire document in
* one write — so the dialog explains the outcome *before* it happens, by
* comparing the chosen template's positions against the positions the paper
* has content at:
*
* * matched — content that lands under a heading of the new template;
* * unmatched — content the new template has nothing at, which is kept and
* rendered under 未设定 rather than deleted;
* * new empty paragraphs — structure the new template adds, empty for now.
*
* Nothing else changes: the sentences themselves are never touched, which is
* why switching back restores the previous layout exactly.
*/
import { computed, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { errorMessage } from '@/api/client'
import { updatePaper, type PaperDetail, type PaperParagraph } from '@/api/papers'
import { fetchAllTemplates, getTemplate, type TemplateListItem } from '@/api/templates'
import { PARAGRAPH_UNSET_LABEL } from '@/utils/format'
const props = defineProps<{
/** Visibility, used with `v-model`. */
modelValue: boolean
paper: PaperDetail
/** The paper's paragraphs, so the impact of a switch can be previewed. */
paragraphs: PaperParagraph[]
}>()
const emit = defineEmits<{
'update:modelValue': [value: boolean]
/** Emitted with the updated paper after a successful switch. */
saved: [paper: PaperDetail]
}>()
const visible = computed({
get: () => props.modelValue,
set: (value: boolean) => emit('update:modelValue', value),
})
const templates = ref<TemplateListItem[]>([])
const selected = ref<number | null>(null)
const loading = ref(false)
const previewing = ref(false)
const saving = ref(false)
/** Paragraph positions and names of the candidate template. */
const candidate = ref<{ sort: number; name: string }[]>([])
/** Positions that hold content today. */
const contentSorts = computed(() =>
props.paragraphs
.filter((paragraph) => paragraph.sentences.length > 0)
.map((paragraph) => paragraph.paper_template_filed_sort)
.sort((a, b) => a - b),
)
const candidateSorts = computed(() => new Set(candidate.value.map((item) => item.sort)))
/** Content that will keep a heading under the new template. */
const matched = computed(() =>
contentSorts.value.filter((sort) => candidateSorts.value.has(sort)),
)
/** Content the new template has no position for — kept, shown as 未设定. */
const unmatched = computed(() =>
contentSorts.value.filter((sort) => !candidateSorts.value.has(sort)),
)
/** Positions the new template adds, which will read as empty paragraphs. */
const addedEmpty = computed(() =>
candidate.value.filter((item) => !contentSorts.value.includes(item.sort)).length,
)
const changed = computed(
() => selected.value != null && selected.value !== props.paper.template_id,
)
watch(
() => props.modelValue,
async (open) => {
if (!open) return
selected.value = props.paper.template_id
candidate.value = []
loading.value = true
try {
templates.value = await fetchAllTemplates()
if (selected.value != null) await loadCandidate(selected.value)
} catch (error) {
ElMessage.error(errorMessage(error))
} finally {
loading.value = false
}
},
)
/** Load the candidate template's outline, so the impact can be previewed. */
async function loadCandidate(templateId: number | null): Promise<void> {
if (templateId == null) {
candidate.value = []
return
}
previewing.value = true
try {
const detail = await getTemplate(templateId)
candidate.value = detail.fields.map((field) => ({ sort: field.sort, name: field.name }))
} catch (error) {
ElMessage.error(errorMessage(error))
candidate.value = []
} finally {
previewing.value = false
}
}
watch(selected, (value) => {
void loadCandidate(value)
})
async function submit(): Promise<void> {
if (!changed.value || selected.value == null) return
saving.value = true
try {
const paper = await updatePaper(props.paper.id, { template_id: selected.value })
ElMessage.success('已切换模板')
emit('saved', paper)
visible.value = false
} catch (error) {
ElMessage.error(errorMessage(error))
} finally {
saving.value = false
}
}
</script>
<template>
<el-dialog
v-model="visible"
title="切换模板"
width="min(660px, 94vw)"
:close-on-click-modal="false"
append-to-body
>
<div v-loading="loading" class="switcher">
<el-alert
type="info"
:closable="false"
show-icon
title="切换模板只改结构,不动内容"
description="句子的位置(sort)会保留,所以在旧模板里写的内容不会丢;切回来就恢复原样。"
/>
<div class="row">
<span class="label">当前模板</span>
<el-tag effect="plain">{{ paper.template_name ?? PARAGRAPH_UNSET_LABEL }}</el-tag>
</div>
<div class="row">
<span class="label">切换为</span>
<el-select v-model="selected" placeholder="选择模板" class="select" :loading="previewing">
<el-option
v-for="template in templates"
:key="template.id"
:value="template.id"
:label="template.name"
:disabled="template.id === paper.template_id"
>
<span>{{ template.name }}</span>
<span class="option-hint">{{ template.field_count }} 段</span>
</el-option>
</el-select>
</div>
<template v-if="changed">
<el-divider content-position="left">切换后的影响</el-divider>
<ul class="impact">
<li class="ok">
<strong>{{ matched.length }}</strong> 段内容会落到新模板对应的段落标题下
</li>
<li v-if="addedEmpty" class="muted">
新模板另有 <strong>{{ addedEmpty }}</strong> 个段落暂时为空,正文里显示为空白
</li>
<li v-if="unmatched.length" class="warn">
有 <strong>{{ unmatched.length }}</strong> 段内容在新模板里没有对应位置(sort
{{ unmatched.join('、') }}),会按顺序保留,标题显示为「未设定」
</li>
<li v-else class="ok">没有内容会失去位置</li>
</ul>
<el-alert
v-if="unmatched.length"
type="warning"
:closable="false"
show-icon
title="这些段落不会丢失"
description="它们照常出现在正文里,只是没有标题。可以逐个用段落编辑里的「所属段落」搬到新模板的段落上。"
/>
</template>
</div>
<template #footer>
<el-button @click="visible = false">取消</el-button>
<el-button type="primary" :disabled="!changed" :loading="saving" @click="submit">
确认切换
</el-button>
</template>
</el-dialog>
</template>
<style scoped>
.switcher {
display: flex;
flex-direction: column;
gap: 12px;
}
.row {
display: flex;
align-items: center;
gap: 12px;
}
.label {
flex: 0 0 72px;
font-size: 13px;
color: var(--el-text-color-regular);
}
.select {
width: 280px;
}
.option-hint {
float: right;
color: var(--el-text-color-placeholder);
font-size: 12px;
}
.impact {
margin: 0;
padding-left: 18px;
line-height: 2;
font-size: 13px;
}
.impact .ok {
color: var(--el-text-color-regular);
}
.impact .muted {
color: var(--el-text-color-secondary);
}
.impact .warn {
color: var(--el-color-warning);
}
</style>