bookmark-Authors #208
@@ -0,0 +1 @@
|
||||
"""User bookmark feature."""
|
||||
@@ -0,0 +1,36 @@
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from pydantic import BaseModel, Field as PydanticField
|
||||
from sqlalchemy import UniqueConstraint
|
||||
from sqlmodel import Field, SQLModel
|
||||
|
||||
|
||||
class PersonBookmark(SQLModel, table=True):
|
||||
__tablename__ = "person_bookmark"
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
"account_id", "person_id", name="uq_person_bookmark_account_person"
|
||||
),
|
||||
)
|
||||
|
||||
id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True)
|
||||
account_id: uuid.UUID = Field(
|
||||
foreign_key="account.id", nullable=False, index=True
|
||||
)
|
||||
person_id: str = Field(nullable=False, index=True)
|
||||
person_name: str | None = Field(default=None)
|
||||
created_at: datetime = Field(
|
||||
default_factory=lambda: datetime.now(timezone.utc), nullable=False, index=True
|
||||
)
|
||||
|
||||
|
||||
class CreatePersonBookmark(BaseModel):
|
||||
person_name: str | None = PydanticField(default=None, max_length=500)
|
||||
|
||||
|
||||
class PersonBookmarkResponse(BaseModel):
|
||||
person_id: str
|
||||
person_name: str | None
|
||||
created_at: datetime
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
from fastapi import APIRouter, Response, status
|
||||
|
||||
from inse.auth import service as auth_service
|
||||
from inse.auth.model import AccessTokenMetadata
|
||||
from inse.database import SessionDep
|
||||
|
||||
from . import service
|
||||
from .model import CreatePersonBookmark, PersonBookmarkResponse
|
||||
|
||||
|
||||
router = APIRouter(prefix="/api/bookmarks", tags=["Bookmarks"])
|
||||
|
||||
|
||||
@router.get("/persons", operation_id="listPersonBookmarks")
|
||||
def list_person_bookmarks(
|
||||
session: SessionDep,
|
||||
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> list[PersonBookmarkResponse]:
|
||||
return service.list_person_bookmarks(session, access_token.effective_account_id)
|
||||
|
||||
|
||||
@router.put("/persons/{person_id}", operation_id="bookmarkPerson")
|
||||
def bookmark_person(
|
||||
person_id: str,
|
||||
payload: CreatePersonBookmark,
|
||||
session: SessionDep,
|
||||
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> PersonBookmarkResponse:
|
||||
return service.create_person_bookmark(
|
||||
session, access_token.effective_account_id, person_id, payload
|
||||
)
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/persons/{person_id}",
|
||||
operation_id="removePersonBookmark",
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
)
|
||||
def remove_person_bookmark(
|
||||
person_id: str,
|
||||
session: SessionDep,
|
||||
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> Response:
|
||||
service.delete_person_bookmark(
|
||||
session, access_token.effective_account_id, person_id
|
||||
)
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
@@ -0,0 +1,81 @@
|
||||
import uuid
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from .model import CreatePersonBookmark, PersonBookmark, PersonBookmarkResponse
|
||||
|
||||
|
||||
def normalize_person_id(person_id: str) -> str:
|
||||
normalized = person_id.strip().rstrip("/").split("/")[-1]
|
||||
if not normalized:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="A person ID is required.",
|
||||
)
|
||||
return normalized
|
||||
|
||||
|
||||
def list_person_bookmarks(
|
||||
session: Session, account_id: uuid.UUID
|
||||
) -> list[PersonBookmarkResponse]:
|
||||
bookmarks = session.exec(
|
||||
select(PersonBookmark)
|
||||
.where(PersonBookmark.account_id == account_id)
|
||||
.order_by(PersonBookmark.created_at.desc())
|
||||
).all()
|
||||
return [
|
||||
PersonBookmarkResponse(
|
||||
person_id=bookmark.person_id,
|
||||
person_name=bookmark.person_name,
|
||||
created_at=bookmark.created_at,
|
||||
)
|
||||
for bookmark in bookmarks
|
||||
]
|
||||
|
||||
|
||||
def create_person_bookmark(
|
||||
session: Session,
|
||||
account_id: uuid.UUID,
|
||||
person_id: str,
|
||||
payload: CreatePersonBookmark,
|
||||
) -> PersonBookmarkResponse:
|
||||
normalized_id = normalize_person_id(person_id)
|
||||
bookmark = session.exec(
|
||||
select(PersonBookmark).where(
|
||||
PersonBookmark.account_id == account_id,
|
||||
PersonBookmark.person_id == normalized_id,
|
||||
)
|
||||
).first()
|
||||
if bookmark is None:
|
||||
bookmark = PersonBookmark(
|
||||
account_id=account_id,
|
||||
person_id=normalized_id,
|
||||
person_name=payload.person_name,
|
||||
)
|
||||
session.add(bookmark)
|
||||
elif payload.person_name:
|
||||
bookmark.person_name = payload.person_name
|
||||
|
||||
session.commit()
|
||||
session.refresh(bookmark)
|
||||
return PersonBookmarkResponse(
|
||||
person_id=bookmark.person_id,
|
||||
person_name=bookmark.person_name,
|
||||
created_at=bookmark.created_at,
|
||||
)
|
||||
|
||||
|
||||
def delete_person_bookmark(
|
||||
session: Session, account_id: uuid.UUID, person_id: str
|
||||
) -> None:
|
||||
normalized_id = normalize_person_id(person_id)
|
||||
bookmark = session.exec(
|
||||
select(PersonBookmark).where(
|
||||
PersonBookmark.account_id == account_id,
|
||||
PersonBookmark.person_id == normalized_id,
|
||||
)
|
||||
).first()
|
||||
if bookmark is not None:
|
||||
session.delete(bookmark)
|
||||
session.commit()
|
||||
@@ -0,0 +1,71 @@
|
||||
import uuid
|
||||
|
||||
from sqlmodel import Session, SQLModel, create_engine
|
||||
|
||||
from inse.auth.model import Account, Organization
|
||||
|
||||
from .model import CreatePersonBookmark
|
||||
from .service import (
|
||||
create_person_bookmark,
|
||||
delete_person_bookmark,
|
||||
list_person_bookmarks,
|
||||
)
|
||||
|
||||
|
||||
def _session_with_account():
|
||||
engine = create_engine(
|
||||
"sqlite:///:memory:", connect_args={"check_same_thread": False}
|
||||
)
|
||||
SQLModel.metadata.create_all(engine)
|
||||
session = Session(engine)
|
||||
organization = Organization(name="Bookmark Test Org")
|
||||
session.add(organization)
|
||||
session.flush()
|
||||
account = Account(
|
||||
email="bookmarks@example.org",
|
||||
name="Bookmark Tester",
|
||||
password_hash="not-used",
|
||||
organization_id=organization.id,
|
||||
)
|
||||
session.add(account)
|
||||
session.commit()
|
||||
return session, account.id
|
||||
|
||||
|
||||
def test_person_bookmarks_are_idempotent_and_normalize_openalex_ids():
|
||||
session, account_id = _session_with_account()
|
||||
assert isinstance(account_id, uuid.UUID)
|
||||
|
||||
create_person_bookmark(
|
||||
session,
|
||||
account_id,
|
||||
"https://openalex.org/A123",
|
||||
CreatePersonBookmark(person_name="Ada Example"),
|
||||
)
|
||||
create_person_bookmark(
|
||||
session,
|
||||
account_id,
|
||||
"A123",
|
||||
CreatePersonBookmark(person_name="Ada Updated"),
|
||||
)
|
||||
|
||||
bookmarks = list_person_bookmarks(session, account_id)
|
||||
assert len(bookmarks) == 1
|
||||
assert bookmarks[0].person_id == "A123"
|
||||
assert bookmarks[0].person_name == "Ada Updated"
|
||||
|
||||
|
||||
def test_deleting_a_person_bookmark_is_idempotent():
|
||||
session, account_id = _session_with_account()
|
||||
assert isinstance(account_id, uuid.UUID)
|
||||
create_person_bookmark(
|
||||
session,
|
||||
account_id,
|
||||
"A123",
|
||||
CreatePersonBookmark(person_name="Ada Example"),
|
||||
)
|
||||
|
||||
delete_person_bookmark(session, account_id, "A123")
|
||||
delete_person_bookmark(session, account_id, "A123")
|
||||
|
||||
assert list_person_bookmarks(session, account_id) == []
|
||||
@@ -16,9 +16,72 @@ engine = create_engine(
|
||||
)
|
||||
|
||||
|
||||
def _migrate_secret_table():
|
||||
"""Upgrade the legacy login-only secret table without losing its data."""
|
||||
columns = {column["name"] for column in inspect(engine).get_columns("secret")}
|
||||
required_columns = {
|
||||
"purpose",
|
||||
"request_count",
|
||||
"request_window_started_at",
|
||||
}
|
||||
if required_columns.issubset(columns):
|
||||
return
|
||||
|
||||
# SQLite cannot alter a UNIQUE constraint in place. Rebuild the table so an
|
||||
# account can hold both a login OTK and a password-reset secret.
|
||||
with engine.begin() as connection:
|
||||
connection.execute(text("ALTER TABLE secret RENAME TO secret_legacy"))
|
||||
connection.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE secret (
|
||||
id CHAR(32) NOT NULL PRIMARY KEY,
|
||||
account_id CHAR(32) NOT NULL,
|
||||
purpose VARCHAR NOT NULL,
|
||||
secret_value VARCHAR NOT NULL,
|
||||
expires_at DATETIME NOT NULL,
|
||||
request_count INTEGER NOT NULL DEFAULT 0,
|
||||
request_window_started_at DATETIME,
|
||||
CONSTRAINT uq_secret_account_purpose
|
||||
UNIQUE (account_id, purpose),
|
||||
FOREIGN KEY(account_id) REFERENCES account (id)
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
connection.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO secret (
|
||||
id, account_id, purpose, secret_value, expires_at,
|
||||
request_count, request_window_started_at
|
||||
)
|
||||
SELECT id, account_id, 'LOGIN_OTK', secret_value, expires_at,
|
||||
0, NULL
|
||||
FROM secret_legacy
|
||||
"""
|
||||
)
|
||||
)
|
||||
connection.execute(text("DROP TABLE secret_legacy"))
|
||||
connection.execute(
|
||||
text("CREATE INDEX ix_secret_account_id ON secret (account_id)")
|
||||
)
|
||||
connection.execute(text("CREATE INDEX ix_secret_purpose ON secret (purpose)"))
|
||||
connection.execute(
|
||||
text("CREATE INDEX ix_secret_expires_at ON secret (expires_at)")
|
||||
)
|
||||
connection.execute(
|
||||
text(
|
||||
"CREATE INDEX ix_secret_request_window_started_at "
|
||||
"ON secret (request_window_started_at)"
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def create_db_and_tables():
|
||||
"""Creates the database and tables based on the SQLModel metadata."""
|
||||
SQLModel.metadata.create_all(engine)
|
||||
_migrate_secret_table()
|
||||
columns = {column["name"] for column in inspect(engine).get_columns("account")}
|
||||
if "activated" not in columns:
|
||||
with engine.begin() as connection:
|
||||
|
||||
@@ -38,6 +38,7 @@ from inse.auth.router import router as auth_router
|
||||
from inse.account_management.router import router as account_management_router
|
||||
from inse.organization_management.router import router as organization_management_router
|
||||
from inse.dashboard.router import router as dashboard_router
|
||||
from inse.bookmarks.router import router as bookmarks_router
|
||||
|
||||
from inse.institutions.router import router as institutions_router
|
||||
from inse.database import create_db_and_tables, get_session
|
||||
@@ -103,7 +104,7 @@ app.include_router(auth_router)
|
||||
app.include_router(account_management_router)
|
||||
app.include_router(organization_management_router)
|
||||
app.include_router(dashboard_router)
|
||||
|
||||
app.include_router(bookmarks_router)
|
||||
|
||||
app.add_middleware(
|
||||
ETagCacheMiddleware,
|
||||
|
||||
@@ -25,7 +25,9 @@ class ETagCacheMiddleware(BaseHTTPMiddleware):
|
||||
if request.method != "GET":␍
|
||||
return await call_next(request)␍
|
||||
␍
|
||||
if request.url.path.startswith(("/api/auth", "/api/accounts")):␍
|
||||
if request.url.path.startswith(
|
||||
("/api/auth", "/api/accounts", "/api/bookmarks")
|
||||
):
|
||||
return await call_next(request)␍
|
||||
␍
|
||||
if request.headers.get("authorization"):␍
|
||||
|
||||
@@ -68,6 +68,14 @@ export const routes: Routes = [
|
||||
(mod) => mod.DashboardComponent,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'bookmarks',
|
||||
canActivate: [userGuard],
|
||||
loadComponent: () =>
|
||||
import('./modules/bookmarks/bookmarks.component').then(
|
||||
(mod) => mod.BookmarksComponent,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'persons',
|
||||
canActivate: [userGuard],
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
<main class="bookmarks-page">
|
||||
<header class="page-header">
|
||||
<div>
|
||||
<p class="eyebrow">Meine Sammlung</p>
|
||||
<h1>Bookmarks</h1>
|
||||
<p>Gespeicherte Personen für den schnellen Zugriff.</p>
|
||||
</div>
|
||||
<div class="bookmark-count">
|
||||
<mat-icon>bookmarks</mat-icon>
|
||||
<strong>{{ persons().length }}</strong>
|
||||
<span>Personen</span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
@if (loading()) {
|
||||
<div class="loading-state">
|
||||
<mat-spinner diameter="42"></mat-spinner>
|
||||
<p>Bookmarks werden geladen …</p>
|
||||
</div>
|
||||
} @else if (persons().length) {
|
||||
<section class="person-grid" aria-label="Gespeicherte Personen">
|
||||
@for (person of persons(); track person.id) {
|
||||
<app-person-card
|
||||
[person]="person"
|
||||
[isBookmarked]="bookmarkService.isBookmarked(person.id)"
|
||||
(bookmarkToggle)="toggleBookmark($event)">
|
||||
</app-person-card>
|
||||
}
|
||||
</section>
|
||||
} @else {
|
||||
<section class="empty-state">
|
||||
<mat-icon>bookmark_border</mat-icon>
|
||||
<h2>Noch keine Bookmarks</h2>
|
||||
<p>
|
||||
Speichere Personen über das Bookmark-Symbol auf einer Personenkarte.
|
||||
</p>
|
||||
</section>
|
||||
}
|
||||
</main>
|
||||
@@ -0,0 +1,98 @@
|
||||
:host {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.bookmarks-page {
|
||||
padding: 32px;
|
||||
}
|
||||
|
||||
.page-header {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
justify-content: space-between;
|
||||
gap: 24px;
|
||||
margin-bottom: 30px;
|
||||
|
||||
h1 {
|
||||
margin: 2px 0 6px;
|
||||
font-size: 2rem;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
color: #667085;
|
||||
}
|
||||
|
||||
.eyebrow {
|
||||
color: #3f51b5;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.12em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
}
|
||||
|
||||
.bookmark-count {
|
||||
display: grid;
|
||||
grid-template-columns: auto auto;
|
||||
align-items: center;
|
||||
gap: 0 10px;
|
||||
padding: 14px 18px;
|
||||
border: 1px solid #e4e7ec;
|
||||
border-radius: 14px;
|
||||
background: white;
|
||||
|
||||
mat-icon {
|
||||
grid-row: 1 / 3;
|
||||
color: #3f51b5;
|
||||
}
|
||||
|
||||
strong {
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
|
||||
span {
|
||||
color: #667085;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
}
|
||||
|
||||
.person-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.loading-state,
|
||||
.empty-state {
|
||||
display: flex;
|
||||
min-height: 320px;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
text-align: center;
|
||||
color: #667085;
|
||||
}
|
||||
|
||||
.empty-state mat-icon {
|
||||
width: 54px;
|
||||
height: 54px;
|
||||
font-size: 54px;
|
||||
color: #98a2b3;
|
||||
}
|
||||
|
||||
.empty-state h2 {
|
||||
margin: 16px 0 6px;
|
||||
color: #1d2939;
|
||||
}
|
||||
|
||||
@media (max-width: 700px) {
|
||||
.bookmarks-page {
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.page-header {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { Component, DestroyRef, inject, signal } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
|
||||
import { catchError, forkJoin, map, of, switchMap } from 'rxjs';
|
||||
|
||||
import { CustomAuthor, PersonsService } from '../../api';
|
||||
import { BookmarkService } from '../../shared/services/bookmark.service';
|
||||
import { PersonCardComponent } from '../person-card/person-card.component';
|
||||
|
||||
const PERSON_INCLUDE_TAGS =
|
||||
'display_name,works_count,cited_by_count,summary_stats,ids,' +
|
||||
'last_known_institutions,affiliations,topics,orcid,topics_full,' +
|
||||
'topic_share,career_metrics';
|
||||
|
||||
@Component({
|
||||
selector: 'app-bookmarks',
|
||||
standalone: true,
|
||||
imports: [
|
||||
CommonModule,
|
||||
MatIconModule,
|
||||
MatProgressSpinnerModule,
|
||||
PersonCardComponent,
|
||||
],
|
||||
templateUrl: './bookmarks.component.html',
|
||||
styleUrl: './bookmarks.component.scss',
|
||||
})
|
||||
export class BookmarksComponent {
|
||||
readonly bookmarkService = inject(BookmarkService);
|
||||
private readonly personsService = inject(PersonsService);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
|
||||
readonly persons = signal<CustomAuthor[]>([]);
|
||||
readonly loading = signal(true);
|
||||
|
||||
constructor() {
|
||||
this.loadBookmarks();
|
||||
}
|
||||
|
||||
toggleBookmark(person: CustomAuthor): void {
|
||||
this.bookmarkService
|
||||
.confirmToggle(person)
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe({
|
||||
next: (bookmarked) => {
|
||||
if (!bookmarked) {
|
||||
const id = this.personId(person);
|
||||
this.persons.update((persons) =>
|
||||
persons.filter((item) => this.personId(item) !== id),
|
||||
);
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private loadBookmarks(): void {
|
||||
this.bookmarkService
|
||||
.load(true)
|
||||
.pipe(
|
||||
switchMap((bookmarks) => {
|
||||
if (!bookmarks.length) return of([] as CustomAuthor[]);
|
||||
return forkJoin(
|
||||
bookmarks.map((bookmark) =>
|
||||
this.personsService
|
||||
.getPersonByID(bookmark.person_id, PERSON_INCLUDE_TAGS)
|
||||
.pipe(
|
||||
map(
|
||||
(response) =>
|
||||
response.results?.[0] ?? {
|
||||
id: bookmark.person_id,
|
||||
display_name: bookmark.person_name,
|
||||
},
|
||||
),
|
||||
catchError(() =>
|
||||
of({
|
||||
id: bookmark.person_id,
|
||||
display_name: bookmark.person_name,
|
||||
} as CustomAuthor),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
takeUntilDestroyed(this.destroyRef),
|
||||
)
|
||||
.subscribe({
|
||||
next: (persons) => {
|
||||
this.persons.set(persons);
|
||||
this.loading.set(false);
|
||||
},
|
||||
error: () => this.loading.set(false),
|
||||
});
|
||||
}
|
||||
|
||||
private personId(person: CustomAuthor): string {
|
||||
return person.id?.replace(/\/$/, '').split('/').pop() ?? '';
|
||||
}
|
||||
}
|
||||
@@ -5,25 +5,31 @@
|
||||
{{ initials() }}
|
||||
</div>
|
||||
<div class="header-main">
|
||||
<div class="bookmark">
|
||||
<div class="name-row">
|
||||
<h2
|
||||
[skText]="loading()"
|
||||
class="person-name"
|
||||
[title]="person().display_name ?? ''">
|
||||
{{ person().display_name ?? '' }}
|
||||
</h2>
|
||||
<button
|
||||
type="button"
|
||||
class="bookmark-btn"
|
||||
(click)="
|
||||
toggleBookmark(); $event.stopPropagation(); $event.preventDefault()
|
||||
"
|
||||
[class.bookmarked]="isBookmarked()"
|
||||
aria-label="Bookmark person">
|
||||
[attr.aria-label]="
|
||||
isBookmarked() ? 'Bookmark entfernen' : 'Person speichern'
|
||||
"
|
||||
[matTooltip]="
|
||||
isBookmarked() ? 'Bookmark entfernen' : 'Person speichern'
|
||||
">
|
||||
<mat-icon>{{
|
||||
isBookmarked() ? 'bookmark' : 'bookmark_border'
|
||||
}}</mat-icon>
|
||||
</button>
|
||||
</div>
|
||||
<h2
|
||||
[skText]="loading()"
|
||||
class="person-name"
|
||||
[title]="person().display_name ?? ''">
|
||||
{{ person().display_name ?? '' }}
|
||||
</h2>
|
||||
<p [skText]="loading()" class="person-id">
|
||||
{{ distinguishingId() }}
|
||||
</p>
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
.card-header {
|
||||
padding: 16px;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 12px;
|
||||
border-bottom: 1px solid var(--sg-surface-soft);
|
||||
text-decoration: none;
|
||||
@@ -52,6 +53,14 @@
|
||||
}
|
||||
}
|
||||
|
||||
.name-row {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
min-height: 40px;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.rating-and-bookmark {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
@@ -82,18 +91,30 @@
|
||||
}
|
||||
|
||||
.bookmark-btn {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
flex: 0 0 32px;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border: none;
|
||||
border-radius: 50%;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
padding: 2px;
|
||||
padding: 0;
|
||||
color: var(--sg-text-soft);
|
||||
transition:
|
||||
color 0.15s ease,
|
||||
background-color 0.15s ease;
|
||||
|
||||
&:hover {
|
||||
&:hover,
|
||||
&:focus-visible {
|
||||
background: var(--sg-primary-soft);
|
||||
color: var(--sg-primary);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
&.bookmarked {
|
||||
color: #e53935;
|
||||
color: var(--sg-success);
|
||||
}
|
||||
|
||||
mat-icon {
|
||||
@@ -104,11 +125,12 @@
|
||||
}
|
||||
|
||||
.person-name {
|
||||
margin: 6px 0 2px;
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: var(--sg-text);
|
||||
min-height: 24px;
|
||||
line-height: 24px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
|
||||
@@ -42,6 +42,7 @@ import {
|
||||
MatAutocompleteSelectedEvent,
|
||||
} from '@angular/material/autocomplete';
|
||||
import { SkTextDirective } from '../../custom-directives/sk-text.directive';
|
||||
import { BookmarkService } from '../../shared/services/bookmark.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-person-list',
|
||||
@@ -73,6 +74,7 @@ export class PersonListComponent {
|
||||
private readonly topicsService = inject(TopicsService);
|
||||
private readonly institutionsService = inject(InstitutionsService);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
private readonly bookmarkService = inject(BookmarkService);
|
||||
public readonly state = inject(SharedStateService);
|
||||
public readonly paginationService = inject(PaginationService);
|
||||
public readonly resolverStateService = inject(ResolverStateService);
|
||||
@@ -120,9 +122,12 @@ export class PersonListComponent {
|
||||
],
|
||||
});
|
||||
|
||||
// Bookmarking
|
||||
bookmarkedIds = new Set<string>();
|
||||
constructor() {
|
||||
this.bookmarkService
|
||||
.load()
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe();
|
||||
|
||||
if (!this.institutionControl.value) {
|
||||
this.yearFilterEnabledControl.disable();
|
||||
}
|
||||
@@ -510,12 +515,10 @@ export class PersonListComponent {
|
||||
|
||||
// Bookmarks
|
||||
toggleBookmark(person: CustomAuthor): void {
|
||||
if (!person.id) return;
|
||||
if (this.bookmarkedIds.has(person.id)) {
|
||||
this.bookmarkedIds.delete(person.id);
|
||||
} else {
|
||||
this.bookmarkedIds.add(person.id);
|
||||
}
|
||||
this.bookmarkService
|
||||
.confirmToggle(person)
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe();
|
||||
}
|
||||
|
||||
onTopicSelectionChange(newSelection: Set<string>): void {
|
||||
@@ -540,7 +543,7 @@ export class PersonListComponent {
|
||||
}
|
||||
|
||||
isBookmarked(person: CustomAuthor): boolean {
|
||||
return !!person.id && this.bookmarkedIds.has(person.id);
|
||||
return this.bookmarkService.isBookmarked(person.id);
|
||||
}
|
||||
|
||||
clearSearch(): void {
|
||||
|
||||
@@ -6,6 +6,27 @@
|
||||
<div class="name-line">
|
||||
<span>Person</span>
|
||||
<h1>{{ displayName() }}</h1>
|
||||
<button
|
||||
type="button"
|
||||
class="profile-bookmark-button"
|
||||
[class.bookmarked]="bookmarkService.isBookmarked(person()?.id)"
|
||||
[attr.aria-label]="
|
||||
bookmarkService.isBookmarked(person()?.id)
|
||||
? 'Bookmark entfernen'
|
||||
: 'Person bookmarken'
|
||||
"
|
||||
[matTooltip]="
|
||||
bookmarkService.isBookmarked(person()?.id)
|
||||
? 'Bookmark entfernen'
|
||||
: 'Person bookmarken'
|
||||
"
|
||||
(click)="toggleBookmark()">
|
||||
<mat-icon>{{
|
||||
bookmarkService.isBookmarked(person()?.id)
|
||||
? 'bookmark'
|
||||
: 'bookmark_border'
|
||||
}}</mat-icon>
|
||||
</button>
|
||||
</div>
|
||||
<div class="institution-line">
|
||||
<mat-icon class="institution-icon">apartment</mat-icon>
|
||||
|
||||
@@ -76,6 +76,32 @@
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.profile-bookmark-button {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
margin-left: 4px;
|
||||
padding: 0;
|
||||
border: 1px solid var(--sg-border);
|
||||
border-radius: 50%;
|
||||
background: white;
|
||||
color: var(--sg-text-muted);
|
||||
cursor: pointer;
|
||||
|
||||
&:hover,
|
||||
&.bookmarked {
|
||||
border-color: var(--sg-primary);
|
||||
color: var(--sg-primary);
|
||||
}
|
||||
|
||||
mat-icon {
|
||||
width: 21px;
|
||||
height: 21px;
|
||||
font-size: 21px;
|
||||
}
|
||||
}
|
||||
|
||||
.institution-line {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -24,6 +24,7 @@ import { PersonInterestingComponent } from '../person-interesting/person-interes
|
||||
import { WorksService } from '../../api';
|
||||
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
|
||||
import { PersonBioResolved } from '../../resolvers/person-bio.resolver';
|
||||
import { BookmarkService } from '../../shared/services/bookmark.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-person',
|
||||
@@ -47,6 +48,14 @@ export class PersonComponent {
|
||||
|
||||
private readonly worksApi = inject(WorksService);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
readonly bookmarkService = inject(BookmarkService);
|
||||
|
||||
constructor() {
|
||||
this.bookmarkService
|
||||
.load()
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe();
|
||||
}
|
||||
|
||||
readonly params = toSignal(this.activatedRoute.paramMap);
|
||||
readonly routerEvents = toSignal(this.router.events);
|
||||
@@ -99,6 +108,15 @@ export class PersonComponent {
|
||||
{ initialValue: null },
|
||||
);
|
||||
|
||||
toggleBookmark(): void {
|
||||
const person = this.person();
|
||||
if (!person) return;
|
||||
this.bookmarkService
|
||||
.confirmToggle(person)
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe();
|
||||
}
|
||||
|
||||
readonly personBio = toSignal(
|
||||
this.activatedRoute.data.pipe(
|
||||
switchMap((data) => {
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Injectable, inject, signal } from '@angular/core';
|
||||
import { MatDialog } from '@angular/material/dialog';
|
||||
import { EMPTY, Observable, finalize, map, of, switchMap, tap } from 'rxjs';
|
||||
|
||||
import { Configuration, CustomAuthor } from '../../api';
|
||||
import { ConfirmationDialogComponent } from '../ui/confirmation-dialog/confirmation-dialog.component';
|
||||
|
||||
export interface PersonBookmark {
|
||||
person_id: string;
|
||||
person_name: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class BookmarkService {
|
||||
private readonly http = inject(HttpClient);
|
||||
private readonly configuration = inject(Configuration, { optional: true });
|
||||
private readonly dialog = inject(MatDialog);
|
||||
private readonly bookmarkState = signal<PersonBookmark[]>([]);
|
||||
private loading = false;
|
||||
private loaded = false;
|
||||
|
||||
readonly bookmarks = this.bookmarkState.asReadonly();
|
||||
|
||||
load(force = false): Observable<PersonBookmark[]> {
|
||||
if (this.loaded && !force) return of(this.bookmarkState());
|
||||
if (this.loading) return of(this.bookmarkState());
|
||||
|
||||
this.loading = true;
|
||||
return this.http
|
||||
.get<PersonBookmark[]>(`${this.basePath}/api/bookmarks/persons`)
|
||||
.pipe(
|
||||
tap((bookmarks) => {
|
||||
this.bookmarkState.set(bookmarks);
|
||||
this.loaded = true;
|
||||
}),
|
||||
finalize(() => (this.loading = false)),
|
||||
);
|
||||
}
|
||||
|
||||
isBookmarked(personId: string | null | undefined): boolean {
|
||||
const id = this.normalizeId(personId);
|
||||
return !!id && this.bookmarkState().some((item) => item.person_id === id);
|
||||
}
|
||||
|
||||
toggle(person: CustomAuthor): Observable<boolean> {
|
||||
const personId = this.normalizeId(person.id);
|
||||
if (!personId) return of(false);
|
||||
|
||||
if (this.isBookmarked(personId)) {
|
||||
return this.http
|
||||
.delete<void>(`${this.basePath}/api/bookmarks/persons/${personId}`)
|
||||
.pipe(
|
||||
tap(() =>
|
||||
this.bookmarkState.update((items) =>
|
||||
items.filter((item) => item.person_id !== personId),
|
||||
),
|
||||
),
|
||||
map(() => false),
|
||||
);
|
||||
}
|
||||
|
||||
return this.http
|
||||
.put<PersonBookmark>(`${this.basePath}/api/bookmarks/persons/${personId}`, {
|
||||
person_name: person.display_name ?? null,
|
||||
})
|
||||
.pipe(
|
||||
tap((bookmark) =>
|
||||
this.bookmarkState.update((items) => [
|
||||
bookmark,
|
||||
...items.filter((item) => item.person_id !== bookmark.person_id),
|
||||
]),
|
||||
),
|
||||
map(() => true),
|
||||
);
|
||||
}
|
||||
|
||||
confirmToggle(person: CustomAuthor): Observable<boolean> {
|
||||
const removing = this.isBookmarked(person.id);
|
||||
const personName = person.display_name?.trim() || 'diese Person';
|
||||
const dialogRef = this.dialog.open(ConfirmationDialogComponent, {
|
||||
data: {
|
||||
title: removing ? 'Bookmark entfernen' : 'Person speichern',
|
||||
message: removing
|
||||
? `Möchtest Du „${personName}“ wirklich aus Deinen Bookmarks entfernen?`
|
||||
: `Möchtest Du „${personName}“ in Deinen Bookmarks speichern?`,
|
||||
confirmText: removing ? 'Entfernen' : 'Speichern',
|
||||
cancelText: 'Abbrechen',
|
||||
},
|
||||
});
|
||||
|
||||
return dialogRef.afterClosed().pipe(
|
||||
switchMap((confirmed) => (confirmed ? this.toggle(person) : EMPTY)),
|
||||
);
|
||||
}
|
||||
|
||||
private normalizeId(personId: string | null | undefined): string {
|
||||
return personId?.trim().replace(/\/$/, '').split('/').pop() ?? '';
|
||||
}
|
||||
|
||||
private get basePath(): string {
|
||||
return this.configuration?.basePath ?? '';
|
||||
}
|
||||
}
|
||||
@@ -74,6 +74,12 @@ export class AppMenuComponent {
|
||||
},
|
||||
disabled: false,
|
||||
},
|
||||
{
|
||||
label: 'Bookmarks',
|
||||
icon: 'bookmarks',
|
||||
route: '/bookmarks',
|
||||
disabled: false,
|
||||
},
|
||||
{
|
||||
label: 'News',
|
||||
icon: 'newspaper',
|
||||
|
||||
@@ -51,11 +51,11 @@ export class ConfirmationDialogComponent {
|
||||
}
|
||||
|
||||
onCancelClick(): void {
|
||||
this.dialogRef.close();
|
||||
this.dialogRef.close(false);
|
||||
}
|
||||
|
||||
onConfirmClick(): void {
|
||||
this.confirmDelete.emit();
|
||||
this.dialogRef.close();
|
||||
this.dialogRef.close(true);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user