Files
paper-doc/frontend/src/components/fields/FieldFormDialog.vue
T
govin 199e328b48 refactor: call a heading a title, and its use a placement
`template_field_library` and `template_field` were one word apart and meant
opposite kinds of thing — a catalogue of rows versus one row — and neither name
said what a row actually is. Every row of the library is a **heading**: a piece
of text like 「1. Introduction」 with a level and typography, which is what the
reader sees at the top of a paragraph; and every row of the join table is that
heading *placed* in a template, `sort` included.

    template_field_library  -> template_title
    template_field          -> template_title_placement
    field_id (the column)   -> title_id
    TemplateFieldLibrary    -> TemplateTitle
    TemplateField           -> TemplateTitlePlacement

The join table keeps its own name rather than becoming `_link`, because it is
not a bare link: it carries `sort`, the only place display order is stored, and
it deliberately allows the same title twice in one template. `_link` would
describe two foreign keys and hide the column the ordering rule rests on.

Carried through every level, because a half-renamed layer is how the confusing
pair got there in the first place: HTTP paths (`/template-field-library` ->
`/template-titles`), the template payload (`fields`/`field_id` ->
`placements`/`title_id`, and `field_count` -> `placement_count`), the Pydantic
schemas, the CRUD modules, the seed script, the frontend API module and types,
and `docs/OVERVIEW.md`, which now states the naming rules outright.

Two deliberate exceptions:

* `paper_template_filed_sort` is untouched — it is a column of the paper module
  and is spelled as the feature was specified.
* The MCP tools keep their agent-facing names (`field_list`, `field_ids`, and
  the `fields`/`field_id` keys in their responses). Agents already call them by
  those names; the storage names they read underneath have changed.

The migration renames in place (data preserved: 4 templates, 45 titles, 63
placements) and is written to tolerate a database where part of it already ran,
which is not hypothetical — the first attempt renamed the tables and then failed
on the column, because Alembic's MySQL dialect wants an explicit type for
`alter_column` and will not rename a column without one. TiDB carries the
foreign key along with both the renamed table and the renamed column, rehearsed
against the cluster first, and it stays enforced.

Verified: seed re-runs clean, the paper smoke test's 45 checks and the MCP
smoke test's 47 pass, `vue-tsc` and the build are clean, and the UI was driven
in a headless browser through the template list, its preview drawer, the title
library page, the template form (which now posts `placements` with `title_id`)
and the paper document with no console errors.
2026-09-22 16:55:02 +08:00

243 lines
6.3 KiB
Vue

