open-law/app/controllers/breadcrumbs.py

90 lines
2.5 KiB
Python
Raw Normal View History

2023-05-01 14:01:03 +00:00
from flask import url_for
2023-05-01 08:15:57 +00:00
from flask_login import current_user
2023-05-01 14:29:54 +00:00
2023-05-01 08:15:57 +00:00
from app import models as m, db
2023-05-01 14:01:03 +00:00
from app import schema as s
2023-05-01 08:15:57 +00:00
2023-05-30 11:10:04 +00:00
def create_collections_breadcrumb(
bread_crumbs: list[s.BreadCrumb], collection: m.Collection
) -> list[s.BreadCrumb]:
bread_crumbs += [
s.BreadCrumb(
type=s.BreadCrumbType.Collection,
url="",
label=collection.label,
)
]
if collection.parent and not collection.parent.is_root:
create_collections_breadcrumb(bread_crumbs, collection.parent)
2023-05-01 08:15:57 +00:00
def create_breadcrumbs(
book_id: int,
2023-05-01 14:01:03 +00:00
collection_path: tuple[int],
2023-05-01 08:15:57 +00:00
section_id: int = 0,
2023-05-01 14:01:03 +00:00
interpretation_id: int = 0,
2023-05-30 11:10:04 +00:00
collection_id: int = 0,
2023-05-01 14:01:03 +00:00
) -> list[s.BreadCrumb]:
"""
How breadcrumbs look like:
Book List -> Book Name -> Top Level Collection -> SubCollection -> Section -> Interpretation
- If i am not owner of a book
John's books -> Book Name -> Top Level Collection -> SubCollection -> Section -> Interpretation
- If i am owner
My Books -> Book Title -> Part I -> Chapter X -> Paragraph 1.7 -> By John
"""
2023-05-01 14:01:03 +00:00
crumples: list[s.BreadCrumb] = []
book: m.Book = db.session.get(m.Book, book_id)
if current_user.is_authenticated and book.user_id == current_user.id:
# My Book
crumples += [
s.BreadCrumb(
type=s.BreadCrumbType.MyBookList,
2023-05-10 12:38:29 +00:00
url=url_for("book.my_library"),
2023-05-01 14:01:03 +00:00
label="My Books",
)
]
else:
# Not mine book
crumples += [
s.BreadCrumb(
type=s.BreadCrumbType.AuthorBookList,
2023-05-25 13:51:42 +00:00
url="",
2023-05-01 14:01:03 +00:00
label=book.owner.username + "'s books",
)
]
crumples += [
s.BreadCrumb(
type=s.BreadCrumbType.Collection,
url=url_for("book.collection_view", book_id=book_id),
label=book.label,
)
]
2023-05-30 11:10:04 +00:00
collections_crumbs = []
collection: m.Collection = db.session.get(m.Collection, collection_id)
create_collections_breadcrumb(collections_crumbs, collection)
crumples += collections_crumbs.reverse()
2023-05-09 13:30:44 +00:00
2023-05-30 11:10:04 +00:00
if section_id and collection_id:
2023-05-09 13:30:44 +00:00
section: m.Section = db.session.get(m.Section, section_id)
crumples += [
s.BreadCrumb(
type=s.BreadCrumbType.Section,
url=url_for(
"book.interpretation_view",
book_id=book_id,
section_id=section_id,
),
label=section.label,
)
]
2023-05-01 14:01:03 +00:00
return crumples