frontend: typeset the LaTeX, and let a sentence start a new line
Two things a paper needs that the paragraph model could not express.
**Formulas.** A sentence stores the LaTeX the writer typed — `$\ell$`,
`$$ … \tag{1} $$` — because that is the editable form, and it was being printed
as source. `src/utils/math.ts` now splits a sentence into text and formulas,
gives the formulas to KaTeX and escapes everything else; `math-error` in red
when KaTeX cannot read one, rather than an exception that blanks the paragraph
(the paper in the database has 106 sentences with formulas, 29 of them
display). Four delimiters are recognised — `$$…$$`, `\[…\]`, `$…$`, `\(…\)` —
and an unmatched `$` is left alone instead of swallowing the rest of the
paragraph. A display formula is a block, so it takes its own line and centres
itself without any flagging; text goes through `v-html` escaped, and KaTeX runs
with trust off.
**Line breaks.** A paragraph is its sentences run together, which is right for
prose and wrong for a display formula, a list of items or an author line.
`paper_sentence.line_break_before` is that request: a flag rather than a
newline inside `content`, because content folds its whitespace on purpose (a
sentence really is one line) and because a break hidden in a string is one
nobody can see or remove. It prints a `<br>`, it is a checkbox on the
sentence's row in the editor, and it *replaces* the separator rather than
adding to it — the new line already separates, and a space as well would indent
the line by a blank.
Verified against the real paper in the browser: 214 inline formulas and 29
display formulas typeset with zero failures and no `$$` left on the page; a
sentence flagged for a break lands on its own line while its neighbour stays
inline; the display formula centres on a line of its own and the sentence after
it starts below. 54 paper checks (2 new), 61 reference checks and 76 MCP checks
pass, with `vue-tsc` and the build clean.
Also: `.pnpm-store/` is ignored — pnpm put its content-addressed store in the
project root rather than the home directory.
This commit is contained in:
@@ -14,6 +14,7 @@
|
||||
"@element-plus/icons-vue": "^2.3.2",
|
||||
"axios": "^1.20.0",
|
||||
"element-plus": "^2.14.5",
|
||||
"katex": "^0.18.7",
|
||||
"pinia": "^4.0.2",
|
||||
"pinia-plugin-persistedstate": "^4.7.1",
|
||||
"vue": "^3.5.40",
|
||||
|
||||
Generated
+17
@@ -17,6 +17,9 @@ importers:
|
||||
element-plus:
|
||||
specifier: ^2.14.5
|
||||
version: 2.14.5(vue@3.5.42(typescript@6.0.3))
|
||||
katex:
|
||||
specifier: ^0.18.7
|
||||
version: 0.18.7
|
||||
pinia:
|
||||
specifier: ^4.0.2
|
||||
version: 4.0.3(@vue/devtools-api@8.2.1)(typescript@6.0.3)(vue@3.5.42(typescript@6.0.3))
|
||||
@@ -543,6 +546,10 @@ packages:
|
||||
resolution: {integrity: sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==}
|
||||
engines: {node: '>= 0.8'}
|
||||
|
||||
commander@15.0.0:
|
||||
resolution: {integrity: sha512-z67u4ZhzCL/Tydu1lJARtEZYWbWaN7oYLHbsuzocr6y4N6WZAagG3RQ4FW61V1/0+jImpj293XfrcYnd1qxtPg==}
|
||||
engines: {node: '>=22.12.0'}
|
||||
|
||||
confbox@0.1.8:
|
||||
resolution: {integrity: sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==}
|
||||
|
||||
@@ -749,6 +756,10 @@ packages:
|
||||
engines: {node: '>=6'}
|
||||
hasBin: true
|
||||
|
||||
katex@0.18.7:
|
||||
resolution: {integrity: sha512-h+UCwkZ+4Jz8WQ7MLGfj7UVFrRCizGb912fwF4luGdYsC5paYG1vx+jy+KRcC/XkpjGva/P7nAWuxNnPzRvzHw==}
|
||||
hasBin: true
|
||||
|
||||
kolorist@1.8.0:
|
||||
resolution: {integrity: sha512-Y+60/zizpJ3HRH8DCss+q95yr6145JXZo46OTpFvDZWLfRCE4qChOyk1b26nMaNpfHHgxagk9dXT5OP0Tfe+dQ==}
|
||||
|
||||
@@ -1761,6 +1772,8 @@ snapshots:
|
||||
dependencies:
|
||||
delayed-stream: 1.0.0
|
||||
|
||||
commander@15.0.0: {}
|
||||
|
||||
confbox@0.1.8: {}
|
||||
|
||||
confbox@0.2.4: {}
|
||||
@@ -1936,6 +1949,10 @@ snapshots:
|
||||
|
||||
json5@2.2.3: {}
|
||||
|
||||
katex@0.18.7:
|
||||
dependencies:
|
||||
commander: 15.0.0
|
||||
|
||||
kolorist@1.8.0: {}
|
||||
|
||||
lightningcss-android-arm64@1.33.0:
|
||||
|
||||
@@ -84,6 +84,14 @@ export interface Sentence {
|
||||
/** Position inside that paragraph. */
|
||||
sort: number
|
||||
content: string
|
||||
/**
|
||||
* Whether a line break prints before this sentence.
|
||||
*
|
||||
* A paragraph is normally its sentences run together; this is how the writer
|
||||
* asks for a new line — a display formula, a list of items, an author line —
|
||||
* without splitting the paragraph in two.
|
||||
*/
|
||||
line_break_before: boolean
|
||||
citations: Citation[]
|
||||
/**
|
||||
* What to print before this sentence when the paragraph is put back
|
||||
@@ -181,6 +189,8 @@ export interface CitationInput {
|
||||
export interface SentenceInput {
|
||||
sort?: number | null
|
||||
content: string
|
||||
/** Start a new line at this sentence. */
|
||||
line_break_before?: boolean
|
||||
citations: CitationInput[]
|
||||
}
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ import { Edit } from '@element-plus/icons-vue'
|
||||
|
||||
import type { PaperParagraph } from '@/api/papers'
|
||||
import { PARAGRAPH_UNSET_LABEL, levelIndent } from '@/utils/format'
|
||||
import { escapeHtml, hasDisplayMath, renderRich } from '@/utils/math'
|
||||
|
||||
const props = defineProps<{
|
||||
paragraph: PaperParagraph
|
||||
@@ -49,10 +50,39 @@ const headingStyle = computed(() => {
|
||||
/** Indentation follows the field's level, exactly as the template outline does. */
|
||||
const headingIndent = computed(() => levelIndent(props.paragraph.level))
|
||||
|
||||
/**
|
||||
* Every sentence, prepared for printing.
|
||||
*
|
||||
* Typesetting happens here rather than in the template so it runs once per
|
||||
* sentence instead of on every re-render, and so the line-break rule — a break
|
||||
* replaces the separator, it does not add to it — is stated in one place.
|
||||
*/
|
||||
interface RenderedSentence {
|
||||
sentence: PaperParagraph['sentences'][number]
|
||||
/** The sentence as HTML: its separator escaped, its formulas typeset. */
|
||||
html: string
|
||||
/** A `$$ … $$` formula, which takes a line of its own by definition. */
|
||||
display: boolean
|
||||
/** The writer asked for a line break before this sentence. */
|
||||
lineBreak: boolean
|
||||
}
|
||||
|
||||
const rendered = computed<RenderedSentence[]>(() =>
|
||||
props.paragraph.sentences.map((sentence) => ({
|
||||
sentence,
|
||||
html:
|
||||
escapeHtml(sentence.line_break_before ? '' : sentence.separator_before) +
|
||||
renderRich(sentence.content),
|
||||
display: hasDisplayMath(sentence.content),
|
||||
lineBreak: sentence.line_break_before,
|
||||
})),
|
||||
)
|
||||
|
||||
/** Whether anything has actually been written here. */
|
||||
const hasContent = computed(() =>
|
||||
props.paragraph.sentences.some(
|
||||
(sentence) => sentence.content.trim().length > 0 || sentence.citations.length > 0,
|
||||
rendered.value.some(
|
||||
(item) =>
|
||||
item.sentence.content.trim().length > 0 || item.sentence.citations.length > 0,
|
||||
),
|
||||
)
|
||||
|
||||
@@ -95,13 +125,22 @@ const anchor = computed(() => `paragraph-${props.paragraph.paper_template_filed_
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<p v-if="hasContent" class="paragraph-body">
|
||||
<template v-for="sentence in paragraph.sentences" :key="sentence.id">
|
||||
<!-- The separator comes from the server: it is a space for English
|
||||
and nothing for Chinese, and only the server knows which. -->
|
||||
<span class="sentence">{{ sentence.separator_before }}{{ sentence.content }}</span>
|
||||
<div v-if="hasContent" class="paragraph-body">
|
||||
<template v-for="item in rendered" :key="item.sentence.id">
|
||||
<!-- A display formula is a block by definition, so it takes its own
|
||||
line whether or not the writer asked for a break. -->
|
||||
<span
|
||||
v-if="item.display"
|
||||
class="sentence sentence--display"
|
||||
v-html="item.html"
|
||||
></span>
|
||||
<template v-else>
|
||||
<br v-if="item.lineBreak" />
|
||||
<span class="sentence" v-html="item.html"></span>
|
||||
</template>
|
||||
|
||||
<el-tooltip
|
||||
v-for="citation in sentence.citations"
|
||||
v-for="citation in item.sentence.citations"
|
||||
:key="citation.id"
|
||||
placement="top"
|
||||
:show-after="120"
|
||||
@@ -126,7 +165,7 @@ const anchor = computed(() => `paragraph-${props.paragraph.paper_template_filed_
|
||||
<sup class="cite-mark">{{ citationIndex[citation.id] ?? '?' }}</sup>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Nothing below the heading when there is nothing to print. An empty
|
||||
paragraph is a position in an outline, and in an academic paper some
|
||||
@@ -220,6 +259,30 @@ const anchor = computed(() => `paragraph-${props.paragraph.paper_template_filed_
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
/* A display formula centres itself; the paragraph's two-character indent and
|
||||
its justification must not fight it. */
|
||||
.sentence--display {
|
||||
display: block;
|
||||
text-indent: 0;
|
||||
text-align: center;
|
||||
margin: 6px 0;
|
||||
white-space: normal;
|
||||
}
|
||||
|
||||
/* The fallback when KaTeX cannot read a formula: the source, in red, so it can
|
||||
be found and fixed instead of silently vanishing. */
|
||||
.paragraph-body :deep(.math-error) {
|
||||
color: var(--el-color-danger);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.paragraph-body :deep(.katex) {
|
||||
/* Formulas inherit the paragraph's size and colour, and are never justified
|
||||
apart — a stretched equation is unreadable. */
|
||||
font-size: 1.05em;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.cite-mark {
|
||||
margin: 0 1px;
|
||||
padding: 0 2px;
|
||||
|
||||
@@ -65,6 +65,8 @@ interface SentenceDraft {
|
||||
key: number
|
||||
sort: number
|
||||
content: string
|
||||
/** Print a line break before this sentence. */
|
||||
lineBreak: boolean
|
||||
citations: CitationDraft[]
|
||||
}
|
||||
|
||||
@@ -131,6 +133,7 @@ watch(
|
||||
key: nextKey++,
|
||||
sort: sentence.sort,
|
||||
content: sentence.content,
|
||||
lineBreak: sentence.line_break_before,
|
||||
citations: sentence.citations.map((citation) => ({
|
||||
key: nextKey++,
|
||||
reference_id: citation.reference_id,
|
||||
@@ -152,7 +155,13 @@ function nextSort(): number {
|
||||
}
|
||||
|
||||
function addSentence(): void {
|
||||
rows.value.push({ key: nextKey++, sort: nextSort(), content: '', citations: [] })
|
||||
rows.value.push({
|
||||
key: nextKey++,
|
||||
sort: nextSort(),
|
||||
content: '',
|
||||
lineBreak: false,
|
||||
citations: [],
|
||||
})
|
||||
}
|
||||
|
||||
function removeSentence(key: number): void {
|
||||
@@ -237,6 +246,7 @@ async function submit(): Promise<void> {
|
||||
.map((row) => ({
|
||||
sort: row.sort,
|
||||
content: foldWhitespace(row.content),
|
||||
line_break_before: row.lineBreak,
|
||||
citations: row.citations
|
||||
.filter((citation) => citation.quote.trim().length > 0)
|
||||
.map((citation) => ({
|
||||
@@ -331,7 +341,9 @@ async function submit(): Promise<void> {
|
||||
|
||||
<div class="editor-toolbar">
|
||||
<span class="toolbar-title">共 {{ orderedRows.length }} 句</span>
|
||||
<span class="toolbar-hint">按 sort 升序拼成这个段落</span>
|
||||
<span class="toolbar-hint">
|
||||
按 sort 升序拼成这个段落;公式写 LaTeX:行内 $x$,独立成行 $$x$$
|
||||
</span>
|
||||
<div class="toolbar-spacer" />
|
||||
<el-button size="small" :icon="Refresh" :disabled="!orderedRows.length" @click="autoNumber">
|
||||
自动编号
|
||||
@@ -359,6 +371,13 @@ async function submit(): Promise<void> {
|
||||
:max="9999"
|
||||
class="sort-input"
|
||||
/>
|
||||
<el-tooltip
|
||||
content="这一句单独起一行,不与上一句连排(独立成行的公式用 $$…$$ 会自动换行)"
|
||||
placement="top"
|
||||
:show-after="300"
|
||||
>
|
||||
<el-checkbox v-model="row.lineBreak" size="small" label="另起一行" />
|
||||
</el-tooltip>
|
||||
<div class="toolbar-spacer" />
|
||||
<el-button
|
||||
link
|
||||
|
||||
@@ -5,6 +5,10 @@ import ElementPlus from 'element-plus'
|
||||
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
|
||||
|
||||
import 'element-plus/dist/index.css'
|
||||
// Typesetting for the LaTeX a sentence may contain. Imported here rather than
|
||||
// in the component that renders it, because KaTeX ships fonts as well as rules
|
||||
// and a second import would duplicate them.
|
||||
import 'katex/dist/katex.min.css'
|
||||
|
||||
// Global reset and application-shell layout contract. Imported after Element
|
||||
// Plus so it can override its component defaults (e.g. .el-main overflow).
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* Rendering a sentence that contains LaTeX.
|
||||
*
|
||||
* A sentence is stored as the writer typed it, LaTeX and all, because that is
|
||||
* what can be edited — `$\ell$` is one character to change and an equation
|
||||
* image is not. Reading it is this module's job: it splits the text into plain
|
||||
* segments and formulas, hands the formulas to KaTeX, and escapes everything
|
||||
* that is not a formula.
|
||||
*
|
||||
* Four delimiters are recognised, because a paper written in LaTeX, in
|
||||
* Markdown, or by hand uses whichever the writer's habit prefers:
|
||||
*
|
||||
* ================== ==========
|
||||
* `$$ … $$` display (own line, centred, may carry `\tag{1}`)
|
||||
* `\[ … \]` display
|
||||
* `$ … $` inline
|
||||
* `\( … \)` inline
|
||||
* ================== ==========
|
||||
*
|
||||
* An unmatched `$` is left alone: money in a sentence, or a formula half
|
||||
* typed, must not swallow the rest of the paragraph.
|
||||
*
|
||||
* `throwOnError: false` is deliberate. A broken formula renders as its own
|
||||
* source in red rather than an exception, so one typo cannot blank out the
|
||||
* paper the writer is reading.
|
||||
*/
|
||||
import katex from 'katex'
|
||||
|
||||
/** One piece of a sentence: plain text, or a formula and how to set it. */
|
||||
export type RichSegment =
|
||||
| { kind: 'text'; value: string }
|
||||
| { kind: 'math'; value: string; display: boolean }
|
||||
|
||||
/**
|
||||
* Display delimiters are matched first: `$$…$$` contains `$…$`, so the other
|
||||
* order would read an empty inline formula and leave the rest as text.
|
||||
*/
|
||||
const MATH_PATTERN = /\$\$([\s\S]+?)\$\$|\\\[([\s\S]+?)\\\]|\$([^$\n]+?)\$|\\\(([\s\S]+?)\\\)/g
|
||||
|
||||
const HTML_ESCAPES: Record<string, string> = {
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
'"': '"',
|
||||
"'": ''',
|
||||
}
|
||||
|
||||
/** Escape text that is going into `v-html`, since it is not markup. */
|
||||
export function escapeHtml(value: string): string {
|
||||
return value.replace(/[&<>"']/g, (character) => HTML_ESCAPES[character] ?? character)
|
||||
}
|
||||
|
||||
/** Split a sentence into its plain and mathematical parts. */
|
||||
export function splitRich(content: string): RichSegment[] {
|
||||
const segments: RichSegment[] = []
|
||||
let cursor = 0
|
||||
|
||||
MATH_PATTERN.lastIndex = 0
|
||||
for (let match = MATH_PATTERN.exec(content); match; match = MATH_PATTERN.exec(content)) {
|
||||
if (match.index > cursor) {
|
||||
segments.push({ kind: 'text', value: content.slice(cursor, match.index) })
|
||||
}
|
||||
const [whole, doubleDollar, doubleBracket, singleDollar, singleBracket] = match
|
||||
segments.push({
|
||||
kind: 'math',
|
||||
value: doubleDollar ?? doubleBracket ?? singleDollar ?? singleBracket ?? '',
|
||||
display: doubleDollar !== undefined || doubleBracket !== undefined,
|
||||
})
|
||||
cursor = match.index + whole.length
|
||||
}
|
||||
|
||||
if (cursor < content.length) {
|
||||
segments.push({ kind: 'text', value: content.slice(cursor) })
|
||||
}
|
||||
return segments
|
||||
}
|
||||
|
||||
/** Whether a sentence contains a formula that belongs on its own line. */
|
||||
export function hasDisplayMath(content: string): boolean {
|
||||
return splitRich(content).some((segment) => segment.kind === 'math' && segment.display)
|
||||
}
|
||||
|
||||
/** Render one formula, or the source in red when KaTeX cannot read it. */
|
||||
function renderMath(value: string, display: boolean): string {
|
||||
try {
|
||||
return katex.renderToString(value, {
|
||||
displayMode: display,
|
||||
throwOnError: false,
|
||||
strict: false,
|
||||
})
|
||||
} catch {
|
||||
// KaTeX throws only for input it cannot process at all; showing the source
|
||||
// is more useful to the writer than an empty space.
|
||||
return `<code class="math-error">${escapeHtml(value)}</code>`
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a sentence to HTML: text escaped, formulas typeset.
|
||||
*
|
||||
* The result is for `v-html`. KaTeX's own output is the only markup in it —
|
||||
* `trust` is off, so no command can inject HTML — and every text segment is
|
||||
* escaped here.
|
||||
*/
|
||||
export function renderRich(content: string): string {
|
||||
return splitRich(content)
|
||||
.map((segment) =>
|
||||
segment.kind === 'text'
|
||||
? escapeHtml(segment.value)
|
||||
: renderMath(segment.value, segment.display),
|
||||
)
|
||||
.join('')
|
||||
}
|
||||
Reference in New Issue
Block a user