diff --git a/Database/pb_migrations/1762400000_favorites.js b/Database/pb_migrations/1762400000_favorites.js new file mode 100644 index 0000000..38b36ef --- /dev/null +++ b/Database/pb_migrations/1762400000_favorites.js @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +/// + +// Per-user favorites and recently visited pages. workspace is copied from the +// page so the sidebar can list one workspace's entries without a join. + +migrate( + (app) => { + const users = app.findCollectionByNameOrId("users"); + const pages = app.findCollectionByNameOrId("pages"); + const workspaces = app.findCollectionByNameOrId("workspaces"); + const refs = () => [ + { name: "user", type: "relation", collectionId: users.id, maxSelect: 1, required: true, cascadeDelete: true }, + { name: "page", type: "relation", collectionId: pages.id, maxSelect: 1, required: true, cascadeDelete: true }, + { name: "workspace", type: "relation", collectionId: workspaces.id, maxSelect: 1, required: true, cascadeDelete: true }, + ]; + + app.save( + new Collection({ + type: "base", + name: "favorites", + fields: [ + ...refs(), + { name: "created", type: "autodate", onCreate: true, onUpdate: false }, + { name: "updated", type: "autodate", onCreate: true, onUpdate: true }, + ], + indexes: [ + "CREATE UNIQUE INDEX idx_favorites_unique ON favorites (user, page)", + "CREATE INDEX idx_favorites_list ON favorites (user, workspace)", + ], + }), + ); + + app.save( + new Collection({ + type: "base", + name: "page_visits", + fields: [ + ...refs(), + { name: "visited", type: "date", required: true }, + { name: "created", type: "autodate", onCreate: true, onUpdate: false }, + { name: "updated", type: "autodate", onCreate: true, onUpdate: true }, + ], + indexes: [ + "CREATE UNIQUE INDEX idx_page_visits_unique ON page_visits (user, page)", + "CREATE INDEX idx_page_visits_list ON page_visits (user, workspace, visited)", + ], + }), + ); + }, + (app) => { + for (const name of ["page_visits", "favorites"]) { + try { + app.delete(app.findCollectionByNameOrId(name)); + } catch (_) {} + } + }, +); diff --git a/Packages/api-client/src/index.ts b/Packages/api-client/src/index.ts index 7c627d2..68f3694 100644 --- a/Packages/api-client/src/index.ts +++ b/Packages/api-client/src/index.ts @@ -34,6 +34,7 @@ export type InstanceSettings = Schemas["InstanceSettings"]; export type InstanceSettingsUpdate = Schemas["InstanceSettingsUpdate"]; export type Invite = Schemas["Invite"]; export type Group = Schemas["Group"]; +export type PageItem = Schemas["PageItem"]; export type GroupRequest = Schemas["GroupRequest"]; export type SpaceGroup = Schemas["SpaceGroup"]; export type MemberUser = Schemas["MemberUser"]; @@ -180,6 +181,9 @@ export function createClient(opts: ClientOptions) { createSpace: (id: string, input: CreateSpaceRequest) => post(`/api/v1/workspaces/${encodeURIComponent(id)}/spaces`, input), groups: (id: string) => request("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/groups`), + favorites: (id: string) => request("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/favorites`), + recent: (id: string, limit?: number) => + request("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/recent${query({ limit })}`), createGroup: (id: string, input: GroupRequest) => post(`/api/v1/workspaces/${encodeURIComponent(id)}/groups`, input), }, @@ -237,6 +241,10 @@ export function createClient(opts: ClientOptions) { post(`/api/v1/pages/${encodeURIComponent(id)}/move`, { parent, index }), trash: (id: string) => request("DELETE", `/api/v1/pages/${encodeURIComponent(id)}`), restore: (id: string) => post(`/api/v1/pages/${encodeURIComponent(id)}/restore`), + setFavorite: (id: string, on: boolean) => + request(on ? "PUT" : "DELETE", `/api/v1/pages/${encodeURIComponent(id)}/favorite`), + /** Records that the user opened the page, for their recent list. */ + visit: (id: string) => post(`/api/v1/pages/${encodeURIComponent(id)}/visit`), purge: (id: string) => request("DELETE", `/api/v1/pages/${encodeURIComponent(id)}?permanent=true`), }, }; diff --git a/Packages/api-client/src/schema.d.ts b/Packages/api-client/src/schema.d.ts index ba5d0c3..f4c6e72 100644 --- a/Packages/api-client/src/schema.d.ts +++ b/Packages/api-client/src/schema.d.ts @@ -966,6 +966,83 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/workspaces/{id}/favorites": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + /** The caller's favorite pages in the workspace, newest first */ + get: operations["listFavorites"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/workspaces/{id}/recent": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + /** Pages the caller visited last in the workspace */ + get: operations["listRecentPages"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/pages/{id}/favorite": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + get?: never; + /** Add the page to the caller's favorites */ + put: operations["addFavorite"]; + post?: never; + /** Remove the page from the caller's favorites */ + delete: operations["removeFavorite"]; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/pages/{id}/visit": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + get?: never; + put?: never; + /** Note that the caller opened the page (for the recent list) */ + post: operations["recordPageVisit"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; } export type webhooks = Record; export interface components { @@ -1115,6 +1192,8 @@ export interface components { /** @description Root first */ ancestors: components["schemas"]["PageRef"][]; role: components["schemas"]["SpaceRole"]; + /** @description In the caller's favorites */ + favorite: boolean; }; PageContent: { /** @description Tiptap JSON with type "doc"; null for a page that was never edited */ @@ -1307,6 +1386,15 @@ export interface components { }; role: components["schemas"]["SpaceRole"]; }; + PageItem: { + id: string; + title: string; + icon: string; + space: string; + spaceName: string; + /** @description When it was favorited */ + at: string; + }; }; responses: { /** @description Signed in */ @@ -3118,4 +3206,115 @@ export interface operations { 404: components["responses"]["Error"]; }; }; + listFavorites: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["PageItem"][]; + }; + }; + 404: components["responses"]["Error"]; + }; + }; + listRecentPages: { + parameters: { + query?: { + limit?: number; + }; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["PageItem"][]; + }; + }; + 404: components["responses"]["Error"]; + }; + }; + addFavorite: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Added */ + 204: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + 404: components["responses"]["Error"]; + }; + }; + removeFavorite: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Removed */ + 204: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + 404: components["responses"]["Error"]; + }; + }; + recordPageVisit: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Recorded */ + 204: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + 404: components["responses"]["Error"]; + }; + }; } diff --git a/Packages/ui/src/DwIcon.vue b/Packages/ui/src/DwIcon.vue index 25ac37b..4fe0c1b 100644 --- a/Packages/ui/src/DwIcon.vue +++ b/Packages/ui/src/DwIcon.vue @@ -4,7 +4,10 @@ import { computed } from "vue"; import { iconPaths, type IconName } from "./icons"; // 16 in tree rows and small buttons, 18 in buttons, 20 in callouts and menus. -const props = withDefaults(defineProps<{ name: IconName; size?: number; label?: string }>(), { size: 18 }); +// filled paints the shape too, for on/off states such as a favorite star. +const props = withDefaults(defineProps<{ name: IconName; size?: number; label?: string; filled?: boolean }>(), { + size: 18, +}); const paths = computed(() => iconPaths[props.name] ?? iconPaths.page); @@ -14,7 +17,7 @@ const paths = computed(() => iconPaths[props.name] ?? iconPaths.page); :width="size" :height="size" viewBox="0 0 24 24" - fill="none" + :fill="filled ? 'currentColor' : 'none'" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" diff --git a/Packages/ui/src/icons.ts b/Packages/ui/src/icons.ts index 0bde9f2..9157ec0 100644 --- a/Packages/ui/src/icons.ts +++ b/Packages/ui/src/icons.ts @@ -50,6 +50,38 @@ export const iconPaths = { moon: ["M19.5 14.5A8 8 0 0 1 9.5 4.5a8 8 0 1 0 10 10z"], monitor: ["M4 5h16v11H4z", "M9 20h6", "M12 16v4"], selector: ["M8 9l4-4 4 4", "M8 15l4 4 4-4"], + // Phase 1: favorites, sharing, files, comments and editor formatting. + star: ["M12 4l2.5 5.2 5.5.8-4 3.9.9 5.6L12 16.9l-4.9 2.6.9-5.6-4-3.9 5.5-.8z"], + clock: ["M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z", "M12 7v5l3 2"], + share: ["M12 4v11", "M8 8l4-4 4 4", "M6 13v7h12v-7"], + link: ["M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1", "M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1"], + upload: ["M12 16V4", "M7 9l5-5 5 5", "M4 20h16"], + download: ["M12 4v12", "M7 11l5 5 5-5", "M4 20h16"], + file: ["M6 3h8l4 4v14H6z", "M14 3v4h4"], + paperclip: ["M18 11.5l-6.4 6.4a4.2 4.2 0 0 1-6-6l7-7a2.8 2.8 0 0 1 4 4l-7 7a1.4 1.4 0 0 1-2-2l6.4-6.4"], + comment: ["M5 5h14v10H9l-4 4z"], + at: ["M12 8a4 4 0 1 0 0 8a4 4 0 1 0 0-8z", "M16 12v1.5a2.5 2.5 0 0 0 5 0V12a9 9 0 1 0-3.5 7.1"], + bold: ["M7 5h6a3.5 3.5 0 0 1 0 7H7z", "M7 12h7a3.5 3.5 0 0 1 0 7H7z"], + italic: ["M10 5h8", "M6 19h8", "M14 5l-4 14"], + strike: [ + "M5 12h14", + "M16 7.5A3.5 3 0 0 0 12.5 5h-1A3.5 3 0 0 0 8 8c0 4 8 3 8 7.5a3.5 3.5 0 0 1-3.5 3.5h-1A3.5 3 0 0 1 8 16.5", + ], + underline: ["M7 4v7a5 5 0 0 0 10 0V4", "M5 20h14"], + "list-ordered": ["M10 6h10", "M10 12h10", "M10 18h10", "M4 5l1.5-1v5", "M4 15.5a1.5 1.5 0 0 1 3 .5L4 19h3"], + divider: ["M4 12h16"], + globe: [ + "M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z", + "M3 12h18", + "M12 3c2.5 2.5 3.5 5.5 3.5 9s-1 6.5-3.5 9", + "M12 3C9.5 5.5 8.5 8.5 8.5 12s1 6.5 3.5 9", + ], + users: [ + "M9 11a3.5 3.5 0 1 0 0-7a3.5 3.5 0 1 0 0 7z", + "M3 20a6 6 0 0 1 12 0", + "M16 4.5a3.5 3.5 0 0 1 0 6.5", + "M18 14a6 6 0 0 1 3 6", + ], } as const; export type IconName = keyof typeof iconPaths; diff --git a/Phone-App/lib/api/generated/models.dart b/Phone-App/lib/api/generated/models.dart index f8f9f85..26d4edc 100644 --- a/Phone-App/lib/api/generated/models.dart +++ b/Phone-App/lib/api/generated/models.dart @@ -635,6 +635,7 @@ class Page { required this.inTrash, required this.ancestors, required this.role, + required this.favorite, }); factory Page.fromJson(Map json) => Page( @@ -652,6 +653,7 @@ class Page { .map((e) => PageRef.fromJson(e as Map)) .toList(), role: SpaceRole.fromJson(json['role'] as String), + favorite: json['favorite'] as bool, ); final String id; @@ -681,6 +683,9 @@ class Page { final SpaceRole role; + /// In the caller's favorites + final bool favorite; + Map toJson() => { 'id': id, 'workspace': workspace, @@ -694,6 +699,7 @@ class Page { 'inTrash': inTrash, 'ancestors': ancestors.map((e) => e.toJson()).toList(), 'role': role.toJson(), + 'favorite': favorite, }; } @@ -1558,3 +1564,45 @@ class SpaceGroup { 'role': role.toJson(), }; } + +class PageItem { + const PageItem({ + required this.id, + required this.title, + required this.icon, + required this.space, + required this.spaceName, + required this.at, + }); + + factory PageItem.fromJson(Map json) => PageItem( + id: json['id'] as String, + title: json['title'] as String, + icon: json['icon'] as String, + space: json['space'] as String, + spaceName: json['spaceName'] as String, + at: json['at'] as String, + ); + + final String id; + + final String title; + + final String icon; + + final String space; + + final String spaceName; + + /// When it was favorited + final String at; + + Map toJson() => { + 'id': id, + 'title': title, + 'icon': icon, + 'space': space, + 'spaceName': spaceName, + 'at': at, + }; +} diff --git a/Server/internal/api/api.gen.go b/Server/internal/api/api.gen.go index fffbb62..9745fbb 100644 --- a/Server/internal/api/api.gen.go +++ b/Server/internal/api/api.gen.go @@ -379,8 +379,11 @@ type Page struct { // DeletedAt When the page itself was trashed; empty otherwise DeletedAt string `json:"deletedAt"` - Icon string `json:"icon"` - Id string `json:"id"` + + // Favorite In the caller's favorites + Favorite bool `json:"favorite"` + Icon string `json:"icon"` + Id string `json:"id"` // InTrash The page or one of its ancestors is in the trash InTrash bool `json:"inTrash"` @@ -399,6 +402,17 @@ type PageContent struct { Updated string `json:"updated"` } +// PageItem defines model for PageItem. +type PageItem struct { + // At When it was favorited + At string `json:"at"` + Icon string `json:"icon"` + Id string `json:"id"` + Space string `json:"space"` + SpaceName string `json:"spaceName"` + Title string `json:"title"` +} + // PageNode defines model for PageNode. type PageNode struct { Icon string `json:"icon"` @@ -763,6 +777,11 @@ type SetWorkspaceMemberJSONBody struct { Role WorkspaceRole `json:"role"` } +// ListRecentPagesParams defines parameters for ListRecentPages. +type ListRecentPagesParams struct { + Limit *int `form:"limit,omitempty" json:"limit,omitempty"` +} + // CreateSpaceJSONBody defines parameters for CreateSpace. type CreateSpaceJSONBody struct { Description *string `json:"description,omitempty"` diff --git a/Server/internal/directory/favorites.go b/Server/internal/directory/favorites.go new file mode 100644 index 0000000..9ced30a --- /dev/null +++ b/Server/internal/directory/favorites.go @@ -0,0 +1,183 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package directory + +import ( + "context" + "fmt" + "time" + + "docwell/server/internal/access" + "docwell/server/internal/store/pocketbase" +) + +// ---- Favorites and recent pages -------------------------------------------- +// +// Both are per user. Lists are filtered by the caller's current rights, so a +// page that was moved out of reach, or trashed, quietly drops out. + +// maxRecent is how many recently visited pages a workspace keeps per user. +const maxRecent = 50 + +// PageItem is a page in a favorites or recent list. +type PageItem struct { + ID string `json:"id"` + Title string `json:"title"` + Icon string `json:"icon"` + Space string `json:"space"` + SpaceName string `json:"spaceName"` + // At is when it was added to favorites, or last visited. + At string `json:"at"` +} + +// userPageRecord is a favorites or page_visits row with its page inlined +// (without the page's large content fields). +type userPageRecord struct { + ID string `json:"id"` + Page string `json:"page"` + Created string `json:"created"` + Visited string `json:"visited"` + Expand struct { + Page *pageRecord `json:"page"` + } `json:"expand"` +} + +const userPageFields = "id,page,created,visited," + + "expand.page.id,expand.page.space,expand.page.title,expand.page.icon,expand.page.deleted_at" + +// visibleItems keeps the rows whose page c can still open, with space names. +func (s *Service) visibleItems(ctx context.Context, c access.Caller, rows []userPageRecord, at func(userPageRecord) string) []PageItem { + spaceNames := map[string]string{} // space id → name, "" = no access + out := []PageItem{} + for _, r := range rows { + p := r.Expand.Page + if p == nil || p.DeletedAt != "" { + continue + } + name, seen := spaceNames[p.Space] + if !seen { + if a, err := s.spaceFor(ctx, c, p.Space); err == nil { + name = a.space.Name + } + spaceNames[p.Space] = name + } + if name == "" { + continue + } + out = append(out, PageItem{ID: p.ID, Title: p.Title, Icon: p.Icon, Space: p.Space, SpaceName: name, At: at(r)}) + } + return out +} + +// ListFavorites lists the caller's favorite pages in a workspace, newest first. +func (s *Service) ListFavorites(ctx context.Context, c access.Caller, wsID string) ([]PageItem, error) { + ws, _, err := s.workspaceFor(ctx, c, wsID) + if err != nil { + return nil, err + } + rows, err := listAll[userPageRecord](ctx, s, "favorites", pocketbase.ListOptions{ + Filter: fmt.Sprintf("user = '%s' && workspace = '%s'", c.ID, ws.ID), Sort: "-created", + Expand: "page", Fields: userPageFields, + }) + if err != nil { + return nil, err + } + return s.visibleItems(ctx, c, rows, func(r userPageRecord) string { return r.Created }), nil +} + +func (s *Service) favoriteRow(ctx context.Context, userID, pageID string) (string, error) { + res, err := pocketbase.List[userPageRecord](ctx, s.pb, "favorites", pocketbase.ListOptions{ + PerPage: 1, Filter: fmt.Sprintf("user = '%s' && page = '%s'", userID, pageID), Fields: "id", + }) + if err != nil || len(res.Items) == 0 { + return "", err + } + return res.Items[0].ID, nil +} + +// SetFavorite adds a page the caller can open to their favorites, or removes it. +func (s *Service) SetFavorite(ctx context.Context, c access.Caller, pageID string, on bool) error { + p, _, err := s.pageFor(ctx, c, pageID) + if err != nil { + return err + } + id, err := s.favoriteRow(ctx, c.ID, p.ID) + if err != nil { + return err + } + switch { + case on && id == "": + _, err = pocketbase.Create[userPageRecord](ctx, s.pb, "favorites", map[string]any{ + "user": c.ID, "page": p.ID, "workspace": p.Workspace, + }) + case !on && id != "": + err = s.pb.Delete(ctx, "favorites", id) + } + return mapPB(err, "page not found") +} + +// RecordVisit notes that the caller opened a page, for their recent list. +func (s *Service) RecordVisit(ctx context.Context, c access.Caller, pageID string) error { + p, _, err := s.pageFor(ctx, c, pageID) + if err != nil { + return err + } + res, err := pocketbase.List[userPageRecord](ctx, s.pb, "page_visits", pocketbase.ListOptions{ + PerPage: 1, Filter: fmt.Sprintf("user = '%s' && page = '%s'", c.ID, p.ID), Fields: "id", + }) + if err != nil { + return err + } + now := pbTime(time.Now()) + if len(res.Items) > 0 { + _, err = pocketbase.Update[userPageRecord](ctx, s.pb, "page_visits", res.Items[0].ID, map[string]any{"visited": now}) + return mapPB(err, "page not found") + } + if _, err := pocketbase.Create[userPageRecord](ctx, s.pb, "page_visits", map[string]any{ + "user": c.ID, "page": p.ID, "workspace": p.Workspace, "visited": now, + }); err != nil { + return mapPB(err, "page not found") + } + s.trimVisits(ctx, c.ID, p.Workspace) + return nil +} + +// trimVisits keeps the newest maxRecent visits per user and workspace (best effort). +func (s *Service) trimVisits(ctx context.Context, userID, wsID string) { + res, err := pocketbase.List[userPageRecord](ctx, s.pb, "page_visits", pocketbase.ListOptions{ + Page: 2, PerPage: maxRecent, Filter: fmt.Sprintf("user = '%s' && workspace = '%s'", userID, wsID), + Sort: "-visited", Fields: "id", + }) + if err != nil { + return + } + for _, r := range res.Items { + _ = s.pb.Delete(ctx, "page_visits", r.ID) + } +} + +// ListRecent lists the pages the caller visited last in a workspace. +func (s *Service) ListRecent(ctx context.Context, c access.Caller, wsID string, limit int) ([]PageItem, error) { + ws, _, err := s.workspaceFor(ctx, c, wsID) + if err != nil { + return nil, err + } + if limit <= 0 || limit > maxRecent { + limit = 20 + } + res, err := pocketbase.List[userPageRecord](ctx, s.pb, "page_visits", pocketbase.ListOptions{ + PerPage: maxRecent, Filter: fmt.Sprintf("user = '%s' && workspace = '%s'", c.ID, ws.ID), Sort: "-visited", + Expand: "page", Fields: userPageFields, + }) + if err != nil { + return nil, err + } + out := s.visibleItems(ctx, c, res.Items, func(r userPageRecord) string { return r.Visited }) + return out[:min(limit, len(out))], nil +} + +// isFavorite reports whether the caller has the page in their favorites. +func (s *Service) isFavorite(ctx context.Context, userID, pageID string) bool { + id, err := s.favoriteRow(ctx, userID, pageID) + return err == nil && id != "" +} diff --git a/Server/internal/directory/pages.go b/Server/internal/directory/pages.go index d7a49f3..a747876 100644 --- a/Server/internal/directory/pages.go +++ b/Server/internal/directory/pages.go @@ -74,6 +74,8 @@ type Page struct { InTrash bool `json:"inTrash"` Ancestors []PageRef `json:"ancestors"` Role string `json:"role"` + // Favorite is whether the caller has the page in their favorites. + Favorite bool `json:"favorite"` } type TrashedPage struct { @@ -199,7 +201,7 @@ func (s *Service) GetPage(ctx context.Context, c access.Caller, id string) (Page page := Page{ ID: p.ID, Workspace: p.Workspace, Space: p.Space, Parent: p.Parent, Title: p.Title, Icon: p.Icon, Created: p.Created, Updated: p.Updated, DeletedAt: p.DeletedAt, InTrash: p.DeletedAt != "", - Ancestors: []PageRef{}, Role: a.role, + Ancestors: []PageRef{}, Role: a.role, Favorite: s.isFavorite(ctx, c.ID, p.ID), } parent := p.Parent for depth := 0; parent != "" && depth < 100; depth++ { diff --git a/Server/internal/httpapi/auth.go b/Server/internal/httpapi/auth.go index 248588d..7a984d4 100644 --- a/Server/internal/httpapi/auth.go +++ b/Server/internal/httpapi/auth.go @@ -144,6 +144,7 @@ func (a *api) routes(mux *routeMux) { a.settingsRoutes(mux) a.inviteRoutes(mux) a.groupRoutes(mux) + a.favoriteRoutes(mux) } func (a *api) decode(w http.ResponseWriter, r *http.Request, v any) bool { diff --git a/Server/internal/httpapi/directory.go b/Server/internal/httpapi/directory.go index f5e5cb0..2a14138 100644 --- a/Server/internal/httpapi/directory.go +++ b/Server/internal/httpapi/directory.go @@ -35,6 +35,7 @@ type DirectoryService interface { SpaceService InviteService GroupService + FavoriteService } func caller(r *http.Request) access.Caller { diff --git a/Server/internal/httpapi/favorites.go b/Server/internal/httpapi/favorites.go new file mode 100644 index 0000000..50398cb --- /dev/null +++ b/Server/internal/httpapi/favorites.go @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package httpapi + +import ( + "context" + "net/http" + "strconv" + + "docwell/server/internal/access" + "docwell/server/internal/directory" +) + +// FavoriteService is the part of directory.Service for favorites and recent pages. +type FavoriteService interface { + ListFavorites(ctx context.Context, c access.Caller, wsID string) ([]directory.PageItem, error) + SetFavorite(ctx context.Context, c access.Caller, pageID string, on bool) error + RecordVisit(ctx context.Context, c access.Caller, pageID string) error + ListRecent(ctx context.Context, c access.Caller, wsID string, limit int) ([]directory.PageItem, error) +} + +func (a *api) favoriteRoutes(mux *routeMux) { + mux.HandleFunc("GET /api/v1/workspaces/{id}/favorites", a.requireUser(func(w http.ResponseWriter, r *http.Request) { + list, err := a.dir.ListFavorites(r.Context(), caller(r), r.PathValue("id")) + a.respond(w, list, err) + })) + mux.HandleFunc("GET /api/v1/workspaces/{id}/recent", a.requireUser(func(w http.ResponseWriter, r *http.Request) { + limit, _ := strconv.Atoi(r.URL.Query().Get("limit")) + list, err := a.dir.ListRecent(r.Context(), caller(r), r.PathValue("id"), limit) + a.respond(w, list, err) + })) + mux.HandleFunc("PUT /api/v1/pages/{id}/favorite", a.requireUser(func(w http.ResponseWriter, r *http.Request) { + a.respondNoContent(w, a.dir.SetFavorite(r.Context(), caller(r), r.PathValue("id"), true)) + })) + mux.HandleFunc("DELETE /api/v1/pages/{id}/favorite", a.requireUser(func(w http.ResponseWriter, r *http.Request) { + a.respondNoContent(w, a.dir.SetFavorite(r.Context(), caller(r), r.PathValue("id"), false)) + })) + mux.HandleFunc("POST /api/v1/pages/{id}/visit", a.requireUser(func(w http.ResponseWriter, r *http.Request) { + a.respondNoContent(w, a.dir.RecordVisit(r.Context(), caller(r), r.PathValue("id"))) + })) +} diff --git a/Web-App/frontend/src/components/AppLayout.vue b/Web-App/frontend/src/components/AppLayout.vue index 6d8f1bb..a44ea44 100644 --- a/Web-App/frontend/src/components/AppLayout.vue +++ b/Web-App/frontend/src/components/AppLayout.vue @@ -6,6 +6,7 @@ import { useRoute, useRouter } from "vue-router"; import { useFormErrors } from "../composables/useFormErrors"; import { SIDEBAR_DEFAULT, clampWidth, useSidebar } from "../composables/useSidebar"; import { useAuthStore } from "../stores/auth"; +import { useFavoritesStore } from "../stores/favorites"; import { useSpacesStore } from "../stores/spaces"; import { atLeast, useWorkspacesStore } from "../stores/workspaces"; import PageTreeNode from "./PageTreeNode.vue"; @@ -18,6 +19,7 @@ import WorkspaceSwitcher from "./WorkspaceSwitcher.vue"; const auth = useAuthStore(); const workspaces = useWorkspacesStore(); const spaces = useSpacesStore(); +const favorites = useFavoritesStore(); const router = useRouter(); const route = useRoute(); const { mode } = useTheme(); @@ -34,7 +36,11 @@ function showError(e: unknown) { onMounted(() => workspaces.load().catch(showError)); watch( () => workspaces.current?.id, - (id) => id && spaces.load(id).catch(showError), + (id) => { + if (!id) return; + spaces.load(id).catch(showError); + favorites.load(id).catch(showError); + }, { immediate: true }, ); watch( @@ -190,6 +196,24 @@ function signOut() { {{ error }}