Files
Docwell/Server/internal/directory/pages.go
T
tajniak81andClaude Opus 5.5 c98b127f1e
CI / go (Media) (push) Successful in 13m40s
CI / go (Server) (push) Failing after 23m20s
CI / go (Web-App) (push) Canceled after 0s
CI / frontend (push) Failing after 10m35s
Docs / build (push) Canceled after 0s
Docs / deploy (push) Canceled after 0s
CI / desktop (ubuntu-latest) (push) Failing after 3h4m42s
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
CI / mobile (push) Failing after 9m19s
CI / docker (push) Successful in 2h2m57s
Add columns, suggesting mode, verified pages, scanned PDF search and server translations
- Columns: /columns puts 2 to 4 columns side by side, with widths dragged
  between them; they stack on phones. HTML export and import keep them
  (also Notion column lists and Confluence page layouts).
- Suggesting mode: edits become suggested insertions and deletions that
  editors accept or reject one by one or all at once. Text only.
- Verified pages: editors verify a page for a while or without end; the
  verifier is notified when it runs out (migration 1764700000).
- Scanned PDFs attached to pages are read by AI for search where a
  workspace turns it on.
- The server writes error messages, emails, digests and phone
  notifications in English, Polish, German, French and Spanish; the apps
  send their language with each request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 08:38:08 +01:00

