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:
@@ -15,6 +15,9 @@ backend/.env
|
|||||||
|
|
||||||
# --- Node / frontend ---
|
# --- Node / frontend ---
|
||||||
node_modules/
|
node_modules/
|
||||||
|
# pnpm keeps a content-addressed store; when it lands here rather than in the
|
||||||
|
# home directory it is build output, not source.
|
||||||
|
.pnpm-store/
|
||||||
frontend/dist/
|
frontend/dist/
|
||||||
frontend/dist-ssr/
|
frontend/dist-ssr/
|
||||||
*.tsbuildinfo
|
*.tsbuildinfo
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
"""give a sentence the option to start a new line
|
||||||
|
|
||||||
|
A paragraph is its sentences concatenated, which is right for prose and wrong
|
||||||
|
for the things a paper also puts inside a paragraph: a display formula, a list
|
||||||
|
of items, an author line. Those want a line break between them, and until now
|
||||||
|
there was nowhere to say so — text pasted with newlines was folded onto one line
|
||||||
|
on purpose, so the writer had no way to ask for one.
|
||||||
|
|
||||||
|
So the sentence carries the request: ``line_break_before`` prints a break before
|
||||||
|
this sentence and nothing else. It is a property of the sentence rather than a
|
||||||
|
character in its content because the content is a sentence — folding whitespace
|
||||||
|
is what keeps it one — and because a break the writer cannot see cannot be
|
||||||
|
removed.
|
||||||
|
|
||||||
|
Existing rows default to 0: today's documents render exactly as they did.
|
||||||
|
|
||||||
|
Revision ID: f8c2d5a73b91
|
||||||
|
Revises: 063f6def01fa
|
||||||
|
Create Date: 2026-09-22
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision: str = "f8c2d5a73b91"
|
||||||
|
down_revision: str | None = "063f6def01fa"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.add_column(
|
||||||
|
"paper_sentence",
|
||||||
|
sa.Column(
|
||||||
|
"line_break_before",
|
||||||
|
sa.Boolean(),
|
||||||
|
server_default=sa.text("0"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_column("paper_sentence", "line_break_before")
|
||||||
@@ -419,7 +419,13 @@ def build_document(db: Session, paper: Paper) -> PaperDocumentRead:
|
|||||||
# than by whoever prints them, so a reader, an export and a preview
|
# than by whoever prints them, so a reader, an export and a preview
|
||||||
# cannot each invent their own spacing.
|
# cannot each invent their own spacing.
|
||||||
for earlier, later in zip(sentences, sentences[1:]):
|
for earlier, later in zip(sentences, sentences[1:]):
|
||||||
later.separator_before = sentence_separator(earlier.content, later.content)
|
later.separator_before = (
|
||||||
|
""
|
||||||
|
if later.line_break_before
|
||||||
|
# A line break already separates the two, and printing a space
|
||||||
|
# as well would indent the new line by one blank.
|
||||||
|
else sentence_separator(earlier.content, later.content)
|
||||||
|
)
|
||||||
|
|
||||||
paragraph = ParagraphRead(
|
paragraph = ParagraphRead(
|
||||||
paper_template_filed_sort=position,
|
paper_template_filed_sort=position,
|
||||||
@@ -678,6 +684,7 @@ def replace_paragraph(
|
|||||||
paper_template_filed_sort=target,
|
paper_template_filed_sort=target,
|
||||||
sort=item.sort if item.sort is not None else base + offset,
|
sort=item.sort if item.sort is not None else base + offset,
|
||||||
content=item.content,
|
content=item.content,
|
||||||
|
line_break_before=item.line_break_before,
|
||||||
citations=_build_citations(item.citations),
|
citations=_build_citations(item.citations),
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
@@ -700,6 +707,7 @@ def append_sentence(db: Session, paper: Paper, data: SentenceCreate) -> PaperSen
|
|||||||
paper_template_filed_sort=data.paper_template_filed_sort,
|
paper_template_filed_sort=data.paper_template_filed_sort,
|
||||||
sort=sort,
|
sort=sort,
|
||||||
content=data.content,
|
content=data.content,
|
||||||
|
line_break_before=data.line_break_before,
|
||||||
citations=_build_citations(data.citations),
|
citations=_build_citations(data.citations),
|
||||||
)
|
)
|
||||||
db.add(sentence)
|
db.add(sentence)
|
||||||
@@ -729,6 +737,8 @@ def update_sentence(
|
|||||||
sentence.paper_template_filed_sort = data.paper_template_filed_sort
|
sentence.paper_template_filed_sort = data.paper_template_filed_sort
|
||||||
if data.content is not None:
|
if data.content is not None:
|
||||||
sentence.content = data.content
|
sentence.content = data.content
|
||||||
|
if data.line_break_before is not None:
|
||||||
|
sentence.line_break_before = data.line_break_before
|
||||||
if data.citations is not None:
|
if data.citations is not None:
|
||||||
sentence.citations.clear()
|
sentence.citations.clear()
|
||||||
db.flush()
|
db.flush()
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ is assembled on read from the paper's template plus these rows. See
|
|||||||
|
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
from sqlalchemy import ForeignKey, Index, Integer, Text
|
from sqlalchemy import Boolean, ForeignKey, Index, Integer, Text, text
|
||||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||||
|
|
||||||
from app.db.base import Base
|
from app.db.base import Base
|
||||||
@@ -86,6 +86,21 @@ class PaperSentence(TimestampMixin, Base):
|
|||||||
#: placeholder and renders as a blank line rather than disappearing.
|
#: placeholder and renders as a blank line rather than disappearing.
|
||||||
content: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
content: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||||
|
|
||||||
|
#: Print a line break before this sentence.
|
||||||
|
#:
|
||||||
|
#: A paragraph is its sentences concatenated, which is right for prose and
|
||||||
|
#: wrong for what else a paper puts inside one: a display formula, a list of
|
||||||
|
#: items, an author line. The break is a flag rather than a newline in
|
||||||
|
#: ``content`` for two reasons — content folds its whitespace so a sentence
|
||||||
|
#: really is one line, and a break hidden in a string is a break the writer
|
||||||
|
#: cannot see or remove.
|
||||||
|
line_break_before: Mapped[bool] = mapped_column(
|
||||||
|
Boolean,
|
||||||
|
nullable=False,
|
||||||
|
default=False,
|
||||||
|
server_default=text("0"),
|
||||||
|
)
|
||||||
|
|
||||||
paper: Mapped["Paper"] = relationship(back_populates="sentences")
|
paper: Mapped["Paper"] = relationship(back_populates="sentences")
|
||||||
|
|
||||||
#: References quoted by this sentence, in citation order. Eager-loaded
|
#: References quoted by this sentence, in citation order. Eager-loaded
|
||||||
|
|||||||
@@ -97,6 +97,8 @@ class SentenceInput(BaseModel):
|
|||||||
|
|
||||||
sort: int | None = Field(default=None, ge=-1_000_000, le=1_000_000)
|
sort: int | None = Field(default=None, ge=-1_000_000, le=1_000_000)
|
||||||
content: str = ""
|
content: str = ""
|
||||||
|
#: Start a new line at this sentence rather than running on from the last.
|
||||||
|
line_break_before: bool = False
|
||||||
citations: list[CitationInput] = Field(default_factory=list)
|
citations: list[CitationInput] = Field(default_factory=list)
|
||||||
|
|
||||||
@field_validator("content")
|
@field_validator("content")
|
||||||
@@ -135,6 +137,7 @@ class SentenceUpdate(BaseModel):
|
|||||||
default=None, ge=-1_000_000, le=1_000_000
|
default=None, ge=-1_000_000, le=1_000_000
|
||||||
)
|
)
|
||||||
content: str | None = None
|
content: str | None = None
|
||||||
|
line_break_before: bool | None = None
|
||||||
citations: list[CitationInput] | None = None
|
citations: list[CitationInput] | None = None
|
||||||
|
|
||||||
@field_validator("content")
|
@field_validator("content")
|
||||||
@@ -168,6 +171,9 @@ class SentenceRead(BaseModel):
|
|||||||
paper_template_filed_sort: int
|
paper_template_filed_sort: int
|
||||||
sort: int
|
sort: int
|
||||||
content: str
|
content: str
|
||||||
|
#: Whether a line break prints before this sentence. See
|
||||||
|
#: :attr:`app.models.paper_sentence.PaperSentence.line_break_before`.
|
||||||
|
line_break_before: bool
|
||||||
citations: list[CitationRead]
|
citations: list[CitationRead]
|
||||||
#: Text to print before this sentence when the paragraph is put back
|
#: Text to print before this sentence when the paragraph is put back
|
||||||
#: together — ``""`` or a single space, never anything else. Derived on
|
#: together — ``""`` or a single space, never anything else. Derived on
|
||||||
|
|||||||
@@ -267,7 +267,42 @@ def main() -> int:
|
|||||||
# Clear it again so the counts asserted below stay meaningful.
|
# Clear it again so the counts asserted below stay meaningful.
|
||||||
call("PUT", f"/papers/{paper['id']}/paragraphs/{second_sort}", {"sentences": []})
|
call("PUT", f"/papers/{paper['id']}/paragraphs/{second_sort}", {"sentences": []})
|
||||||
|
|
||||||
print("8. reject a citation with no quote")
|
print("8. a sentence can ask for a line break")
|
||||||
|
# The flag replaces the separator rather than adding to it: a break
|
||||||
|
# already separates the two, and a space as well would indent the new
|
||||||
|
# line by one blank.
|
||||||
|
broken = call(
|
||||||
|
"PUT",
|
||||||
|
f"/papers/{paper['id']}/paragraphs/{second_sort}",
|
||||||
|
{
|
||||||
|
"sentences": [
|
||||||
|
{"content": "连排的第一句。"},
|
||||||
|
{"content": "另起一行的一句。", "line_break_before": True},
|
||||||
|
{"content": "English runs on.", "line_break_before": True},
|
||||||
|
]
|
||||||
|
},
|
||||||
|
)
|
||||||
|
paragraph_breaks = next(
|
||||||
|
p
|
||||||
|
for p in broken["paragraphs"]
|
||||||
|
if p["paper_template_filed_sort"] == second_sort
|
||||||
|
)
|
||||||
|
check(
|
||||||
|
"the flag is stored per sentence",
|
||||||
|
[s["line_break_before"] for s in paragraph_breaks["sentences"]]
|
||||||
|
== [False, True, True],
|
||||||
|
str([s["line_break_before"] for s in paragraph_breaks["sentences"]]),
|
||||||
|
)
|
||||||
|
check(
|
||||||
|
"it also survives a read back",
|
||||||
|
all(
|
||||||
|
s["line_break_before"] is False or s["separator_before"] == ""
|
||||||
|
for s in paragraph_breaks["sentences"]
|
||||||
|
),
|
||||||
|
)
|
||||||
|
call("PUT", f"/papers/{paper['id']}/paragraphs/{second_sort}", {"sentences": []})
|
||||||
|
|
||||||
|
print("9. reject a citation with no quote")
|
||||||
bad = call(
|
bad = call(
|
||||||
"PUT",
|
"PUT",
|
||||||
f"/papers/{paper['id']}/paragraphs/{first_sort}",
|
f"/papers/{paper['id']}/paragraphs/{first_sort}",
|
||||||
@@ -285,7 +320,7 @@ def main() -> int:
|
|||||||
)
|
)
|
||||||
check("citation without content refused", "detail" in bad)
|
check("citation without content refused", "detail" in bad)
|
||||||
|
|
||||||
print("9. a sentence with no paragraph in the template survives a switch")
|
print("10. a sentence with no paragraph in the template survives a switch")
|
||||||
# A position neither template defines, so the check means the same
|
# A position neither template defines, so the check means the same
|
||||||
# thing before and after the switch below.
|
# thing before and after the switch below.
|
||||||
orphan_sort = (
|
orphan_sort = (
|
||||||
@@ -313,7 +348,7 @@ def main() -> int:
|
|||||||
p for p in document["paragraphs"] if p["paper_template_filed_sort"] == orphan_sort
|
p for p in document["paragraphs"] if p["paper_template_filed_sort"] == orphan_sort
|
||||||
)["name"] is None)
|
)["name"] is None)
|
||||||
|
|
||||||
print("10. switch the template")
|
print("11. switch the template")
|
||||||
switched = call("PATCH", f"/papers/{paper['id']}", {"template_id": narrow["id"]})
|
switched = call("PATCH", f"/papers/{paper['id']}", {"template_id": narrow["id"]})
|
||||||
check("template changed", switched["template_id"] == narrow["id"])
|
check("template changed", switched["template_id"] == narrow["id"])
|
||||||
document = call("GET", f"/papers/{paper['id']}/document")
|
document = call("GET", f"/papers/{paper['id']}/document")
|
||||||
@@ -343,7 +378,7 @@ def main() -> int:
|
|||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
print("11. move one paragraph onto another position")
|
print("12. move one paragraph onto another position")
|
||||||
document = call(
|
document = call(
|
||||||
"PUT",
|
"PUT",
|
||||||
f"/papers/{paper['id']}/paragraphs/{orphan_sort}",
|
f"/papers/{paper['id']}/paragraphs/{orphan_sort}",
|
||||||
@@ -358,18 +393,18 @@ def main() -> int:
|
|||||||
all(p["paper_template_filed_sort"] != orphan_sort for p in document["paragraphs"]),
|
all(p["paper_template_filed_sort"] != orphan_sort for p in document["paragraphs"]),
|
||||||
)
|
)
|
||||||
|
|
||||||
print("12. paper list reports progress")
|
print("13. paper list reports progress")
|
||||||
listing = call("GET", f"/papers?keyword=冒烟&status=writing")
|
listing = call("GET", f"/papers?keyword=冒烟&status=writing")
|
||||||
check("found by keyword and status", listing["total"] == 1, str(listing["total"]))
|
check("found by keyword and status", listing["total"] == 1, str(listing["total"]))
|
||||||
row = listing["items"][0]
|
row = listing["items"][0]
|
||||||
check("paragraph count", row["paragraph_count"] == 1, str(row["paragraph_count"]))
|
check("paragraph count", row["paragraph_count"] == 1, str(row["paragraph_count"]))
|
||||||
check("sentence count", row["sentence_count"] == 3, str(row["sentence_count"]))
|
check("sentence count", row["sentence_count"] == 3, str(row["sentence_count"]))
|
||||||
|
|
||||||
print("13. a template in use cannot be deleted")
|
print("14. a template in use cannot be deleted")
|
||||||
conflict = call("DELETE", f"/templates/{narrow['id']}", expect=409)
|
conflict = call("DELETE", f"/templates/{narrow['id']}", expect=409)
|
||||||
check("template delete refused", "正被论文使用" in conflict["detail"], conflict["detail"])
|
check("template delete refused", "正被论文使用" in conflict["detail"], conflict["detail"])
|
||||||
|
|
||||||
print("14. single sentence edit and delete")
|
print("15. single sentence edit and delete")
|
||||||
sentence_id = target["sentences"][0]["id"]
|
sentence_id = target["sentences"][0]["id"]
|
||||||
updated = call(
|
updated = call(
|
||||||
"PATCH",
|
"PATCH",
|
||||||
@@ -385,7 +420,7 @@ def main() -> int:
|
|||||||
sum(len(p["sentences"]) for p in document["paragraphs"]) == 2,
|
sum(len(p["sentences"]) for p in document["paragraphs"]) == 2,
|
||||||
)
|
)
|
||||||
|
|
||||||
print("15. a paper with no template still works")
|
print("16. a paper with no template still works")
|
||||||
bare = call(
|
bare = call(
|
||||||
"POST",
|
"POST",
|
||||||
"/papers",
|
"/papers",
|
||||||
@@ -408,7 +443,7 @@ def main() -> int:
|
|||||||
call("DELETE", f"/papers/{bare['id']}", expect=204)
|
call("DELETE", f"/papers/{bare['id']}", expect=204)
|
||||||
created_papers.remove(bare["id"])
|
created_papers.remove(bare["id"])
|
||||||
|
|
||||||
print("16. delete the paper")
|
print("17. delete the paper")
|
||||||
call("DELETE", f"/papers/{paper['id']}", expect=204)
|
call("DELETE", f"/papers/{paper['id']}", expect=204)
|
||||||
created_papers.clear()
|
created_papers.clear()
|
||||||
for reference_id in created_references:
|
for reference_id in created_references:
|
||||||
|
|||||||
@@ -306,6 +306,23 @@ stop (`。`) and nothing else — deliberately conservative: an English abstract
|
|||||||
survives that migration as a single row rather than being cut at the first
|
survives that migration as a single row rather than being cut at the first
|
||||||
`et al.`, and one long line is a line the writer can split by hand.
|
`et al.`, and one long line is a line the writer can split by hand.
|
||||||
|
|
||||||
|
#### A line break is asked for, never guessed
|
||||||
|
|
||||||
|
A paragraph is its sentences run together — that is the model. Everything a
|
||||||
|
paper also puts *inside* a paragraph that is not prose (a display formula, a
|
||||||
|
list of items, an author line) therefore needs a way to say "start a new line
|
||||||
|
here", and that is `paper_sentence.line_break_before`.
|
||||||
|
|
||||||
|
It is a flag rather than a newline inside `content` for two reasons. Content
|
||||||
|
folds its whitespace, deliberately, so that a sentence really is one line and a
|
||||||
|
pasted newline cannot split one in half; and a break buried in a string is a
|
||||||
|
break nobody can see, count or remove. A flag prints a `<br>` and is visible in
|
||||||
|
the editor as a checkbox on the sentence's row.
|
||||||
|
|
||||||
|
A break also **replaces** the separator rather than adding to it: the new line
|
||||||
|
already separates the two sentences, and a space as well would indent the line
|
||||||
|
by one blank.
|
||||||
|
|
||||||
#### What goes at the seam
|
#### What goes at the seam
|
||||||
|
|
||||||
A paragraph is printed by concatenating its sentences in `sort` order, so the
|
A paragraph is printed by concatenating its sentences in `sort` order, so the
|
||||||
@@ -662,6 +679,29 @@ are not lists (the paper document) keep scrolling normally.
|
|||||||
| `/references` | reference table + CRUD (`?tag=<id>` filters, `?new=1` opens the create dialog) | `references` |
|
| `/references` | reference table + CRUD (`?tag=<id>` filters, `?new=1` opens the create dialog) | `references` |
|
||||||
| `/references/tags` | tag library + CRUD (the UI label is 标签管理) | `references` |
|
| `/references/tags` | tag library + CRUD (the UI label is 标签管理) | `references` |
|
||||||
|
|
||||||
|
### Sentences are stored as LaTeX and typeset on read
|
||||||
|
|
||||||
|
A formula is stored exactly as the writer typed it — `$\ell$`, `$$ … \tag{1} $$`
|
||||||
|
— because that is the form that can be edited; an equation image cannot be
|
||||||
|
changed by one character. Typesetting happens when the paper is read, in
|
||||||
|
`src/utils/math.ts`, which splits a sentence into text and formulas, hands the
|
||||||
|
formulas to KaTeX and escapes everything else.
|
||||||
|
|
||||||
|
Four delimiters are recognised, because a writer's habit decides which they use:
|
||||||
|
`$$…$$` and `\[…\]` for display, `$…$` and `\(…\)` for inline. An unmatched
|
||||||
|
`$` is left alone rather than swallowing the rest of the paragraph.
|
||||||
|
|
||||||
|
Two rules are worth knowing when reading the renderer:
|
||||||
|
|
||||||
|
- **A display formula is a block.** It takes its own line whether or not the
|
||||||
|
sentence asked for a break, because that is what "display" means — so the
|
||||||
|
formulas in a paper sit centred on their own lines with no extra flagging.
|
||||||
|
- **KaTeX never throws.** `throwOnError: false` renders a formula it cannot read
|
||||||
|
as its own source in red, so one typo shows itself instead of blanking the
|
||||||
|
paragraph the writer is looking at. Text segments are escaped before they go
|
||||||
|
through `v-html`, and KaTeX runs with `trust` off, so a sentence cannot inject
|
||||||
|
markup.
|
||||||
|
|
||||||
### The paper view
|
### The paper view
|
||||||
|
|
||||||
`PapersView` is the library; `papers/PaperDetailView` is the writing surface.
|
`PapersView` is the library; `papers/PaperDetailView` is the writing surface.
|
||||||
|
|||||||
@@ -14,6 +14,7 @@
|
|||||||
"@element-plus/icons-vue": "^2.3.2",
|
"@element-plus/icons-vue": "^2.3.2",
|
||||||
"axios": "^1.20.0",
|
"axios": "^1.20.0",
|
||||||
"element-plus": "^2.14.5",
|
"element-plus": "^2.14.5",
|
||||||
|
"katex": "^0.18.7",
|
||||||
"pinia": "^4.0.2",
|
"pinia": "^4.0.2",
|
||||||
"pinia-plugin-persistedstate": "^4.7.1",
|
"pinia-plugin-persistedstate": "^4.7.1",
|
||||||
"vue": "^3.5.40",
|
"vue": "^3.5.40",
|
||||||
|
|||||||
Generated
+17
@@ -17,6 +17,9 @@ importers:
|
|||||||
element-plus:
|
element-plus:
|
||||||
specifier: ^2.14.5
|
specifier: ^2.14.5
|
||||||
version: 2.14.5(vue@3.5.42(typescript@6.0.3))
|
version: 2.14.5(vue@3.5.42(typescript@6.0.3))
|
||||||
|
katex:
|
||||||
|
specifier: ^0.18.7
|
||||||
|
version: 0.18.7
|
||||||
pinia:
|
pinia:
|
||||||
specifier: ^4.0.2
|
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))
|
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==}
|
resolution: {integrity: sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==}
|
||||||
engines: {node: '>= 0.8'}
|
engines: {node: '>= 0.8'}
|
||||||
|
|
||||||
|
commander@15.0.0:
|
||||||
|
resolution: {integrity: sha512-z67u4ZhzCL/Tydu1lJARtEZYWbWaN7oYLHbsuzocr6y4N6WZAagG3RQ4FW61V1/0+jImpj293XfrcYnd1qxtPg==}
|
||||||
|
engines: {node: '>=22.12.0'}
|
||||||
|
|
||||||
confbox@0.1.8:
|
confbox@0.1.8:
|
||||||
resolution: {integrity: sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==}
|
resolution: {integrity: sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==}
|
||||||
|
|
||||||
@@ -749,6 +756,10 @@ packages:
|
|||||||
engines: {node: '>=6'}
|
engines: {node: '>=6'}
|
||||||
hasBin: true
|
hasBin: true
|
||||||
|
|
||||||
|
katex@0.18.7:
|
||||||
|
resolution: {integrity: sha512-h+UCwkZ+4Jz8WQ7MLGfj7UVFrRCizGb912fwF4luGdYsC5paYG1vx+jy+KRcC/XkpjGva/P7nAWuxNnPzRvzHw==}
|
||||||
|
hasBin: true
|
||||||
|
|
||||||
kolorist@1.8.0:
|
kolorist@1.8.0:
|
||||||
resolution: {integrity: sha512-Y+60/zizpJ3HRH8DCss+q95yr6145JXZo46OTpFvDZWLfRCE4qChOyk1b26nMaNpfHHgxagk9dXT5OP0Tfe+dQ==}
|
resolution: {integrity: sha512-Y+60/zizpJ3HRH8DCss+q95yr6145JXZo46OTpFvDZWLfRCE4qChOyk1b26nMaNpfHHgxagk9dXT5OP0Tfe+dQ==}
|
||||||
|
|
||||||
@@ -1761,6 +1772,8 @@ snapshots:
|
|||||||
dependencies:
|
dependencies:
|
||||||
delayed-stream: 1.0.0
|
delayed-stream: 1.0.0
|
||||||
|
|
||||||
|
commander@15.0.0: {}
|
||||||
|
|
||||||
confbox@0.1.8: {}
|
confbox@0.1.8: {}
|
||||||
|
|
||||||
confbox@0.2.4: {}
|
confbox@0.2.4: {}
|
||||||
@@ -1936,6 +1949,10 @@ snapshots:
|
|||||||
|
|
||||||
json5@2.2.3: {}
|
json5@2.2.3: {}
|
||||||
|
|
||||||
|
katex@0.18.7:
|
||||||
|
dependencies:
|
||||||
|
commander: 15.0.0
|
||||||
|
|
||||||
kolorist@1.8.0: {}
|
kolorist@1.8.0: {}
|
||||||
|
|
||||||
lightningcss-android-arm64@1.33.0:
|
lightningcss-android-arm64@1.33.0:
|
||||||
|
|||||||
@@ -84,6 +84,14 @@ export interface Sentence {
|
|||||||
/** Position inside that paragraph. */
|
/** Position inside that paragraph. */
|
||||||
sort: number
|
sort: number
|
||||||
content: string
|
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[]
|
citations: Citation[]
|
||||||
/**
|
/**
|
||||||
* What to print before this sentence when the paragraph is put back
|
* What to print before this sentence when the paragraph is put back
|
||||||
@@ -181,6 +189,8 @@ export interface CitationInput {
|
|||||||
export interface SentenceInput {
|
export interface SentenceInput {
|
||||||
sort?: number | null
|
sort?: number | null
|
||||||
content: string
|
content: string
|
||||||
|
/** Start a new line at this sentence. */
|
||||||
|
line_break_before?: boolean
|
||||||
citations: CitationInput[]
|
citations: CitationInput[]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ import { Edit } from '@element-plus/icons-vue'
|
|||||||
|
|
||||||
import type { PaperParagraph } from '@/api/papers'
|
import type { PaperParagraph } from '@/api/papers'
|
||||||
import { PARAGRAPH_UNSET_LABEL, levelIndent } from '@/utils/format'
|
import { PARAGRAPH_UNSET_LABEL, levelIndent } from '@/utils/format'
|
||||||
|
import { escapeHtml, hasDisplayMath, renderRich } from '@/utils/math'
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
paragraph: PaperParagraph
|
paragraph: PaperParagraph
|
||||||
@@ -49,10 +50,39 @@ const headingStyle = computed(() => {
|
|||||||
/** Indentation follows the field's level, exactly as the template outline does. */
|
/** Indentation follows the field's level, exactly as the template outline does. */
|
||||||
const headingIndent = computed(() => levelIndent(props.paragraph.level))
|
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. */
|
/** Whether anything has actually been written here. */
|
||||||
const hasContent = computed(() =>
|
const hasContent = computed(() =>
|
||||||
props.paragraph.sentences.some(
|
rendered.value.some(
|
||||||
(sentence) => sentence.content.trim().length > 0 || sentence.citations.length > 0,
|
(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>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<p v-if="hasContent" class="paragraph-body">
|
<div v-if="hasContent" class="paragraph-body">
|
||||||
<template v-for="sentence in paragraph.sentences" :key="sentence.id">
|
<template v-for="item in rendered" :key="item.sentence.id">
|
||||||
<!-- The separator comes from the server: it is a space for English
|
<!-- A display formula is a block by definition, so it takes its own
|
||||||
and nothing for Chinese, and only the server knows which. -->
|
line whether or not the writer asked for a break. -->
|
||||||
<span class="sentence">{{ sentence.separator_before }}{{ sentence.content }}</span>
|
<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
|
<el-tooltip
|
||||||
v-for="citation in sentence.citations"
|
v-for="citation in item.sentence.citations"
|
||||||
:key="citation.id"
|
:key="citation.id"
|
||||||
placement="top"
|
placement="top"
|
||||||
:show-after="120"
|
:show-after="120"
|
||||||
@@ -126,7 +165,7 @@ const anchor = computed(() => `paragraph-${props.paragraph.paper_template_filed_
|
|||||||
<sup class="cite-mark">{{ citationIndex[citation.id] ?? '?' }}</sup>
|
<sup class="cite-mark">{{ citationIndex[citation.id] ?? '?' }}</sup>
|
||||||
</el-tooltip>
|
</el-tooltip>
|
||||||
</template>
|
</template>
|
||||||
</p>
|
</div>
|
||||||
|
|
||||||
<!-- Nothing below the heading when there is nothing to print. An empty
|
<!-- 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
|
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;
|
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 {
|
.cite-mark {
|
||||||
margin: 0 1px;
|
margin: 0 1px;
|
||||||
padding: 0 2px;
|
padding: 0 2px;
|
||||||
|
|||||||
@@ -65,6 +65,8 @@ interface SentenceDraft {
|
|||||||
key: number
|
key: number
|
||||||
sort: number
|
sort: number
|
||||||
content: string
|
content: string
|
||||||
|
/** Print a line break before this sentence. */
|
||||||
|
lineBreak: boolean
|
||||||
citations: CitationDraft[]
|
citations: CitationDraft[]
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -131,6 +133,7 @@ watch(
|
|||||||
key: nextKey++,
|
key: nextKey++,
|
||||||
sort: sentence.sort,
|
sort: sentence.sort,
|
||||||
content: sentence.content,
|
content: sentence.content,
|
||||||
|
lineBreak: sentence.line_break_before,
|
||||||
citations: sentence.citations.map((citation) => ({
|
citations: sentence.citations.map((citation) => ({
|
||||||
key: nextKey++,
|
key: nextKey++,
|
||||||
reference_id: citation.reference_id,
|
reference_id: citation.reference_id,
|
||||||
@@ -152,7 +155,13 @@ function nextSort(): number {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function addSentence(): void {
|
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 {
|
function removeSentence(key: number): void {
|
||||||
@@ -237,6 +246,7 @@ async function submit(): Promise<void> {
|
|||||||
.map((row) => ({
|
.map((row) => ({
|
||||||
sort: row.sort,
|
sort: row.sort,
|
||||||
content: foldWhitespace(row.content),
|
content: foldWhitespace(row.content),
|
||||||
|
line_break_before: row.lineBreak,
|
||||||
citations: row.citations
|
citations: row.citations
|
||||||
.filter((citation) => citation.quote.trim().length > 0)
|
.filter((citation) => citation.quote.trim().length > 0)
|
||||||
.map((citation) => ({
|
.map((citation) => ({
|
||||||
@@ -331,7 +341,9 @@ async function submit(): Promise<void> {
|
|||||||
|
|
||||||
<div class="editor-toolbar">
|
<div class="editor-toolbar">
|
||||||
<span class="toolbar-title">共 {{ orderedRows.length }} 句</span>
|
<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" />
|
<div class="toolbar-spacer" />
|
||||||
<el-button size="small" :icon="Refresh" :disabled="!orderedRows.length" @click="autoNumber">
|
<el-button size="small" :icon="Refresh" :disabled="!orderedRows.length" @click="autoNumber">
|
||||||
自动编号
|
自动编号
|
||||||
@@ -359,6 +371,13 @@ async function submit(): Promise<void> {
|
|||||||
:max="9999"
|
:max="9999"
|
||||||
class="sort-input"
|
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" />
|
<div class="toolbar-spacer" />
|
||||||
<el-button
|
<el-button
|
||||||
link
|
link
|
||||||
|
|||||||
@@ -5,6 +5,10 @@ import ElementPlus from 'element-plus'
|
|||||||
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
|
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
|
||||||
|
|
||||||
import 'element-plus/dist/index.css'
|
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
|
// Global reset and application-shell layout contract. Imported after Element
|
||||||
// Plus so it can override its component defaults (e.g. .el-main overflow).
|
// 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