Compare commits

...

3 Commits

Author SHA1 Message Date
govin a29badd362 docs: describe the tags, the library pages, and the way in
Ten tables now, and the two new ones are argued for where the other
schema decisions are: why a tag is not a keyword, why the link is bare,
why a tag is made before it is applied, and why deleting one is not
refused while deleting a cited reference is.

Also corrects the table count — the section claimed nine while listing
eight — and the shell diagram, which had a header with two entries and
named the wrong side for the second-level menu.
2026-09-22 17:55:23 +08:00
govin 872ad8cf3b frontend: add the reference library, its tags, and a way in
参考文献 now sits in the header to the right of 论文 and 模板 — the library is
drawn *from* rather than worked in, so it is a button one step away. Its
own second-level menu marks out 文献列表 / 新增文献 / 标签管理 and then lists
the tags themselves, read from their store, so a label can be picked
straight from the rail.

A tag in the rail links to `/references?tag=<id>`, which makes the query
parameter part of the view rather than hidden filter state: the table's own
selector writes the same parameter, so the two cannot disagree and a
filtered view is a link someone can be sent.

The form keeps the order the feature intends — a tag is created before it
is applied, so no stored reference can point at a label that is not there —
and the citation count in a row opens the answer it exists to give (which
paper, which paragraph, which quoted passage).

Tag colours are painted from the row rather than a class map: the palette
is the writer's, and the chip has to be that hue in the table, in the rail
and in the picker.
2026-09-22 17:55:20 +08:00
govin 6020310b3f backend: tag the literature, in a table of its own
A tag is the writer's filing of a row — 「综述」, 「必读」 — and it is a
different fact from `reference.keywords`, which are the 关键词 printed on
the article. A tag never prints, one document carries several, and the same
label is on many documents, so it gets two tables rather than a column:

  reference_tag       name (unique), colour, note
  reference_tag_link  reference_id + tag_id — the pair is the primary key

The link is a bare link, which is why it is `_link` and not `_placement`:
there is no `sort` to own, so the pair *is* the row and the same label
cannot be applied twice.

A tag is made first and applied second: `tag_ids`, never tag names, so a
typo cannot invent a label — an unknown id is a 400 naming it, and nothing
is written. Deleting a tag is deliberately *not* guarded the way deleting a
cited reference is: both foreign keys cascade, so the labels go and the
literature stays.

`GET /references?tag=1&tag=2` narrows rather than widens — the rows carrying
both labels — because that is what a second filter reads as.