821 lines
26 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package directory
import (
"context"
"encoding/json"
"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.
// Archiving sets archived_at: the page and its subtree leave the page tree
// but stay readable (and read-only) until someone unarchives them.
// pageFields skips the large content columns.
const pageFields = "id,workspace,space,parent,title,icon,position,restricted,is_template,creator,last_editor,deleted_at,archived_at,pinned_at,full_width,font,default_mode,tags,journal_date,verified_by,verified_at,verified_until,created,updated"
// pageDetailFields adds the page's property values.
const pageDetailFields = pageFields + ",properties"
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"`
IsTemplate bool `json:"is_template"`
Creator string `json:"creator"`
LastEditor string `json:"last_editor"`
DeletedAt string `json:"deleted_at"`
ArchivedAt string `json:"archived_at"`
PinnedAt string `json:"pinned_at"`
FullWidth bool `json:"full_width"`
Font string `json:"font"`
// DefaultMode is "edgeless" for pages that open as a canvas; empty for text.
DefaultMode string `json:"default_mode"`
// Tags are tag ids; Properties maps workspace property ids to values
// (only loaded with pageDetailFields).
Tags []string `json:"tags"`
Properties map[string]json.RawMessage `json:"properties"`
JournalDate string `json:"journal_date"`
// Verification (verify.go): who vouched for the page, when, and until when.
VerifiedBy string `json:"verified_by"`
VerifiedAt string `json:"verified_at"`
VerifiedUntil string `json:"verified_until"`
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"`
// ArchivedAt is when the page itself was archived; Archived is true when
// it or one of its ancestors is.
ArchivedAt string `json:"archivedAt"`
Archived bool `json:"archived"`
Ancestors []PageRef `json:"ancestors"`
Role string `json:"role"`
// Restricted is true when the page or an ancestor is restricted.
Restricted bool `json:"restricted"`
// IsTemplate marks a page offered as a template for new pages.
IsTemplate bool `json:"isTemplate"`
// Favorite is whether the caller has the page in their favorites.
Favorite bool `json:"favorite"`
// PinnedAt is when the page was pinned to its space's home; empty if not.
PinnedAt string `json:"pinnedAt"`
// FullWidth and Font are how the page is shown to everyone.
FullWidth bool `json:"fullWidth"`
Font string `json:"font"`
// DefaultMode is the view the page opens in: "page" or "edgeless".
DefaultMode string `json:"defaultMode"`
// Tags are the page's tag ids, Properties its custom property values by
// property id (see properties.go).
Tags []string `json:"tags"`
Properties map[string]json.RawMessage `json:"properties"`
// JournalDate is the day (YYYY-MM-DD) of a journal page; empty otherwise.
JournalDate string `json:"journalDate"`
CreatedBy PageUser `json:"createdBy"`
LastEditedBy PageUser `json:"lastEditedBy"`
// Verification is who vouched for the page and until when (verify.go).
Verification PageVerification `json:"verification"`
}
// PageUser is a person named on a page; Name is empty when the account is gone.
type PageUser struct {
ID string `json:"id"`
Name string `json:"name"`
}
type TrashedPage struct {
ID string `json:"id"`
Title string `json:"title"`
Icon string `json:"icon"`
DeletedAt string `json:"deletedAt"`
}
type ArchivedPage struct {
ID string `json:"id"`
Title string `json:"title"`
Icon string `json:"icon"`
ArchivedAt string `json:"archivedAt"`
}
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: pageDetailFields,
})
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
}
// archived reports whether a page or one of its ancestors is archived.
func (t tree) archived(id string) bool {
for depth := 0; id != "" && depth < 1000; depth++ {
p, ok := t.byID[id]
if !ok {
return false
}
if p.ArchivedAt != "" {
return true
}
id = p.Parent
}
return false
}
// 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). Archived
// pages and their subtrees are left out.
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] {
if p.ArchivedAt != "" {
continue
}
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 != "",
ArchivedAt: p.ArchivedAt, Archived: p.ArchivedAt != "",
Ancestors: []PageRef{}, Role: a.role, Restricted: p.Restricted, IsTemplate: p.IsTemplate,
Favorite: s.isFavorite(ctx, c.ID, p.ID), PinnedAt: p.PinnedAt,
FullWidth: p.FullWidth, Font: p.Font, DefaultMode: pageMode(p.DefaultMode),
Tags: nonNil(p.Tags), Properties: p.Properties, JournalDate: p.JournalDate,
CreatedBy: s.pageUser(ctx, p.Creator), LastEditedBy: s.pageUser(ctx, p.LastEditor),
Verification: s.verification(ctx, p, time.Now()),
}
if page.Properties == nil {
page.Properties = map[string]json.RawMessage{}
}
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.Archived = page.Archived || anc.ArchivedAt != ""
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 t.archived(parent) {
return apperr.InvalidFields(map[string]string{"parent": "Unarchive the parent page first."})
}
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{}, "links": []string{},
}
if in.Parent != "" {
body["parent"] = in.Parent
}
// New pages open the way their workspace says (ADR-14).
if ws, err := s.getWorkspace(ctx, a.space.Workspace); err == nil && ws.DefaultPageMode == "edgeless" {
body["default_mode"] = "edgeless"
}
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)
s.emitPage(ctx, "page.created", rec, c.ID, nil)
return s.GetPage(ctx, c, rec.ID)
}
type UpdatePageInput struct {
Title *string `json:"title"`
Icon *string `json:"icon"`
IsTemplate *bool `json:"isTemplate"`
FullWidth *bool `json:"fullWidth"`
Font *string `json:"font"`
// DefaultMode is "page" or "edgeless".
DefaultMode *string `json:"defaultMode"`
// Tags replaces the page's tags (ids of the workspace's tags).
Tags *[]string `json:"tags"`
// Properties sets the named property values; null clears one.
Properties map[string]json.RawMessage `json:"properties"`
}
// UpdatePage renames a page, changes its icon or how it is shown (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")
}
if s.isArchived(ctx, p) {
return Page{}, apperr.Invalid("unarchive the page 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 in.IsTemplate != nil {
patch["is_template"] = *in.IsTemplate
}
if in.FullWidth != nil {
patch["full_width"] = *in.FullWidth
}
if in.Font != nil {
switch *in.Font {
case "", "serif", "mono":
patch["font"] = *in.Font
default:
return Page{}, apperr.InvalidFields(map[string]string{"font": "Font must be empty, serif or mono."})
}
}
if in.DefaultMode != nil {
switch *in.DefaultMode {
case "page":
patch["default_mode"] = ""
case "edgeless":
patch["default_mode"] = "edgeless"
default:
return Page{}, apperr.InvalidFields(map[string]string{"defaultMode": "Mode must be page or edgeless."})
}
}
if in.Tags != nil {
tags, err := s.checkTags(ctx, p.Workspace, *in.Tags)
if err != nil {
return Page{}, err
}
patch["tags"] = tags
}
if len(in.Properties) > 0 {
props, err := s.mergeProperties(ctx, p, in.Properties)
if err != nil {
return Page{}, err
}
patch["properties"] = props
}
updated, err := pocketbase.Update[pageRecord](ctx, s.pb, "pages", p.ID, patch)
if err != nil {
return Page{}, mapPB(err, "page not found")
}
s.emitPage(ctx, "page.updated", updated, c.ID, map[string]any{"change": "details"})
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 t.archived(p.ID) {
return Page{}, apperr.Invalid("unarchive the page 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
}
moved, err := pocketbase.Update[pageRecord](ctx, s.pb, "pages", p.ID, map[string]any{
"parent": in.Parent, "position": pos,
})
if err != nil {
return Page{}, mapPB(err, "page not found")
}
s.emitPage(ctx, "page.moved", moved, c.ID, map[string]any{"from": p.Parent})
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)
s.emitPage(ctx, "page.trashed", p, c.ID, nil)
}
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)
s.emitPage(ctx, "page.restored", p, c.ID, nil)
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
}
// isArchived reports whether p or one of its ancestors is archived.
func (s *Service) isArchived(ctx context.Context, p pageRecord) bool {
for depth := 0; depth < 100; depth++ {
if p.ArchivedAt != "" {
return true
}
if p.Parent == "" {
return false
}
var err error
if p, err = s.getPage(ctx, p.Parent); err != nil {
return false
}
}
return false
}
// ArchivePage takes a page and its subtree out of the page tree (editor).
// They stay readable and come back with UnarchivePage. Idempotent.
func (s *Service) ArchivePage(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 Page{}, apperr.Invalid("restore the page from the trash first")
}
if p.ArchivedAt == "" {
if _, err := pocketbase.Update[pageRecord](ctx, s.pb, "pages", p.ID, map[string]any{
"archived_at": pbTime(time.Now()), "last_editor": c.ID,
}); err != nil {
return Page{}, mapPB(err, "page not found")
}
// Open editors reconnect read-only.
s.docs.Kick(p.ID)
s.emitPage(ctx, "page.archived", p, c.ID, nil)
}
return s.GetPage(ctx, c, p.ID)
}
// UnarchivePage puts an archived page back in the tree (editor). If its
// parent is gone, trashed or archived, it goes to the end of the top level.
func (s *Service) UnarchivePage(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.ArchivedAt == "" {
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{"archived_at": "", "last_editor": c.ID}
if p.Parent != "" && (!t.live(p.Parent) || t.archived(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)
s.emitPage(ctx, "page.unarchived", p, c.ID, nil)
return s.GetPage(ctx, c, p.ID)
}
// ListArchive lists a space's archived pages c can open, newest first.
// Pages under an archived page are not listed separately, and archived
// pages in the trash are listed in the trash instead.
func (s *Service) ListArchive(ctx context.Context, c access.Caller, spaceID string) ([]ArchivedPage, 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 := []ArchivedPage{}
for _, p := range t.byID {
if p.ArchivedAt != "" && t.live(p.ID) && !t.archived(p.Parent) && rules.role(p.ID) != "" {
out = append(out, ArchivedPage{ID: p.ID, Title: p.Title, Icon: p.Icon, ArchivedAt: p.ArchivedAt})
}
}
sort.Slice(out, func(i, j int) bool { return out[i].ArchivedAt > out[j].ArchivedAt })
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)
s.emitPage(ctx, "page.deleted", p, c.ID, nil)
return nil
}
// pageUser names a person on a page (best effort: a deleted account keeps its id).
func (s *Service) pageUser(ctx context.Context, id string) PageUser {
if id == "" {
return PageUser{}
}
u, err := s.getUser(ctx, id)
if err != nil {
return PageUser{ID: id}
}
return PageUser{ID: id, Name: u.Name}
}
func nonNil(list []string) []string {
if list == nil {
return []string{}
}
return list
}
// pageMode is how the API names a page's default mode: "page" when the
// stored value is empty.
func pageMode(stored string) string {
if stored == "edgeless" {
return "edgeless"
}
return "page"
}