Files
Docwell/Server/internal/directory/properties.go
T
tajniak81andClaude Opus 5.5 ec11abd8b8 Add page properties, tags, All docs, collections and journals
Phase B (items 1-6) of docs/AFFINE.md.

Properties: workspaces define custom page properties (text, number,
checkbox, date, select, multi-select, person, link) in the new
workspace_properties collection; pages keep their values in
pages.properties, checked against each property's type. The Info panel
under the title shows tags, custom and built-in properties, following
each property's visibility; the Info side panel shows them all, with the
page's collections and the journal. Settings gains Page properties and
Tags sections.

Tags: coloured, per workspace (tags collection, pages.tags); create from
the picker, rename, recolour, merge and delete. Search filters by tag.

All docs: GET /workspaces/{id}/docs lists the pages the caller can open
with their properties, narrowed by space, tag, collection or filter
rules evaluated on the server. The view shows a list, grid or cards,
groups and orders by any property, picks the properties shown, and acts
on several pages at once (tag, move, trash, collect).

Collections (page_collections): saved rules plus pages added or taken
out by hand, private to their creator until shared with the workspace,
listed in the sidebar.

Journals: one page per person and day in a private journal space
(spaces.journal_owner) that workspace admins do not see into, made on
first use. A week strip marks days with pages, new days can start from
a template, and dates in read mode open that day's journal.

The migration and schema snapshot, OpenAPI spec and generated Go, TS and
Dart types are updated (the Dart generator learns untyped values), the
mobile editor bundle is rebuilt, the new strings are translated into all
five languages, and the user guide covers the new features.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 16:35:42 +01:00