The smoke test now walks the whole flow in the order the feature intends:
labels first, then tagged references, then a rename that follows every row.
2026-09-22 17:55:15 +08:00
27 changed files with 4017 additions and 93 deletions
@@ -0,0 +1,97 @@
"""create reference tags (文献标签)
Two tables that hold the writer's own labels on the literature:
``reference_tag`` one label: its name, its colour, a note.
``reference_tag_link`` which literature carries which label — two foreign keys
and nothing else, so the *pair* is the primary key. A
reference tagged twice with the same label is therefore
not a duplicate row; it is the same row.
Why this is not a column on ``reference``
-----------------------------------------
``reference.keywords`` already exists and is a different fact: those are the
关键词 printed on the document, part of the citation record. A tag is the
writer's filing (「综述」, 「必读」), it never prints, one document carries
several, and the same label is on many documents. That is a second table by the
same argument that made a citation a table rather than a column.
The link table is named ``_link`` rather than ``_placement`` on purpose: unlike
``template_title_placement`` it carries no ``sort``, so there is no ordering to
own and no payload to grow into. It is a bare link, and the name says so.
Both foreign keys cascade. Deleting a tag removes its labels and leaves the
literature alone — a label is not a claim the paper makes, which is why deleting
a *cited reference* is refused at the API while deleting a tag is not.
Nothing is backfilled: the tables are new and the library starts unlabelled.
Revision ID: 063f6def01fa
Revises: e4b7c1f9a036
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 = "063f6def01fa"
down_revision: str | None = "e4b7c1f9a036"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
_NOW = sa.text("CURRENT_TIMESTAMP")
def upgrade() -> None:
op.create_table(
"reference_tag",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column("name", sa.String(length=64), nullable=False),
sa.Column(
"color",
sa.String(length=7),
server_default=sa.text("'#409EFF'"),
nullable=False,
),
sa.Column("note", sa.String(length=255), nullable=True),
sa.Column("created_at", sa.DateTime(), server_default=_NOW, nullable=False),
sa.Column("updated_at", sa.DateTime(), server_default=_NOW, nullable=False),
sa.PrimaryKeyConstraint("id"),
# One row per label: two tags spelled the same are the same tag, and
# nothing in the UI could explain a second one.
sa.UniqueConstraint("name", name="uq_reference_tag_name"),
)
op.create_table(
"reference_tag_link",
sa.Column("reference_id", sa.Integer(), nullable=False),
sa.Column("tag_id", sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(
["reference_id"], ["reference.id"], ondelete="CASCADE"
),
sa.ForeignKeyConstraint(
["tag_id"], ["reference_tag.id"], ondelete="CASCADE"
),
# The pair is the identity, so it is the key — which also means the
# table cannot hold the same label on the same document twice.
sa.PrimaryKeyConstraint("reference_id", "tag_id"),
)
# The primary key already serves "what is this document tagged with" (its
# leading column is ``reference_id``); the reverse — "what carries this
# label", which the tag table counts — needs an index of its own.
op.create_index(
"ix_reference_tag_link_tag",
"reference_tag_link",
["tag_id"],
unique=False,
)
def downgrade() -> None:
op.drop_index("ix_reference_tag_link_tag", table_name="reference_tag_link")
op.drop_table("reference_tag_link")
op.drop_table("reference_tag")
+9 -1
View File
@@ -2,11 +2,19 @@
from fastapi import APIRouter
from app.api.routes import health, papers, references, template_titles, templates
from app.api.routes import (
health,
papers,
reference_tags,
references,
template_titles,
templates,
)
api_router = APIRouter()
api_router.include_router(health.router)
api_router.include_router(papers.router)
api_router.include_router(reference_tags.router)
api_router.include_router(references.router)
api_router.include_router(template_titles.router)
api_router.include_router(templates.router)
+128
View File
@@ -0,0 +1,128 @@
"""Reference-tag endpoints (文献标签).
The label library the reference table and the reference form draw on. It is
managed first and applied second: a reference is created *with* tags, and an id
that names a label that does not exist is refused rather than silently ignored.
Deleting a tag is **not** guarded the way deleting a field or a cited reference
is. A tag is the writer's own filing — it says "this is one of the papers I
should reread", not something the document claims — so removing it removes
labels and leaves the literature exactly where it was. The confirmation in the
UI says how many rows will lose the label, which is the honest form of that
warning.
"""
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
from sqlalchemy.orm import Session
from app.crud import reference_tag as crud
from app.crud.reference_tag import DuplicateTagName
from app.db.session import get_db
from app.models import ReferenceTag
from app.schemas.common import BatchDeleteRequest, BatchDeleteResult, PageResult
from app.schemas.reference_tag import (
ReferenceTagCreate,
ReferenceTagRead,
ReferenceTagUpdate,
)
router = APIRouter(prefix="/reference-tags", tags=["reference-tags"])
def _get_or_404(db: Session, tag_id: int) -> ReferenceTag:
tag = crud.get(db, tag_id)
if tag is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"标签 {tag_id} 不存在",
)
return tag
def _conflict(error: DuplicateTagName) -> HTTPException:
"""Report a taken name as ``409`` naming the label."""
return HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(error))
@router.get("", response_model=PageResult[ReferenceTagRead], summary="List tags")
def list_tags(
db: Session = Depends(get_db),
keyword: str | None = Query(default=None, description="按标签名称或备注模糊搜索"),
page: int = Query(default=1, ge=1),
page_size: int = Query(default=50, ge=1, le=500),
) -> PageResult[ReferenceTagRead]:
"""Browse the tag library, alphabetical, each with how many rows carry it."""
items, total = crud.list_tags(
db,
keyword=keyword,
page=page,
page_size=page_size,
)
return PageResult.build(items=items, total=total, page=page, page_size=page_size)
@router.post(
"",
response_model=ReferenceTagRead,
status_code=status.HTTP_201_CREATED,
summary="Create a tag",
)
def create_tag(
payload: ReferenceTagCreate,
db: Session = Depends(get_db),
) -> ReferenceTagRead:
"""Add one label to the library."""
try:
tag = crud.create(db, payload)
except DuplicateTagName as error:
raise _conflict(error) from error
return crud.read(db, tag)
@router.post(
"/batch-delete",
response_model=BatchDeleteResult,
summary="Delete several tags",
)
def batch_delete_tags(
payload: BatchDeleteRequest,
db: Session = Depends(get_db),
) -> BatchDeleteResult:
"""Delete the given tags, removing their labels from the literature."""
return BatchDeleteResult(deleted=crud.delete_many(db, payload.ids))
@router.get("/{tag_id}", response_model=ReferenceTagRead, summary="Fetch one tag")
def get_tag(tag_id: int, db: Session = Depends(get_db)) -> ReferenceTagRead:
"""Return one label, with how many references carry it."""
return crud.read(db, _get_or_404(db, tag_id))
@router.patch("/{tag_id}", response_model=ReferenceTagRead, summary="Update a tag")
def update_tag(
tag_id: int,
payload: ReferenceTagUpdate,
db: Session = Depends(get_db),
) -> ReferenceTagRead:
"""Rename or recolour a label.
Every reference carrying it follows, because a reference links to the tag
rather than storing its name.
"""
tag = _get_or_404(db, tag_id)
try:
updated = crud.update(db, tag, payload)
except DuplicateTagName as error:
raise _conflict(error) from error
return crud.read(db, updated)
@router.delete(
"/{tag_id}",
status_code=status.HTTP_204_NO_CONTENT,
summary="Delete a tag",
)
def delete_tag(tag_id: int, db: Session = Depends(get_db)) -> Response:
"""Delete a label. Its literature stays; only the labelling goes."""
crud.delete(db, _get_or_404(db, tag_id))
return Response(status_code=status.HTTP_204_NO_CONTENT)
+30 -5
View File
@@ -15,6 +15,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
from sqlalchemy.orm import Session
from app.crud import reference as crud
from app.crud.reference_tag import UnknownTag
from app.db.session import get_db
from app.models import REFERENCE_TYPES, Reference
from app.schemas.common import BatchDeleteRequest, BatchDeleteResult, PageResult
@@ -64,6 +65,16 @@ def _assert_not_cited(db: Session, references: list[Reference]) -> None:
)
def _unknown_tag(error: UnknownTag) -> HTTPException:
"""Report an applied tag that does not exist as ``400`` naming it.
A ``400`` rather than a ``422``: the body parsed, and the offending value is
a real integer — it is the library that has no such label. The message names
the ids so the client can tell a stale picker from a typo.
"""
return HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(error))
@router.get("", response_model=PageResult[ReferenceListItem], summary="List references")
def list_references(
db: Session = Depends(get_db),
@@ -79,6 +90,10 @@ def list_references(
cited: bool | None = Query(
default=None, description="true 只看已被引用的,false 只看还没用过的"
),
tag: list[int] | None = Query(
default=None,
description="按标签过滤,可重复;给多个标签时取交集(都打了才留下)",
),
page: int = Query(default=1, ge=1),
page_size: int = Query(default=20, ge=1, le=200),
) -> PageResult[ReferenceListItem]:
@@ -89,6 +104,7 @@ def list_references(
type_=type_filter,
year=year,
cited_only=cited,
tag_ids=tag,
page=page,
page_size=page_size,
)
@@ -105,8 +121,12 @@ def create_reference(
payload: ReferenceCreate,
db: Session = Depends(get_db),
) -> ReferenceRead:
"""Add one document to the library, with its contributors in order."""
return crud.read(db, crud.create(db, payload))
"""Add one document to the library, with its contributors and its tags."""
try:
created = crud.create(db, payload)
except UnknownTag as error:
raise _unknown_tag(error) from error
return crud.read(db, created)
@router.post(
@@ -158,11 +178,16 @@ def update_reference(
) -> ReferenceRead:
"""Update any part of a reference.
``authors`` is a full replacement when present — the citation prints them in
the order sent, so there is no partial form of that list.
``authors`` and ``tag_ids`` are full replacements when present — the citation
prints the contributors in the order sent, and the tag list *is* the set of
labels on the row, so ``[]`` clears them.
"""
reference = _get_or_404(db, reference_id)
return crud.read(db, crud.update(db, reference, payload))
try:
updated = crud.update(db, reference, payload)
except UnknownTag as error:
raise _unknown_tag(error) from error
return crud.read(db, updated)
@router.delete(
+2 -2
View File
@@ -5,6 +5,6 @@ models. They own the commit: a route calls one function and gets back either a
persisted object or ``None``.
"""
from app.crud import paper, reference, template, template_title
from app.crud import paper, reference, reference_tag, template, template_title
__all__ = ["paper", "reference", "template", "template_title"]
__all__ = ["paper", "reference", "reference_tag", "template", "template_title"]
+53 -4
View File
@@ -8,6 +8,10 @@ table row never has to load the rows behind it.
Writes keep the two lists (authors, citations) on their own side: authors belong
to the reference and are replaced wholesale, citations belong to the papers that
made them and are never touched from here.
Tags are the third list and follow the same rule as authors — sent as ids, stored
as links, replaced wholesale — except that the ids must already exist: a tag is
made first and applied second, so a typo cannot invent a label.
"""
from collections.abc import Sequence
@@ -15,6 +19,7 @@ from collections.abc import Sequence
from sqlalchemy import Select, func, or_, select
from sqlalchemy.orm import Session
from app.crud import reference_tag as tag_crud
from app.crud.filters import LIKE_ESCAPE, like_pattern
from app.models import (
Paper,
@@ -22,8 +27,10 @@ from app.models import (
PaperSentenceReference,
Reference,
ReferenceAuthor,
ReferenceTag,
TemplateTitle,
TemplateTitlePlacement,
reference_tag_link,
)
from app.schemas.reference import (
ReferenceCitationRead,
@@ -32,6 +39,7 @@ from app.schemas.reference import (
ReferenceRead,
ReferenceUpdate,
)
from app.schemas.reference_tag import ReferenceTagRef
#: How many authors a table row prints before it cuts the line short.
_LIST_AUTHOR_LIMIT = 3
@@ -42,6 +50,7 @@ def _conditions(
type_: str | None,
year: int | None,
cited_only: bool | None,
tag_ids: Sequence[int] | None = None,
) -> list:
"""Translate the list filters into SQLAlchemy predicates."""
conditions = []
@@ -73,6 +82,18 @@ def _conditions(
conditions.append(_citation_count_column() > 0)
if cited_only is False:
conditions.append(_citation_count_column() == 0)
# One EXISTS per tag rather than an IN over the link table: IN would ask
# "carries at least one of these", while repeated filters read as a
# narrowing — 「方法」 plus 「必读」 means both labels are on the row.
for tag_id in dict.fromkeys(tag_ids or ()):
conditions.append(
select(reference_tag_link.c.reference_id)
.where(
reference_tag_link.c.reference_id == Reference.id,
reference_tag_link.c.tag_id == tag_id,
)
.exists()
)
return conditions
@@ -119,11 +140,12 @@ def list_references(
type_: str | None = None,
year: int | None = None,
cited_only: bool | None = None,
tag_ids: Sequence[int] | None = None,
page: int = 1,
page_size: int = 20,
) -> tuple[list[ReferenceListItem], int]:
"""Return one page of the library, plus the unpaged total."""
conditions = _conditions(keyword, type_, year, cited_only)
conditions = _conditions(keyword, type_, year, cited_only, tag_ids)
total = db.scalar(select(func.count(Reference.id)).where(*conditions)) or 0
@@ -147,6 +169,7 @@ def list_references(
title=row.title,
subtitle=row.subtitle,
container_title=row.container_title,
publisher=row.publisher,
publication_year=row.publication_year,
volume=row.volume,
issue=row.issue,
@@ -154,6 +177,7 @@ def list_references(
doi=row.doi,
authors_line=authors_line(row.authors),
author_count=len(row.authors),
tags=[ReferenceTagRef.model_validate(tag) for tag in row.tags],
citation_count=counts.get(row.id, 0),
created_at=row.created_at,
updated_at=row.updated_at,
@@ -241,6 +265,7 @@ def read(db: Session, reference: Reference) -> ReferenceRead:
for column in Reference.__table__.columns
},
"authors": reference.authors,
"tags": reference.tags,
"citation_count": counts.get(reference.id, 0),
}
)
@@ -263,16 +288,28 @@ def _build_authors(
def create(db: Session, data: ReferenceCreate) -> Reference:
"""Insert a reference together with its contributors."""
values = data.model_dump(exclude={"authors"})
"""Insert a reference together with its contributors and its tags."""
tags = _resolve_tags(db, data.tag_ids)
values = data.model_dump(exclude={"authors", "tag_ids"})
reference = Reference(**values)
reference.authors = _build_authors(data.authors)
reference.tags = tags
db.add(reference)
db.commit()
db.refresh(reference)
return reference
def _resolve_tags(db: Session, tag_ids: Sequence[int]) -> list[ReferenceTag]:
"""Load the tags to apply, refusing ids the library does not have.
Nothing is written before this returns, so a reference naming a tag that
does not exist is rejected whole rather than stored half-labelled.
"""
tag_crud.assert_exist(db, tag_ids)
return tag_crud.get_many(db, tag_ids)
def update(
db: Session,
reference: Reference,
@@ -283,8 +320,14 @@ def update(
``exclude_unset`` is what makes PATCH semantics work: a key the client did
not send leaves the column alone, so clearing a field is an explicit
``null`` and omitting it is not.
``authors`` and ``tag_ids`` are full replacements when present — the first
because a citation prints the list in the order sent, the second because the
list *is* the set of labels on the row.
"""
values = data.model_dump(exclude_unset=True, exclude={"authors"})
tags = _resolve_tags(db, data.tag_ids) if data.tag_ids is not None else None
values = data.model_dump(exclude_unset=True, exclude={"authors", "tag_ids"})
for key, value in values.items():
setattr(reference, key, value)
@@ -295,6 +338,12 @@ def update(
db.flush()
reference.authors.extend(_build_authors(data.authors))
if tags is not None:
# Assigning to a secondary relationship rewrites the link rows: the ones
# that stayed are untouched, the new ones are inserted, the dropped ones
# deleted. An empty list therefore clears every label.
reference.tags = tags
db.commit()
db.refresh(reference)
return reference
+254
View File
@@ -0,0 +1,254 @@
"""Data access for the reference tags (文献标签).
A tag library is small and is read whole — the picker in the reference form and
the rail in the shell both want every label — so the list here is paged only to
keep the shape of every other list endpoint, not because a page is expected.
Each tag carries how many references hold it. The number is what makes the table
useful ("is this label actually used?") and what the delete confirmation warns
about, and it is a grouped count over the link table rather than a loop.
Two refusals live here because they are domain rules, not HTTP ones:
* **A name is unique.** Two tags spelled the same would be one label under two
ids, and nothing in the UI could explain the difference.
* **A tag must exist before it is applied.** Applying one is a write to the link
table, and the layer that knows a label is missing is this one — so it says so
by name, in the same way the reference side names a citation to literature the
library does not have.
"""
from collections.abc import Sequence
from sqlalchemy import Select, func, or_, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from app.crud.filters import LIKE_ESCAPE, like_pattern
from app.models import ReferenceTag, reference_tag_link
from app.schemas.reference_tag import (
ReferenceTagCreate,
ReferenceTagRead,
ReferenceTagUpdate,
)
class DuplicateTagName(ValueError):
"""A write asked for a tag name that is already taken."""
def __init__(self, name: str) -> None:
self.name = name
super().__init__(f"标签「{name}」已存在")
class UnknownTag(ValueError):
"""A write named a tag the library does not have."""
def __init__(self, missing: Sequence[int]) -> None:
self.missing = list(missing)
joined = "、".join(str(tag_id) for tag_id in self.missing)
super().__init__(f"标签不存在:{joined}")
def _conditions(keyword: str | None) -> list:
"""Translate the list filters into SQLAlchemy predicates."""
conditions = []
if keyword:
pattern = like_pattern(keyword)
conditions.append(
or_(
ReferenceTag.name.like(pattern, escape=LIKE_ESCAPE),
ReferenceTag.note.like(pattern, escape=LIKE_ESCAPE),
)
)
return conditions
def _ordered(stmt: Select) -> Select:
"""Alphabetical, then by insertion order for a stable tie-break.
A tag library is scanned by name — the writer looks for 「方法」 where they
expect it — which is the opposite of the reference list, where the newest
publication leads.
"""
return stmt.order_by(ReferenceTag.name.asc(), ReferenceTag.id.asc())
def reference_counts(db: Session, tag_ids: Sequence[int]) -> dict[int, int]:
"""How many references carry each tag.
``COUNT`` over the link table, grouped — the number of *links*, which is the
number of references because the pair is the primary key.
"""
wanted = list({tag_id for tag_id in tag_ids})
if not wanted:
return {}
stmt = (
select(reference_tag_link.c.tag_id, func.count(reference_tag_link.c.reference_id))
.where(reference_tag_link.c.tag_id.in_(wanted))
.group_by(reference_tag_link.c.tag_id)
)
return {tag_id: count for tag_id, count in db.execute(stmt).all()}
def read(db: Session, tag: ReferenceTag) -> ReferenceTagRead:
"""Build the payload for one tag, count included."""
counts = reference_counts(db, [tag.id])
return ReferenceTagRead.model_validate(
{
"id": tag.id,
"name": tag.name,
"color": tag.color,
"note": tag.note,
"reference_count": counts.get(tag.id, 0),
"created_at": tag.created_at,
"updated_at": tag.updated_at,
}
)
def list_tags(
db: Session,
*,
keyword: str | None = None,
page: int = 1,
page_size: int = 50,
) -> tuple[list[ReferenceTagRead], int]:
"""Return one page of the tag library, plus the unpaged total."""
conditions = _conditions(keyword)
total = db.scalar(select(func.count(ReferenceTag.id)).where(*conditions)) or 0
stmt = _ordered(
select(ReferenceTag)
.where(*conditions)
.offset((page - 1) * page_size)
.limit(page_size)
)
rows = list(db.scalars(stmt).all())
counts = reference_counts(db, [row.id for row in rows])
items = [
ReferenceTagRead.model_validate(
{
"id": row.id,
"name": row.name,
"color": row.color,
"note": row.note,
"reference_count": counts.get(row.id, 0),
"created_at": row.created_at,
"updated_at": row.updated_at,
}
)
for row in rows
]
return items, total
def get(db: Session, tag_id: int) -> ReferenceTag | None:
"""Return one tag, or ``None``."""
return db.get(ReferenceTag, tag_id)
def get_many(db: Session, tag_ids: Sequence[int]) -> list[ReferenceTag]:
"""Return every tag whose id is in ``tag_ids`` (missing ids ignored)."""
if not tag_ids:
return []
stmt = select(ReferenceTag).where(ReferenceTag.id.in_(list(tag_ids)))
return list(db.scalars(stmt).all())
def by_name(db: Session, name: str) -> ReferenceTag | None:
"""Return the tag with this exact name, or ``None``.
Used by the create/rename guard, and by nothing else — a lookup by id is
what the rest of the application does.
"""
return db.scalar(select(ReferenceTag).where(ReferenceTag.name == name))
def missing_ids(db: Session, tag_ids: Sequence[int]) -> list[int]:
"""Which of ``tag_ids`` are not in the library, sorted."""
wanted = set(tag_ids)
if not wanted:
return []
found = set(
db.scalars(select(ReferenceTag.id).where(ReferenceTag.id.in_(wanted))).all()
)
return sorted(wanted - found)
def assert_exist(db: Session, tag_ids: Sequence[int]) -> None:
"""Refuse a write that applies tags the library does not have."""
missing = missing_ids(db, tag_ids)
if missing:
raise UnknownTag(missing)
def _assert_name_free(db: Session, name: str, *, except_id: int | None = None) -> None:
"""Refuse a name another tag already holds.
Checked before the insert so the failure is a message naming the label
rather than a raw unique-constraint error from the driver. The constraint
stays as the authority; this is the explanation.
"""
existing = by_name(db, name)
if existing is not None and existing.id != except_id:
raise DuplicateTagName(name)
def create(db: Session, data: ReferenceTagCreate) -> ReferenceTag:
"""Insert a tag."""
_assert_name_free(db, data.name)
tag = ReferenceTag(**data.model_dump())
db.add(tag)
try:
db.commit()
except IntegrityError as error: # pragma: no cover - lost race only
db.rollback()
raise DuplicateTagName(data.name) from error
db.refresh(tag)
return tag
def update(db: Session, tag: ReferenceTag, data: ReferenceTagUpdate) -> ReferenceTag:
"""Apply a partial update.
Renaming is visible everywhere the label is used, because a reference links
to the tag rather than storing its name — the same reason renaming a heading
updates every template that places it.
"""
values = data.model_dump(exclude_unset=True)
name = values.get("name")
if name is not None and name != tag.name:
_assert_name_free(db, name, except_id=tag.id)
for key, value in values.items():
setattr(tag, key, value)
try:
db.commit()
except IntegrityError as error: # pragma: no cover - lost race only
db.rollback()
raise DuplicateTagName(name or tag.name) from error
db.refresh(tag)
return tag
def delete(db: Session, tag: ReferenceTag) -> None:
"""Delete a tag.
Its links go with it — both sides cascade — so the literature keeps its
place in the library and only loses the label. Callers do not need to check
usage first: unlike a citation, a label is not a claim the paper makes.
"""
db.delete(tag)
db.commit()
def delete_many(db: Session, tag_ids: Sequence[int]) -> int:
"""Delete several tags, returning how many actually existed."""
tags = get_many(db, tag_ids)
for tag in tags:
db.delete(tag)
db.commit()
return len(tags)
+12
View File
@@ -19,6 +19,10 @@ after its table (``Template`` -> ``template``):
paper the 论文 module
paper_sentence one sentence of one paper
paper_sentence_reference a citation of one sentence
reference the 参考文献 module
reference_author its contributors, in print order
reference_tag the writer's labels (文献标签)
reference_tag_link which literature carries which label
``template_title_placement`` and ``template_title`` are one word apart and mean
opposite things: the first is a *placement* (this template puts this field
@@ -42,11 +46,17 @@ from app.models.reference import (
Reference,
)
from app.models.reference_author import ReferenceAuthor
from app.models.reference_tag import (
DEFAULT_TAG_COLOR,
ReferenceTag,
reference_tag_link,
)
from app.models.template import Template
from app.models.template_title_placement import TemplateTitlePlacement
from app.models.template_title import TemplateTitle
__all__ = [
"DEFAULT_TAG_COLOR",
"PAPER_STATUSES",
"STATUS_DONE",
"STATUS_DRAFT",
@@ -59,8 +69,10 @@ __all__ = [
"REFERENCE_TYPES",
"Reference",
"ReferenceAuthor",
"ReferenceTag",
"Template",
"TemplateTitlePlacement",
"TemplateTitle",
"TimestampMixin",
"reference_tag_link",
]
+20
View File
@@ -32,6 +32,14 @@ holds. Formats disagree about names anyway — 「张三」, ``Zhang San``,
``Zhang, S.`` are the same person in three styles — so the printed form and the
two halves are stored separately and a style picks what it needs.
Labels are not columns either
-----------------------------
``keywords`` here are the 关键词 printed on the document — part of the citation
record. The writer's *own* filing of a row (「综述」, 「必读」) is a different
fact with a different lifetime, and it lives in
:mod:`app.models.reference_tag`, reachable as :attr:`Reference.tags`. A tag never
prints in a reference list, so it must not be able to reach one by accident.
What is deliberately missing
----------------------------
The 103 CSL fields include roles this project will never print (narrator,
@@ -51,6 +59,7 @@ from app.models.mixins import TimestampMixin
if TYPE_CHECKING: # pragma: no cover - typing only
from app.models.reference_author import ReferenceAuthor
from app.models.reference_tag import ReferenceTag
#: Document types this library holds, with the marker each format uses for it.
#:
@@ -238,5 +247,16 @@ class Reference(TimestampMixin, Base):
lazy="selectin",
)
#: The writer's own labels (:mod:`app.models.reference_tag`). Not a column of
#: the citation: a document may carry several, the same label is on many
#: documents, and none of them prints. Loaded eagerly for the same reason the
#: contributors are — every table row shows them.
tags: Mapped[list["ReferenceTag"]] = relationship(
secondary="reference_tag_link",
back_populates="references",
order_by="ReferenceTag.id",
lazy="selectin",
)
def __repr__(self) -> str: # pragma: no cover - debugging aid
return f"<Reference id={self.id} type={self.type} title={self.title!r}>"
+127
View File
@@ -0,0 +1,127 @@
"""Tags on the literature (文献标签).
A tag is a label the *writer* puts on a document — 「综述」, 「方法」,
「必读」, 「待精读」 — so a library of a few hundred entries can be narrowed to
the handful that matter for the paragraph being written. It is a filing decision,
not a fact about the document, which is why it is not the same thing as
:attr:`~app.models.reference.Reference.keywords`: those are the 关键词 printed
on the article itself and belong to the citation record, while a tag belongs to
the writer and never prints. One column could not hold both, so they do not
share one.
Two tables, following the naming rule of this package (a module's name plus what
the table holds):
reference_tag one label: its name, and the colour a table paints it in
reference_tag_link which literature carries which label
Why the link is a bare link
---------------------------
A tag on a reference carries nothing of its own: no position, no mark, no text.
It is only "this label applies to this document". That is exactly the case where
``template_title_placement`` had to be a *placement* — it carries ``sort``, the
only home of display order — and here there is no such column, so the pair is
the primary key and the table is named ``_link`` for what it honestly is. A
reference tagged twice with the same tag is therefore not a duplicate row: it is
the same row, because the pair is the identity.
One label, one row
------------------
``name`` is unique. Two tags spelled 「方法」 are one tag, and the API refuses
the second with a message naming it rather than letting a library accumulate
labels that differ only by a trailing space. Nothing else about a tag is
canonical: the colour is decoration, and the note is for the writer.
Deleting a tag deletes labels, not literature
---------------------------------------------
Both foreign keys cascade, so removing a tag removes its links and leaves the
documents alone. That is the opposite of what happens to a reference a sentence
cites — a citation is a claim the paper makes, while a label is only a way of
finding the row again — and the API allows it for the same reason it refuses the
other.
"""
from typing import TYPE_CHECKING
from sqlalchemy import (
Column,
ForeignKey,
Index,
Integer,
String,
Table,
text,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.db.base import Base
from app.models.mixins import TimestampMixin
if TYPE_CHECKING: # pragma: no cover - typing only
from app.models.reference import Reference
#: Which literature carries which label.
#:
#: A Core ``Table`` rather than a mapped class: the pair *is* the row, so there
#: is no attribute to declare and nothing to add later without changing what the
#: table means. Both sides cascade, so deleting a reference or a tag takes its
#: links with it and never leaves a label pointing at a row that is gone.
reference_tag_link = Table(
"reference_tag_link",
Base.metadata,
Column(
"reference_id",
Integer,
ForeignKey("reference.id", ondelete="CASCADE"),
primary_key=True,
),
Column(
"tag_id",
Integer,
ForeignKey("reference_tag.id", ondelete="CASCADE"),
primary_key=True,
),
# The primary key is already the index a reference's own tags are read
# through (its leading column is ``reference_id``). The reverse question —
# "which literature carries this tag?", which is what the tag table's count
# and the by-tag filter ask — needs its own.
Index("ix_reference_tag_link_tag", "tag_id"),
)
#: The colour a new tag is given when the writer does not pick one.
DEFAULT_TAG_COLOR = "#409EFF"
class ReferenceTag(TimestampMixin, Base):
"""One label in the reference module's tag library."""
__tablename__ = "reference_tag"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
#: The label as the writer types it. Unique: a second tag with the same
#: spelling would be the same label under another id.
name: Mapped[str] = mapped_column(String(64), nullable=False, unique=True)
#: ``#RRGGBB``, normalised on write exactly as a heading's colour is, so the
#: table can paint it without parsing. Decoration only — nothing reads it.
color: Mapped[str] = mapped_column(
String(7),
nullable=False,
default=DEFAULT_TAG_COLOR,
server_default=text("'#409EFF'"),
)
#: Free text: what the label is for, who else uses it, when to apply it.
note: Mapped[str | None] = mapped_column(String(255), nullable=True)
#: The literature carrying this label, ordered by when each tag was created
#: so the same reference always prints its labels in the same order.
references: Mapped[list["Reference"]] = relationship(
secondary=reference_tag_link,
back_populates="tags",
order_by="Reference.id",
)
def __repr__(self) -> str: # pragma: no cover - debugging aid
return f"<ReferenceTag id={self.id} name={self.name!r} color={self.color}>"
+10
View File
@@ -33,6 +33,12 @@ from app.schemas.reference import (
ReferenceUpdate,
normalize_doi,
)
from app.schemas.reference_tag import (
ReferenceTagCreate,
ReferenceTagRead,
ReferenceTagRef,
ReferenceTagUpdate,
)
from app.schemas.template import (
TemplateCreate,
TemplateListItem,
@@ -56,6 +62,10 @@ __all__ = [
"ReferenceCreate",
"ReferenceListItem",
"ReferenceRead",
"ReferenceTagCreate",
"ReferenceTagRead",
"ReferenceTagRef",
"ReferenceTagUpdate",
"ReferenceUpdate",
"normalize_doi",
"CitationInput",
+16
View File
@@ -23,6 +23,7 @@ from app.models.reference import (
REFERENCE_LANGUAGES,
REFERENCE_TYPES,
)
from app.schemas.reference_tag import ReferenceTagRef
#: Prefixes people paste along with a DOI. Stripped on write so the column has
#: one spelling, and so a citation builder never has to test for them.
@@ -141,6 +142,10 @@ class ReferenceBase(BaseModel):
citation_key: str | None = Field(default=None, max_length=64)
language: str | None = Field(default=None, max_length=16)
authors: list[ReferenceAuthorInput] = Field(default_factory=list)
#: The tags to apply, by id. Tags are made first and applied second, so this
#: names labels that already exist rather than carrying spellings that could
#: invent new ones. Unknown ids are refused by name.
tag_ids: list[int] = Field(default_factory=list)
@field_validator("title")
@classmethod
@@ -269,6 +274,10 @@ class ReferenceUpdate(BaseModel):
citation_key: str | None = Field(default=None, max_length=64)
language: str | None = Field(default=None, max_length=16)
authors: list[ReferenceAuthorInput] | None = None
#: Full replacement when present, like ``authors``: the list is the set of
#: labels on the row, so sending it means "these and no others" and ``[]``
#: clears every label. Omitting the key leaves the labels alone.
tag_ids: list[int] | None = None
@field_validator("title")
@classmethod
@@ -312,6 +321,9 @@ class ReferenceListItem(BaseModel):
title: str
subtitle: str | None
container_title: str | None
#: 出版者. Carried on the row because a book, a thesis and a report have no
#: container to show and the publisher *is* their "where".
publisher: str | None
publication_year: int | None
volume: str | None
issue: str | None
@@ -321,6 +333,9 @@ class ReferenceListItem(BaseModel):
#: rows behind it.
authors_line: str
author_count: int
#: The labels the writer put on it, ready to paint. Loading them here rather
#: than per row is what keeps a page of the library one query for the tags.
tags: list[ReferenceTagRef] = Field(default_factory=list)
#: How many sentences cite it. Drives the refusal message on delete, and
#: tells the writer at a glance what is already used.
citation_count: int
@@ -370,6 +385,7 @@ class ReferenceRead(BaseModel):
citation_key: str | None
language: str | None
authors: list[ReferenceAuthorRead]
tags: list[ReferenceTagRef] = Field(default_factory=list)
citation_count: int
created_at: datetime
updated_at: datetime
+123
View File
@@ -0,0 +1,123 @@
"""Request/response schemas for the reference tags (文献标签).
The tables and the reasoning behind them are documented on
:mod:`app.models.reference_tag`; this module is the wire format:
* A tag is **made first and applied second**. ``ReferenceCreate.tag_ids`` names
existing tags rather than carrying their names, so a typo cannot silently
invent a label and two clients tagging the same document cannot create two
spellings of it.
* Colours are canonicalised the same way a heading's are — :func:`normalize_hex_color`
accepts ``rgb(r, g, b)``, ``#abc`` and bare ``aabbcc`` — so the column has one
comparable spelling.
* A tag's ``reference_count`` is derived, never sent.
"""
from datetime import datetime
from pydantic import BaseModel, ConfigDict, Field, field_validator
from app.models.reference_tag import DEFAULT_TAG_COLOR
from app.schemas.common import normalize_hex_color
class ReferenceTagBase(BaseModel):
"""The parts of a tag the writer sets."""
name: str = Field(min_length=1, max_length=64)
#: Accepted in any spelling the normaliser understands — ``rgb(64, 158, 255)``
#: is 17 characters — and stored as the canonical 7, so the bound here is on
#: what may *arrive*, not on what the column holds.
color: str = Field(default=DEFAULT_TAG_COLOR, max_length=32)
note: str | None = Field(default=None, max_length=255)
@field_validator("name")
@classmethod
def _require_name(cls, value: str) -> str:
text = value.strip()
if not text:
raise ValueError("标签名称不能为空")
# Inner runs collapse too: " 综述 " and "综述" are one label, and a
# name with a trailing space in it would be a second one.
return " ".join(text.split())
@field_validator("color")
@classmethod
def _canonical_colour(cls, value: str) -> str:
# Raises with its own message when the spelling is not a colour, which
# pydantic turns into a field error naming this field.
return normalize_hex_color(value)
@field_validator("note")
@classmethod
def _blank_to_none(cls, value: str | None) -> str | None:
if value is None:
return None
return value.strip() or None
class ReferenceTagCreate(ReferenceTagBase):
"""Payload for ``POST /reference-tags``."""
class ReferenceTagUpdate(BaseModel):
"""Payload for ``PATCH /reference-tags/{id}`` — every part optional."""
name: str | None = Field(default=None, min_length=1, max_length=64)
color: str | None = Field(default=None, max_length=32)
note: str | None = Field(default=None, max_length=255)
@field_validator("name")
@classmethod
def _require_name(cls, value: str | None) -> str | None:
if value is None:
return None
text = " ".join(value.split())
if not text:
raise ValueError("标签名称不能为空")
return text
@field_validator("color")
@classmethod
def _canonical_colour(cls, value: str | None) -> str | None:
if value is None:
return None
return normalize_hex_color(value)
class ReferenceTagRead(BaseModel):
"""A stored tag, with how much literature carries it."""
model_config = ConfigDict(from_attributes=True)
id: int
name: str
color: str
note: str | None
#: How many references carry this label. Computed on read; it is what the
#: tag table shows and what the delete confirmation warns about.
reference_count: int = 0
created_at: datetime
updated_at: datetime
class ReferenceTagRef(BaseModel):
"""A tag as it appears on a reference — the label, not its usage count.
The library table paints one of these per label, so it carries exactly what
a chip needs and nothing that would have to be loaded per row.
"""
model_config = ConfigDict(from_attributes=True)
id: int
name: str
color: str
__all__ = [
"ReferenceTagCreate",
"ReferenceTagRead",
"ReferenceTagRef",
"ReferenceTagUpdate",
]
+161 -17
View File
@@ -4,11 +4,17 @@ Run it while the backend is up::
.venv/bin/python scripts/smoke_references.py
It walks the whole loop the library exists for — add literature, find it again
by author and by type, link a sentence to it, look the citation up from the
reference side, be refused when deleting something in use, then clean up — and
exits non-zero on the first failed expectation. Everything it creates is
deleted, including the throwaway paper it cites from.
It walks the whole loop the library exists for — make the labels, add
literature and tag it, find it again by author, by type and by tag, link a
sentence to it, look the citation up from the reference side, be refused when
deleting something in use, then clean up — and exits non-zero on the first
failed expectation. Everything it creates is deleted, including the throwaway
paper it cites from.
The order of the first two steps is the point of the tag library rather than an
accident of the script: **tags are made first and applied second**. A reference
is created *with* tag ids, never with tag names, so a typo cannot invent a label
— which is what step 4 checks.
"""
from __future__ import annotations
@@ -60,9 +66,44 @@ def check(label: str, condition: bool, detail: str = "") -> None:
def main() -> int:
created_references: list[int] = []
created_papers: list[int] = []
created_tags: list[int] = []
try:
print("1. add an article with four authors")
print("1. the labels come first: create two tags")
survey = call(
"POST",
"/reference-tags",
{"name": " 综述 ", "color": "rgb(64, 158, 255)", "note": "综述性文献"},
expect=201,
)
created_tags.append(survey["id"])
check("a name is trimmed to one spelling", survey["name"] == "综述", survey["name"])
check(
"a colour is canonicalised",
survey["color"] == "#409EFF",
survey["color"],
)
check("nothing carries it yet", survey["reference_count"] == 0)
must_read = call(
"POST",
"/reference-tags",
{"name": "必读", "color": "#f56c6c"},
expect=201,
)
created_tags.append(must_read["id"])
check("the second tag is stored", must_read["name"] == "必读")
print("2. a tag name is unique, and only a real colour is accepted")
duplicate = call(
"POST", "/reference-tags", {"name": "综述"}, expect=409
)
check("the refusal names the label", "综述" in duplicate["detail"], duplicate["detail"])
call("POST", "/reference-tags", {"name": "怪颜色", "color": "blue"}, expect=422)
call("POST", "/reference-tags", {"name": " "}, expect=422)
check("a blank name and a non-colour are refused", True)
print("3. add an article with four authors and both tags")
article = call(
"POST",
"/references",
@@ -81,6 +122,7 @@ def main() -> int:
"doi": "https://doi.org/10.1016/j.techfore.2024.123456",
"language": "zh",
"keywords": "技术演化, 惯性, 冲量",
"tag_ids": [survey["id"], must_read["id"]],
"authors": [
{"name": "张三", "family_name": "张", "given_name": "三"},
{"name": "李四"},
@@ -107,8 +149,24 @@ def main() -> int:
check("partial date kept as sent", article["publication_year"] == 2024 and article["publication_month"] == 5)
check("no day invented", article["publication_day"] is None)
check("not cited yet", article["citation_count"] == 0)
check(
"both tags are on the row",
sorted(tag["name"] for tag in article["tags"]) == ["必读", "综述"],
str(article["tags"]),
)
print("2. add a patent, which needs a country and a number")
print("4. a tag that does not exist is refused by name, not invented")
missing_tag = call(
"POST",
"/references",
{"title": "引用了不存在的标签", "type": "book", "tag_ids": [999999]},
expect=400,
)
check("the refusal names the id", "999999" in missing_tag["detail"], missing_tag["detail"])
orphan = call("GET", "/references?keyword=引用了不存在的标签")
check("nothing was stored half-labelled", orphan["total"] == 0, str(orphan["total"]))
print("5. add a patent, which needs a country and a number")
patent = call(
"POST",
"/references",
@@ -118,14 +176,20 @@ def main() -> int:
"patent_country": "中国",
"patent_number": "CN114000000A",
"publication_year": 2023,
"tag_ids": [must_read["id"]],
"authors": [{"name": "张三"}],
},
expect=201,
)
created_references.append(patent["id"])
check("patent stored", patent["type"] == "patent" and patent["patent_number"] == "CN114000000A")
check(
"tagging works on create for more than one entry",
[tag["name"] for tag in patent["tags"]] == ["必读"],
str(patent["tags"]),
)
print("3. a webpage without a URL is refused")
print("6. a webpage without a URL is refused")
call(
"POST",
"/references",
@@ -134,20 +198,21 @@ def main() -> int:
)
check("web page without URL refused", True)
print("4. a bad type, a phantom citation target and a missing title are refused")
print("7. a bad type and a missing title are refused")
call("POST", "/references", {"type": "blog-post", "title": "x"}, expect=422)
call("POST", "/references", {"title": " "}, expect=422)
call(
"POST",
"/references",
{"title": "引用了不存在的文献", "authors": [{"name": "甲"}], "type": "book"},
{"title": "没有标签的书", "authors": [{"name": "甲"}], "type": "book"},
expect=201,
)
probe = call("GET", "/references?keyword=引用了不存在")
probe = call("GET", "/references?keyword=没有标签的书")
created_references.append(probe["items"][0]["id"])
check("a book needs nothing else", probe["total"] == 1)
check("and may carry no tags at all", probe["items"][0]["tags"] == [])
print("5. find it again: by author, by type, by year")
print("8. find it again: by author, by type, by year, by tag")
by_author = call("GET", "/references?keyword=Wang")
check("search matches an author name", by_author["total"] == 1, str(by_author["total"]))
check(
@@ -162,12 +227,52 @@ def main() -> int:
uncited = call("GET", "/references?cited=false")
check("filter by not-yet-cited", uncited["total"] == len(created_references))
print("6. edit it: replace the contributor list, change a field")
by_tag = call("GET", f"/references?tag={must_read['id']}")
check("filter by tag", by_tag["total"] == 2, str(by_tag["total"]))
both = call(
"GET",
f"/references?tag={survey['id']}&tag={must_read['id']}",
)
check(
"two tags narrow to the rows carrying both",
both["total"] == 1 and both["items"][0]["id"] == article["id"],
str(both["total"]),
)
print("9. the tag table counts what carries each label")
tags = call("GET", "/reference-tags")
counts = {tag["name"]: tag["reference_count"] for tag in tags["items"]}
check("two labels in the library", tags["total"] == 2, str(tags["total"]))
check("the shared label counts two rows", counts["必读"] == 2, str(counts))
check("the other counts one", counts["综述"] == 1, str(counts))
found = call("GET", "/reference-tags?keyword=综述")
check("tags are searchable by name", found["total"] == 1, str(found["total"]))
print("10. renaming a label follows it everywhere it is used")
renamed = call(
"PATCH",
f"/reference-tags/{survey['id']}",
{"name": "综述文章", "note": "综述与述评"},
)
check("the label is renamed", renamed["name"] == "综述文章")
after = call("GET", f"/references/{article['id']}")
check(
"the reference prints the new name",
sorted(tag["name"] for tag in after["tags"]) == ["必读", "综述文章"],
str(after["tags"]),
)
taken = call(
"PATCH", f"/reference-tags/{survey['id']}", {"name": "必读"}, expect=409
)
check("renaming onto a taken name is refused", "必读" in taken["detail"], taken["detail"])
print("11. edit it: replace the contributor list, a field and its tags")
updated = call(
"PATCH",
f"/references/{article['id']}",
{
"pages": "122-145",
"tag_ids": [must_read["id"]],
"authors": [
{"name": "张三", "family_name": "张", "given_name": "三"},
{"name": "李四"},
@@ -176,9 +281,21 @@ def main() -> int:
)
check("pages updated", updated["pages"] == "122-145")
check("author list replaced wholesale", len(updated["authors"]) == 2)
check(
"tag list replaced wholesale too",
[tag["name"] for tag in updated["tags"]] == ["必读"],
str(updated["tags"]),
)
check("untouched fields kept", updated["container_title"] == "Technological Forecasting and Social Change")
print("7. cite it from a sentence")
cleared = call("PATCH", f"/references/{patent['id']}", {"tag_ids": None})
check(
"omitting tags leaves them alone",
[tag["name"] for tag in cleared["tags"]] == ["必读"],
str(cleared["tags"]),
)
print("12. cite it from a sentence")
templates = call("GET", "/templates?page_size=1")["items"]
paper = call(
"POST",
@@ -214,7 +331,7 @@ def main() -> int:
)
check("a citation to nothing is refused by name", "999999" in missing["detail"], missing["detail"])
print("8. the reverse lookup: which sentences use this article?")
print("13. the reverse lookup: which sentences use this article?")
citations = call("GET", f"/references/{article['id']}/citations")
check("one citation found", len(citations) == 1, str(len(citations)))
check("it names the sentence", "技术惯性约束" in citations[0]["sentence_content"])
@@ -224,21 +341,42 @@ def main() -> int:
cited = call("GET", "/references?cited=true")
check("the cited filter now finds it", cited["total"] == 1, str(cited["total"]))
print("9. a cited reference cannot be deleted; an uncited one can")
print("14. a cited reference cannot be deleted; an uncited one can")
conflict = call("DELETE", f"/references/{article['id']}", expect=409)
check("refusal explains itself", "正被论文引用" in conflict["detail"], conflict["detail"])
call("DELETE", f"/references/{patent['id']}", expect=204)
created_references.remove(patent["id"])
check("an uncited reference deletes cleanly", True)
print("10. clean up")
print("15. deleting a tag unlabels the literature instead of deleting it")
call("DELETE", f"/reference-tags/{must_read['id']}", expect=204)
created_tags.remove(must_read["id"])
survivor = call("GET", f"/references/{article['id']}")
check("the reference is still there", survivor["title"] == article["title"])
check("and has lost that label", survivor["tags"] == [], str(survivor["tags"]))
left = call("GET", f"/references?tag={survey['id']}")
check(
"the other label no longer matches anything",
left["total"] == 0,
str(left["total"]),
)
print("16. clean up")
call("DELETE", f"/papers/{paper['id']}", expect=204)
created_papers.clear()
for reference_id in created_references:
call("DELETE", f"/references/{reference_id}", expect=204)
created_references.clear()
for tag_id in created_tags:
call("DELETE", f"/reference-tags/{tag_id}", expect=204)
created_tags.clear()
remaining = call("GET", "/references")
check("nothing of ours is left", remaining["total"] == 0, str(remaining["total"]))
check(
"and no labels either",
call("GET", "/reference-tags")["total"] == 0,
str(call("GET", "/reference-tags")["total"]),
)
print(f"\nall {_checks} checks passed")
return 0
@@ -254,6 +392,12 @@ def main() -> int:
print(f"cleaned up reference {reference_id}")
except Exception as error: # noqa: BLE001
print(f"cleanup of reference {reference_id} failed: {error}", file=sys.stderr)
for tag_id in created_tags:
try:
call("DELETE", f"/reference-tags/{tag_id}", expect=204)
print(f"cleaned up tag {tag_id}")
except Exception as error: # noqa: BLE001
print(f"cleanup of tag {tag_id} failed: {error}", file=sys.stderr)
if __name__ == "__main__":
+131 -30
View File
@@ -58,7 +58,7 @@ Browser ──HTTP/JSON──▶ FastAPI ──SQLAlchemy──▶ TiDB (k3s)
## Domain Model
Nine tables. Every one is prefixed with the module it belongs to, and a model
Ten tables. Every one is prefixed with the module it belongs to, and a model
class is named after its table, so the schema can be read as four groups:
```
@@ -87,6 +87,13 @@ reference the 参考文献 module: the literature itself
reference_author its contributors, in print order
id, reference_id → reference, sort, name, family_name, given_name, role
reference_tag the writer's own labels (文献标签)
id, name (unique), color, note
reference_tag_link which literature carries which label
reference_id → reference, — the pair is the primary key and the
tag_id → reference_tag row holds nothing else
```
### How the tables are named
@@ -244,6 +251,39 @@ The 103 CSL fields include roles this project will never print (narrator,
performer, curator) and archival fields (call-number, archive-place). They are
left out on purpose; see :mod:`app.models.reference`.
### Tags are the writer's filing, not the document's keywords
``reference.keywords`` is a field of the *document* — the 关键词 printed on the
article, transcribed because a citation record should be able to reproduce it.
A tag is a fact about the *writer*: 「综述」, 「必读」, 「待精读」, the labels that
narrow a library of a few hundred entries to the handful that matter for the
paragraph being written. They never print, one document carries several, and the
same label is on many documents. Two different facts with two different
lifetimes cannot share a column, so labels live in their own two tables:
```
reference_tag one label: name (unique), colour, note
reference_tag_link reference_id + tag_id — the pair is the primary key
```
The link table is named ``_link`` and not ``_placement`` for the reason
``template_title_placement`` is not: it carries nothing of its own. There is no
``sort`` here, so the pair *is* the row — which also means the same label cannot
be applied to the same document twice, and that is a property of the key rather
than a rule anyone has to remember to enforce.
**A tag is made first and applied second.** A reference is created with
``tag_ids``, never with tag names, so a typo cannot invent a label and two
clients cannot create two spellings of one. An id the library does not have is
refused with ``400`` naming it, and nothing is written.
**Deleting a tag is not guarded, deliberately.** Both foreign keys cascade, so
removing a label removes labels and leaves the literature where it was. That is
the opposite of deleting a *cited reference*, which is refused with ``409``: a
citation is a claim the paper makes, while a label is only a way of finding the
row again. The confirmation in the UI says how many entries will lose the label,
which is the honest form of that warning.
### A sentence is a line, not parsed text
Nothing in the writing path splits text. There is no sentence detector, no
@@ -349,11 +389,15 @@ All routes are mounted under `/api`. Interactive docs at `/docs`.
| `POST` | `/papers` | title + template + author/status/keywords/journal; no sentence rows are created |
| `GET` `PATCH` `DELETE` | `/papers/{id}` | `PATCH` with `template_id` **is** the template switch |
| `POST` | `/papers/batch-delete` | body `{ "ids": [...] }` |
| `GET` | `/references` | `keyword` (题名/刊名/作者/DOI/关键词/备注), `type`, `year`, `cited` |
| `POST` | `/references` | the whole entry, `authors` in print order |
| `GET` `PATCH` `DELETE` | `/references/{id}` | `PATCH` with `authors` replaces the list |
| `GET` | `/references` | `keyword` (题名/刊名/作者/DOI/关键词/备注), `type`, `year`, `cited`, `tag` |
| `POST` | `/references` | the whole entry, `authors` in print order, `tag_ids` to label it |
| `GET` `PATCH` `DELETE` | `/references/{id}` | `PATCH` with `authors` or `tag_ids` replaces that list |
| `POST` | `/references/batch-delete` | body `{ "ids": [...] }` |
| `GET` | `/references/{id}/citations` | which sentences cite it, and in which paragraph |
| `GET` | `/reference-tags` | `keyword` matches 标签名称 **or** 备注; each row carries its 文献数 |
| `POST` | `/reference-tags` | name is unique — a duplicate is `409` naming it |
| `GET` `PATCH` `DELETE` | `/reference-tags/{id}` | renaming follows every reference carrying it |
| `POST` | `/reference-tags/batch-delete` | body `{ "ids": [...] }`; unlabels, never deletes literature |
| `GET` | `/papers/{id}/document` | the whole paper: paragraphs in order, citations, warnings |
| `GET` | `/papers/{id}/paragraphs/{sort}` | one paragraph, assembled as the document renders it |
| `PUT` | `/papers/{id}/paragraphs/{sort}` | full replacement; optional `target_sort` moves it |
@@ -388,6 +432,15 @@ Conventions worth knowing:
quote may be written before it is linked.
- Deleting a reference a sentence cites is refused with `409`, naming the entry
and how many citations use it.
- Applying a tag that does not exist is a `400` naming the ids, not a
foreign-key error: the library is checked before the write, and a reference
naming a label that is not there is refused whole rather than stored
half-labelled.
- Deleting a tag is **not** refused. The label rows go and the literature stays,
because a label is the writer's filing rather than a claim the paper makes.
- `tag` may be given more than once, and the filters narrow rather than widen:
`?tag=1&tag=2` returns the rows carrying **both** labels, which is how the
rail's labels compose with the toolbar's.
- A DOI is stored without its ``https://doi.org/`` prefix, so the column holds
one spelling whichever way it was pasted.
@@ -447,29 +500,41 @@ nothing.
### Shell
```
┌───────────────────┬──────────────────────────────────────┐
│ [mark] paper-doc │ 论文 模板 [mk] │ header
├───────────────────┼──────────────────────────────────────┤
┌───────────────────────────┬──────────────────────────────────────┐
│ [mark] paper-doc │ 论文 模板 参考文献 [mk] │ header
├───────────────────────────┼──────────────────────────────────────┤
│ 论文 │ │ second-level
│ 论文列表 │ <RouterView> │ menu, left
│ 新建论文 │ │
│ ── 我的论文 ── │ │
│ ● 论文标题 A │ │
│ ● 论文标题 B │ │
└───────────────────┴──────────────────────────────────────┘
└───────────────────────────┴──────────────────────────────────────┘
<- 208px ->
```
The mark appears at both ends of the header. The second-level menu sits on the
**left** and is driven by `route.meta.section`, so a route declares which menu
it belongs to and deep links render correctly on first paint. Routes without a
`section` (the welcome page) show no menu.
The mark appears at both ends of the header. The three top-level entries are the
two surfaces a paper is worked *in* — 论文 and 模板 — and, marked out to their
right, 参考文献: the library is drawn *from* rather than worked in, so it is a
button one step away instead of a third thing to choose between (§ the rail
lists what is in it).
The 论文 menu is the one that is not a static list: it carries the papers
themselves, read from the `papers` store, so a paper can be opened straight from
the rail. Every page that creates, renames or deletes a paper reloads that
store, which is what keeps the rail and the table showing the same thing. A
filter box appears once there are more than six papers.
The second-level menu sits on the **left** and is driven by `route.meta.section`,
so a route declares which menu it belongs to and deep links render correctly on
first paint. Routes without a `section` (the welcome page) show no menu.
Two menus are not static lists, and both carry real data rather than links. 论文
lists the papers themselves, read from the `papers` store, so a paper can be
opened straight from the rail. 参考文献 lists the tags, read from the
`referenceTags` store, so a label can be picked straight from the rail — and
because both are driven by their stores, every page that creates, renames or
deletes one reloads it, which is what keeps the rail and the table showing the
same thing. Each rail grows a filter box once its list passes six entries.
A tag in the rail links to `/references?tag=<id>`, which makes the query
parameter part of the *view* rather than a hidden filter state:
`SectionAside` highlights that entry by matching the parameter, and the table's
own tag selector writes the same parameter back.
Two things about this layout are deliberate and easy to break by accident:
@@ -499,10 +564,10 @@ stylesheet.
A table is the page. Left alone it is as tall as its rows, so on a large screen
most of the window sits empty below the last row while the *page* is still the
thing that scrolls — the wrong half of the screen moving for a list that should
simply show more. The three list pages (`/papers`, `/templates/list`,
`/templates/fields`) therefore stretch the table to the height the window
offers, with the toolbar above it and the pagination below it staying put while
the rows scroll inside the table.
simply show more. The five list pages (`/papers`, `/templates/list`,
`/templates/fields`, `/references`, `/references/tags`) therefore stretch the
table to the height the window offers, with the toolbar above it and the
pagination below it staying put while the rows scroll inside the table.
It is CSS only — no resize listener, no measured pixel height, nothing to go
stale when the rail collapses or the window changes. Four links carry it, and
@@ -539,6 +604,8 @@ are not lists (the paper document) keep scrolling normally.
| `/templates` | redirects to `/templates/list` | — |
| `/templates/list` | template table + CRUD | `templates` |
| `/templates/fields` | title library + CRUD (the UI label is 字段管理) | `templates` |
| `/references` | reference table + CRUD (`?tag=<id>` filters, `?new=1` opens the create dialog) | `references` |
| `/references/tags` | tag library + CRUD (the UI label is 标签管理) | `references` |
### The paper view
@@ -559,14 +626,42 @@ alone knows how to do:
Changing a paper's template from the metadata form is deliberately disabled: a
silent re-shape of the document is exactly what the preview exists to prevent.
### The reference library view
`references/ReferenceListView` is the library and `references/TagManageView` is
the label library beside it. Three things about the pair are decisions rather
than layout:
- **The tag filter lives in the URL.** The rail links to
`/references?tag=<id>` and the toolbar's selector writes the same parameter
back, so the two cannot disagree about which label is being looked at, the
rail can highlight it, and a filtered view is a link someone can be sent. The
page reads `route.query.tag`, which is why the filter survives a refresh and a
back-navigation.
- **The citation count is a door.** "Which of my sentences use this?" is the
question that decides whether an entry is safe to delete, and the count in the
row opens the answer (`ReferenceCitationsDialog`: the paper, the paragraph
heading, the sentence, and the quoted passage) rather than being a number to
interpret.
- **A tag is created before it is applied.** The form's picker offers the labels
that exist and allows a new name to be typed; that name is created through the
tag API *before* the reference is written, so no stored reference can point at
a label that is not there. The dialog says so, and links to 标签管理 for anyone
who would rather file first and tag second — which is the intended order.
The form itself is grouped by tab (基本信息 / 责任者 / 出版信息 / 标识与链接 /
摘要与备注) rather than listed flat: the field set is the union of what CSL,
GB/T 7714 and BibTeX need, and forty inputs in a column is a form nobody fills
in correctly.
## Directory Structure
```
paper-doc/
├── backend/ # FastAPI application
│ ├── app/
│ │ ├── api/routes/ # route handlers (health, papers, templates,
│ │ │ # template_title)
│ │ ├── api/routes/ # route handlers (health, papers, references,
│ │ │ # reference_tags, templates, template_title)
│ │ ├── core/ # settings and configuration
│ │ ├── crud/ # data-access helpers
│ │ ├── db/ # engine, session, declarative base
@@ -577,6 +672,7 @@ paper-doc/
│ ├── scripts/seed.py # idempotent seed for the title library + templates
│ ├── scripts/smoke_papers.py # end-to-end check of the writing loop
│ ├── scripts/smoke_references.py # end-to-end check of the reference library
│ │ # and its tags
│ ├── scripts/mcp_server.py # MCP entry point (stdio / http)
│ ├── scripts/smoke_mcp.py # the same loop, spoken over MCP by a real client
│ ├── alembic.ini
@@ -585,12 +681,15 @@ paper-doc/
├── frontend/ # Vue 3 SPA
│ ├── src/
│ │ ├── api/ # axios instance and endpoint modules
│ │ ├── components/ # shell, field, template and paper components
│ │ ├── components/ # shell, field, template, paper and reference
│ │ │ # components
│ │ ├── router/ # vue-router configuration
│ │ ├── stores/ # pinia stores (UI prefs persisted, the paper list not)
│ │ ├── stores/ # pinia stores (UI prefs persisted, the paper and
│ │ │ # tag lists not)
│ │ ├── styles/ # global reset and the shell viewport contract
│ │ ├── utils/ # formatting helpers
│ │ └── views/ # route-level components (papers/, templates/)
│ │ └── views/ # route-level components (papers/, references/,
│ │ # templates/)
│ ├── package.json
│ └── vite.config.ts
├── deploy/ # packaging and the k3s manifests
@@ -658,10 +757,12 @@ cd backend
**Checking the reference library end to end**
`scripts/smoke_references.py` adds literature, finds it again by author, type,
year and whether it has been cited, edits it, cites it from a sentence, looks
the citation up from the reference side, and checks that a cited entry cannot be
deleted. It cleans up after itself:
`scripts/smoke_references.py` makes the labels first, adds literature and tags
it, finds it again by author, type, year and tag, edits it, cites it from a
sentence, looks the citation up from the reference side, checks that a cited
entry cannot be deleted while a tag can, and checks that a tag id the library
does not have is refused by name rather than invented. It cleans up after
itself:
```bash
cd backend
+15 -6
View File
@@ -2,10 +2,10 @@
/**
* Application shell.
*
* Three bands, in this order: a header holding the mark, the two top-level
* sections, and the mark again at the far right; then the row below it, which
* is the second-level menu on the left followed by the content area. The menu
* is present only on routes that declare a `section` in their meta.
* Three bands, in this order: a header holding the mark, the top-level sections,
* and the mark again at the far right; then the row below it, which is the
* second-level menu on the left followed by the content area. The menu is
* present only on routes that declare a `section` in their meta.
*/
import { computed } from 'vue'
import { RouterView, RouterLink, useRoute } from 'vue-router'
@@ -18,10 +18,18 @@ import { useAppStore } from '@/stores/app'
const route = useRoute()
const appStore = useAppStore()
/** The two top-level sections. `index` is the path `el-menu` routes to. */
/**
* The top-level sections. `index` is the path `el-menu` routes to.
*
* 参考文献 sits to the right of 论文 and 模板 because it is a different kind of
* thing: the writing surface and the templates are worked *in*, while the
* library is drawn *from* — one button away rather than one more thing to
* choose between.
*/
const TOP_MENU = [
{ index: '/papers', label: '论文' },
{ index: '/templates', label: '模板' },
{ index: '/references', label: '参考文献' },
] as const
/**
@@ -29,7 +37,8 @@ const TOP_MENU = [
*
* Derived from the path rather than tracked in state, so browser back/forward
* and a pasted deep link both leave the header highlighting the right entry.
* `/templates/list` and `/templates/fields` both resolve to `/templates`.
* `/templates/list` and `/templates/fields` both resolve to `/templates`, and
* `/references/tags` resolves to `/references`.
*/
const activeTop = computed(() => {
const match = TOP_MENU.find(
+129
View File
@@ -0,0 +1,129 @@
import http from './client'
import type { BatchDeleteResult, PageQuery, PageResult } from './types'
/**
* Reference tags (文献标签) — the writer's own labels on the literature.
*
* A tag is *made first and applied second*: a reference is created with
* `tag_ids`, never with tag names, so a typo cannot invent a label. This module
* is the first half of that flow; `references.ts` is the second.
*
* A tag never prints in a reference list — it exists so a library of a few
* hundred entries can be narrowed to the handful that matter for the paragraph
* being written. That is why it is a separate table from the document's own
* 关键词, which are transcribed from the article and do print.
*/
/** A tag as the pickers and the chips need it: no counts, no timestamps. */
export interface ReferenceTagRef {
id: number
name: string
/** Canonical `#RRGGBB`, normalised by the API on write. */
color: string
}
/** A tag as the tag table shows it. */
export interface ReferenceTag extends ReferenceTagRef {
note: string | null
/** How many references carry this label. Computed on read. */
reference_count: number
created_at: string
updated_at: string
}
export interface ReferenceTagPayload {
name: string
color: string
note: string | null
}
export interface ReferenceTagQuery extends PageQuery {
page?: number
page_size?: number
}
/**
* The colours the picker offers.
*
* Chips are the only place a tag colour is ever read, and a table of labels is
* read at a glance — so the palette is a small set of hues that stay legible
* against the tag's own tinted background, plus two greys for labels that are
* meant to recede.
*/
export const TAG_COLOR_PRESETS = [
'#409EFF',
'#67C23A',
'#E6A23C',
'#F56C6C',
'#9B59B6',
'#14B8A6',
'#8C8C8C',
'#1F1F1F',
] as const
/** The label a tag with no colour of its own gets. */
export const DEFAULT_TAG_COLOR = '#409EFF'
export async function listReferenceTags(
query: ReferenceTagQuery = {},
): Promise<PageResult<ReferenceTag>> {
const params: Record<string, unknown> = {}
if (query.keyword) params.keyword = query.keyword
if (query.page) params.page = query.page
if (query.page_size) params.page_size = query.page_size
const { data } = await http.get<PageResult<ReferenceTag>>('/reference-tags', { params })
return data
}
/** The API caps `page_size` at 500; a picker wants every label, so it loops. */
const TAG_PAGE_SIZE = 200
/**
* Fetch every tag, following pagination.
*
* The reference form and the shell's rail both want the whole library: a picker
* that showed one page would hide the label the writer is looking for, and the
* rail would show a partial list that looks complete.
*/
export async function fetchAllReferenceTags(keyword?: string): Promise<ReferenceTag[]> {
const all: ReferenceTag[] = []
let page = 1
for (;;) {
const result = await listReferenceTags({ keyword, page, page_size: TAG_PAGE_SIZE })
all.push(...result.items)
if (page >= result.pages || result.items.length === 0) {
return all
}
page += 1
}
}
export async function createReferenceTag(
payload: ReferenceTagPayload,
): Promise<ReferenceTag> {
const { data } = await http.post<ReferenceTag>('/reference-tags', payload)
return data
}
export async function updateReferenceTag(
id: number,
payload: Partial<ReferenceTagPayload>,
): Promise<ReferenceTag> {
const { data } = await http.patch<ReferenceTag>(`/reference-tags/${id}`, payload)
return data
}
export async function deleteReferenceTag(id: number): Promise<void> {
await http.delete(`/reference-tags/${id}`)
}
export async function batchDeleteReferenceTags(
ids: number[],
): Promise<BatchDeleteResult> {
const { data } = await http.post<BatchDeleteResult>('/reference-tags/batch-delete', {
ids,
})
return data
}
+301
View File
@@ -0,0 +1,301 @@
import http from './client'
import type { ReferenceTagRef } from './referenceTags'
import type { BatchDeleteResult, PageQuery, PageResult } from './types'
/**
* The reference library (参考文献) — the literature a paper cites.
*
* One row is one document the writer has read: a journal article, a book, a
* patent, a standard, a dataset. It is **global**, not owned by a paper, because
* the same article is cited from several papers; the citation itself (which
* sentence quotes which passage) lives on the paper side.
*
* The fields are the intersection of the formats a Chinese journal paper has to
* survive — CSL JSON, GB/T 7714-2015, BibTeX/RIS — which is what the labels on
* the form mirror. Contributors arrive as an ordered list and replace the stored
* list wholesale, exactly like a template's placements.
*/
/**
* The document types this library holds.
*
* `marker` is the GB/T 7714 文献类型标志 a reference list prints after the
* title, which is why it is carried here rather than derived per view.
*/
export const REFERENCE_TYPE_OPTIONS = [
{ value: 'journal-article', label: '期刊论文', marker: 'J' },
{ value: 'book', label: '专著', marker: 'M' },
{ value: 'book-chapter', label: '析出文献', marker: 'M' },
{ value: 'conference-paper', label: '会议论文', marker: 'C' },
{ value: 'thesis', label: '学位论文', marker: 'D' },
{ value: 'patent', label: '专利', marker: 'P' },
{ value: 'standard', label: '标准', marker: 'S' },
{ value: 'report', label: '报告', marker: 'R' },
{ value: 'newspaper-article', label: '报纸文章', marker: 'N' },
{ value: 'web-page', label: '网页', marker: 'EB/OL' },
{ value: 'dataset', label: '数据集', marker: 'DS' },
{ value: 'software', label: '计算机程序', marker: 'CP' },
{ value: 'preprint', label: '预印本', marker: 'EB/OL' },
{ value: 'other', label: '其他', marker: 'Z' },
] as const
export type ReferenceType = (typeof REFERENCE_TYPE_OPTIONS)[number]['value']
const TYPE_LABELS = new Map<string, string>(
REFERENCE_TYPE_OPTIONS.map((option) => [option.value as string, option.label]),
)
const TYPE_MARKERS = new Map<string, string>(
REFERENCE_TYPE_OPTIONS.map((option) => [option.value as string, option.marker]),
)
/** The Chinese name of a type token, falling back to the token itself. */
export function referenceTypeLabel(type: string): string {
return TYPE_LABELS.get(type) ?? type
}
/** The GB/T 7714 marker of a type token, or `''` for one we do not know. */
export function referenceTypeMarker(type: string): string {
return TYPE_MARKERS.get(type) ?? ''
}
/** 语种 — decides which of the two titles a style prints first. */
export const REFERENCE_LANGUAGE_OPTIONS = [
{ value: 'zh', label: '中文' },
{ value: 'en', label: '英文' },
{ value: 'ja', label: '日文' },
{ value: 'other', label: '其他' },
] as const
/** 责任者角色 — what prints after a name (编 / 译 / 主编). */
export const REFERENCE_AUTHOR_ROLE_OPTIONS = [
{ value: 'author', label: '作者' },
{ value: 'editor', label: '编者' },
{ value: 'translator', label: '译者' },
{ value: 'compiler', label: '汇编' },
] as const
/** A stored contributor of a reference. */
export interface ReferenceAuthor {
id: number
/** Print order, ascending. */
sort: number
/** What prints: 「张三」, "John Smith", 「世界卫生组织」. */
name: string
/** Optional halves, for styles that invert or initialise a name. */
family_name: string | null
given_name: string | null
role: string
}
/** A contributor as the form sends it. */
export interface ReferenceAuthorInput {
name: string
family_name: string | null
given_name: string | null
role: string
sort?: number | null
}
/** A reference as it appears in the library table. */
export interface ReferenceListItem {
id: number
type: string
title: string
subtitle: string | null
container_title: string | null
/** 出版者 — the "where" for a book, a thesis or a report, which has no container. */
publisher: string | null
publication_year: number | null
volume: string | null
issue: string | null
pages: string | null
doi: string | null
/** The printed author line, already truncated for a row by the API. */
authors_line: string
author_count: number
tags: ReferenceTagRef[]
/** How many sentences cite it. */
citation_count: number
created_at: string
updated_at: string
}
/**
* A reference with everything the table does not need.
*
* The list row deliberately drops the abstract, the note and the contributor
* rows; the form needs them, so editing fetches this shape by id.
*/
export interface ReferenceDetail {
id: number
type: string
title: string
subtitle: string | null
title_translated: string | null
title_short: string | null
container_title: string | null
container_title_short: string | null
series_title: string | null
series_number: string | null
edition: string | null
volume: string | null
issue: string | null
pages: string | null
article_number: string | null
publisher: string | null
publisher_place: string | null
event_title: string | null
event_place: string | null
event_date: string | null
publication_year: number | null
publication_month: number | null
publication_day: number | null
accessed_date: string | null
doi: string | null
isbn: string | null
issn: string | null
url: string | null
patent_country: string | null
patent_number: string | null
standard_number: string | null
report_number: string | null
arxiv_id: string | null
abstract: string | null
keywords: string | null
note: string | null
citation_key: string | null
language: string | null
authors: ReferenceAuthor[]
tags: ReferenceTagRef[]
citation_count: number
created_at: string
updated_at: string
}
/** One sentence that cites a reference — the reverse lookup. */
export interface ReferenceCitation {
citation_id: number
sentence_id: number
sentence_content: string
/** 引用内容 — the passage the sentence quotes. */
quote: string
paper_id: number
paper_title: string
paper_template_filed_sort: number
/** The heading the paper's template puts at that position, if any. */
paragraph_name: string | null
}
/** Everything a reference may carry. Only `title` is required. */
export interface ReferencePayload {
type: string
title: string
subtitle: string | null
title_translated: string | null
title_short: string | null
container_title: string | null
container_title_short: string | null
series_title: string | null
series_number: string | null
edition: string | null
volume: string | null
issue: string | null
pages: string | null
article_number: string | null
publisher: string | null
publisher_place: string | null
event_title: string | null
event_place: string | null
event_date: string | null
publication_year: number | null
publication_month: number | null
publication_day: number | null
accessed_date: string | null
doi: string | null
isbn: string | null
issn: string | null
url: string | null
patent_country: string | null
patent_number: string | null
standard_number: string | null
report_number: string | null
arxiv_id: string | null
abstract: string | null
keywords: string | null
note: string | null
citation_key: string | null
language: string | null
authors: ReferenceAuthorInput[]
tag_ids: number[]
}
export interface ReferenceQuery extends PageQuery {
type?: string | null
year?: number | null
/** `true` only what is already cited, `false` only what is not. */
cited?: boolean | null
/** Tag ids; more than one narrows to the rows carrying all of them. */
tag_ids?: number[]
}
export async function listReferences(
query: ReferenceQuery = {},
): Promise<PageResult<ReferenceListItem>> {
// Built as a `URLSearchParams` rather than a plain object because the tag
// filter repeats its key: `tag=1&tag=2` means "carries both labels", while
// the default array serialisation would send `tag[]=1`.
const search = new URLSearchParams()
const set = (
key: string,
value: string | number | boolean | null | undefined,
): void => {
if (value == null || value === '') return
search.set(key, String(value))
}
set('keyword', query.keyword)
set('type', query.type)
set('year', query.year)
set('cited', query.cited)
set('page', query.page)
set('page_size', query.page_size)
for (const tagId of query.tag_ids ?? []) search.append('tag', String(tagId))
const { data } = await http.get<PageResult<ReferenceListItem>>('/references', {
params: search,
})
return data
}
export async function getReference(id: number): Promise<ReferenceDetail> {
const { data } = await http.get<ReferenceDetail>(`/references/${id}`)
return data
}
/** Every sentence that cites this reference, with the paper it sits in. */
export async function listReferenceCitations(id: number): Promise<ReferenceCitation[]> {
const { data } = await http.get<ReferenceCitation[]>(`/references/${id}/citations`)
return data
}
export async function createReference(payload: ReferencePayload): Promise<ReferenceDetail> {
const { data } = await http.post<ReferenceDetail>('/references', payload)
return data
}
export async function updateReference(
id: number,
payload: Partial<ReferencePayload>,
): Promise<ReferenceDetail> {
const { data } = await http.patch<ReferenceDetail>(`/references/${id}`, payload)
return data
}
export async function deleteReference(id: number): Promise<void> {
await http.delete(`/references/${id}`)
}
export async function batchDeleteReferences(ids: number[]): Promise<BatchDeleteResult> {
const { data } = await http.post<BatchDeleteResult>('/references/batch-delete', { ids })
return data
}
+168 -19
View File
@@ -4,22 +4,36 @@
*
* It is driven by `route.meta.section`, so the menu a URL belongs to is a
* property of the route table rather than of component state — deep linking to
* `/templates/fields` or `/papers/12` shows the right menu on first paint, and
* the aside disappears on routes that declare no section (the welcome page).
* `/templates/fields`, `/papers/12` or `/references?tag=3` shows the right menu
* on first paint, and the aside disappears on routes that declare no section
* (the welcome page).
*
* The 论文 menu is the exception to the static list: it carries the papers
* themselves, so it is read from the store rather than written here. Every page
* that creates, renames or deletes a paper reloads that store, which is what
* keeps the menu and the table showing the same thing.
* Two menus are exceptions to the static list, and both carry real data rather
* than links: 论文 lists the papers themselves, and 参考文献 lists the tags, so
* either can be opened straight from the rail. Each is read from its store, and
* every page that changes one reloads that store, which is what keeps the rail
* and the table showing the same thing.
*/
import { computed, onMounted, ref, watch, type Component } from 'vue'
import { useRoute } from 'vue-router'
import { Document, Expand, Files, Fold, Plus, Search, Setting } from '@element-plus/icons-vue'
import {
Collection,
Document,
Expand,
Files,
Fold,
Plus,
PriceTag,
Search,
Setting,
} from '@element-plus/icons-vue'
import type { PaperListItem } from '@/api/papers'
import type { ReferenceTag } from '@/api/referenceTags'
import { ASIDE_INSET, asideWidth } from '@/layout'
import { useAppStore } from '@/stores/app'
import { usePapersStore } from '@/stores/papers'
import { useReferenceTagsStore } from '@/stores/referenceTags'
interface AsideItem {
index: string
@@ -38,6 +52,7 @@ const props = defineProps<{ section: string }>()
const route = useRoute()
const appStore = useAppStore()
const papersStore = usePapersStore()
const tagsStore = useReferenceTagsStore()
const MENUS: Record<string, AsideMenu> = {
papers: {
@@ -56,6 +71,17 @@ const MENUS: Record<string, AsideMenu> = {
{ index: '/templates/fields', label: '字段管理', icon: Setting },
],
},
// 标签管理 is listed as a page of this section rather than as a fourth
// top-level entry: a tag exists to file the literature, so it is managed next
// to it.
references: {
title: '参考文献',
items: [
{ index: '/references', label: '文献列表', icon: Collection },
{ index: '/references?new=1', label: '新增文献', icon: Plus },
{ index: '/references/tags', label: '标签管理', icon: PriceTag },
],
},
}
const menu = computed<AsideMenu | null>(() => MENUS[props.section] ?? null)
@@ -68,13 +94,18 @@ const inset = ASIDE_INSET
/** Filter for the paper list: a rail this narrow cannot show every paper. */
const paperFilter = ref('')
/** The same problem for the tag list, which grows with the library. */
const tagFilter = ref('')
const papers = computed<PaperListItem[]>(() => papersStore.items)
const tags = computed<ReferenceTag[]>(() => tagsStore.items)
/**
* The filter appears only once the list is long enough to need it. Below that
* it would occupy a menu item's worth of height to hide nothing.
* A filter appears only once the list is long enough to need it. Below that it
* would occupy a menu item's worth of height to hide nothing.
*/
const filterable = computed(() => papers.value.length > 6)
const tagsFilterable = computed(() => tags.value.length > 6)
const filteredPapers = computed(() => {
const keyword = paperFilter.value.trim().toLowerCase()
@@ -82,19 +113,41 @@ const filteredPapers = computed(() => {
return papers.value.filter((paper) => paper.title.toLowerCase().includes(keyword))
})
/** The active entry: either a static one or the paper currently open. */
const activeIndex = computed(() =>
route.path === '/papers' && route.query.new ? '/papers?new=1' : route.path,
)
const filteredTags = computed(() => {
const keyword = tagFilter.value.trim().toLowerCase()
if (!keyword) return tags.value
return tags.value.filter((tag) => tag.name.toLowerCase().includes(keyword))
})
/** Load the menu's list the first time the 论文 section is opened. */
function ensurePapers(): void {
if (props.section !== 'papers') return
if (!papersStore.loaded && !papersStore.loading) void papersStore.reload()
/**
* The active entry.
*
* The two list menus are entered through a query parameter that *is* the view —
* 新建论文 opens the create dialog, a tag narrows the library — so the highlight
* has to follow the parameter rather than the path alone.
*/
const activeIndex = computed(() => {
if (props.section === 'papers' && route.path === '/papers' && route.query.new) {
return '/papers?new=1'
}
if (props.section === 'references' && route.path === '/references' && route.query.tag) {
return `/references?tag=${route.query.tag}`
}
return route.path
})
/** Load the menu's list the first time its section is opened. */
function ensureLists(): void {
if (props.section === 'papers' && !papersStore.loaded && !papersStore.loading) {
void papersStore.reload()
}
if (props.section === 'references') {
void tagsStore.ensureLoaded()
}
}
watch(() => props.section, ensurePapers)
onMounted(ensurePapers)
watch(() => props.section, ensureLists)
onMounted(ensureLists)
</script>
<template>
@@ -184,6 +237,60 @@ onMounted(ensurePapers)
没有匹配的论文。
</p>
</template>
<!-- 参考文献 carries the labels themselves: picking one filters the
library, which is the whole reason the tags exist. -->
<template v-if="section === 'references'">
<div v-if="tagsFilterable && !collapsed" class="aside-filter">
<el-input
v-model="tagFilter"
size="small"
placeholder="筛选标签"
clearable
:prefix-icon="Search"
/>
</div>
<el-menu
:default-active="activeIndex"
:collapse="collapsed"
:collapse-transition="false"
router
class="aside-menu aside-menu--tags"
>
<el-menu-item
v-for="tag in filteredTags"
:key="tag.id"
:index="`/references?tag=${tag.id}`"
>
<el-icon><PriceTag /></el-icon>
<template #title>
<el-tooltip
:content="`${tag.name}(${tag.reference_count} 篇文献)`"
placement="right"
:show-after="400"
:disabled="collapsed"
>
<span class="aside-tag">
<span
class="aside-tag-dot"
:style="{ backgroundColor: tag.color }"
/>
<span class="aside-tag-name">{{ tag.name }}</span>
<span class="aside-tag-count">{{ tag.reference_count }}</span>
</span>
</el-tooltip>
</template>
</el-menu-item>
</el-menu>
<p v-if="!collapsed && tags.length === 0" class="aside-empty">
还没有标签。先在「标签管理」里建几个,用来给文献归档。
</p>
<p v-else-if="!collapsed && filteredTags.length === 0" class="aside-empty">
没有匹配的标签。
</p>
</template>
</div>
</el-aside>
</template>
@@ -249,6 +356,12 @@ onMounted(ensurePapers)
border-top: 1px solid var(--el-border-color-lighter);
}
.aside-menu--tags {
margin-top: 4px;
padding-top: 4px;
border-top: 1px solid var(--el-border-color-lighter);
}
/* A collapsed el-menu keeps a fixed 64px width that no longer matches the
56px rail, so the items would sit off-centre. */
.aside-menu.el-menu--collapse {
@@ -302,6 +415,42 @@ onMounted(ensurePapers)
overflow: hidden;
}
/* A tag in the rail: its colour, its name, and how much carries it — the count
is what tells the writer whether a label is worth keeping. */
.aside-tag {
display: flex;
align-items: center;
gap: 6px;
min-width: 0;
}
.aside-tag-dot {
flex: 0 0 auto;
width: 8px;
height: 8px;
border-radius: 2px;
}
.aside-tag-name {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.aside-tag-count {
margin-left: auto;
padding-left: 6px;
font-size: 12px;
color: var(--el-text-color-placeholder);
font-variant-numeric: tabular-nums;
}
.aside-menu--tags :deep(.el-menu-item > span) {
min-width: 0;
overflow: hidden;
}
.aside-empty {
margin: 8px 12px;
font-size: 12px;
@@ -0,0 +1,128 @@
<script setup lang="ts">
/**
* "Where have I used this?" — the reverse lookup for one reference.
*
* A sentence knows which articles it quotes; only the library can answer the
* other direction, and it is the question that decides whether an entry is safe
* to delete. The dialog shows the paper, the paragraph heading the template puts
* the sentence under, and the passage the citation quotes.
*/
import { computed, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { errorMessage } from '@/api/client'
import {
listReferenceCitations,
type ReferenceCitation,
type ReferenceListItem,
} from '@/api/references'
import { PARAGRAPH_UNSET_LABEL } from '@/utils/format'
const props = defineProps<{
modelValue: boolean
reference: ReferenceListItem | null
}>()
const emit = defineEmits<{ 'update:modelValue': [value: boolean] }>()
const visible = computed({
get: () => props.modelValue,
set: (value: boolean) => emit('update:modelValue', value),
})
const loading = ref(false)
const rows = ref<ReferenceCitation[]>([])
watch(
() => props.modelValue,
async (open) => {
if (!open || !props.reference) return
loading.value = true
rows.value = []
try {
rows.value = await listReferenceCitations(props.reference.id)
} catch (error) {
ElMessage.error(errorMessage(error))
} finally {
loading.value = false
}
},
)
/** The heading a citation sits under, or the label the document renders. */
function paragraphName(row: ReferenceCitation): string {
return row.paragraph_name ?? PARAGRAPH_UNSET_LABEL
}
</script>
<template>
<el-dialog
v-model="visible"
:title="`引用情况 · ${reference?.title ?? ''}`"
width="min(860px, 95vw)"
append-to-body
>
<el-table v-loading="loading" :data="rows" size="small" class="citations">
<el-table-column label="论文" min-width="180">
<template #default="{ row }">
<RouterLink :to="`/papers/${row.paper_id}`" class="paper-link">
{{ row.paper_title }}
</RouterLink>
</template>
</el-table-column>
<el-table-column label="段落" min-width="150">
<template #default="{ row }">{{ paragraphName(row) }}</template>
</el-table-column>
<el-table-column label="句子" min-width="260">
<template #default="{ row }">
<span class="sentence">{{ row.sentence_content || '(空行,只挂引用)' }}</span>
</template>
</el-table-column>
<el-table-column label="引用内容" min-width="220">
<template #default="{ row }">
<span class="quote">{{ row.quote }}</span>
</template>
</el-table-column>
<template #empty>
<el-empty
:description="
reference?.citation_count
? '没有找到引用记录'
: '这篇文献还没有被任何句子引用'
"
/>
</template>
</el-table>
<template #footer>
<el-button @click="visible = false">关闭</el-button>
</template>
</el-dialog>
</template>
<style scoped>
.citations {
width: 100%;
}
.paper-link {
color: var(--el-color-primary);
text-decoration: none;
}
.sentence {
display: block;
overflow-wrap: anywhere;
}
.quote {
display: block;
color: var(--el-text-color-secondary);
overflow-wrap: anywhere;
}
</style>
@@ -0,0 +1,875 @@
<script setup lang="ts">
/**
* Create / edit dialog for one reference in the library.
*
* The form is the field set of :mod:`app.models.reference` grouped the way a
* citation is read — what it is, who wrote it, where it was published, how to
* find it again — rather than one flat list of forty inputs. Everything except
* the title is optional, because the same schema has to hold a one-line journal
* article and a patent with a country, a number and a 公告日期.
*
* Two behaviours are deliberate:
*
* * **Tags are chosen, not typed into existence.** The picker offers the labels
* that exist; typing a new name is allowed, but the label is created through
* the tag API *before* the reference is saved, so a reference can never be
* stored pointing at a label that does not exist. Creating it first is also
* what lets the same label be applied to the next document from the list.
* * **Editing fetches the full row.** The table's shape deliberately drops the
* contributors, the abstract and the note, so the dialog asks for the detail
* rather than editing a list item and losing what it never carried.
*/
import { computed, reactive, ref, watch } from 'vue'
import { ArrowDown, ArrowUp, Delete, Plus } from '@element-plus/icons-vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { errorMessage } from '@/api/client'
import {
createReference,
getReference,
updateReference,
REFERENCE_AUTHOR_ROLE_OPTIONS,
REFERENCE_LANGUAGE_OPTIONS,
REFERENCE_TYPE_OPTIONS,
referenceTypeLabel,
referenceTypeMarker,
type ReferenceListItem,
type ReferencePayload,
} from '@/api/references'
import {
createReferenceTag,
TAG_COLOR_PRESETS,
type ReferenceTag,
} from '@/api/referenceTags'
import { useReferenceTagsStore } from '@/stores/referenceTags'
const props = defineProps<{
/** Visibility, used with `v-model`. */
modelValue: boolean
/** The reference being edited, or `null` to add a new one. */
reference: ReferenceListItem | null
}>()
const emit = defineEmits<{
'update:modelValue': [value: boolean]
/** Emitted after a successful write, so the table and the rail can refresh. */
saved: []
}>()
const tagsStore = useReferenceTagsStore()
const visible = computed({
get: () => props.modelValue,
set: (value: boolean) => emit('update:modelValue', value),
})
/** One contributor row as the form edits it. */
interface AuthorRow {
name: string
family_name: string
given_name: string
role: string
}
/** The text fields, all of them strings, `''` standing for "not filled in". */
interface FormState {
type: string
title: string
subtitle: string
title_translated: string
title_short: string
container_title: string
container_title_short: string
series_title: string
series_number: string
edition: string
volume: string
issue: string
pages: string
article_number: string
publisher: string
publisher_place: string
event_title: string
event_place: string
event_date: string
doi: string
isbn: string
issn: string
url: string
patent_country: string
patent_number: string
standard_number: string
report_number: string
arxiv_id: string
abstract: string
keywords: string
note: string
citation_key: string
language: string
}
function emptyForm(): FormState {
return {
type: 'journal-article',
title: '',
subtitle: '',
title_translated: '',
title_short: '',
container_title: '',
container_title_short: '',
series_title: '',
series_number: '',
edition: '',
volume: '',
issue: '',
pages: '',
article_number: '',
publisher: '',
publisher_place: '',
event_title: '',
event_place: '',
event_date: '',
doi: '',
isbn: '',
issn: '',
url: '',
patent_country: '',
patent_number: '',
standard_number: '',
report_number: '',
arxiv_id: '',
abstract: '',
keywords: '',
note: '',
citation_key: '',
language: '',
}
}
const formRef = ref<FormInstance>()
const loading = ref(false)
const saving = ref(false)
const activeTab = ref('basic')
const form = reactive<FormState>(emptyForm())
const authors = ref<AuthorRow[]>([])
/** Year / month / day are independently optional, exactly as the API stores them. */
const dates = reactive<{
year: number | undefined
month: number | undefined
day: number | undefined
accessed: string | null
}>({ year: undefined, month: undefined, day: undefined, accessed: null })
/**
* The chosen labels.
*
* A number is a tag that exists; a string is a name typed into the picker that
* has no id yet. The distinction is resolved on save, where a missing label is
* created first — which is what keeps "the tag exists" true for every stored
* reference.
*/
const tagValues = ref<(number | string)[]>([])
const rules: FormRules = {
title: [{ required: true, message: '请填写文献题名', trigger: 'blur' }],
}
const title = computed(() => (props.reference ? '编辑文献' : '新增文献'))
const tags = computed<ReferenceTag[]>(() => tagsStore.items)
/** An online resource is identified by its location and nothing else. */
const needsUrl = computed(() => form.type === 'web-page' || form.type === 'dataset')
/** What the chosen type prints after the title, so the writer can see the shape. */
const typeHint = computed(() => {
const marker = referenceTypeMarker(form.type)
const label = referenceTypeLabel(form.type)
return marker ? `${label} · GB/T 7714 标志 [${marker}]` : label
})
watch(
() => props.modelValue,
async (open) => {
if (!open) return
formRef.value?.clearValidate()
Object.assign(form, emptyForm())
authors.value = []
Object.assign(dates, { year: undefined, month: undefined, day: undefined, accessed: null })
tagValues.value = []
activeTab.value = 'basic'
loading.value = true
try {
void tagsStore.ensureLoaded()
if (props.reference) {
const detail = await getReference(props.reference.id)
Object.assign(form, {
type: detail.type,
title: detail.title,
subtitle: detail.subtitle ?? '',
title_translated: detail.title_translated ?? '',
title_short: detail.title_short ?? '',
container_title: detail.container_title ?? '',
container_title_short: detail.container_title_short ?? '',
series_title: detail.series_title ?? '',
series_number: detail.series_number ?? '',
edition: detail.edition ?? '',
volume: detail.volume ?? '',
issue: detail.issue ?? '',
pages: detail.pages ?? '',
article_number: detail.article_number ?? '',
publisher: detail.publisher ?? '',
publisher_place: detail.publisher_place ?? '',
event_title: detail.event_title ?? '',
event_place: detail.event_place ?? '',
event_date: detail.event_date ?? '',
doi: detail.doi ?? '',
isbn: detail.isbn ?? '',
issn: detail.issn ?? '',
url: detail.url ?? '',
patent_country: detail.patent_country ?? '',
patent_number: detail.patent_number ?? '',
standard_number: detail.standard_number ?? '',
report_number: detail.report_number ?? '',
arxiv_id: detail.arxiv_id ?? '',
abstract: detail.abstract ?? '',
keywords: detail.keywords ?? '',
note: detail.note ?? '',
citation_key: detail.citation_key ?? '',
language: detail.language ?? '',
})
authors.value = detail.authors.map((author) => ({
name: author.name,
family_name: author.family_name ?? '',
given_name: author.given_name ?? '',
role: author.role,
}))
dates.year = detail.publication_year ?? undefined
dates.month = detail.publication_month ?? undefined
dates.day = detail.publication_day ?? undefined
dates.accessed = detail.accessed_date
tagValues.value = detail.tags.map((tag) => tag.id)
} else {
// A journal article is what most additions are, and it is already the
// API's default; one contributor row is the minimum that reads as a
// form rather than an empty table.
authors.value = [{ name: '', family_name: '', given_name: '', role: 'author' }]
}
} catch (error) {
ElMessage.error(errorMessage(error))
} finally {
loading.value = false
}
},
)
function addAuthor(): void {
authors.value.push({ name: '', family_name: '', given_name: '', role: 'author' })
}
function removeAuthor(index: number): void {
authors.value.splice(index, 1)
}
/** Move a contributor one place, because the printed order is the stored order. */
function moveAuthor(index: number, delta: number): void {
const target = index + delta
const row = authors.value[index]
if (!row || target < 0 || target >= authors.value.length) return
authors.value.splice(index, 1)
authors.value.splice(target, 0, row)
}
/** A colour for a label created from the picker, cycling the shared palette. */
function nextTagColor(): string {
const preset = TAG_COLOR_PRESETS[tagsStore.items.length % TAG_COLOR_PRESETS.length]
return preset ?? '#409EFF'
}
/**
* Turn the picker's values into tag ids, creating labels that do not exist yet.
*
* Runs before the reference is written, so a failure here leaves nothing
* half-saved. A label that turns out to exist after all — typed twice, or added
* in another tab while this dialog was open — is matched by name instead of
* being reported as a conflict.
*/
async function resolveTagIds(values: (number | string)[]): Promise<number[]> {
const ids: number[] = []
for (const value of values) {
if (typeof value === 'number') {
ids.push(value)
continue
}
const name = value.trim()
if (!name) continue
const known = tagsStore.byName(name)
if (known) {
ids.push(known.id)
continue
}
try {
const created = await createReferenceTag({
name,
color: nextTagColor(),
note: null,
})
ids.push(created.id)
await tagsStore.reload()
} catch (error) {
await tagsStore.reload()
const raced = tagsStore.byName(name)
if (!raced) throw error
ids.push(raced.id)
}
}
// A label cannot be applied twice, and two ids can name the same row only by
// mistake — de-duplicate rather than sending a list the API would store once.
return [...new Set(ids)]
}
function optional(value: string): string | null {
const text = value.trim()
return text ? text : null
}
async function submit(): Promise<void> {
const valid = await formRef.value?.validate().catch(() => false)
if (!valid) return
const named = authors.value.filter((author) => author.name.trim())
const blank = authors.value.length - named.length
if (blank > 0) {
ElMessage.warning('有责任者还没填姓名,请补全或删掉那一行')
activeTab.value = 'authors'
return
}
saving.value = true
try {
const payload: ReferencePayload = {
type: form.type,
title: form.title.trim(),
subtitle: optional(form.subtitle),
title_translated: optional(form.title_translated),
title_short: optional(form.title_short),
container_title: optional(form.container_title),
container_title_short: optional(form.container_title_short),
series_title: optional(form.series_title),
series_number: optional(form.series_number),
edition: optional(form.edition),
volume: optional(form.volume),
issue: optional(form.issue),
pages: optional(form.pages),
article_number: optional(form.article_number),
publisher: optional(form.publisher),
publisher_place: optional(form.publisher_place),
event_title: optional(form.event_title),
event_place: optional(form.event_place),
event_date: optional(form.event_date),
publication_year: dates.year ?? null,
publication_month: dates.month ?? null,
publication_day: dates.day ?? null,
accessed_date: dates.accessed || null,
doi: optional(form.doi),
isbn: optional(form.isbn),
issn: optional(form.issn),
url: optional(form.url),
patent_country: optional(form.patent_country),
patent_number: optional(form.patent_number),
standard_number: optional(form.standard_number),
report_number: optional(form.report_number),
arxiv_id: optional(form.arxiv_id),
abstract: optional(form.abstract),
keywords: optional(form.keywords),
note: optional(form.note),
citation_key: optional(form.citation_key),
language: form.language || null,
authors: named.map((author, index) => ({
name: author.name.trim(),
family_name: optional(author.family_name),
given_name: optional(author.given_name),
role: author.role,
sort: index + 1,
})),
tag_ids: await resolveTagIds(tagValues.value),
}
if (props.reference) {
await updateReference(props.reference.id, payload)
ElMessage.success('文献已更新')
} else {
await createReference(payload)
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="min(880px, 95vw)"
:close-on-click-modal="false"
append-to-body
class="reference-dialog"
>
<el-alert
v-if="needsUrl"
type="warning"
:closable="false"
show-icon
title="网页、数据集类型的文献必须至少填 URL 或 DOI"
class="form-alert"
/>
<el-form
ref="formRef"
v-loading="loading"
:model="form"
:rules="rules"
label-width="96px"
label-position="right"
>
<el-tabs v-model="activeTab" class="form-tabs">
<el-tab-pane label="基本信息" name="basic">
<div class="grid">
<el-form-item label="文献类型">
<el-select v-model="form.type" class="full">
<el-option
v-for="option in REFERENCE_TYPE_OPTIONS"
:key="option.value"
:value="option.value"
:label="`${option.label} [${option.marker}]`"
/>
</el-select>
<div class="field-hint">{{ typeHint }}</div>
</el-form-item>
<el-form-item label="语种">
<el-select v-model="form.language" clearable placeholder="未指定" class="full">
<el-option
v-for="option in REFERENCE_LANGUAGE_OPTIONS"
:key="option.value"
:value="option.value"
:label="option.label"
/>
</el-select>
</el-form-item>
</div>
<el-form-item label="文献题名" prop="title">
<el-input
v-model="form.title"
placeholder="如 技术惯性与冲量的耦合机制"
maxlength="512"
show-word-limit
clearable
/>
</el-form-item>
<div class="grid">
<el-form-item label="副题名">
<el-input v-model="form.subtitle" placeholder="冒号后的那半句" clearable />
</el-form-item>
<el-form-item label="并列题名">
<el-input v-model="form.title_translated" placeholder="另一个语种的题名" clearable />
</el-form-item>
<el-form-item label="简称">
<el-input v-model="form.title_short" placeholder="正文里简称它什么" clearable />
</el-form-item>
<el-form-item label="文献关键词">
<el-input
v-model="form.keywords"
placeholder="逗号分隔,如 技术演化, 惯性"
clearable
/>
</el-form-item>
</div>
<el-form-item label="标签">
<el-select
v-model="tagValues"
multiple
filterable
allow-create
default-first-option
:reserve-keyword="false"
placeholder="选择已有标签,或直接输入新名称"
class="full"
>
<el-option
v-for="tag in tags"
:key="tag.id"
:value="tag.id"
:label="tag.name"
>
<span class="tag-option">
<span class="tag-dot" :style="{ backgroundColor: tag.color }" />
<span>{{ tag.name }}</span>
<span v-if="tag.note" class="tag-option-note">{{ tag.note }}</span>
</span>
</el-option>
</el-select>
<div class="field-hint">
标签是给自己归档用的,不会出现在参考文献表里;输入库里没有的名称会在保存时自动建好。
也可以先去
<RouterLink to="/references/tags">标签管理</RouterLink>
里整理。
</div>
</el-form-item>
</el-tab-pane>
<el-tab-pane label="责任者" name="authors">
<div class="authors-head">
<span class="authors-hint">
按引用时打印的顺序排列;姓名是必填的,姓 / 名供需要缩写或倒装的格式使用。
</span>
<el-button :icon="Plus" size="small" @click="addAuthor">添加责任者</el-button>
</div>
<div v-if="authors.length === 0" class="authors-empty">
还没有责任者。机构作者(如 世界卫生组织)直接填姓名即可。
</div>
<div v-for="(author, index) in authors" :key="index" class="author-row">
<span class="author-order">{{ index + 1 }}</span>
<el-input v-model="author.name" placeholder="姓名,如 张三" class="author-name" />
<el-input v-model="author.family_name" placeholder="姓" class="author-part" />
<el-input v-model="author.given_name" placeholder="名" class="author-part" />
<el-select v-model="author.role" class="author-role">
<el-option
v-for="option in REFERENCE_AUTHOR_ROLE_OPTIONS"
:key="option.value"
:value="option.value"
:label="option.label"
/>
</el-select>
<div class="author-actions">
<el-button
link
:icon="ArrowUp"
:disabled="index === 0"
@click="moveAuthor(index, -1)"
/>
<el-button
link
:icon="ArrowDown"
:disabled="index === authors.length - 1"
@click="moveAuthor(index, 1)"
/>
<el-button link type="danger" :icon="Delete" @click="removeAuthor(index)" />
</div>
</div>
</el-tab-pane>
<el-tab-pane label="出版信息" name="publish">
<div class="grid">
<el-form-item label="刊名/书名">
<el-input v-model="form.container_title" placeholder="期刊名、论文集名、报纸名" clearable />
</el-form-item>
<el-form-item label="刊名缩写">
<el-input v-model="form.container_title_short" clearable />
</el-form-item>
<el-form-item label="丛书名">
<el-input v-model="form.series_title" clearable />
</el-form-item>
<el-form-item label="丛书号">
<el-input v-model="form.series_number" clearable />
</el-form-item>
<el-form-item label="版本">
<el-input v-model="form.edition" placeholder="如 3版 / 2nd ed." clearable />
</el-form-item>
<el-form-item label="文章编号">
<el-input v-model="form.article_number" placeholder="没有页码时用" clearable />
</el-form-item>
<el-form-item label="卷">
<el-input v-model="form.volume" placeholder="如 198、S1" clearable />
</el-form-item>
<el-form-item label="期">
<el-input v-model="form.issue" placeholder="如 3、Suppl." clearable />
</el-form-item>
<el-form-item label="页码">
<el-input v-model="form.pages" placeholder="如 122-141" clearable />
</el-form-item>
<el-form-item label="出版者">
<el-input v-model="form.publisher" placeholder="出版社 / 学校 / 发布机构" clearable />
</el-form-item>
<el-form-item label="出版地">
<el-input v-model="form.publisher_place" clearable />
</el-form-item>
<el-form-item label="引用日期">
<el-date-picker
v-model="dates.accessed"
type="date"
value-format="YYYY-MM-DD"
placeholder="在线资源的访问日期"
class="full"
/>
</el-form-item>
</div>
<div class="grid grid--dates">
<el-form-item label="出版年">
<el-input-number
v-model="dates.year"
:min="1"
:max="2999"
:controls="false"
placeholder="2024"
class="full"
/>
</el-form-item>
<el-form-item label="月">
<el-input-number
v-model="dates.month"
:min="1"
:max="12"
:controls="false"
placeholder="月"
class="full"
/>
</el-form-item>
<el-form-item label="日">
<el-input-number
v-model="dates.day"
:min="1"
:max="31"
:controls="false"
placeholder="日"
class="full"
/>
</el-form-item>
</div>
<p class="tab-note">
年月日各自独立,知道多少填多少:书通常只有年份,报纸文章有日期,专利填公告日期。
</p>
<el-divider content-position="left">会议(会议论文填这里)</el-divider>
<div class="grid">
<el-form-item label="会议名称">
<el-input v-model="form.event_title" clearable />
</el-form-item>
<el-form-item label="会议地点">
<el-input v-model="form.event_place" clearable />
</el-form-item>
<el-form-item label="会期">
<el-input v-model="form.event_date" placeholder="如 2024-05-01/03" clearable />
</el-form-item>
</div>
</el-tab-pane>
<el-tab-pane label="标识与链接" name="ids">
<div class="grid">
<el-form-item label="DOI">
<el-input
v-model="form.doi"
placeholder="10.1016/j.techfore.2024.123456"
clearable
/>
</el-form-item>
<el-form-item label="URL">
<el-input v-model="form.url" placeholder="https://…" clearable />
</el-form-item>
<el-form-item label="ISBN">
<el-input v-model="form.isbn" clearable />
</el-form-item>
<el-form-item label="ISSN">
<el-input v-model="form.issn" clearable />
</el-form-item>
<el-form-item label="专利国别">
<el-input v-model="form.patent_country" placeholder="如 中国" clearable />
</el-form-item>
<el-form-item label="专利号">
<el-input v-model="form.patent_number" placeholder="如 CN114000000A" clearable />
</el-form-item>
<el-form-item label="标准编号">
<el-input v-model="form.standard_number" placeholder="如 GB/T 7714-2015" clearable />
</el-form-item>
<el-form-item label="报告编号">
<el-input v-model="form.report_number" clearable />
</el-form-item>
<el-form-item label="arXiv">
<el-input v-model="form.arxiv_id" placeholder="如 arXiv:2405.12345" clearable />
</el-form-item>
<el-form-item label="引用键">
<el-input v-model="form.citation_key" placeholder="BibTeX key,供导出用" clearable />
</el-form-item>
</div>
<p class="tab-note">
DOI 会按规范存成不带 <code>https://doi.org/</code> 前缀的形式,粘贴时带前缀也没关系。
</p>
</el-tab-pane>
<el-tab-pane label="摘要与备注" name="notes">
<el-form-item label="摘要">
<el-input
v-model="form.abstract"
type="textarea"
:rows="5"
placeholder="文献摘要,选填"
/>
</el-form-item>
<el-form-item label="备注">
<el-input
v-model="form.note"
type="textarea"
:rows="4"
placeholder="为什么留这篇、PDF 放在哪、要引用哪一段……"
/>
</el-form-item>
</el-tab-pane>
</el-tabs>
</el-form>
<template #footer>
<el-button @click="visible = false">取消</el-button>
<el-button type="primary" :loading="saving" @click="submit">
{{ reference ? '保存修改' : '加入文献库' }}
</el-button>
</template>
</el-dialog>
</template>
<style scoped>
.form-alert {
margin-bottom: 12px;
}
/* The tab strip stays put; only the fields scroll, so the footer never moves
out of reach on a form this long. */
.form-tabs :deep(.el-tabs__content) {
max-height: min(62vh, 620px);
overflow-y: auto;
padding-right: 4px;
scrollbar-width: thin;
}
/* Two fields per row on a wide dialog, one on a narrow one, without a media
query: `auto-fit` collapses the columns when there is no room for two. */
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 0 16px;
}
.grid--dates {
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
}
.full {
width: 100%;
}
.field-hint {
width: 100%;
margin-top: 4px;
font-size: 12px;
line-height: 1.6;
color: var(--el-text-color-secondary);
}
.tab-note {
margin: 0 0 8px;
font-size: 12px;
line-height: 1.7;
color: var(--el-text-color-secondary);
}
.tag-option {
display: flex;
align-items: center;
gap: 6px;
}
.tag-dot {
width: 8px;
height: 8px;
border-radius: 50%;
flex: 0 0 auto;
}
.tag-option-note {
margin-left: auto;
padding-left: 12px;
font-size: 12px;
color: var(--el-text-color-placeholder);
}
.authors-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 10px;
}
.authors-hint {
font-size: 12px;
line-height: 1.6;
color: var(--el-text-color-secondary);
}
.authors-empty {
padding: 12px;
font-size: 13px;
color: var(--el-text-color-placeholder);
border: 1px dashed var(--el-border-color);
border-radius: 6px;
}
.author-row {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 8px;
}
.author-order {
flex: 0 0 auto;
width: 20px;
text-align: center;
font-size: 12px;
color: var(--el-text-color-placeholder);
font-variant-numeric: tabular-nums;
}
.author-name {
flex: 2 1 0;
min-width: 0;
}
.author-part {
flex: 1 1 0;
min-width: 0;
}
.author-role {
flex: 0 0 92px;
}
.author-actions {
flex: 0 0 auto;
display: flex;
align-items: center;
}
</style>
@@ -0,0 +1,59 @@
<script setup lang="ts">
/**
* One tag painted as a chip.
*
* The colour comes from the tag row itself rather than from a class map, because
* the palette is the writer's: a label is created with whatever hue they picked,
* and the chip has to be that hue in the table, in the rail and in the picker.
* The tint is derived from the colour with an alpha suffix instead of a second
* stored value, so there is nothing to keep in step.
*/
import { computed } from 'vue'
const props = withDefaults(
defineProps<{
name: string
color: string
/** `small` in a table row, `default` where the chip carries the meaning. */
size?: 'small' | 'default'
/** How many references carry the label, shown as a suffix when > 0. */
count?: number | null
}>(),
{ size: 'small', count: null },
)
const style = computed(() => ({
color: props.color,
borderColor: props.color,
backgroundColor: `${props.color}1A`,
}))
</script>
<template>
<el-tag :size="size" effect="plain" :style="style" class="tag-chip">
<span class="tag-chip-dot" :style="{ backgroundColor: color }" />
{{ name }}<span v-if="count" class="tag-chip-count">{{ count }}</span>
</el-tag>
</template>
<style scoped>
.tag-chip {
display: inline-flex;
align-items: center;
gap: 4px;
max-width: 100%;
}
.tag-chip-dot {
width: 6px;
height: 6px;
border-radius: 50%;
flex: 0 0 auto;
}
.tag-chip-count {
margin-left: 4px;
opacity: 0.75;
font-variant-numeric: tabular-nums;
}
</style>
@@ -0,0 +1,200 @@
<script setup lang="ts">
/**
* Create / edit dialog for one reference tag.
*
* The live chip underneath the form is the point of the dialog: a tag is only
* ever read as a coloured chip in a table, and neither the name nor the colour
* alone tells the writer whether the label will be recognisable at a glance.
*/
import { computed, reactive, ref, watch } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { errorMessage } from '@/api/client'
import {
createReferenceTag,
updateReferenceTag,
DEFAULT_TAG_COLOR,
TAG_COLOR_PRESETS,
type ReferenceTag,
type ReferenceTagPayload,
} from '@/api/referenceTags'
import { normalizeHexColor } from '@/utils/format'
const props = defineProps<{
/** Visibility, used with `v-model`. */
modelValue: boolean
/** The tag being edited, or `null` to create a new one. */
tag: ReferenceTag | null
}>()
const emit = defineEmits<{
'update:modelValue': [value: boolean]
/** Emitted after a successful write, so the table and the rail 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<ReferenceTagPayload>({
name: '',
color: DEFAULT_TAG_COLOR,
note: null,
})
const rules: FormRules<ReferenceTagPayload> = {
name: [
{ required: true, message: '请填写标签名称', trigger: 'blur' },
{ max: 64, message: '标签名称最多 64 个字符', trigger: 'blur' },
],
}
const title = computed(() => (props.tag ? '编辑标签' : '新建标签'))
// 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()
form.name = props.tag?.name ?? ''
form.color = props.tag?.color ?? DEFAULT_TAG_COLOR
form.note = props.tag?.note ?? null
},
)
/** Tidy a hand-typed colour when the input loses focus. */
function commitColor(): void {
const normalized = normalizeHexColor(form.color)
if (normalized) {
form.color = normalized
return
}
ElMessage.warning('颜色格式无效,请使用 #RRGGBB 或 rgb(r,g,b)')
form.color = props.tag?.color ?? DEFAULT_TAG_COLOR
}
async function submit(): Promise<void> {
const valid = await formRef.value?.validate().catch(() => false)
if (!valid) return
saving.value = true
try {
const payload: ReferenceTagPayload = {
name: form.name.trim(),
color: form.color,
note: form.note?.trim() ? form.note.trim() : null,
}
if (props.tag) {
await updateReferenceTag(props.tag.id, payload)
ElMessage.success('标签已更新,打过它的文献会同步显示新名称')
} else {
await createReferenceTag(payload)
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="min(520px, 94vw)" 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="如 综述、方法、必读"
maxlength="64"
show-word-limit
clearable
/>
</el-form-item>
<el-form-item label="颜色">
<div class="color-row">
<el-color-picker v-model="form.color" :predefine="[...TAG_COLOR_PRESETS]" />
<el-input
v-model="form.color"
class="color-input"
placeholder="#RRGGBB 或 rgb(r,g,b)"
@blur="commitColor"
/>
</div>
</el-form-item>
<el-form-item label="备注">
<el-input
v-model="form.note"
placeholder="这个标签是干什么用的,选填"
maxlength="255"
show-word-limit
clearable
/>
</el-form-item>
<el-form-item label="预览">
<div class="preview">
<el-tag
:style="{
color: form.color,
borderColor: form.color,
backgroundColor: `${form.color}1A`,
}"
effect="plain"
>
{{ form.name || '(未命名标签)' }}
</el-tag>
<span class="preview-meta">文献表里就长这样</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>
.color-row {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
}
.color-input {
width: 180px;
}
.preview {
display: flex;
align-items: center;
gap: 10px;
width: 100%;
min-height: 40px;
padding: 4px 12px;
border: 1px dashed var(--el-border-color);
border-radius: 6px;
background-color: var(--el-fill-color-lighter);
}
.preview-meta {
font-size: 12px;
color: var(--el-text-color-secondary);
}
</style>
+18 -2
View File
@@ -3,9 +3,9 @@ import { createRouter, createWebHistory } from 'vue-router'
/**
* Route table.
*
* `meta.section` groups a route under one of the two top-level entries in the
* `meta.section` groups a route under one of the top-level entries in the
* header. The shell reads it to decide whether — and which — second-level menu
* to render on the right, so a new page only has to declare where it belongs.
* to render on the left, so a new page only has to declare where it belongs.
*/
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
@@ -48,6 +48,22 @@ const router = createRouter({
component: () => import('@/views/templates/FieldManageView.vue'),
meta: { title: '字段管理', section: 'templates' },
},
{
// The reference library, reached from the header button to the right of
// 论文 and 模板. `?tag=<id>` is a supported state of this page rather than
// a separate route: the rail lists the labels and links straight to the
// filtered library, and the table's own filter writes the same parameter.
path: '/references',
name: 'references',
component: () => import('@/views/references/ReferenceListView.vue'),
meta: { title: '参考文献', section: 'references' },
},
{
path: '/references/tags',
name: 'reference-tags',
component: () => import('@/views/references/TagManageView.vue'),
meta: { title: '标签管理', section: 'references' },
},
{
path: '/:pathMatch(.*)*',
name: 'not-found',
+73
View File
@@ -0,0 +1,73 @@
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { errorMessage } from '@/api/client'
import { fetchAllReferenceTags, type ReferenceTag } from '@/api/referenceTags'
/**
* The tag library, shared by the second-level menu and the pages that change it.
*
* Same arrangement as the paper list and for the same reason: the rail in the
* application shell shows the labels and the reference pages apply them, so
* neither owns the list. A page that creates, renames or deletes a tag calls
* `reload()` and the rail follows, without the two knowing about each other.
*
* The reference form reads it too, because a picker wants every label at once —
* the API pages the list, this holds the whole of it.
*
* Deliberately *not* persisted: it is server data, and a stale copy restored
* from localStorage would offer labels that no longer exist.
*/
export const useReferenceTagsStore = defineStore('referenceTags', () => {
const items = ref<ReferenceTag[]>([])
const loading = ref(false)
/** Whether a load has ever finished, so an empty list can be told from unloaded. */
const loaded = ref(false)
const error = ref<string | null>(null)
/** Reload the whole library. Concurrent callers share one request. */
let inFlight: Promise<void> | null = null
async function reload(): Promise<void> {
if (inFlight) return inFlight
loading.value = true
inFlight = (async () => {
try {
items.value = await fetchAllReferenceTags()
error.value = null
loaded.value = true
} catch (cause) {
error.value = errorMessage(cause)
} finally {
loading.value = false
inFlight = null
}
})()
return inFlight
}
/** Load the library once, unless it is already loaded or loading. */
async function ensureLoaded(): Promise<void> {
if (loaded.value || loading.value) return
await reload()
}
/** The tag with this id, or `undefined` — for painting a chip from an id. */
function byId(id: number): ReferenceTag | undefined {
return items.value.find((tag) => tag.id === id)
}
/** The tag with this exact name, or `undefined` — used when applying labels. */
function byName(name: string): ReferenceTag | undefined {
return items.value.find((tag) => tag.name === name)
}
function reset(): void {
items.value = []
loaded.value = false
error.value = null
}
return { items, loading, loaded, error, reload, ensureLoaded, byId, byName, reset }
})
@@ -0,0 +1,568 @@
<script setup lang="ts">
/**
* 参考文献 — the library table.
*
* One row per document, with the whole CRUD surface around it. Two things here
* are the reason the table exists in this shape:
*
* * **The tag column is a filter as much as a column.** The rail lists the labels
* and links to `/references?tag=<id>`; the select in the toolbar writes the
* same query parameter back, so the URL is the single source of truth for the
* filter and a filtered view can be pasted to someone else.
* * **The citation count is a door, not a number.** "Which of my sentences use
* this?" is the question that decides whether an entry is safe to delete, and
* answering it is one click rather than a different page.
*/
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ChatLineSquare, Delete, Edit, Plus, Refresh, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { errorMessage } from '@/api/client'
import {
batchDeleteReferences,
deleteReference,
listReferences,
REFERENCE_TYPE_OPTIONS,
referenceTypeLabel,
referenceTypeMarker,
type ReferenceListItem,
type ReferenceType,
} from '@/api/references'
import ReferenceCitationsDialog from '@/components/references/ReferenceCitationsDialog.vue'
import ReferenceFormDialog from '@/components/references/ReferenceFormDialog.vue'
import TagChip from '@/components/references/TagChip.vue'
import { useReferenceTagsStore } from '@/stores/referenceTags'
import { formatDateTime } from '@/utils/format'
const route = useRoute()
const router = useRouter()
const tagsStore = useReferenceTagsStore()
const loading = ref(false)
const rows = ref<ReferenceListItem[]>([])
const total = ref(0)
const selection = ref<ReferenceListItem[]>([])
const query = reactive({
keyword: '',
type: null as ReferenceType | null,
year: undefined as number | undefined,
cited: null as boolean | null,
page: 1,
page_size: 20,
})
const dialogVisible = ref(false)
const editing = ref<ReferenceListItem | null>(null)
const citationsVisible = ref(false)
const citationsTarget = ref<ReferenceListItem | null>(null)
const CITED_FILTERS = [
{ value: null, label: '全部文献' },
{ value: true, label: '已被引用' },
{ value: false, label: '还没引用' },
]
const tags = computed(() => tagsStore.items)
/**
* The tag filter lives in the URL, not in this component.
*
* The rail links to a filtered library and the toolbar changes the same filter,
* so one of them has to own it — and the URL is the one both can read. That is
* also why the rail can highlight the label you are looking at.
*/
const tagFilter = computed<number | null>({
get: () => {
const raw = route.query.tag
const value = Array.isArray(raw) ? raw[0] : raw
const parsed = value ? Number(value) : null
return parsed != null && Number.isFinite(parsed) ? parsed : null
},
set: (value) => {
void router.replace({
path: '/references',
query: value == null ? {} : { tag: String(value) },
})
},
})
async function load(): Promise<void> {
loading.value = true
try {
const result = await listReferences({
keyword: query.keyword,
type: query.type,
year: query.year ?? null,
cited: query.cited,
tag_ids: tagFilter.value == null ? [] : [tagFilter.value],
page: query.page,
page_size: query.page_size,
})
rows.value = result.items
total.value = result.total
// A delete can empty the last page. Stepping back keeps the table from
// showing "no data" while the pager still claims a page beyond the end.
if (result.items.length === 0 && result.total > 0 && query.page > 1) {
query.page -= 1
await load()
}
} catch (error) {
ElMessage.error(errorMessage(error))
} finally {
loading.value = false
}
}
function search(): void {
query.page = 1
void load()
}
function resetFilters(): void {
query.keyword = ''
query.type = null
query.year = undefined
query.cited = null
query.page = 1
tagFilter.value = null
void load()
}
function onCreate(): void {
editing.value = null
dialogVisible.value = true
}
function onEdit(row: ReferenceListItem): void {
editing.value = row
dialogVisible.value = true
}
function onShowCitations(row: ReferenceListItem): void {
citationsTarget.value = row
citationsVisible.value = true
}
/** Refresh the table and the rail's tag counts, which this page can change. */
async function refreshAll(): Promise<void> {
await Promise.all([load(), tagsStore.reload()])
}
async function onDelete(row: ReferenceListItem): Promise<void> {
try {
await ElMessageBox.confirm(`确定从文献库删除「${row.title}」?`, '删除文献', {
type: 'warning',
confirmButtonText: '删除',
cancelButtonText: '取消',
})
} catch {
return // dismissed
}
try {
await deleteReference(row.id)
ElMessage.success('已删除')
await refreshAll()
} catch (error) {
// A cited entry is refused with the count, which is worth showing whole.
ElMessage.error(errorMessage(error))
}
}
async function onBatchDelete(): Promise<void> {
const ids = selection.value.map((row) => row.id)
if (ids.length === 0) return
try {
await ElMessageBox.confirm(
`确定删除选中的 ${ids.length} 篇文献?已被正文引用的会被拒绝。`,
'批量删除',
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' },
)
} catch {
return // dismissed
}
try {
const result = await batchDeleteReferences(ids)
ElMessage.success(`已删除 ${result.deleted} 篇文献`)
selection.value = []
await refreshAll()
} catch (error) {
ElMessage.error(errorMessage(error))
}
}
/** The heading a row prints: the type's Chinese name, with its GB/T marker. */
function typeLabel(row: ReferenceListItem): string {
const marker = referenceTypeMarker(row.type)
const label = referenceTypeLabel(row.type)
return marker ? `${label} [${marker}]` : label
}
/** Where it was published, as one column: the container, else the publisher. */
function sourceLine(row: ReferenceListItem): string {
const parts = [row.container_title ?? row.publisher ?? ''].filter(Boolean)
if (row.volume) parts.push(`第 ${row.volume} 卷`)
if (row.issue) parts.push(`第 ${row.issue} 期`)
if (row.pages) parts.push(row.pages)
return parts.join(' · ')
}
/**
* Open the add dialog when the rail's 新建文献 entry sent us here.
*
* The query is cleared straight away, so a refresh or a back-navigation does
* not reopen the dialog.
*/
watch(
() => route.query.new,
(flag) => {
if (!flag) return
onCreate()
void router.replace({ path: '/references', query: route.query.tag ? { tag: route.query.tag } : {} })
},
{ immediate: true },
)
// The tag filter is read from the URL, so a change to it is a change of view.
watch(
() => route.query.tag,
() => {
query.page = 1
void load()
},
{ immediate: true },
)
onMounted(() => {
void tagsStore.ensureLoaded()
})
</script>
<template>
<div class="page page--fill">
<el-card shadow="never" class="card--fill">
<template #header>
<div class="card-header">
<div>
<span class="card-title">参考文献库</span>
<span class="card-subtitle">
文献是全局的,可以被任意多篇论文引用;标签用来给自己归档
</span>
</div>
<el-tag type="info" effect="plain">共 {{ total }} 篇</el-tag>
</div>
</template>
<div class="toolbar">
<el-input
v-model="query.keyword"
placeholder="搜索题名、刊名、作者、DOI、关键词"
clearable
class="search"
@keyup.enter="search"
@clear="search"
>
<template #prefix><el-icon><Search /></el-icon></template>
</el-input>
<el-select
v-model="query.type"
placeholder="全部类型"
clearable
class="type-filter"
@change="search"
>
<el-option
v-for="option in REFERENCE_TYPE_OPTIONS"
:key="option.value"
:value="option.value"
:label="`${option.label} [${option.marker}]`"
/>
</el-select>
<el-select
v-model="tagFilter"
placeholder="全部标签"
clearable
class="tag-filter"
@change="search"
>
<el-option v-for="tag in tags" :key="tag.id" :value="tag.id" :label="tag.name">
<span class="tag-option">
<span class="tag-dot" :style="{ backgroundColor: tag.color }" />
<span>{{ tag.name }}</span>
<span class="tag-option-count">{{ tag.reference_count }}</span>
</span>
</el-option>
</el-select>
<el-select
v-model="query.cited"
placeholder="引用情况"
clearable
class="cited-filter"
@change="search"
>
<el-option
v-for="option in CITED_FILTERS"
:key="String(option.value)"
:value="option.value"
:label="option.label"
/>
</el-select>
<el-input-number
v-model="query.year"
:min="1"
:max="2999"
:controls="false"
placeholder="年份"
class="year-filter"
@change="search"
/>
<el-button @click="search">查询</el-button>
<el-button text @click="resetFilters">重置</el-button>
<div class="toolbar-spacer" />
<el-button :icon="Refresh" :loading="loading" @click="load">刷新</el-button>
<el-button
type="danger"
plain
:icon="Delete"
:disabled="selection.length === 0"
@click="onBatchDelete"
>
批量删除{{ selection.length ? `(${selection.length})` : '' }}
</el-button>
<el-button type="primary" :icon="Plus" @click="onCreate">新增文献</el-button>
</div>
<el-table
v-loading="loading"
:data="rows"
row-key="id"
stripe
class="table table-fill"
height="100%"
@selection-change="(value: ReferenceListItem[]) => (selection = value)"
>
<el-table-column type="selection" width="46" reserve-selection />
<el-table-column label="题名" min-width="260">
<template #default="{ row }">
<el-button link type="primary" class="title-link" @click="onEdit(row)">
{{ row.title }}
</el-button>
<div v-if="row.subtitle" class="subtitle">{{ row.subtitle }}</div>
</template>
</el-table-column>
<el-table-column label="类型" width="120">
<template #default="{ row }">
<el-tag size="small" effect="plain">{{ typeLabel(row) }}</el-tag>
</template>
</el-table-column>
<el-table-column label="责任者" min-width="150" show-overflow-tooltip>
<template #default="{ row }">
<span v-if="row.authors_line">{{ row.authors_line }}</span>
<span v-else class="muted">—</span>
</template>
</el-table-column>
<el-table-column label="出版信息" min-width="180" show-overflow-tooltip>
<template #default="{ row }">
<span v-if="sourceLine(row)">{{ sourceLine(row) }}</span>
<span v-else class="muted">—</span>
</template>
</el-table-column>
<el-table-column label="年份" width="80" align="center">
<template #default="{ row }">
<span v-if="row.publication_year">{{ row.publication_year }}</span>
<span v-else class="muted">—</span>
</template>
</el-table-column>
<el-table-column label="标签" min-width="180">
<template #default="{ row }">
<template v-if="row.tags.length">
<TagChip
v-for="tag in row.tags.slice(0, 3)"
:key="tag.id"
:name="tag.name"
:color="tag.color"
class="row-tag"
@click="tagFilter = tag.id"
/>
<span v-if="row.tags.length > 3" class="muted">
+{{ row.tags.length - 3 }}
</span>
</template>
<span v-else class="muted">—</span>
</template>
</el-table-column>
<el-table-column label="引用" width="90" align="center">
<template #default="{ row }">
<el-button
v-if="row.citation_count"
link
type="primary"
@click="onShowCitations(row)"
>
{{ row.citation_count }} 处
</el-button>
<span v-else class="muted">—</span>
</template>
</el-table-column>
<el-table-column label="更新时间" width="150">
<template #default="{ row }">{{ formatDateTime(row.updated_at) }}</template>
</el-table-column>
<el-table-column label="操作" width="210" fixed="right">
<template #default="{ row }">
<el-button link type="primary" :icon="Edit" @click="onEdit(row)">编辑</el-button>
<el-button
link
type="primary"
:icon="ChatLineSquare"
@click="onShowCitations(row)"
>
引用
</el-button>
<el-button link type="danger" :icon="Delete" @click="onDelete(row)">删除</el-button>
</template>
</el-table-column>
<template #empty>
<el-empty
:description="
query.keyword || query.type || tagFilter != null
? '没有匹配的文献'
: '文献库还是空的,先加一篇'
"
>
<el-button type="primary" :icon="Plus" @click="onCreate">新增文献</el-button>
</el-empty>
</template>
</el-table>
<div class="table-pagination">
<el-pagination
v-model:current-page="query.page"
v-model:page-size="query.page_size"
:total="total"
:page-sizes="[10, 20, 50, 100]"
layout="total, sizes, prev, pager, next, jumper"
background
@current-change="load"
@size-change="search"
/>
</div>
</el-card>
<ReferenceFormDialog
v-model="dialogVisible"
:reference="editing"
@saved="refreshAll"
/>
<ReferenceCitationsDialog v-model="citationsVisible" :reference="citationsTarget" />
</div>
</template>
<style scoped>
.card-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.card-title {
font-weight: 600;
margin-right: 10px;
}
.card-subtitle {
color: var(--el-text-color-secondary);
font-size: 12px;
}
.search {
width: 240px;
}
.type-filter {
width: 150px;
}
.tag-filter {
width: 150px;
}
.cited-filter {
width: 130px;
}
.year-filter {
width: 100px;
}
.table {
margin-top: 16px;
}
.title-link {
font-weight: 600;
padding: 0;
height: auto;
text-align: left;
white-space: normal;
}
.subtitle {
font-size: 12px;
color: var(--el-text-color-secondary);
line-height: 1.5;
}
.row-tag {
margin: 0 4px 4px 0;
cursor: pointer;
}
.muted {
color: var(--el-text-color-placeholder);
}
.tag-option {
display: flex;
align-items: center;
gap: 6px;
}
.tag-dot {
width: 8px;
height: 8px;
border-radius: 50%;
flex: 0 0 auto;
}
.tag-option-count {
margin-left: auto;
padding-left: 12px;
font-size: 12px;
color: var(--el-text-color-placeholder);
}
</style>
@@ -0,0 +1,303 @@
<script setup lang="ts">
/**
* 标签管理 — the label library the reference module draws on.
*
* This page is the first half of the tagging flow: labels are **made here and
* applied in the reference form**, so a reference is never stored pointing at a
* label that does not exist. The library is global, so a label means the same
* thing in every paper.
*
* Deleting is not guarded the way deleting a library field is. A tag is the
* writer's own filing rather than something the document claims, so removing it
* removes labels and leaves the literature where it was — the confirmation says
* how many entries will lose the label, which is the honest form of that
* warning.
*/
import { onMounted, reactive, ref } from 'vue'
import { Delete, Edit, Plus, Refresh, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { errorMessage } from '@/api/client'
import {
batchDeleteReferenceTags,
deleteReferenceTag,
listReferenceTags,
type ReferenceTag,
} from '@/api/referenceTags'
import TagChip from '@/components/references/TagChip.vue'
import TagFormDialog from '@/components/references/TagFormDialog.vue'
import { useReferenceTagsStore } from '@/stores/referenceTags'
import { formatDateTime } from '@/utils/format'
const tagsStore = useReferenceTagsStore()
const loading = ref(false)
const rows = ref<ReferenceTag[]>([])
const total = ref(0)
const selection = ref<ReferenceTag[]>([])
const query = reactive({
keyword: '',
page: 1,
page_size: 20,
})
const dialogVisible = ref(false)
const editing = ref<ReferenceTag | null>(null)
async function load(): Promise<void> {
loading.value = true
try {
const result = await listReferenceTags(query)
rows.value = result.items
total.value = result.total
if (result.items.length === 0 && result.total > 0 && query.page > 1) {
query.page -= 1
await load()
}
} catch (error) {
ElMessage.error(errorMessage(error))
} finally {
loading.value = false
}
}
function search(): void {
query.page = 1
void load()
}
function onCreate(): void {
editing.value = null
dialogVisible.value = true
}
function onEdit(row: ReferenceTag): void {
editing.value = row
dialogVisible.value = true
}
/**
* Refresh this table and the shared library together.
*
* The rail lists the same labels and the reference form picks from them, so a
* page that renames or deletes one has to reload the store as well or the two
* would disagree until the next navigation.
*/
async function refreshAll(): Promise<void> {
await Promise.all([load(), tagsStore.reload()])
}
async function onDelete(row: ReferenceTag): Promise<void> {
const warning = row.reference_count
? `「${row.name}」正被 ${row.reference_count} 篇文献使用,删除后这些文献会失去这个标签(文献本身不会删)。`
: `确定删除标签「${row.name}」?`
try {
await ElMessageBox.confirm(warning, '删除标签', {
type: 'warning',
confirmButtonText: '删除',
cancelButtonText: '取消',
})
} catch {
return // dismissed
}
try {
await deleteReferenceTag(row.id)
ElMessage.success('已删除标签')
await refreshAll()
} catch (error) {
ElMessage.error(errorMessage(error))
}
}
async function onBatchDelete(): Promise<void> {
const ids = selection.value.map((row) => row.id)
if (ids.length === 0) return
const labels = selection.value
.reduce((sum, row) => sum + row.reference_count, 0)
try {
await ElMessageBox.confirm(
`确定删除选中的 ${ids.length} 个标签?相关文献会失去这些标签(文献本身不会删)。` +
(labels ? `涉及 ${labels} 处标注。` : ''),
'批量删除',
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' },
)
} catch {
return // dismissed
}
try {
const result = await batchDeleteReferenceTags(ids)
ElMessage.success(`已删除 ${result.deleted} 个标签`)
selection.value = []
await refreshAll()
} catch (error) {
ElMessage.error(errorMessage(error))
}
}
onMounted(async () => {
await load()
void tagsStore.reload()
})
</script>
<template>
<div class="page page--fill">
<el-card shadow="never" class="card--fill">
<template #header>
<div class="card-header">
<div>
<span class="card-title">标签库</span>
<span class="card-subtitle">
先在这里建好标签,再在文献里勾选;标签是给自己归档用的,不会出现在参考文献表里
</span>
</div>
<el-tag type="info" effect="plain">共 {{ total }} 个</el-tag>
</div>
</template>
<div class="toolbar">
<el-input
v-model="query.keyword"
placeholder="搜索标签名称或备注"
clearable
class="search"
@keyup.enter="search"
@clear="search"
>
<template #prefix><el-icon><Search /></el-icon></template>
</el-input>
<el-button @click="search">查询</el-button>
<div class="toolbar-spacer" />
<el-button :icon="Refresh" :loading="loading" @click="load">刷新</el-button>
<el-button
type="danger"
plain
:icon="Delete"
:disabled="selection.length === 0"
@click="onBatchDelete"
>
批量删除{{ selection.length ? `(${selection.length})` : '' }}
</el-button>
<el-button type="primary" :icon="Plus" @click="onCreate">新建标签</el-button>
</div>
<el-table
v-loading="loading"
:data="rows"
row-key="id"
stripe
class="table table-fill"
height="100%"
@selection-change="(value: ReferenceTag[]) => (selection = value)"
>
<el-table-column type="selection" width="46" reserve-selection />
<el-table-column label="标签" min-width="200">
<template #default="{ row }">
<TagChip :name="row.name" :color="row.color" size="default" />
</template>
</el-table-column>
<el-table-column label="备注" min-width="240" show-overflow-tooltip>
<template #default="{ row }">
<span v-if="row.note">{{ row.note }}</span>
<span v-else class="muted">—</span>
</template>
</el-table-column>
<el-table-column label="文献数" width="110" align="center">
<template #default="{ row }">
<RouterLink
v-if="row.reference_count"
:to="{ path: '/references', query: { tag: String(row.id) } }"
class="count-link"
>
{{ row.reference_count }} 篇
</RouterLink>
<span v-else class="muted">未使用</span>
</template>
</el-table-column>
<el-table-column label="更新时间" width="170">
<template #default="{ row }">{{ formatDateTime(row.updated_at) }}</template>
</el-table-column>
<el-table-column label="操作" width="150" fixed="right">
<template #default="{ row }">
<el-button link type="primary" :icon="Edit" @click="onEdit(row)">编辑</el-button>
<el-button link type="danger" :icon="Delete" @click="onDelete(row)">删除</el-button>
</template>
</el-table-column>
<template #empty>
<el-empty
:description="query.keyword ? '没有匹配的标签' : '还没有标签,先建一个再给文献打标'"
>
<el-button type="primary" :icon="Plus" @click="onCreate">新建标签</el-button>
</el-empty>
</template>
</el-table>
<div class="table-pagination">
<el-pagination
v-model:current-page="query.page"
v-model:page-size="query.page_size"
:total="total"
:page-sizes="[10, 20, 50, 100]"
layout="total, sizes, prev, pager, next, jumper"
background
@current-change="load"
@size-change="search"
/>
</div>
</el-card>
<TagFormDialog v-model="dialogVisible" :tag="editing" @saved="refreshAll" />
</div>
</template>
<style scoped>
.card-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.card-title {
font-weight: 600;
margin-right: 10px;
}
.card-subtitle {
color: var(--el-text-color-secondary);
font-size: 12px;
}
.search {
width: 240px;
}
.table {
margin-top: 16px;
}
.count-link {
color: var(--el-color-primary);
text-decoration: none;
}
.muted {
color: var(--el-text-color-placeholder);
}
</style>