Files
Docwell/Server/internal/directory/pages.go
T
tajniak81andClaude Opus 5.5 2b78c167e2 Add comment threads, reactions, notifications and page watching
Comments are now threads: replies hang off a thread's first comment,
which alone points at text and can be resolved. Authors can edit their
own comments, and anyone who can comment can react with an emoji.
Resolved threads stop lighting text in the editor and fold away in the
panel. Comments can @mention people.

People watch the pages they create or comment on, and can watch or mute
a page from its menu. Muting is remembered. The inbox collects comments
on watched pages, replies in your threads, mentions (in comments and in
page text), pages shared with you and resolved threads. It shows an
unread badge in the sidebar, polled every minute, and links straight to
the thread. Nobody hears about their own actions or about pages they
cannot open, and a notification hides its text once access is lost.

Unread notifications are emailed as a digest every few minutes unless
the person turns that off. Read ones are pruned after 90 days. The jobs
registry can now run jobs on a timer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 22:27:55 +01:00

540 lines
16 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package directory
import (
"context"
"fmt"
"sort"
"strings"
"time"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/store/pocketbase"
)
// ---- Pages -----------------------------------------------------------------
//
// Pages form a tree per space (pages.parent, "" = top level), ordered among
// siblings by pages.position (see position.go). Trashing sets deleted_at on
// one page; its subtree is hidden with it and comes back when it is restored.
// Purging deletes the record, and PocketBase cascades to the subtree.
// pageFields skips the large content columns.
const pageFields = "id,workspace,space,parent,title,icon,position,restricted,creator,last_editor,deleted_at,created,updated"
type pageRecord struct {
ID string `json:"id"`
Workspace string `json:"workspace"`
Space string `json:"space"`
Parent string `json:"parent"`
Title string `json:"title"`
Icon string `json:"icon"`
Position string `json:"position"`
Restricted bool `json:"restricted"`
Creator string `json:"creator"`
LastEditor string `json:"last_editor"`
DeletedAt string `json:"deleted_at"`
Created string `json:"created"`
Updated string `json:"updated"`
}
// PageNode is one entry of a space's page tree.
type PageNode struct {
ID string `json:"id"`
Parent string `json:"parent"`
Title string `json:"title"`
Icon string `json:"icon"`
Position string `json:"position"`
// Restricted is set on the page that is restricted itself (not its subtree).
Restricted bool `json:"restricted"`
Updated string `json:"updated"`
}
func (r pageRecord) node() PageNode {
return PageNode{ID: r.ID, Parent: r.Parent, Title: r.Title, Icon: r.Icon, Position: r.Position, Restricted: r.Restricted, Updated: r.Updated}
}
type PageRef struct {
ID string `json:"id"`
Title string `json:"title"`
Icon string `json:"icon"`
}
// Page is one page with its breadcrumb trail and the caller's space role.
type Page struct {
ID string `json:"id"`
Workspace string `json:"workspace"`
Space string `json:"space"`
Parent string `json:"parent"`
Title string `json:"title"`
Icon string `json:"icon"`
Created string `json:"created"`
Updated string `json:"updated"`
DeletedAt string `json:"deletedAt"`
// InTrash is true when the page or one of its ancestors is in the trash.
InTrash bool `json:"inTrash"`
Ancestors []PageRef `json:"ancestors"`
Role string `json:"role"`
// Restricted is true when the page or an ancestor is restricted.
Restricted bool `json:"restricted"`
// Favorite is whether the caller has the page in their favorites.
Favorite bool `json:"favorite"`
}
type TrashedPage struct {
ID string `json:"id"`
Title string `json:"title"`
Icon string `json:"icon"`
DeletedAt string `json:"deletedAt"`
}
func (s *Service) getPage(ctx context.Context, id string) (pageRecord, error) {
if !validID(id) {
return pageRecord{}, apperr.NotFound("page not found")
}
res, err := pocketbase.List[pageRecord](ctx, s.pb, "pages", pocketbase.ListOptions{
PerPage: 1, Filter: fmt.Sprintf("id = '%s'", id), Fields: pageFields,
})
if err != nil {
return pageRecord{}, err
}
if len(res.Items) == 0 {
return pageRecord{}, apperr.NotFound("page not found")
}
return res.Items[0], nil
}
// pageFor loads a page and c's access to it; a.role is c's role on the page
// (see pageAccess).
func (s *Service) pageFor(ctx context.Context, c access.Caller, id string) (pageRecord, spaceAccess, error) {
p, a, _, err := s.pageAccess(ctx, c, id)
return p, a, err
}
// tree is every page of one space, live or trashed.
type tree struct {
byID map[string]pageRecord
children map[string][]pageRecord // parent id ("" = top level) → live children in order
}
func (s *Service) loadTree(ctx context.Context, spaceID string) (tree, error) {
all, err := listAll[pageRecord](ctx, s, "pages", pocketbase.ListOptions{
Filter: fmt.Sprintf("space = '%s'", spaceID), Fields: pageFields,
})
if err != nil {
return tree{}, err
}
t := tree{byID: make(map[string]pageRecord, len(all)), children: map[string][]pageRecord{}}
for _, p := range all {
t.byID[p.ID] = p
}
for _, p := range all {
if p.DeletedAt == "" {
t.children[p.Parent] = append(t.children[p.Parent], p)
}
}
for _, list := range t.children {
sort.Slice(list, func(i, j int) bool {
if list[i].Position != list[j].Position {
return list[i].Position < list[j].Position
}
return list[i].ID < list[j].ID
})
}
return t, nil
}
// live reports whether a page and all of its ancestors are out of the trash.
func (t tree) live(id string) bool {
for depth := 0; id != "" && depth < 1000; depth++ {
p, ok := t.byID[id]
if !ok || p.DeletedAt != "" {
return false
}
id = p.Parent
}
return true
}
// within reports whether page id is ancestor or the page itself.
func (t tree) within(id, ancestor string) bool {
for depth := 0; id != "" && depth < 1000; depth++ {
if id == ancestor {
return true
}
id = t.byID[id].Parent
}
return false
}
// restrictedBelow reports whether page id, or an ancestor of it below
// ancestor, is restricted.
func (t tree) restrictedBelow(id, ancestor string) bool {
for depth := 0; id != "" && id != ancestor && depth < 1000; depth++ {
if t.byID[id].Restricted {
return true
}
id = t.byID[id].Parent
}
return false
}
// ListPages returns the space's live pages c can open, siblings in order;
// clients build the tree. A visible page under hidden ones hangs from its
// nearest visible ancestor (the top level when there is none).
func (s *Service) ListPages(ctx context.Context, c access.Caller, spaceID string) ([]PageNode, error) {
a, rules, err := s.spaceRules(ctx, c, spaceID)
if err != nil {
return nil, err
}
t, err := s.loadTree(ctx, a.space.ID)
if err != nil {
return nil, err
}
out := []PageNode{}
var walk func(parent, shownParent string)
walk = func(parent, shownParent string) {
for _, p := range t.children[parent] {
under := shownParent
if rules.role(p.ID) != "" {
n := p.node()
n.Parent = shownParent
out = append(out, n)
under = p.ID
}
walk(p.ID, under)
}
}
walk("", "")
return out, nil
}
// GetPage returns a page with its breadcrumbs.
func (s *Service) GetPage(ctx context.Context, c access.Caller, id string) (Page, error) {
p, a, rules, err := s.pageAccess(ctx, c, id)
if err != nil {
return Page{}, err
}
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, Restricted: p.Restricted, Favorite: s.isFavorite(ctx, c.ID, p.ID),
}
parent := p.Parent
for depth := 0; parent != "" && depth < 100; depth++ {
anc, err := s.getPage(ctx, parent)
if err != nil {
break
}
page.InTrash = page.InTrash || anc.DeletedAt != ""
page.Restricted = page.Restricted || anc.Restricted
// Breadcrumbs leave out pages the caller cannot open.
if rules.role(anc.ID) != "" {
page.Ancestors = append([]PageRef{{ID: anc.ID, Title: anc.Title, Icon: anc.Icon}}, page.Ancestors...)
}
parent = anc.Parent
}
return page, nil
}
// placement computes the position for a page at index among siblings (which
// must not contain the page itself). When keys get too long it renumbers the
// siblings and returns the updates to apply first.
func placement(siblings []pageRecord, index int) (string, map[string]string) {
index = min(max(index, 0), len(siblings))
before, after := "", ""
if index > 0 {
before = siblings[index-1].Position
}
if index < len(siblings) {
after = siblings[index].Position
}
if before < after || after == "" {
if key := keyBetween(before, after); len(key) <= maxKeyLen {
return key, nil
}
}
keys := evenKeys(len(siblings) + 1)
renumber := map[string]string{}
for i, sib := range siblings {
k := keys[i]
if i >= index {
k = keys[i+1]
}
if sib.Position != k {
renumber[sib.ID] = k
}
}
return keys[index], renumber
}
func (s *Service) renumber(ctx context.Context, updates map[string]string) error {
for id, pos := range updates {
if _, err := pocketbase.Update[pageRecord](ctx, s.pb, "pages", id, map[string]any{"position": pos}); err != nil {
return mapPB(err, "page not found")
}
}
return nil
}
func cleanTitle(title string) (string, error) {
title = strings.TrimSpace(title)
if len(title) > 500 {
return "", apperr.InvalidFields(map[string]string{"title": "Title is too long (max 500)."})
}
return title, nil
}
// checkParent validates a new parent ("" = top level) inside t; moving (the
// page being moved, "" when creating) may not go under itself.
func checkParent(t tree, parent, moving string) error {
if parent == "" {
return nil
}
if _, ok := t.byID[parent]; !ok || !t.live(parent) {
return apperr.InvalidFields(map[string]string{"parent": "Parent page not found in this space."})
}
if moving != "" && t.within(parent, moving) {
return apperr.InvalidFields(map[string]string{"parent": "A page cannot be moved inside itself."})
}
return nil
}
type CreatePageInput struct {
Parent string `json:"parent"`
Title string `json:"title"`
// Index among the parent's children; nil appends at the end.
Index *int `json:"index"`
}
// CreatePage adds a page to a space (editor of the parent page, or of the
// space for a top-level page).
func (s *Service) CreatePage(ctx context.Context, c access.Caller, spaceID string, in CreatePageInput) (Page, error) {
a, rules, err := s.spaceRules(ctx, c, spaceID)
if err != nil {
return Page{}, err
}
if err := access.CreatePageUnder(a.role, rules.role(in.Parent), in.Parent == ""); err != nil {
return Page{}, err
}
title, err := cleanTitle(in.Title)
if err != nil {
return Page{}, err
}
t, err := s.loadTree(ctx, a.space.ID)
if err != nil {
return Page{}, err
}
if err := checkParent(t, in.Parent, ""); err != nil {
return Page{}, err
}
siblings := t.children[in.Parent]
index := len(siblings)
if in.Index != nil {
index = *in.Index
}
pos, renumber := placement(siblings, index)
if err := s.renumber(ctx, renumber); err != nil {
return Page{}, err
}
body := map[string]any{
"workspace": a.space.Workspace, "space": a.space.ID, "title": title, "position": pos,
"creator": c.ID, "last_editor": c.ID,
// Mention tracking starts empty, so first mentions notify (see PageSaved).
"mentions": []string{},
}
if in.Parent != "" {
body["parent"] = in.Parent
}
rec, err := pocketbase.Create[pageRecord](ctx, s.pb, "pages", body)
if err != nil {
return Page{}, mapPB(err, "page not found")
}
s.autoWatch(ctx, rec.ID, c.ID)
return s.GetPage(ctx, c, rec.ID)
}
type UpdatePageInput struct {
Title *string `json:"title"`
Icon *string `json:"icon"`
}
// UpdatePage renames a page or changes its icon (editor).
func (s *Service) UpdatePage(ctx context.Context, c access.Caller, id string, in UpdatePageInput) (Page, error) {
p, a, err := s.pageFor(ctx, c, id)
if err != nil {
return Page{}, err
}
if err := access.EditPages(a.role); err != nil {
return Page{}, err
}
if p.DeletedAt != "" {
return Page{}, apperr.Invalid("restore the page from the trash first")
}
patch := map[string]any{"last_editor": c.ID}
if in.Title != nil {
title, err := cleanTitle(*in.Title)
if err != nil {
return Page{}, err
}
patch["title"] = title
}
if in.Icon != nil {
icon := strings.TrimSpace(*in.Icon)
if len(icon) > 32 {
return Page{}, apperr.InvalidFields(map[string]string{"icon": "Icon is too long."})
}
patch["icon"] = icon
}
if _, err := pocketbase.Update[pageRecord](ctx, s.pb, "pages", p.ID, patch); err != nil {
return Page{}, mapPB(err, "page not found")
}
return s.GetPage(ctx, c, p.ID)
}
type MovePageInput struct {
// Parent is the new parent ("" = top level of the space).
Parent string `json:"parent"`
// Index among the new parent's other children.
Index int `json:"index"`
}
// MovePage moves a page (with its subtree) within its space (editor of the
// page and of where it goes).
func (s *Service) MovePage(ctx context.Context, c access.Caller, id string, in MovePageInput) (Page, error) {
p, a, rules, err := s.pageAccess(ctx, c, id)
if err != nil {
return Page{}, err
}
if err := access.EditPages(a.role); err != nil {
return Page{}, err
}
if err := access.CreatePageUnder(a.spaceRole, rules.role(in.Parent), in.Parent == ""); err != nil {
return Page{}, err
}
t, err := s.loadTree(ctx, a.space.ID)
if err != nil {
return Page{}, err
}
if !t.live(p.ID) {
return Page{}, apperr.Invalid("restore the page from the trash first")
}
if err := checkParent(t, in.Parent, p.ID); err != nil {
return Page{}, err
}
siblings := make([]pageRecord, 0, len(t.children[in.Parent]))
for _, sib := range t.children[in.Parent] {
if sib.ID != p.ID {
siblings = append(siblings, sib)
}
}
pos, renumber := placement(siblings, in.Index)
if err := s.renumber(ctx, renumber); err != nil {
return Page{}, err
}
if _, err := pocketbase.Update[pageRecord](ctx, s.pb, "pages", p.ID, map[string]any{
"parent": in.Parent, "position": pos,
}); err != nil {
return Page{}, mapPB(err, "page not found")
}
return s.GetPage(ctx, c, p.ID)
}
// pbTime formats t the way PocketBase stores dates.
func pbTime(t time.Time) string { return t.UTC().Format("2006-01-02 15:04:05.000Z") }
// TrashPage moves a page and its subtree to the trash (editor). Idempotent.
func (s *Service) TrashPage(ctx context.Context, c access.Caller, id string) error {
p, a, err := s.pageFor(ctx, c, id)
if err != nil {
return err
}
if err := access.EditPages(a.role); err != nil {
return err
}
if p.DeletedAt != "" {
return nil
}
_, err = pocketbase.Update[pageRecord](ctx, s.pb, "pages", p.ID, map[string]any{
"deleted_at": pbTime(time.Now()), "last_editor": c.ID,
})
if err == nil {
s.docs.Kick(p.ID)
}
return mapPB(err, "page not found")
}
// RestorePage takes a page out of the trash (editor). If its parent is gone or
// still trashed, it goes to the end of the top level.
func (s *Service) RestorePage(ctx context.Context, c access.Caller, id string) (Page, error) {
p, a, err := s.pageFor(ctx, c, id)
if err != nil {
return Page{}, err
}
if err := access.EditPages(a.role); err != nil {
return Page{}, err
}
if p.DeletedAt == "" {
return s.GetPage(ctx, c, p.ID)
}
t, err := s.loadTree(ctx, a.space.ID)
if err != nil {
return Page{}, err
}
patch := map[string]any{"deleted_at": "", "last_editor": c.ID}
if p.Parent != "" && !t.live(p.Parent) {
pos, renumber := placement(t.children[""], len(t.children[""]))
if err := s.renumber(ctx, renumber); err != nil {
return Page{}, err
}
patch["parent"], patch["position"] = "", pos
}
if _, err := pocketbase.Update[pageRecord](ctx, s.pb, "pages", p.ID, patch); err != nil {
return Page{}, mapPB(err, "page not found")
}
s.docs.Kick(p.ID)
return s.GetPage(ctx, c, p.ID)
}
// ListTrash lists a space's trashed pages c can open, newest first. Pages
// inside a trashed page are not listed separately: they come back with it.
func (s *Service) ListTrash(ctx context.Context, c access.Caller, spaceID string) ([]TrashedPage, error) {
a, rules, err := s.spaceRules(ctx, c, spaceID)
if err != nil {
return nil, err
}
t, err := s.loadTree(ctx, a.space.ID)
if err != nil {
return nil, err
}
out := []TrashedPage{}
for _, p := range t.byID {
if p.DeletedAt != "" && t.live(p.Parent) && rules.role(p.ID) != "" {
out = append(out, TrashedPage{ID: p.ID, Title: p.Title, Icon: p.Icon, DeletedAt: p.DeletedAt})
}
}
sort.Slice(out, func(i, j int) bool { return out[i].DeletedAt > out[j].DeletedAt })
return out, nil
}
// PurgePage permanently deletes a trashed page and its subtree (space admin).
func (s *Service) PurgePage(ctx context.Context, c access.Caller, id string) error {
p, a, err := s.pageFor(ctx, c, id)
if err != nil {
return err
}
if err := access.PurgePage(a.role); err != nil {
return err
}
if p.DeletedAt == "" {
return apperr.Invalid("move the page to the trash first")
}
if err := s.pb.Delete(ctx, "pages", p.ID); err != nil {
return mapPB(err, "page not found")
}
s.docs.Drop(p.ID)
return nil
}