458 lines
13 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package directory
import (
"context"
"crypto/rand"
"encoding/json"
"fmt"
"math"
"net/url"
"slices"
"sort"
"strings"
"time"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/store/pocketbase"
)
// ---- Page properties -------------------------------------------------------
//
// A workspace defines the custom properties its pages can fill in
// (workspace_properties); each page keeps its values in pages.properties as
// { "<property id>": value }. Built-in properties (tags, created, updated,
// created by, last edited by, template, journal, width) come from the page's
// own fields and are not defined here. A value whose property was deleted
// stays in the page until it is next saved, and is ignored meanwhile.
// Property types and what their values look like in JSON.
const (
PropText = "text" // "free text"
PropNumber = "number" // 42.5
PropCheckbox = "checkbox" // true
PropDate = "date" // "2026-11-14"
PropSelect = "select" // "<option id>"
PropMultiSelect = "multi_select" // ["<option id>", …]
PropMember = "member" // ["<user id>", …]
PropLink = "link" // "https://…"
)
var propertyTypes = []string{PropText, PropNumber, PropCheckbox, PropDate, PropSelect, PropMultiSelect, PropMember, PropLink}
// Colours for select options and tags; the apps draw them from the theme.
var labelColors = []string{"", "gray", "red", "orange", "yellow", "green", "teal", "blue", "purple", "pink"}
const (
maxProperties = 100
maxOptions = 200
maxListValues = 100
maxTextValue = 5000
maxPropertyName = 80
)
// PropertyOption is one choice of a select or multi-select property.
type PropertyOption struct {
ID string `json:"id"`
Name string `json:"name"`
Color string `json:"color"`
}
// Property is a custom page property of a workspace.
type Property struct {
ID string `json:"id"`
Workspace string `json:"workspace"`
Name string `json:"name"`
Type string `json:"type"`
Options []PropertyOption `json:"options"`
// Visibility is whether the page's Info panel shows it: always, only when
// it has a value (hide_empty), or never (it is then only in the side panel).
Visibility string `json:"visibility"`
Position float64 `json:"position"`
}
type propertyRecord struct {
ID string `json:"id"`
Workspace string `json:"workspace"`
Name string `json:"name"`
Type string `json:"type"`
Options []PropertyOption `json:"options"`
Visibility string `json:"visibility"`
Position float64 `json:"position"`
}
func (r propertyRecord) view() Property {
v := Property(r)
if v.Options == nil {
v.Options = []PropertyOption{}
}
if v.Visibility == "" {
v.Visibility = "always"
}
return v
}
func (s *Service) workspaceProperties(ctx context.Context, wsID string) ([]propertyRecord, error) {
rows, err := listAll[propertyRecord](ctx, s, "workspace_properties", pocketbase.ListOptions{
Filter: fmt.Sprintf("workspace = '%s'", wsID), Sort: "position,created",
})
return rows, err
}
// ListProperties lists a workspace's custom page properties in order.
func (s *Service) ListProperties(ctx context.Context, c access.Caller, wsID string) ([]Property, error) {
ws, _, err := s.workspaceFor(ctx, c, wsID)
if err != nil {
return nil, err
}
rows, err := s.workspaceProperties(ctx, ws.ID)
if err != nil {
return nil, err
}
out := make([]Property, len(rows))
for i, r := range rows {
out[i] = r.view()
}
return out, nil
}
// PropertyInput creates a property, or changes the fields that are set.
type PropertyInput struct {
Name *string `json:"name"`
Type *string `json:"type"`
Options *[]PropertyOption `json:"options"`
Visibility *string `json:"visibility"`
Position *float64 `json:"position"`
}
// CreateProperty adds a custom property to a workspace (members).
func (s *Service) CreateProperty(ctx context.Context, c access.Caller, wsID string, in PropertyInput) (Property, error) {
ws, role, err := s.workspaceFor(ctx, c, wsID)
if err != nil {
return Property{}, err
}
if err := access.OrganizeWorkspace(role); err != nil {
return Property{}, err
}
if in.Name == nil || in.Type == nil {
return Property{}, apperr.InvalidFields(map[string]string{"name": "Name and type are required."})
}
existing, err := s.workspaceProperties(ctx, ws.ID)
if err != nil {
return Property{}, err
}
if len(existing) >= maxProperties {
return Property{}, apperr.Invalid("a workspace can have at most 100 properties")
}
body, err := propertyPatch(in, true)
if err != nil {
return Property{}, err
}
body["workspace"] = ws.ID
if in.Position == nil {
next := 0.0
for _, p := range existing {
next = math.Max(next, p.Position+1)
}
body["position"] = next
}
if _, ok := body["visibility"]; !ok {
body["visibility"] = "always"
}
rec, err := pocketbase.Create[propertyRecord](ctx, s.pb, "workspace_properties", body)
if err != nil {
return Property{}, mapPB(err, "property not found")
}
return rec.view(), nil
}
func (s *Service) propertyFor(ctx context.Context, c access.Caller, id string) (propertyRecord, string, error) {
if !validID(id) {
return propertyRecord{}, "", apperr.NotFound("property not found")
}
rec, err := pocketbase.Get[propertyRecord](ctx, s.pb, "workspace_properties", id)
if err != nil {
return rec, "", mapPB(err, "property not found")
}
_, role, err := s.workspaceFor(ctx, c, rec.Workspace)
if err != nil {
return rec, "", apperr.NotFound("property not found")
}
return rec, role, nil
}
// UpdateProperty renames a property, changes its options, visibility or
// place. A changed type keeps the values that still fit and drops the rest
// as pages are next saved; reading ignores values of the wrong shape.
func (s *Service) UpdateProperty(ctx context.Context, c access.Caller, id string, in PropertyInput) (Property, error) {
rec, role, err := s.propertyFor(ctx, c, id)
if err != nil {
return Property{}, err
}
if err := access.OrganizeWorkspace(role); err != nil {
return Property{}, err
}
patch, err := propertyPatch(in, false)
if err != nil {
return Property{}, err
}
if len(patch) == 0 {
return rec.view(), nil
}
updated, err := pocketbase.Update[propertyRecord](ctx, s.pb, "workspace_properties", rec.ID, patch)
if err != nil {
return Property{}, mapPB(err, "property not found")
}
return updated.view(), nil
}
// DeleteProperty removes a property from the workspace (members). Pages'
// values for it are ignored from then on.
func (s *Service) DeleteProperty(ctx context.Context, c access.Caller, id string) error {
rec, role, err := s.propertyFor(ctx, c, id)
if err != nil {
return err
}
if err := access.OrganizeWorkspace(role); err != nil {
return err
}
return mapPB(s.pb.Delete(ctx, "workspace_properties", rec.ID), "property not found")
}
// propertyPatch checks a property's fields; creating needs name and type.
func propertyPatch(in PropertyInput, creating bool) (map[string]any, error) {
patch := map[string]any{}
if in.Name != nil {
name := strings.TrimSpace(*in.Name)
switch {
case name == "":
return nil, apperr.InvalidFields(map[string]string{"name": "Name is required."})
case len([]rune(name)) > maxPropertyName:
return nil, apperr.InvalidFields(map[string]string{"name": "Name is too long (max 80)."})
}
patch["name"] = name
}
if in.Type != nil {
if !slices.Contains(propertyTypes, *in.Type) {
return nil, apperr.InvalidFields(map[string]string{"type": "Unknown property type."})
}
patch["type"] = *in.Type
}
if in.Options != nil {
opts, err := cleanOptions(*in.Options)
if err != nil {
return nil, err
}
patch["options"] = opts
} else if creating {
patch["options"] = []PropertyOption{}
}
if in.Visibility != nil {
switch *in.Visibility {
case "always", "hide_empty", "never":
patch["visibility"] = *in.Visibility
default:
return nil, apperr.InvalidFields(map[string]string{"visibility": "Visibility must be always, hide_empty or never."})
}
}
if in.Position != nil {
if math.IsNaN(*in.Position) || math.IsInf(*in.Position, 0) {
return nil, apperr.InvalidFields(map[string]string{"position": "Position must be a number."})
}
patch["position"] = *in.Position
}
return patch, nil
}
// cleanOptions checks select choices, giving new ones an id.
func cleanOptions(in []PropertyOption) ([]PropertyOption, error) {
if len(in) > maxOptions {
return nil, apperr.InvalidFields(map[string]string{"options": "At most 200 options."})
}
out := make([]PropertyOption, 0, len(in))
seen := map[string]bool{}
for _, o := range in {
name := strings.TrimSpace(o.Name)
if name == "" || len([]rune(name)) > 60 {
return nil, apperr.InvalidFields(map[string]string{"options": "Each option needs a name of at most 60 characters."})
}
if !slices.Contains(labelColors, o.Color) {
return nil, apperr.InvalidFields(map[string]string{"options": "Unknown option colour."})
}
id := o.ID
if id == "" {
id = newOptionID()
} else if !validID(id) {
return nil, apperr.InvalidFields(map[string]string{"options": "Invalid option id."})
}
if seen[id] {
continue
}
seen[id] = true
out = append(out, PropertyOption{ID: id, Name: name, Color: o.Color})
}
return out, nil
}
func newOptionID() string {
const letters = "abcdefghijklmnopqrstuvwxyz0123456789"
b := make([]byte, 10)
_, _ = rand.Read(b)
for i := range b {
b[i] = letters[int(b[i])%len(letters)]
}
return string(b)
}
// mergeProperties applies values to a page's properties, dropping values of
// properties that no longer exist. A null value clears one.
func (s *Service) mergeProperties(ctx context.Context, p pageRecord, in map[string]json.RawMessage) (map[string]json.RawMessage, error) {
defs, err := s.workspaceProperties(ctx, p.Workspace)
if err != nil {
return nil, err
}
byID := make(map[string]propertyRecord, len(defs))
for _, d := range defs {
byID[d.ID] = d
}
out := map[string]json.RawMessage{}
for id, v := range p.Properties {
if _, ok := byID[id]; ok {
out[id] = v
}
}
keys := make([]string, 0, len(in))
for id := range in {
keys = append(keys, id)
}
sort.Strings(keys)
for _, id := range keys {
def, ok := byID[id]
if !ok {
return nil, apperr.InvalidFields(map[string]string{"properties": "Unknown property " + id + "."})
}
v, err := cleanValue(def, in[id])
if err != nil {
return nil, apperr.InvalidFields(map[string]string{"properties": def.Name + ": " + err.Error()})
}
if v == nil {
delete(out, id)
} else {
out[id] = v
}
}
return out, nil
}
// cleanValue checks a value against its property's type and returns it as
// stored, or nil when it clears the property (null, "", [], false is kept).
func cleanValue(def propertyRecord, raw json.RawMessage) (json.RawMessage, error) {
if len(raw) == 0 || string(raw) == "null" {
return nil, nil
}
enc := func(v any) (json.RawMessage, error) {
b, err := json.Marshal(v)
return b, err
}
switch def.Type {
case PropText, PropLink:
var v string
if json.Unmarshal(raw, &v) != nil {
return nil, fmt.Errorf("expected text")
}
v = strings.TrimSpace(v)
if v == "" {
return nil, nil
}
if len(v) > maxTextValue {
return nil, fmt.Errorf("text is too long")
}
if def.Type == PropLink && !validLink(v) {
return nil, fmt.Errorf("expected an http, https or mailto link")
}
return enc(v)
case PropNumber:
var v float64
if json.Unmarshal(raw, &v) != nil || math.IsNaN(v) || math.IsInf(v, 0) {
return nil, fmt.Errorf("expected a number")
}
return enc(v)
case PropCheckbox:
var v bool
if json.Unmarshal(raw, &v) != nil {
return nil, fmt.Errorf("expected true or false")
}
return enc(v)
case PropDate:
var v string
if json.Unmarshal(raw, &v) != nil {
return nil, fmt.Errorf("expected a date")
}
if v == "" {
return nil, nil
}
if _, err := time.Parse(time.DateOnly, v); err != nil {
return nil, fmt.Errorf("dates look like 2026-11-14")
}
return enc(v)
case PropSelect:
var v string
if json.Unmarshal(raw, &v) != nil {
return nil, fmt.Errorf("expected an option id")
}
if v == "" {
return nil, nil
}
if !hasOption(def, v) {
return nil, fmt.Errorf("unknown option")
}
return enc(v)
case PropMultiSelect, PropMember:
var list []string
if json.Unmarshal(raw, &list) != nil {
return nil, fmt.Errorf("expected a list of ids")
}
out := []string{}
for _, id := range list {
if slices.Contains(out, id) {
continue
}
if def.Type == PropMultiSelect && !hasOption(def, id) {
return nil, fmt.Errorf("unknown option")
}
if def.Type == PropMember && !validID(id) {
return nil, fmt.Errorf("invalid person")
}
out = append(out, id)
}
if len(out) == 0 {
return nil, nil
}
if len(out) > maxListValues {
return nil, fmt.Errorf("too many values")
}
return enc(out)
}
return nil, fmt.Errorf("unknown property type")
}
func hasOption(def propertyRecord, id string) bool {
return slices.ContainsFunc(def.Options, func(o PropertyOption) bool { return o.ID == id })
}
func validLink(v string) bool {
u, err := url.Parse(v)
if err != nil {
return false
}
switch u.Scheme {
case "http", "https":
return u.Host != ""
case "mailto":
return u.Opaque != "" || u.Path != ""
}
return false
}