<script setup lang="ts">
/**
* Create / edit dialog for one library field.
*
* The live preview underneath the form is the point of the dialog: font size
* and colour are the two settings whose effect is impossible to judge from the
* value alone, so the preview renders the name exactly as the outline will.
*/
import { computed, reactive, ref, watch } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { errorMessage } from '@/api/client'
import {
createTemplateTitle,
updateTemplateTitle,
type TemplateTitle,
type TemplateTitlePayload,
} from '@/api/templateTitles'
import { normalizeHexColor, typographyStyle } from '@/utils/format'
const props = defineProps<{
/** Visibility, used with `v-model`. */
modelValue: boolean
/** The field being edited, or `null` to create a new one. */
field: TemplateTitle | null
}>()
const emit = defineEmits<{
'update:modelValue': [value: boolean]
/** Emitted after a successful write, so the list can refresh. */
saved: []
}>()
const visible = computed({
get: () => props.modelValue,
set: (value: boolean) => emit('update:modelValue', value),
})
const formRef = ref<FormInstance>()
const saving = ref(false)
const form = reactive<TemplateTitlePayload>({
name: '',
level: 1,
// 小四, the conventional body size for a Chinese thesis.
font_size: 12,
font_color: '#000000',
})
const rules: FormRules<TemplateTitlePayload> = {
name: [
{ required: true, message: '请填写字段名称', trigger: 'blur' },
{ max: 255, message: '字段名称最多 255 个字符', trigger: 'blur' },
],
}
const LEVEL_OPTIONS = [
{ value: 1, label: '1 级 · 如 1. / 2.' },
{ value: 2, label: '2 级 · 如 1.1 / 1.2' },
{ value: 3, label: '3 级 · 如 1.1.1' },
{ value: 4, label: '4 级' },
]
/** Swatches offered by the picker — the greys match the seeded field colours. */
const PRESET_COLORS = [
'#000000',
'#1F1F1F',
'#404040',
'#595959',
'#8C8C8C',
'#409EFF',
'#67C23A',
'#E6A23C',
'#F56C6C',
]
const previewStyle = computed(() => typographyStyle(form))
/** The title states which mode the dialog is in, so it is never ambiguous. */
const title = computed(() => (props.field ? '编辑字段' : '新增字段'))
// Re-seed the form each time the dialog opens, so a cancelled edit never leaks
// into the next one.
watch(
() => props.modelValue,
(open) => {
if (!open) return
formRef.value?.clearValidate()
const source = props.field
form.name = source?.name ?? ''
form.level = source?.level ?? 1
form.font_size = source?.font_size ?? 12
form.font_color = source?.font_color ?? '#000000'
},
)
/**
* Tidy a hand-typed colour when the input loses focus.
*
* The picker only ever produces `#RRGGBB`, but the text box next to it accepts
* `rgb(...)` and shorthand too, matching what the API takes.
*/
function commitColor(): void {
const normalized = normalizeHexColor(form.font_color)
if (normalized) {
form.font_color = normalized
return
}
ElMessage.warning('颜色格式无效,请使用 #RRGGBB 或 rgb(r,g,b)')
form.font_color = props.field?.font_color ?? '#000000'
}
async function submit(): Promise<void> {
const valid = await formRef.value?.validate().catch(() => false)
if (!valid) return
saving.value = true
try {
if (props.field) {
await updateTemplateTitle(props.field.id, { ...form })
ElMessage.success('字段已更新,使用它的模板会同步生效')
} else {
await createTemplateTitle({ ...form })
ElMessage.success('字段已创建')
}
emit('saved')
visible.value = false
} catch (error) {
ElMessage.error(errorMessage(error))
} finally {
saving.value = false
}
}
</script>
<template>
<el-dialog v-model="visible" :title="title" width="520px" append-to-body>
<el-form ref="formRef" :model="form" :rules="rules" label-width="88px">
<el-form-item label="字段名称" prop="name">
<el-input
v-model="form.name"
placeholder="如 1. Introduction,编号自己写,系统不会改"
maxlength="255"
show-word-limit
clearable
/>
</el-form-item>
<el-form-item label="字段等级">
<el-select v-model="form.level" class="full">
<el-option
v-for="option in LEVEL_OPTIONS"
:key="option.value"
:label="option.label"
:value="option.value"
/>
</el-select>
</el-form-item>
<el-form-item label="字体大小">
<el-input-number
v-model="form.font_size"
:min="6"
:max="48"
:step="0.5"
:precision="1"
controls-position="right"
/>
<span class="unit">pt</span>
</el-form-item>
<el-form-item label="字体颜色">
<div class="color-row">
<el-color-picker v-model="form.font_color" :predefine="PRESET_COLORS" />
<el-input
v-model="form.font_color"
class="color-input"
placeholder="#RRGGBB 或 rgb(r,g,b)"
@blur="commitColor"
/>
</div>
</el-form-item>
<el-form-item label="预览">
<div class="preview">
<span :style="previewStyle">{{ form.name || '(未命名字段)' }}</span>
<span class="preview-meta">
{{ form.level }} 级 · {{ form.font_size }}pt · {{ form.font_color }}
</span>
</div>
</el-form-item>
</el-form>
<template #footer>
<el-button @click="visible = false">取消</el-button>
<el-button type="primary" :loading="saving" @click="submit">保存</el-button>
</template>
</el-dialog>
</template>
<style scoped>
.full {
width: 100%;
}
.unit {
margin-left: 8px;
color: var(--el-text-color-secondary);
font-size: 13px;
}
.color-row {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
}
.color-input {
width: 180px;
}
.preview {
display: flex;
flex-direction: column;
gap: 4px;
width: 100%;
padding: 10px 12px;
border: 1px dashed var(--el-border-color);
border-radius: 6px;
background-color: var(--el-fill-color-lighter);
/* Long names wrap rather than widening the dialog. */
min-width: 0;
overflow-wrap: anywhere;
}
.preview-meta {
font-size: 12px;
color: var(--el-text-color-secondary);
}
</style>