Add section grouping to shared note tabs

Notes can now be clustered into named sections in the tab bar: each tab
gets a 🏷 button to assign it to a section, and clicking a section's
label renames (or, given an empty name, ungroups) every page in it.

note_pages gains a `section` column. Since the app has no migration
framework, database.py adds the column to existing SQLite files at
startup via PRAGMA table_info + ALTER TABLE. core/notes.set_section()
keeps same-section pages contiguous by renumbering position whenever a
page's section changes, so the tab bar and the AI-facing title list
(now grouped under "## section" headings) can both treat "adjacent" as
"same group" without a separate ordering field.

Also fixes a bug in the tab rename input: ref="renameInput" sits inside
a nested v-for, which Vue 3 binds as an array rather than a single
element, so renameInput.value?.select() was throwing on every rename.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-20 00:28:36 +09:00
co-authored by Claude Opus 5
parent b1350eb8bc
commit 1c21fc3406
10 changed files with 388 additions and 68 deletions
+23 -1
View File
@@ -4,7 +4,7 @@ from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from sqlalchemy.orm import Session as DBSession
from app.core.notes import next_position
from app.core.notes import next_position, rename_section, set_section
from app.db.database import get_db
from app.db.models import NotePage
@@ -16,6 +16,7 @@ class NotePageResponse(BaseModel):
title: str
content: str
position: int
section: str | None
updated_at: datetime
class Config:
@@ -25,11 +26,18 @@ class NotePageResponse(BaseModel):
class NotePageCreate(BaseModel):
title: str = "新しいページ"
content: str = ""
section: str | None = None
class NotePageUpdate(BaseModel):
title: str | None = None
content: str | None = None
section: str | None = None
class SectionRenameRequest(BaseModel):
old_name: str
new_name: str | None = None
@router.get("", response_model=list[NotePageResponse])
@@ -44,9 +52,18 @@ def create_page(req: NotePageCreate, db: DBSession = Depends(get_db)):
db.add(page)
db.commit()
db.refresh(page)
if req.section is not None and req.section.strip():
page = set_section(db, page.id, req.section)
return page
@router.post("/sections/rename")
def rename_section_endpoint(req: SectionRenameRequest, db: DBSession = Depends(get_db)):
"""old_name セクションに属する全ページを new_name セクションへ一括で付け替える。new_name が空ならグループ解除。"""
count = rename_section(db, req.old_name, req.new_name)
return {"renamed": count}
@router.patch("/{page_id}", response_model=NotePageResponse)
def update_page(page_id: int, req: NotePageUpdate, db: DBSession = Depends(get_db)):
page = db.get(NotePage, page_id)
@@ -61,6 +78,11 @@ def update_page(page_id: int, req: NotePageUpdate, db: DBSession = Depends(get_d
page.content = req.content
db.commit()
db.refresh(page)
# section はページの並び順にも影響するため、変更があれば専用ロジックで反映する
if "section" in req.model_fields_set:
page = set_section(db, page_id, req.section)
return page
+50 -2
View File
@@ -75,17 +75,65 @@ def next_position(db: DBSession) -> int:
return (last.position + 1) if last else 0
def set_section(db: DBSession, page_id: int, section: str | None) -> NotePage | None:
"""ページの所属セクションを変更し、同じセクションのページ群の直後に連続配置し直す。
タブバーはposition順に描画され、隣接して同じsectionが続く区間を1つのグループとして
まとめて表示する(app.api.notes / フロントのグルーピング表示を参照)。そのため
セクションを変更したページは、常に同じセクションの最後のページの直後に移動する。
"""
page = db.get(NotePage, page_id)
if not page:
return None
normalized = (section or "").strip() or None
ordered = [p for p in db.query(NotePage).order_by(NotePage.position, NotePage.id).all() if p.id != page_id]
if normalized is None:
insert_at = len(ordered)
else:
matching = [i for i, p in enumerate(ordered) if p.section == normalized]
insert_at = (matching[-1] + 1) if matching else len(ordered)
ordered.insert(insert_at, page)
page.section = normalized
for i, p in enumerate(ordered):
p.position = i
db.commit()
db.refresh(page)
return page
def rename_section(db: DBSession, old_name: str, new_name: str | None) -> int:
"""あるセクションに属する全ページのセクション名を一括で変更する。new_name が空ならグループ解除になる。
戻り値: 変更したページ数。
"""
normalized_new = (new_name or "").strip() or None
pages = db.query(NotePage).filter(NotePage.section == old_name).order_by(NotePage.position, NotePage.id).all()
for page in pages:
page.section = normalized_new
db.commit()
return len(pages)
def get_notes_context(db: DBSession) -> str | None:
"""共有ノートのタイトル一覧をシステムプロンプト用のテキストとして返す。"""
"""共有ノートのタイトル一覧をシステムプロンプト用のテキストとして返す。セクションごとに見出しを付ける。"""
pages = db.query(NotePage).order_by(NotePage.position, NotePage.id).all()
lines = [
"【共有ノート】",
"ユーザーとあなたが共同で編集できるノートです。以下のページがあります。",
"ユーザーとあなたが共同で編集できるノートです。以下のページがあります"
"(セクションはページをグループ化する見出しで、あれば併記します)。",
"",
]
if pages:
current_section = "__unset__" # どのページのsectionとも一致しない番兵
for page in pages:
if page.section != current_section:
current_section = page.section
if current_section:
lines.append(f"## {current_section}")
preview = " ".join(page.content.split())[:40]
suffix = f" — {preview}…" if preview else " — (空)"
lines.append(f"- {page.title}{suffix}")
+12 -1
View File
@@ -1,4 +1,4 @@
from sqlalchemy import create_engine
from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker, DeclarativeBase
from app.core.config import DATABASE_URL
@@ -18,6 +18,17 @@ def get_db():
db.close()
def _add_missing_columns() -> None:
"""マイグレーションフレームワークを使っていないため、既存DBに後から追加されたカラムを
ここで簡易的に補う。create_all() は既存テーブルへのカラム追加は行わないので必要。"""
with engine.connect() as conn:
existing = {row[1] for row in conn.execute(text("PRAGMA table_info(note_pages)"))}
if existing and "section" not in existing:
conn.execute(text("ALTER TABLE note_pages ADD COLUMN section VARCHAR"))
conn.commit()
def init_db():
from app.db import models # noqa: F401
Base.metadata.create_all(bind=engine)
_add_missing_columns()
+2 -1
View File
@@ -115,7 +115,8 @@ class NotePage(Base):
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
title: Mapped[str] = mapped_column(String)
content: Mapped[str] = mapped_column(Text, default="")
position: Mapped[int] = mapped_column(Integer, default=0) # タブの並び順
position: Mapped[int] = mapped_column(Integer, default=0) # タブの並び順(セクションでまとめる際、同じセクションのページは連続させる)
section: Mapped[str | None] = mapped_column(String, nullable=True) # タブをグループ化するセクション名。未設定なら未分類
created_at: Mapped[datetime] = mapped_column(DateTime, default=lambda: datetime.now(timezone.utc))
updated_at: Mapped[datetime] = mapped_column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))