Compare commits

...
8 Commits
Author SHA1 Message Date
Kristian WindandClaude Opus 5 1529c87231 feat(theme): five themes, and a picker that shows them
Release / Build and publish image (push) Failing after 9m58s
Two themes and a toggle between them. Now five, chosen from a grid under
Settings → Konto: the two that existed, a warm dark (Skumring) with amber
where the green was, a warm light (Papir), and a high-contrast one.

Each swatch is painted in its own theme rather than described, so the
choice is made by looking. data-theme sits on the swatch and not on the
card — it redefines --ink too, and a card wearing a dark theme's ink on a
light page has a name nobody can read.

Every theme states its full palette rather than inheriting and patching.
A partial theme looks finished until somebody adds a token, at which
point four themes silently fall back to a colour from a fifth. That is
also why the dark palette is repeated under [data-theme='dark']: :root
carries it as the default and :root only ever matches <html>, so a swatch
asking for it by name would otherwise show whatever the page was wearing.

The theme-color meta is updated too, so an installed PWA's frame and a
phone's address bar follow rather than staying whichever colour shipped
in the markup.

Contrast measured for all five. The new ones clear 4.5:1 down to the
quietest tier — which is where dates and counts live, and the first thing
to disappear. Kontrast reaches 8.9:1 there. The two original themes are
left as they are: their faint ink sits at 3.1–3.8, which is worth
revisiting, but not as a side effect of adding colours.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-17 17:27:18 +02:00
Kristian WindandClaude Opus 5 f15c440942 feat(realtime): keep projects and labels current too, not only tasks
The socket carried task events and nothing else, so a project or a label
created anywhere — another tab, another device, Claude through the
connector — did not appear until a reload. Tasks updated live and the
sidebar did not, which reads as the sidebar being broken rather than as a
gap in what is published.

Projects and labels go to the *user* rather than to a project. A project
that has just been created has no subscribers, because nobody was
watching a thing that did not exist a moment ago.

Labels are announced as "something changed" and re-read, rather than sent
as a payload. The sidebar wants each label's task count, which no single
event carries and which moves whenever a task gains or loses a label —
including through quick add, where "@regnskab" invents the label inside a
task write and no label event is sent at all. Comparing the label lists
on a task change is what catches that, without re-reading on every ticked
checkbox.

And projects now go through an upsert, because the same row arrives twice
— once as the response to the request that created it, once over the
socket. Appending both puts two ids into a keyed {#each}, which throws
and stops the sidebar rendering. The tasks already had that guard; adding
the project event without it reintroduced the identical bug, and the
smoke test caught it on the first run.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-17 17:27:18 +02:00
Kristian WindandClaude Opus 5 d37d240625 feat(search): find a task by its label
Search covered task text only, so "regnskab" found nothing with the task
labelled @regnskab sitting in front of you — which reads as the search
box having lost it.

A label is often the only thing you remember. "That thing about the
accounts" is a search for @regnskab, not for any word in the title.

The label side is a plain lowercase match rather than a second FTS index.
Labels are short, and their names are typed by the same person now
searching for them, so there is no spelling to be generous about — the
diacritic folding that earns its keep on task text does not earn a second
index here.

The join sits inside the WHERE the visibility rules already build, so
somebody else's label cannot pull their task into your results. There is
a test for that, because it is the kind of thing an OR is good at
breaking.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-17 17:27:18 +02:00
Kristian WindandClaude Opus 5 3b521b463c feat(projects): add, rename and delete sections
The board has drawn a column per section since it was written and there
was no way to make one. Sections could only be created by the Todoist
importer or a template — so an ordinary project could never have a
heading in it at all.

Add, rename and delete, in the list view where the headings already are.
The controls appear on hover rather than sitting beside the heading
permanently: a heading with two buttons always next to it stops reading
as a heading.

Deleting says how many tasks are in the section and that they will
survive it, because the API keeps them and drops their section — which is
the right behaviour and not what "delete section" sounds like. The list
is re-read afterwards, since those tasks move to the unsectioned group
and nothing else would tell the view they had.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-17 17:27:18 +02:00
Kristian WindandClaude Opus 5 9056c44c9a feat(tasks): move, repeat, delegate and re-read a task from its drawer
Four things you could not do to a task you had open, and one that had
never worked at all.

**Project, recurrence and assignee** are now fields in the drawer. A task
created in the wrong place could only be fixed by dragging it, a repeat
could only be set by typing it into the title when the task was created,
and delegation had no interface whatsoever despite assignee_id being in
the API from the start. The assignee only appears on a project with
somebody else in it, because on your own there is nobody to choose.

**The title is read the way quick add reads it.** Typing "i morgen kl 14
p1" into a title used to leave it as those words, so where you typed a
sentence decided what it meant. The parse runs on the server — the
grammar is Danish and English and lives there — and applies only when it
consumed something. What it took is said out loud, and the fields on
screen are updated to match: the drawer otherwise seeds its inputs once
per task so a save cannot overwrite what you are typing, and that rule
has to bend exactly here, where the save changed the very fields in front
of you.

**And the member list has never worked.** The share panel, and now the
assignee field, ask for it. Every call errored: the ORDER BY named an
expression, and SQLite only accepts result-set columns across a UNION, so
it failed at query time with "1st ORDER BY term does not match any column
in the result set". Found by the smoke test that opens a task, which is
the second real bug that suite has caught by watching for failed requests
rather than only for what renders.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-17 17:27:18 +02:00
Kristian WindandClaude Opus 5 afc46a5c20 fix(api): do the things the API says yes to
Release / Build and publish image (push) Failing after 9m58s
Three reports from somebody driving the app through the MCP connector,
all the same shape: an argument accepted, an OK returned, and nothing
done.

**project_id on an update never moved the task.** Both the REST handler
and the MCP tool read it, both checked the caller's rights on the
destination — which reads as "understood" — and then neither passed it
on, because store.TaskUpdate has no such field: a project change is a
move, since sort_order is per project. So the task stayed where it was
and the answer said OK. Moving a task between projects was impossible
except by creating it again and closing the old one, which is what the
person ended up doing. Both paths now go through one helper, so they
cannot drift apart again.

**An unknown #project vanished without a word.** The parser reads
"#3Dekoration" correctly; the lookup then fails, the task goes to the
Inbox, and the name is gone from the title with nothing anywhere saying
why. Still not an error — a thought should not be thrown away over a typo
— but quick-add now returns unknown_project, and the MCP tool returns a
note written for a model to relay. The old behaviour was kind in the web
interface, where you see the row appear in the wrong place and fix it. In
a chat nobody sees the row.

**Sub-tasks were unreachable over MCP.** create_task had no parent_id,
though the REST API has had it all along, so importing a parent with
seven children produced eight unrelated tasks with the parent's name
prefixed onto each. A sub-task joins its parent's project — the two
cannot disagree — and a second level is refused rather than silently
flattened.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-17 16:24:58 +02:00
Kristian WindandClaude Opus 5 8c748c2a88 feat(sidebar): drag it wider, fold it away, and have it stay that way
The sidebar was 268px and always there. On a wide monitor that wastes the
room; on a laptop it takes room the list needs.

The width drags from a handle on the border — 7px of target over a 1px
line, because a 1px target is a target you miss — and the whole column
folds away from a button in the topbar. Both are remembered.

In localStorage rather than on the account: this is a property of the
screen you are sitting at, not of you. The same person on a laptop and a
wide monitor wants different answers, and syncing it would make one of
them wrong every time they switch.

The handle is also a slider for the keyboard. Arrow keys move it, Home
puts it back, and so does a double-click — a drag handle with no keyboard
equivalent is a setting some people simply cannot reach.

Folding is desktop-only, and the media query says so rather than leaving
it to chance: below the breakpoint the sidebar is a drawer that opens over
the page, and a collapsed drawer would open to nothing. Clamped to
200–480px in the store, so a stored value from an older build cannot make
it unusable either.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-17 16:09:16 +02:00
Kristian WindandClaude Opus 5 c4e9e1519b feat(projects): drag the sidebar into the order you want
Projects have carried sort_order since the first migration and nothing
ever set it, so the sidebar was ordered by creation date for good.

POST /projects/reorder takes the whole list rather than one move. A
person has a handful of projects, so sending the order you want is
simpler to reason about than midpoints between neighbours — and it cannot
run out of precision, which is the failure the task ordering has to
respace a section to recover from. It also cannot land half-applied the
way a sequence of individual moves can.

Projects you do not own are skipped rather than refused. sort_order is a
column on the project, not a preference per viewer, so a shared project
sits where its owner put it and a member rearranging their own sidebar
does not rearrange somebody else's. The sidebar only makes your own
projects draggable, so that rule never shows up as a row that springs
back.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-17 15:59:31 +02:00
20 changed files with 1645 additions and 47 deletions
+53 -2
View File
@@ -533,7 +533,11 @@ paths:
type: string
description: Where it goes when the text names no project.
responses:
"201": { $ref: "#/components/responses/Task" }
"201":
description: Created
content:
application/json:
schema: { $ref: "#/components/schemas/QuickAddResult" }
"422": { $ref: "#/components/responses/Validation" }
/api/v1/tasks/quick-add/preview:
@@ -756,6 +760,35 @@ paths:
"201": { $ref: "#/components/responses/Project" }
"422": { $ref: "#/components/responses/Validation" }
/api/v1/projects/reorder:
post:
tags: [projects]
summary: Set the order projects appear in.
description: |
The whole list at once rather than one move at a time. A person has a
handful of projects, so sending the order you want is simpler than
midpoints and cannot land half-applied.
Projects you do not own are skipped: `sort_order` is a column on the
project rather than a preference per viewer, so a shared one stays where
its owner put it.
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [ids]
properties:
ids:
type: array
maxItems: 500
items: { type: string }
description: Project ids, top to bottom.
responses:
"204": { description: Reordered. }
"422": { $ref: "#/components/responses/Validation" }
/api/v1/projects/{projectID}:
parameters:
- { name: projectID, in: path, required: true, schema: { type: string } }
@@ -2106,7 +2139,12 @@ components:
TaskInput:
type: object
properties:
project_id: { type: string, description: "Omitted on create, the task goes to the Inbox." }
project_id:
type: string
description: |
Omitted on create, the task goes to the Inbox. On update it moves the
task — which needs editor rights on the destination.
section_id: { type: string }
parent_id: { type: string }
content: { type: string }
@@ -2122,6 +2160,19 @@ components:
items: { type: string }
sort_order: { type: number }
QuickAddResult:
allOf:
- $ref: "#/components/schemas/Task"
- type: object
properties:
unknown_project:
type: string
description: |
Present when the text named a `#project` that does not exist. The
task is still created, in the Inbox — a thought is not thrown away
over a typo — but the caller is told, because the alternative is
that the name vanishes from the title and nothing says why.
ParsedTask:
type: object
description: What the quick-add parser made of a line.
+3
View File
@@ -245,6 +245,7 @@ func (s *Server) handleCreateLabel(w http.ResponseWriter, r *http.Request) {
s.internal(w, "create label", err)
return
}
s.publishToOwner(r, "label.changed", labelJSON{l.ID, l.Name, l.Color, l.SortOrder, 0})
writeJSON(w, http.StatusCreated, labelJSON{l.ID, l.Name, l.Color, l.SortOrder, 0})
}
@@ -263,6 +264,7 @@ func (s *Server) handleUpdateLabel(w http.ResponseWriter, r *http.Request) {
s.storeError(w, "update label", err)
return
}
s.publishToOwner(r, "label.changed", nil)
w.WriteHeader(http.StatusNoContent)
}
@@ -272,5 +274,6 @@ func (s *Server) handleDeleteLabel(w http.ResponseWriter, r *http.Request) {
s.storeError(w, "delete label", err)
return
}
s.publishToOwner(r, "label.changed", nil)
w.WriteHeader(http.StatusNoContent)
}
+170
View File
@@ -983,3 +983,173 @@ func TestWellKnownCalDAVStillRedirects(t *testing.T) {
t.Error("CalDAV discovery was caught by the well-known rule")
}
}
// --- what the API accepts, it must actually do -------------------------------------
// project_id on an update used to be validated and then dropped: the destination
// was permission-checked, which reads as "understood", and the task never moved
// while the answer said OK. Both the REST path and the MCP tool did it.
func TestUpdateMovesTheTaskToAnotherProject(t *testing.T) {
ts := newTestServer(t)
ts.bootstrap(t)
_, project := ts.do(t, "POST", "/api/v1/projects", map[string]string{"name": "Firma"})
projectID := project["id"].(string)
_, task := ts.do(t, "POST", "/api/v1/tasks", map[string]any{"content": "betal moms"})
taskID := task["id"].(string)
if task["project_id"] == projectID {
t.Fatal("the task started in the destination; the test proves nothing")
}
resp, updated := ts.do(t, "PATCH", "/api/v1/tasks/"+taskID,
map[string]any{"project_id": projectID})
if resp.StatusCode != http.StatusOK {
t.Fatalf("patch: status %d, body %v", resp.StatusCode, updated)
}
if updated["project_id"] != projectID {
t.Errorf("project_id = %v, want %v — the move was accepted and not made",
updated["project_id"], projectID)
}
// And it really is there, not merely reported as there.
_, reread := ts.do(t, "GET", "/api/v1/tasks/"+taskID, nil)
if reread["project_id"] != projectID {
t.Errorf("after re-reading, project_id = %v", reread["project_id"])
}
}
func TestMCPUpdateMovesTheTaskToAnotherProject(t *testing.T) {
ts := newTestServer(t)
ts.bootstrap(t)
_, project := ts.do(t, "POST", "/api/v1/projects", map[string]string{"name": "Firma"})
projectID := project["id"].(string)
created := ts.callTool(t, "create_task", map[string]any{"text": "betal moms"})
taskID := created["id"].(string)
moved := ts.callTool(t, "update_task", map[string]any{
"task_id": taskID, "project_id": projectID,
})
if moved["project_id"] != projectID {
t.Errorf("project_id = %v, want %v", moved["project_id"], projectID)
}
}
// A project you cannot write to is refused rather than quietly ignored.
func TestUpdateRefusesAProjectYouCannotWriteTo(t *testing.T) {
ts := newTestServer(t)
ts.bootstrap(t)
other := ts.newUser(t, "anden@example.dk", "Anden")
_, theirs := other.do(t, "POST", "/api/v1/projects", map[string]string{"name": "Deres"})
_, task := ts.do(t, "POST", "/api/v1/tasks", map[string]any{"content": "min opgave"})
taskID := task["id"].(string)
mine := task["project_id"]
resp, _ := ts.do(t, "PATCH", "/api/v1/tasks/"+taskID,
map[string]any{"project_id": theirs["id"]})
if resp.StatusCode != http.StatusNotFound {
t.Errorf("status %d, want 404", resp.StatusCode)
}
_, reread := ts.do(t, "GET", "/api/v1/tasks/"+taskID, nil)
if reread["project_id"] != mine {
t.Error("the task moved into somebody else's project")
}
}
// An unknown #project is still not an error — the thought is kept rather than
// thrown away over a typo — but it is no longer silent. It used to vanish from
// the title while the task went to the Inbox, with nothing saying why.
func TestQuickAddSaysWhenTheProjectDoesNotExist(t *testing.T) {
ts := newTestServer(t)
ts.bootstrap(t)
resp, body := ts.do(t, "POST", "/api/v1/tasks/quick-add",
map[string]any{"text": "Lav plakat #3Dekoration"})
if resp.StatusCode != http.StatusCreated {
t.Fatalf("status %d, want 201 — the task should still be created", resp.StatusCode)
}
if body["unknown_project"] != "3Dekoration" {
t.Errorf("unknown_project = %v, want %q", body["unknown_project"], "3Dekoration")
}
if body["content"] != "Lav plakat" {
t.Errorf("content = %v", body["content"])
}
}
func TestQuickAddSaysNothingWhenTheProjectExists(t *testing.T) {
ts := newTestServer(t)
ts.bootstrap(t)
ts.do(t, "POST", "/api/v1/projects", map[string]string{"name": "Dekoration"})
_, body := ts.do(t, "POST", "/api/v1/tasks/quick-add",
map[string]any{"text": "Lav plakat #Dekoration"})
if _, present := body["unknown_project"]; present {
t.Errorf("reported an unknown project for one that exists: %v", body)
}
}
func TestMCPCreateSaysWhenTheProjectDoesNotExist(t *testing.T) {
ts := newTestServer(t)
ts.bootstrap(t)
created := ts.callTool(t, "create_task", map[string]any{"text": "Lav plakat #3Dekoration"})
note, _ := created["note"].(string)
if !strings.Contains(note, "3Dekoration") {
t.Errorf("note = %q, want it to name the project that does not exist", note)
}
}
// Sub-tasks were unreachable over MCP: create_task had no parent_id, so a parent
// with seven children arrived as eight unrelated tasks.
func TestMCPCreateMakesSubtasks(t *testing.T) {
ts := newTestServer(t)
ts.bootstrap(t)
_, project := ts.do(t, "POST", "/api/v1/projects", map[string]string{"name": "Firma"})
parent := ts.callTool(t, "create_task", map[string]any{
"content": "Runen v2", "project_id": project["id"],
})
parentID := parent["id"].(string)
child := ts.callTool(t, "create_task", map[string]any{
"content": "Tegn ikonet", "parent_id": parentID,
})
if child["parent_id"] != parentID {
t.Errorf("parent_id = %v, want %v", child["parent_id"], parentID)
}
// A sub-task joins its parent's project whatever else was asked for.
if child["project_id"] != project["id"] {
t.Errorf("project_id = %v, want the parent's %v", child["project_id"], project["id"])
}
_, listed := ts.do(t, "GET", "/api/v1/tasks?parent_id="+parentID, nil)
if tasks, _ := listed["tasks"].([]any); len(tasks) != 1 {
t.Errorf("the parent has %d sub-tasks, want 1", len(tasks))
}
}
func TestMCPCreateRefusesASecondLevelOfSubtask(t *testing.T) {
ts := newTestServer(t)
ts.bootstrap(t)
parent := ts.callTool(t, "create_task", map[string]any{"content": "Runen v2"})
child := ts.callTool(t, "create_task", map[string]any{
"content": "Tegn ikonet", "parent_id": parent["id"],
})
// A tool that refuses reports it inside the result with isError, not as a
// JSON-RPC error — the call itself was well formed, the arguments were not.
response := ts.rpc(t, "tools/call", map[string]any{
"name": "create_task",
"arguments": map[string]any{"content": "Endnu dybere", "parent_id": child["id"]},
})
result, _ := response["result"].(map[string]any)
if result == nil || result["isError"] != true {
t.Errorf("a sub-task of a sub-task was accepted: %v", response)
}
}
+51 -4
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
@@ -57,7 +58,8 @@ func (s *Server) buildMCP() *mcp.Server {
InputSchema: mcp.Schema(map[string]any{
"text": mcp.Str("The task as a sentence, parsed for date, time, priority, #project, @label and recurrence."),
"content": mcp.Str("The task title, if not using `text`."),
"project_id": mcp.Str("Which project. Defaults to the Inbox."),
"project_id": mcp.Str("Which project. Defaults to the Inbox. Naming a project that does not exist is not an error — the task goes to the Inbox and the answer says so."),
"parent_id": mcp.Str("Make this a sub-task of that task. It joins the parent's project. One level deep."),
"due_date": mcp.Str("A date as YYYY-MM-DD."),
"priority": mcp.Int("1 (highest) to 4 (none)."),
"description": mcp.Str("Longer notes on the task."),
@@ -253,6 +255,7 @@ func (s *Server) mcpCreateTask(ctx context.Context, userID string, args json.Raw
Text string `json:"text"`
Content string `json:"content"`
ProjectID string `json:"project_id"`
ParentID string `json:"parent_id"`
DueDate string `json:"due_date"`
Priority int `json:"priority"`
Description string `json:"description"`
@@ -268,6 +271,11 @@ func (s *Server) mcpCreateTask(ctx context.Context, userID string, args json.Raw
task := &store.Task{CreatedBy: userID, Priority: 4}
labels := params.Labels
// Reported below rather than swallowed. "#Dekoration" used to vanish from the
// title while the task went to the Inbox, with nothing anywhere saying so —
// invisible in a chat, where nobody sees the row that was written.
unknownProject := ""
if text := strings.TrimSpace(params.Text); text != "" {
parsed := quickadd.Parse(text, time.Now().In(userLocation(user.Timezone)), user.Locale)
task.Content = parsed.Content
@@ -280,6 +288,8 @@ func (s *Server) mcpCreateTask(ctx context.Context, userID string, args json.Raw
if parsed.Project != "" && params.ProjectID == "" {
if id, err := s.db.ProjectByName(ctx, userID, parsed.Project); err == nil {
task.ProjectID = id
} else {
unknownProject = parsed.Project
}
}
}
@@ -305,6 +315,23 @@ func (s *Server) mcpCreateTask(ctx context.Context, userID string, args json.Raw
if params.ProjectID != "" {
task.ProjectID = params.ProjectID
}
// A sub-task belongs to its parent's project, whatever else was asked for:
// the two cannot disagree, and the parent is the more specific instruction.
// Without this the tools could not build a tree at all — an import of a
// parent with seven children arrived as eight unrelated tasks.
if params.ParentID != "" {
parent, err := s.db.GetTask(ctx, params.ParentID, userID)
if err != nil {
return nil, mcp.ArgError("no task with id %q to hang this under", params.ParentID)
}
if parent.ParentID != "" {
return nil, mcp.ArgError("sub-tasks are one level deep; %q is already a sub-task", params.ParentID)
}
task.ParentID = parent.ID
task.ProjectID = parent.ProjectID
}
if task.ProjectID == "" {
if task.ProjectID, err = s.db.InboxID(ctx, userID); err != nil {
return nil, err
@@ -319,10 +346,23 @@ func (s *Server) mcpCreateTask(ctx context.Context, userID string, args json.Raw
}
s.hub.Publish(task.ProjectID, "task.created", toTaskJSON(*task))
return map[string]any{
out := map[string]any{
"id": task.ID, "content": task.Content, "priority": task.Priority,
"due_date": task.DueDate, "project_id": task.ProjectID,
}, nil
}
if task.ParentID != "" {
out["parent_id"] = task.ParentID
}
if unknownProject != "" {
// Phrased for a model to relay: it says what happened and what to do,
// so the person is told rather than left with a task in the wrong place.
out["note"] = fmt.Sprintf(
"There is no project called %q, so this went to the Inbox. "+
"Create the project and move it, or say which project you meant.",
unknownProject)
}
return out, nil
}
func (s *Server) mcpUpdateTask(ctx context.Context, userID string, args json.RawMessage) (any, error) {
@@ -364,8 +404,11 @@ func (s *Server) mcpUpdateTask(ctx context.Context, userID string, args json.Raw
if params.Labels != nil {
update.SetLabels, update.Labels = true, *params.Labels
}
// Moved before the field update, and through the same helper the REST handler
// uses. This used to check the caller's rights on the destination and then
// drop the argument, so the task never moved and the answer still said OK.
if params.ProjectID != nil {
if _, err := store.RequireProjectRole(ctx, s.db, *params.ProjectID, userID, store.RoleEditor); err != nil {
if err := s.moveTaskToProject(ctx, params.TaskID, *params.ProjectID, userID); err != nil {
return nil, mcp.ArgError("no project with id %q that you can write to", *params.ProjectID)
}
}
@@ -379,9 +422,13 @@ func (s *Server) mcpUpdateTask(ctx context.Context, userID string, args json.Raw
}
s.hub.Publish(task.ProjectID, "task.updated", toTaskJSON(*task))
// project_id is in the answer because it is one of the things that can be
// changed here: a caller that asked for a move can see whether it happened
// rather than taking "OK" on trust.
return map[string]any{
"id": task.ID, "content": task.Content, "priority": task.Priority,
"due_date": task.DueDate, "labels": task.Labels,
"project_id": task.ProjectID,
}, nil
}
+36
View File
@@ -69,6 +69,39 @@ type projectRequest struct {
Archived *bool `json:"archived"`
}
type reorderProjectsRequest struct {
// IDs in the order they should appear, top to bottom.
IDs []string `json:"ids"`
}
// handleReorderProjects sets the sidebar order.
//
// The whole list rather than one move: a person has a handful of projects, and
// sending the order you want is both simpler to reason about and impossible to
// get into the half-ordered state a sequence of individual moves can produce if
// one of them fails.
//
// Projects the caller does not own are skipped — sort_order is a column on the
// project, so a shared one sits where its owner put it.
func (s *Server) handleReorderProjects(w http.ResponseWriter, r *http.Request) {
var req reorderProjectsRequest
if err := decodeJSON(w, r, &req); err != nil {
return
}
// A ceiling rather than a guess at what is reasonable: this is a bound on
// the transaction, not an opinion about how many projects somebody may have.
if len(req.IDs) > 500 {
writeFieldErrors(w, map[string]string{"ids": "at most 500 at a time"})
return
}
if err := s.db.ReorderProjects(r.Context(), userFrom(r.Context()).ID, req.IDs); err != nil {
s.internal(w, "reorder projects", err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) handleCreateProject(w http.ResponseWriter, r *http.Request) {
var req projectRequest
if err := decodeJSON(w, r, &req); err != nil {
@@ -100,6 +133,7 @@ func (s *Server) handleCreateProject(w http.ResponseWriter, r *http.Request) {
return
}
s.activity(r, p.ID, "", "project.created", map[string]any{"name": p.Name})
s.publishToOwner(r, "project.created", toProjectJSON(*p))
writeJSON(w, http.StatusCreated, toProjectJSON(*p))
}
@@ -135,6 +169,7 @@ func (s *Server) handleUpdateProject(w http.ResponseWriter, r *http.Request) {
s.storeError(w, "get project", err)
return
}
s.publishToOwner(r, "project.updated", toProjectJSON(*p))
writeJSON(w, http.StatusOK, toProjectJSON(*p))
}
@@ -149,6 +184,7 @@ func (s *Server) handleDeleteProject(w http.ResponseWriter, r *http.Request) {
return
}
s.activity(r, projectID, "", "project.deleted", nil)
s.publishToOwner(r, "project.deleted", map[string]string{"id": projectID})
w.WriteHeader(http.StatusNoContent)
}
+113
View File
@@ -81,3 +81,116 @@ func TestTheTrashIsPerOwner(t *testing.T) {
t.Errorf("status %d, want 404", resp.StatusCode)
}
}
func TestReorderProjectsWritesTheGivenOrder(t *testing.T) {
ts := newTestServer(t)
ts.bootstrap(t)
var ids []string
for _, name := range []string{"Alfa", "Bravo", "Charlie"} {
_, body := ts.do(t, "POST", "/api/v1/projects", map[string]string{"name": name})
ids = append(ids, body["id"].(string))
}
// Back to front.
reversed := []string{ids[2], ids[1], ids[0]}
resp, _ := ts.do(t, "POST", "/api/v1/projects/reorder", map[string]any{"ids": reversed})
if resp.StatusCode != http.StatusNoContent {
t.Fatalf("reorder: status %d", resp.StatusCode)
}
_, list := ts.do(t, "GET", "/api/v1/projects", nil)
projects, _ := list["projects"].([]any)
var got []string
for _, raw := range projects {
p := raw.(map[string]any)
// The Inbox sorts ahead of everything by its own rule; it is not part of
// what was reordered.
if p["is_inbox"] == true {
continue
}
got = append(got, p["id"].(string))
}
if len(got) != 3 || got[0] != reversed[0] || got[1] != reversed[1] || got[2] != reversed[2] {
t.Errorf("order = %v, want %v", got, reversed)
}
}
// sort_order is a column on the project, not a per-viewer preference, so
// reordering must not rearrange a project somebody else owns.
func TestReorderProjectsLeavesSomebodyElsesAlone(t *testing.T) {
ts := newTestServer(t)
ts.bootstrap(t)
other := ts.newUser(t, "anden@example.dk", "Anden")
_, theirs := other.do(t, "POST", "/api/v1/projects", map[string]string{"name": "Deres"})
theirID := theirs["id"].(string)
_, before := other.do(t, "GET", "/api/v1/projects", nil)
var wanted float64
for _, raw := range before["projects"].([]any) {
if p := raw.(map[string]any); p["id"] == theirID {
wanted = p["sort_order"].(float64)
}
}
// Ask, as somebody else, to put their project first.
resp, _ := ts.do(t, "POST", "/api/v1/projects/reorder", map[string]any{
"ids": []string{theirID},
})
if resp.StatusCode != http.StatusNoContent {
t.Fatalf("reorder: status %d", resp.StatusCode)
}
_, after := other.do(t, "GET", "/api/v1/projects", nil)
for _, raw := range after["projects"].([]any) {
if p := raw.(map[string]any); p["id"] == theirID {
if p["sort_order"] != wanted {
t.Errorf("sort_order changed from %v to %v — somebody else moved it",
wanted, p["sort_order"])
}
}
}
}
// The member list errored on every project — the ORDER BY named an expression,
// which SQLite refuses across a UNION — so the share panel had never shown
// anybody, not even the owner.
func TestListMembersWorksAtAll(t *testing.T) {
ts := newTestServer(t)
ts.bootstrap(t)
_, project := ts.do(t, "POST", "/api/v1/projects", map[string]string{"name": "Firma"})
resp, body := ts.do(t, "GET", "/api/v1/projects/"+project["id"].(string)+"/members", nil)
if resp.StatusCode != http.StatusOK {
t.Fatalf("status %d, body %v", resp.StatusCode, body)
}
members, _ := body["members"].([]any)
if len(members) != 1 {
t.Fatalf("a project with no invites lists %d members, want its owner", len(members))
}
if m := members[0].(map[string]any); m["role"] != "owner" {
t.Errorf("role = %v, want owner", m["role"])
}
}
// And the Inbox, which is the one every task drawer asks about.
func TestListMembersWorksForTheInbox(t *testing.T) {
ts := newTestServer(t)
ts.bootstrap(t)
_, list := ts.do(t, "GET", "/api/v1/projects", nil)
var inboxID string
for _, raw := range list["projects"].([]any) {
if p := raw.(map[string]any); p["is_inbox"] == true {
inboxID = p["id"].(string)
}
}
resp, body := ts.do(t, "GET", "/api/v1/projects/"+inboxID+"/members", nil)
if resp.StatusCode != http.StatusOK {
t.Fatalf("status %d, body %v", resp.StatusCode, body)
}
}
+13
View File
@@ -28,6 +28,19 @@ func (s *Server) publish(projectID, event string, payload any) {
s.hub.Publish(projectID, event, payload)
}
// publishToOwner sends a change that belongs to a person rather than to a
// project: their projects, their labels, their saved filters.
//
// Project membership is what the socket subscribes to, and a project that has
// just been created has no subscribers — the person is not watching a thing that
// did not exist a moment ago. So these go to the user instead, which also
// reaches their other devices.
func (s *Server) publishToOwner(r *http.Request, event string, payload any) {
if user := userFrom(r.Context()); user != nil {
s.hub.PublishToUser(user.ID, event, payload)
}
}
// handleWebSocket is the live-sync connection.
func (s *Server) handleWebSocket(w http.ResponseWriter, r *http.Request) {
user := userFrom(r.Context())
+2
View File
@@ -259,6 +259,8 @@ func New(cfg *config.Config, db *store.DB, log *slog.Logger, web fs.FS) *Server
r.Route("/projects", func(r chi.Router) {
r.Get("/", s.handleListProjects)
r.Post("/", s.handleCreateProject)
// Above /{projectID}, or chi reads "reorder" as an id.
r.Post("/reorder", s.handleReorderProjects)
r.Route("/{projectID}", func(r chi.Router) {
// Read access is the floor for the whole subtree; the writes
+65
View File
@@ -1,6 +1,8 @@
package httpapi
import (
"context"
"errors"
"net/http"
"strconv"
"strings"
@@ -249,6 +251,16 @@ func (s *Server) handleUpdateTask(w http.ResponseWriter, r *http.Request) {
return
}
// A change of project is a move, not a field: it has to renumber the task
// among its new neighbours. Done before the rest so a request that both moves
// and edits ends up entirely applied or entirely refused.
if req.ProjectID != nil {
if err := s.moveTaskToProject(r.Context(), taskID, *req.ProjectID, user.ID); err != nil {
writeError(w, http.StatusNotFound, CodeNotFound, err.Error())
return
}
}
u := store.TaskUpdate{
Description: req.Description, Priority: req.Priority,
SectionID: req.SectionID, ParentID: req.ParentID,
@@ -473,11 +485,18 @@ func (s *Server) handleQuickAdd(w http.ResponseWriter, r *http.Request) {
}
projectID := req.ProjectID
// Set when the text named a project that does not exist. The task is still
// created — see below — but the caller is told, because the alternative is
// what it used to be: "#Dekoration" disappears from the title, the task lands
// somewhere else, and nothing anywhere says why.
unknownProject := ""
if parsed.Project != "" {
// An unknown "#name" is not an error: the task still gets created, in the
// Inbox, rather than a thought being thrown away over a typo.
if id, err := s.db.ProjectByName(r.Context(), user.ID, parsed.Project); err == nil {
projectID = id
} else {
unknownProject = parsed.Project
}
}
if projectID == "" {
@@ -510,6 +529,16 @@ func (s *Server) handleQuickAdd(w http.ResponseWriter, r *http.Request) {
t.Labels = parsed.Labels
s.activity(r, t.ProjectID, t.ID, "task.created", map[string]any{"content": t.Content})
s.publish(t.ProjectID, "task.created", toTaskJSON(*t))
if unknownProject != "" {
// Alongside the task rather than instead of it: the task was created, and
// this says what could not be honoured while creating it.
writeJSON(w, http.StatusCreated, struct {
taskJSON
UnknownProject string `json:"unknown_project"`
}{toTaskJSON(*t), unknownProject})
return
}
writeJSON(w, http.StatusCreated, toTaskJSON(*t))
}
@@ -525,6 +554,42 @@ func (s *Server) handleQuickAddPreview(w http.ResponseWriter, r *http.Request) {
// --- helpers --------------------------------------------------------------------
// moveTaskToProject moves a task to another project, if that is really what was
// asked for.
//
// Shared by the REST handler and the MCP tool, because they had drifted: both
// accepted project_id on an update, both checked the caller's rights on the
// destination — which reads as "understood" — and then neither passed it on,
// because store.TaskUpdate has no such field. The task stayed where it was and
// the response said OK. An argument that is validated and then dropped is worse
// than one that is refused.
//
// A move rather than a field assignment: sort_order is per project, so landing
// in a new one means being given a position among its tasks.
func (s *Server) moveTaskToProject(ctx context.Context, taskID, projectID, userID string) error {
if projectID == "" {
return nil
}
current, err := s.db.GetTask(ctx, taskID, userID)
if err != nil {
return errors.New("not found")
}
if current.ProjectID == projectID {
return nil // already there; not worth a write or a renumber
}
if _, err := store.RequireProjectRole(ctx, s.db, projectID, userID, store.RoleEditor); err != nil {
return errors.New("not found")
}
// No neighbours: it lands at the start of the destination, which is the only
// answer available when the caller did not say where. Section is cleared —
// a section belongs to the project being left behind.
if _, err := s.db.MoveTask(ctx, taskID, projectID, "", "", ""); err != nil {
return errors.New("not found")
}
return nil
}
func validateTaskContent(content string, priority *int) map[string]string {
fields := map[string]string{}
switch {
+55
View File
@@ -0,0 +1,55 @@
package httpapi
import "testing"
// A label is how you find a task whose wording you have forgotten. Search
// covered the text only, so "regnskab" found nothing even with the task
// labelled @regnskab in front of you.
func TestSearchFindsTasksByLabel(t *testing.T) {
ts := newTestServer(t)
ts.bootstrap(t)
ts.do(t, "POST", "/api/v1/tasks/quick-add",
map[string]any{"text": "ring til revisoren @regnskab"})
ts.do(t, "POST", "/api/v1/tasks/quick-add",
map[string]any{"text": "køb kaffe"})
_, body := ts.do(t, "GET", "/api/v1/search?q=regnskab", nil)
tasks, _ := body["tasks"].([]any)
if len(tasks) != 1 {
t.Fatalf("found %d tasks searching for a label, want 1: %v", len(tasks), body)
}
if got := tasks[0].(map[string]any)["content"]; got != "ring til revisoren" {
t.Errorf("found %v", got)
}
}
// The text search still works, and a label match does not swallow it.
func TestSearchStillFindsTasksByText(t *testing.T) {
ts := newTestServer(t)
ts.bootstrap(t)
ts.do(t, "POST", "/api/v1/tasks/quick-add", map[string]any{"text": "køb grøn maling"})
// Diacritic folding still applies to the text side.
_, body := ts.do(t, "GET", "/api/v1/search?q=gron", nil)
if tasks, _ := body["tasks"].([]any); len(tasks) != 1 {
t.Errorf("searching \"gron\" found %d tasks, want 1", len(tasks))
}
}
// Somebody else's label must not pull their task into your results — the label
// join has to stay inside the visibility the outer query already applies.
func TestSearchByLabelStaysWithinWhatYouCanSee(t *testing.T) {
ts := newTestServer(t)
ts.bootstrap(t)
other := ts.newUser(t, "anden@example.dk", "Anden")
other.do(t, "POST", "/api/v1/tasks/quick-add",
map[string]any{"text": "deres hemmelighed @regnskab"})
_, body := ts.do(t, "GET", "/api/v1/search?q=regnskab", nil)
if tasks, _ := body["tasks"].([]any); len(tasks) != 0 {
t.Errorf("found somebody else's task: %v", tasks)
}
}
+47 -8
View File
@@ -328,15 +328,27 @@ type Member struct {
// project_members row — ownership is the projects table — so they are unioned in
// rather than left out of the list of people who can see it.
func (db *DB) ListMembers(ctx context.Context, projectID string) ([]Member, error) {
// The owner first, then everybody else by name.
//
// The ordering is a column rather than an expression, and the whole compound
// select is wrapped: SQLite only accepts ORDER BY terms from the result set
// of a UNION, so `ORDER BY role = 'owner' DESC` — which reads perfectly well
// — fails at query time with "1st ORDER BY term does not match any column in
// the result set". Every call errored, so the share panel had never listed
// anybody.
rows, err := db.QueryContext(ctx, `
SELECT u.id, u.email, u.name, u.avatar_color, 'owner' AS role, p.created_at
FROM projects p JOIN users u ON u.id = p.owner_id
WHERE p.id = ?
UNION ALL
SELECT u.id, u.email, u.name, u.avatar_color, m.role, m.added_at
FROM project_members m JOIN users u ON u.id = m.user_id
WHERE m.project_id = ?
ORDER BY role = 'owner' DESC, name`, projectID, projectID)
SELECT id, email, name, avatar_color, role, added_at FROM (
SELECT u.id, u.email, u.name, u.avatar_color, 'owner' AS role,
p.created_at AS added_at, 0 AS rank
FROM projects p JOIN users u ON u.id = p.owner_id
WHERE p.id = ?
UNION ALL
SELECT u.id, u.email, u.name, u.avatar_color, m.role,
m.added_at, 1 AS rank
FROM project_members m JOIN users u ON u.id = m.user_id
WHERE m.project_id = ?
)
ORDER BY rank, name`, projectID, projectID)
if err != nil {
return nil, err
}
@@ -556,3 +568,30 @@ func joinComma(parts []string) string {
}
return out
}
// ReorderProjects writes the given order, and only for projects the user owns.
//
// The whole list at once, rather than the midpoint-between-neighbours dance the
// tasks do. A person has a handful of projects, not a thousand, so writing
// 0, 1, 2 … is one small transaction that cannot run out of precision — the
// failure the task ordering has to respace a section to recover from.
//
// Scoped to ownership because sort_order lives on the project row rather than
// per viewer: a shared project sits where its owner put it, and a member
// reordering their sidebar must not rearrange somebody else's. Ids that are not
// the caller's are skipped rather than refused, so one shared project in the
// list does not fail the whole drag.
func (db *DB) ReorderProjects(ctx context.Context, userID string, ids []string) error {
return db.Tx(ctx, func(tx *sql.Tx) error {
now := time.Now().Unix()
for i, id := range ids {
if _, err := tx.ExecContext(ctx,
`UPDATE projects SET sort_order = ?, updated_at = ?
WHERE id = ? AND owner_id = ? AND deleted_at IS NULL`,
float64(i), now, id, userID); err != nil {
return err
}
}
return nil
})
}
+17 -2
View File
@@ -136,8 +136,23 @@ func (db *DB) ListTasks(ctx context.Context, userID string, f TaskFilter) ([]Tas
args = append(args, f.DueFrom)
}
if expr := MatchExpr(f.Search); expr != "" {
where = append(where, `t.rowid IN (SELECT rowid FROM tasks_fts WHERE tasks_fts MATCH ?)`)
args = append(args, expr)
// Text or a label. A label is how you find a task whose wording you have
// forgotten — "that thing about the accounts" is a search for @regnskab —
// and leaving them out made the box look like it had lost the task.
//
// The label side is a plain lowercase match rather than another FTS index:
// labels are short, and their names are typed by the person searching for
// them, so there is no spelling to be generous about. The diacritic
// folding that matters for task text does not earn a second index here.
where = append(where, `(
t.rowid IN (SELECT rowid FROM tasks_fts WHERE tasks_fts MATCH ?)
OR t.id IN (
SELECT tl.task_id FROM task_labels tl
JOIN labels l ON l.id = tl.label_id
WHERE lower(l.name) LIKE ?
)
)`)
args = append(args, expr, "%"+strings.ToLower(strings.TrimSpace(f.Search))+"%")
}
if f.FilterSQL != "" {
where = append(where, "("+f.FilterSQL+")")
+151 -1
View File
@@ -87,7 +87,157 @@
--content-max: 720px;
}
:root[data-theme='light'] {
/*
* The dark palette again, by name.
*
* :root carries it as the default, and :root only ever matches <html> — so a
* swatch in the settings picker asking for data-theme="dark" would otherwise
* inherit whatever the page is wearing. Repeated rather than restructured: the
* alternative is splitting the token block in two and leaving somebody to work
* out which half a new token belongs in.
*/
[data-theme='dark'] {
--ground: #111312;
--surface: #171a19;
--surface-raised: #1d211f;
--surface-sunken: #0d0f0e;
--line: #262b29;
--line-strong: #343a37;
--ink: #e8ebe9;
--ink-muted: #9aa39e;
--ink-faint: #6b736f;
--accent: #5fbf8f;
--accent-hover: #6fcf9f;
--accent-sunken: #1c3329;
--accent-ink: #0d1411;
--p1: #cf6b6b;
--p2: #d69f5c;
--p3: #6b9ecf;
--p4: var(--ink-faint);
--danger: #cf6b6b;
--danger-sunken: #33201f;
--shadow: 0 1px 2px rgb(0 0 0 / 0.2);
--shadow-lg: 0 8px 32px rgb(0 0 0 / 0.35);
}
/*
* The other themes.
*
* Each one redefines colour and nothing else: no spacing, no type, no radii.
* That is what keeps them themes rather than five separate designs, and it is
* why a component that reaches for a raw hex breaks in four places at once
* instead of one.
*
* Every theme states its full palette rather than inheriting the dark one and
* patching it. A partial theme looks finished until somebody adds a token, at
* which point four themes silently fall back to a colour from a fifth.
*/
/* Skumring — the same dark, turned warm, with amber where the green was. */
[data-theme='dusk'] {
--ground: #14110f;
--surface: #1b1714;
--surface-raised: #221d19;
--surface-sunken: #100d0b;
--line: #2b2521;
--line-strong: #3a322c;
--ink: #ece6df;
--ink-muted: #a3988c;
/* Light enough to clear 4.5:1 against the ground. The quiet tier is where
dates and counts live, and it is the first thing to disappear. */
--ink-faint: #8d8377;
--accent: #d99a4e;
--accent-hover: #e8a95c;
--accent-sunken: #33261480;
--accent-ink: #16110a;
--p1: #cf6b6b;
--p2: #d69f5c;
--p3: #6b9ecf;
--p4: var(--ink-faint);
--danger: #cf6b6b;
--danger-sunken: #33201f;
--shadow: 0 1px 2px rgb(0 0 0 / 0.25);
--shadow-lg: 0 8px 32px rgb(0 0 0 / 0.4);
}
/* Papir — warm light, closer to paper than to a screen. */
[data-theme='paper'] {
--ground: #f6f1e7;
--surface: #fffcf6;
--surface-raised: #fffcf6;
--surface-sunken: #ece5d7;
--line: #ded5c3;
--line-strong: #c8bda6;
--ink: #241f18;
--ink-muted: #665c4c;
--ink-faint: #756a55;
--accent: #8a5a2b;
--accent-hover: #74491f;
--accent-sunken: #ebdfcb;
--accent-ink: #fffcf6;
--p1: #b0452f;
--p2: #96701f;
--p3: #3f6b8a;
--p4: var(--ink-faint);
--danger: #b0452f;
--danger-sunken: #f3e2dc;
--shadow: 0 1px 2px rgb(60 40 10 / 0.08);
--shadow-lg: 0 8px 32px rgb(60 40 10 / 0.14);
}
/*
* Kontrast — for reading in bright sun, or for eyes that the quiet greys of the
* other four do not serve. Pure black on white, borders that are actually
* visible, and an accent dark enough to pass against white text.
*
* The muted inks are deliberately much darker than elsewhere: "secondary text"
* at 60% grey is the first thing to disappear, and it is where dates live.
*/
[data-theme='contrast'] {
--ground: #ffffff;
--surface: #ffffff;
--surface-raised: #f2f2f2;
--surface-sunken: #e8e8e8;
--line: #767676;
--line-strong: #1a1a1a;
--ink: #000000;
--ink-muted: #2b2b2b;
--ink-faint: #4a4a4a;
--accent: #005c2e;
--accent-hover: #00753a;
--accent-sunken: #cfe8da;
--accent-ink: #ffffff;
--p1: #a10000;
--p2: #7a4a00;
--p3: #00417a;
--p4: var(--ink-faint);
--danger: #a10000;
--danger-sunken: #f7dcdc;
--shadow: 0 1px 2px rgb(0 0 0 / 0.3);
--shadow-lg: 0 8px 32px rgb(0 0 0 / 0.35);
}
[data-theme='light'] {
--ground: #faf9f7;
--surface: #ffffff;
--surface-raised: #ffffff;
+1
View File
@@ -176,6 +176,7 @@ export const api = {
createProject: (data) => post('/projects', data),
updateProject: (id, data) => patch(`/projects/${id}`, data),
deleteProject: (id) => del(`/projects/${id}`),
reorderProjects: (ids) => post('/projects/reorder', { ids }),
listTrashedProjects: () => get('/trash/projects'),
restoreProject: (id) => post(`/trash/projects/${id}/restore`),
+186 -2
View File
@@ -1,5 +1,5 @@
<script>
import { app } from '$lib/stores.svelte.js';
import { app, sidebar } from '$lib/stores.svelte.js';
import { api } from '$lib/api.js';
import { page } from '$app/stores';
import { goto } from '$app/navigation';
@@ -27,14 +27,90 @@
let filters = $state([]);
let labels = $state([]);
// Reads app.labelsChanged so the effect re-runs when a label is created,
// renamed or deleted anywhere — including in another tab, or by Claude
// through the connector.
$effect(() => {
app.labelsChanged;
api.listFilters().then((r) => (filters = r.filters)).catch(() => {});
api.listLabels().then((r) => (labels = r.labels)).catch(() => {});
});
let shared = $derived(app.projects.filter((p) => !p.is_inbox && p.shared));
let own = $derived(app.projects.filter((p) => !p.is_inbox && !p.shared));
// Sorted here rather than relying on the order the server sent, so a drag
// settles the moment it is dropped instead of after the round trip.
let own = $derived(
app.projects
.filter((p) => !p.is_inbox && !p.shared)
.sort((a, b) => a.sort_order - b.sort_order)
);
let current = $derived($page.url.pathname);
// --- resizing -------------------------------------------------------------------
let resizing = $state(false);
/**
* Pointer events rather than mouse events, so a trackpad, a mouse and a stylus
* all work. Capturing the pointer means the drag keeps following even when it
* leaves the handle, which at 4px wide it does constantly.
*/
function startResize(event) {
event.preventDefault();
resizing = true;
event.currentTarget.setPointerCapture(event.pointerId);
}
function onResize(event) {
if (!resizing) return;
sidebar.setWidth(event.clientX);
}
function endResize(event) {
if (!resizing) return;
resizing = false;
event.currentTarget.releasePointerCapture?.(event.pointerId);
}
// --- reordering ---------------------------------------------------------------
let draggingId = $state(null);
let overId = $state(null);
let overBelow = $state(false);
function onDragStart(event, project) {
draggingId = project.id;
event.dataTransfer.effectAllowed = 'move';
// Firefox refuses to start a drag unless something is set on the transfer.
event.dataTransfer.setData('text/plain', project.id);
}
function onDragOver(event, project) {
if (!draggingId || draggingId === project.id) return;
event.preventDefault();
event.dataTransfer.dropEffect = 'move';
const box = event.currentTarget.getBoundingClientRect();
overId = project.id;
overBelow = event.clientY > box.top + box.height / 2;
}
async function onDrop(event, target) {
event.preventDefault();
const id = draggingId;
const below = overBelow;
draggingId = null;
overId = null;
if (!id || id === target.id) return;
const without = own.filter((p) => p.id !== id);
const at = without.findIndex((p) => p.id === target.id);
if (at < 0) return;
const ordered = [...without];
ordered.splice(below ? at + 1 : at, 0, own.find((p) => p.id === id));
await app.reorderProjects(ordered.map((p) => p.id));
}
</script>
<nav class="sidebar" aria-label="Hovedmenu">
@@ -90,8 +166,21 @@
{#each own as project (project.id)}
<a
href="/projekt/{project.id}"
class="sortable"
class:active={current === `/projekt/${project.id}`}
class:dragging={draggingId === project.id}
class:drop-above={overId === project.id && !overBelow}
class:drop-below={overId === project.id && overBelow}
onclick={onnavigate}
draggable="true"
ondragstart={(e) => onDragStart(e, project)}
ondragend={() => {
draggingId = null;
overId = null;
}}
ondragover={(e) => onDragOver(e, project)}
ondragleave={() => (overId = null)}
ondrop={(e) => onDrop(e, project)}
>
<span class="dot" aria-hidden="true"></span>
{project.name}
@@ -182,6 +271,29 @@
<span class="signout">Log ud</span>
</button>
</div>
<!-- Also a slider for the keyboard: arrow keys move it, and Home puts it back.
A drag handle with no keyboard equivalent is a setting some people simply
cannot reach. -->
<div
class="resize"
class:resizing
role="separator"
aria-orientation="vertical"
aria-label="Bredde på sidebjælken"
tabindex="0"
onpointerdown={startResize}
onpointermove={onResize}
onpointerup={endResize}
onpointercancel={endResize}
ondblclick={() => sidebar.reset()}
onkeydown={(e) => {
if (e.key === 'ArrowLeft') sidebar.setWidth(sidebar.width - 16);
else if (e.key === 'ArrowRight') sidebar.setWidth(sidebar.width + 16);
else if (e.key === 'Home') sidebar.reset();
else return;
e.preventDefault();
}}
></div>
</nav>
<style>
@@ -196,6 +308,45 @@
border-right: 1px solid var(--line);
overflow-y: auto;
padding-left: max(var(--s3), env(safe-area-inset-left));
position: relative;
}
/* Sits on the border, wider than it looks: a 1px target is a target you miss.
The visible line stays the border; this only widens what the pointer hits. */
.resize {
position: absolute;
top: 0;
bottom: 0;
right: -3px;
width: 7px;
cursor: col-resize;
z-index: 10;
}
.resize::after {
content: '';
position: absolute;
inset: 0 3px;
background: var(--accent);
opacity: 0;
transition: opacity var(--fast) var(--ease);
}
.resize:hover::after,
.resize:focus-visible::after,
.resize.resizing::after {
opacity: 1;
}
.resize:focus-visible {
outline: none;
}
@media (max-width: 820px) {
/* The drawer has a fixed width and no room to drag against. */
.resize {
display: none;
}
}
.brand {
@@ -280,6 +431,39 @@
font-weight: 500;
}
/* Only your own projects reorder. A shared one sits where its owner put it —
sort_order is a column on the project, not a preference per viewer. */
a.sortable {
position: relative;
}
a.sortable.dragging {
opacity: 0.4;
}
/* A line in the gap rather than a highlighted row: the gap is the target. */
a.sortable::before {
content: '';
position: absolute;
left: var(--s2);
right: var(--s2);
height: 2px;
background: var(--accent);
opacity: 0;
pointer-events: none;
transition: opacity var(--fast) var(--ease);
}
a.sortable.drop-above::before {
top: -1px;
opacity: 1;
}
a.sortable.drop-below::before {
bottom: -1px;
opacity: 1;
}
.dot {
width: 6px;
height: 6px;
+136 -10
View File
@@ -20,6 +20,23 @@
let priority = $state(4);
let dueDate = $state('');
let labels = $state('');
let projectId = $state('');
let recurrence = $state('');
let assignee = $state('');
/** Who the task can be given to. Only ever more than one on a shared project. */
let members = $state([]);
// The rules worth a menu entry. Anything more specific is typed into the
// title, where the parser understands far more than a list ever could.
const REPEATS = [
{ rule: '', label: 'Aldrig' },
{ rule: 'FREQ=DAILY', label: 'Hver dag' },
{ rule: 'FREQ=WEEKLY', label: 'Hver uge' },
{ rule: 'FREQ=WEEKLY;INTERVAL=2', label: 'Hver anden uge' },
{ rule: 'FREQ=MONTHLY', label: 'Hver måned' },
{ rule: 'FREQ=YEARLY', label: 'Hvert år' }
];
let subtasks = $state([]);
let comments = $state([]);
@@ -46,6 +63,17 @@
priority = task.priority;
dueDate = task.due_date ?? '';
labels = (task.labels ?? []).join(', ');
projectId = task.project_id;
recurrence = task.recurrence_rule ?? '';
assignee = task.assignee_id ?? '';
members = [];
api.listMembers(task.project_id)
.then((r) => r.members.length > 1 && (members = r.members))
.catch(() => {
// A project you are not the owner of may refuse the member list.
// Then there is nobody to choose from, which is the same as none.
});
subtasks = [];
comments = [];
@@ -73,13 +101,83 @@
await app.update(task.id, patch);
}
function saveContent() {
/**
* Saves the title, reading it the way quick add would.
*
* Typing "i morgen kl. 14" into a title used to leave it as those words. The
* same sentence in the quick-add box becomes a date, which made where you
* typed it decide what it meant.
*
* The parse runs on the server — the grammar is Danish and English and lives
* there — and is only applied when it actually consumed something. What it
* took is said out loud, because a title that edits itself without a word is
* worse than one that does nothing.
*/
async function saveContent() {
const trimmed = content.trim();
if (!trimmed || trimmed === task.content) {
content = task.content;
return;
}
save({ content: trimmed });
let parsed = null;
try {
parsed = await api.quickAddPreview(trimmed);
} catch {
// Offline, or the parser refused. Saving the words is still right.
}
const patch = { content: trimmed };
const took = [];
if (parsed && parsed.content && parsed.content !== trimmed) {
patch.content = parsed.content;
if (parsed.due_date) {
patch.due_date = parsed.due_date;
took.push(parsed.due_date);
}
if (parsed.priority && parsed.priority < 4) {
patch.priority = parsed.priority;
took.push(`P${parsed.priority}`);
}
if (parsed.recurrence) {
patch.recurrence_rule = parsed.recurrence;
took.push('gentagelse');
}
if (parsed.labels?.length) {
patch.labels = [...new Set([...(task.labels ?? []), ...parsed.labels])];
took.push(parsed.labels.map((l) => `@${l}`).join(' '));
}
}
await save(patch);
// The fields are seeded once per task so a save cannot overwrite what
// somebody is typing. That rule has to bend exactly here: this save
// changed the very fields on screen, and leaving them showing what was
// typed while the toast reports something else is the worst of both.
if (took.length) {
content = patch.content;
if (patch.due_date) dueDate = patch.due_date;
if (patch.priority) priority = patch.priority;
if (patch.recurrence_rule) recurrence = patch.recurrence_rule;
if (patch.labels) labels = patch.labels.join(', ');
app.toast(`Læst som ${took.join(', ')}.`);
}
}
async function saveProject() {
if (projectId === task.project_id) return;
await save({ project_id: projectId });
}
async function saveRecurrence() {
if (recurrence === (task.recurrence_rule ?? '')) return;
await save({ recurrence_rule: recurrence });
}
async function saveAssignee() {
if (assignee === (task.assignee_id ?? '')) return;
await save({ assignee_id: assignee });
}
function saveDescription() {
@@ -316,8 +414,42 @@
/>
</div>
{#if task.recurrence_text}
<p class="repeats">Gentages {task.recurrence_text}.</p>
<div class="grid">
<div class="field">
<label for="project">Projekt</label>
<select id="project" bind:value={projectId} onchange={saveProject}>
{#each app.projects as project (project.id)}
<option value={project.id}>{project.name}</option>
{/each}
</select>
</div>
<div class="field">
<label for="repeat">Gentages</label>
<select id="repeat" bind:value={recurrence} onchange={saveRecurrence}>
{#each REPEATS as option (option.rule)}
<option value={option.rule}>{option.label}</option>
{/each}
<!-- A rule typed as "hver anden tirsdag" has no entry in the list;
showing it rather than snapping to the nearest preset is the
difference between a menu and a menu that quietly edits. -->
{#if recurrence && !REPEATS.some((o) => o.rule === recurrence)}
<option value={recurrence}>{task.recurrence_text ?? 'Som skrevet'}</option>
{/if}
</select>
</div>
</div>
{#if members.length > 1}
<div class="field">
<label for="assignee">Ansvarlig</label>
<select id="assignee" bind:value={assignee} onchange={saveAssignee}>
<option value="">Ingen</option>
{#each members as member (member.user_id)}
<option value={member.user_id}>{member.name}</option>
{/each}
</select>
</div>
{/if}
<section>
@@ -567,12 +699,6 @@
gap: var(--s3);
}
.repeats {
margin: 0;
font-size: var(--text-sm);
color: var(--ink-muted);
}
section {
display: flex;
flex-direction: column;
+187 -13
View File
@@ -29,6 +29,16 @@ class AppState {
*/
detailId = $state(null);
/**
* Bumped whenever a label changes anywhere.
*
* A counter rather than the labels themselves: the sidebar wants each label's
* task count, which no single event carries and which changes whenever a task
* gains or loses one. Whoever is showing labels re-reads them; that is one
* small request against modelling a count in two places.
*/
labelsChanged = $state(0);
#socket = null;
#reconnectDelay = 1000;
@@ -110,6 +120,25 @@ class AppState {
case 'task.deleted':
this.tasks = this.tasks.filter((t) => t.id !== task?.id);
break;
// Projects and labels belong to a person rather than to a project, so
// they arrive on the user's own channel — a project that has just been
// created has no subscribers, because nobody was watching a thing that
// did not exist a moment ago.
case 'project.created':
case 'project.updated':
this.upsertProject(task);
break;
case 'project.deleted':
this.projects = this.projects.filter((p) => p.id !== task?.id);
break;
// The payload is not always the label — a rename says only that
// something changed — and the sidebar wants counts anyway, which no
// single event carries. Asking is cheaper than modelling it.
case 'label.changed':
this.labelsChanged++;
break;
}
}
@@ -136,6 +165,13 @@ class AppState {
* copy is not worth a moment's thought next to the class of bug it removes.
*/
replace(id, next) {
// A task can invent a label just by mentioning one — "@regnskab" in quick
// add creates it — and no label event is sent for that, because it happened
// inside a task write. Comparing the two lists is what keeps the sidebar
// honest without re-reading the labels on every completed checkbox.
const before = this.tasks.find((t) => t.id === id)?.labels ?? [];
if ((next?.labels ?? []).join() !== before.join()) this.labelsChanged++;
this.tasks = this.tasks.map((t) => (t.id === id ? next : t));
}
@@ -151,14 +187,33 @@ class AppState {
*/
upsert(task) {
if (!task?.id) return;
if (this.tasks.some((t) => t.id === task.id)) this.replace(task.id, task);
else this.tasks = [...this.tasks, task];
if (this.tasks.some((t) => t.id === task.id)) {
this.replace(task.id, task);
return;
}
if (task.labels?.length) this.labelsChanged++;
this.tasks = [...this.tasks, task];
}
get(id) {
return this.tasks.find((t) => t.id === id);
}
/**
* Adds a project, or replaces it if the list already has it.
*
* The same guard the tasks need, and for the same reason: a project arrives
* twice, once as the response to the request that created it and once over
* the socket. Appending both puts two rows with one id into a keyed `{#each}`,
* which throws and stops the sidebar rendering.
*/
upsertProject(project) {
if (!project?.id) return;
this.projects = this.projects.some((p) => p.id === project.id)
? this.projects.map((p) => (p.id === project.id ? project : p))
: [...this.projects, project];
}
/**
* Ticks a task off. The row is struck through and gone before the request
* leaves — which is the single most-repeated action in the app, and the one
@@ -233,7 +288,7 @@ class AppState {
async createProject(name) {
try {
const project = await api.createProject({ name });
this.projects = [...this.projects, project];
this.upsertProject(project);
return project;
} catch (e) {
this.toast(humanMessage(e));
@@ -246,6 +301,29 @@ class AppState {
this.projects = projects;
}
/**
* Puts the projects in the given order.
*
* The whole list rather than one moved item: it is a handful of rows, and
* sending the order you want cannot land in the half-applied state a sequence
* of individual moves can. `sort_order` is set here as well as on the server,
* so the sidebar settles immediately rather than after a round trip.
*/
async reorderProjects(ids) {
const previous = this.projects;
const rank = new Map(ids.map((id, i) => [id, i]));
this.projects = this.projects.map((p) =>
rank.has(p.id) ? { ...p, sort_order: rank.get(p.id) } : p
);
try {
await api.reorderProjects(ids);
} catch (e) {
this.projects = previous;
this.toast(humanMessage(e));
}
}
// --- toasts -------------------------------------------------------------------
toast(message) {
@@ -263,21 +341,117 @@ class AppState {
export const app = new AppState();
/** Theme, kept in localStorage and applied to the document element. */
export const theme = {
get current() {
if (typeof document === 'undefined') return 'dark';
return document.documentElement.dataset.theme ?? 'dark';
},
/**
* How wide the sidebar is, and whether it is showing at all.
*
* Kept in localStorage rather than on the account: it is a property of the
* screen you are sitting at, not of you. The same person on a laptop and on a
* wide monitor wants different answers, and syncing it would make one of those
* two wrong every time they switch.
*/
const SIDEBAR_MIN = 200;
const SIDEBAR_MAX = 480;
const SIDEBAR_DEFAULT = 268;
function storedNumber(key, fallback) {
if (typeof localStorage === 'undefined') return fallback;
const raw = Number(localStorage.getItem(key));
return Number.isFinite(raw) && raw > 0 ? raw : fallback;
}
class SidebarLayout {
width = $state(storedNumber('verdande:sidebar-width', SIDEBAR_DEFAULT));
collapsed = $state(
typeof localStorage !== 'undefined' && localStorage.getItem('verdande:sidebar-collapsed') === '1'
);
setWidth(px) {
// Clamped here rather than in the drag handler, so every caller gets the
// same rule and a stored value from an older build cannot make the
// sidebar unusably narrow.
this.width = Math.round(Math.min(SIDEBAR_MAX, Math.max(SIDEBAR_MIN, px)));
this.#save('verdande:sidebar-width', String(this.width));
}
toggle() {
const next = this.current === 'dark' ? 'light' : 'dark';
document.documentElement.dataset.theme = next;
this.collapsed = !this.collapsed;
this.#save('verdande:sidebar-collapsed', this.collapsed ? '1' : '0');
}
reset() {
this.setWidth(SIDEBAR_DEFAULT);
}
#save(key, value) {
try {
localStorage.setItem('verdande:theme', next);
localStorage.setItem(key, value);
} catch {
// Private browsing; the choice simply will not persist.
}
}
};
}
export const sidebar = new SidebarLayout();
/**
* The themes on offer.
*
* `dark` is the tokens on bare :root; the rest are [data-theme] blocks in
* app.css. The list lives here so the picker and the stylesheet cannot drift —
* an entry with no CSS behind it renders as the default and looks like a bug in
* the picker rather than a missing block.
*/
export const THEMES = [
{ id: 'dark', name: 'Nordlys', note: 'Mørk med grøn accent.', dark: true },
{ id: 'dusk', name: 'Skumring', note: 'Mørk og varm, med rav.', dark: true },
{ id: 'light', name: 'Dagslys', note: 'Lys og køligt neutral.', dark: false },
{ id: 'paper', name: 'Papir', note: 'Lys og varm, som papir.', dark: false },
{ id: 'contrast', name: 'Kontrast', note: 'Sort på hvidt, til skarpt lys.', dark: false }
];
/** Theme, kept in localStorage and applied to the document element. */
class Theme {
/**
* Mirrors the attribute on <html>, which app.html sets before first paint —
* that is the only way to avoid a white flash on load, and it means the
* document, not this object, is where the truth lives.
*/
current = $state(
typeof document === 'undefined' ? 'dark' : (document.documentElement.dataset.theme ?? 'dark')
);
set(id) {
if (!THEMES.some((t) => t.id === id)) return;
this.current = id;
document.documentElement.dataset.theme = id;
// The browser paints its own chrome from this — the address bar on a
// phone, the frame of an installed PWA. Left alone it stays the colour of
// whichever theme shipped in the markup.
const ground = getComputedStyle(document.documentElement).getPropertyValue('--ground').trim();
document.querySelector('meta[name="theme-color"]')?.setAttribute('content', ground);
try {
localStorage.setItem('verdande:theme', id);
} catch {
// Private browsing; the choice simply will not persist.
}
}
/**
* The topbar button, which flips between light and dark rather than walking
* all five. Somebody who has chosen Skumring wants the light one to be Papir,
* not to be marched back to the default — so it moves to the other side of
* the list and stays warm or stays cool.
*/
toggle() {
const now = THEMES.find((t) => t.id === this.current) ?? THEMES[0];
const opposite = THEMES.filter((t) => t.dark !== now.dark);
const index = THEMES.filter((t) => t.dark === now.dark).indexOf(now);
this.set((opposite[index] ?? opposite[0]).id);
}
}
export const theme = new Theme();
export { ApiError, humanMessage };
+64 -2
View File
@@ -1,6 +1,6 @@
<script>
import '../app.css';
import { app, theme } from '$lib/stores.svelte.js';
import { app, theme, sidebar } from '$lib/stores.svelte.js';
import { goto } from '$app/navigation';
import { page } from '$app/stores';
import Sidebar from '$lib/components/Sidebar.svelte';
@@ -66,11 +66,20 @@
{:else if !app.user}
<SignIn />
{:else}
<div class="shell" class:sidebar-open={sidebarOpen}>
<div
class="shell"
class:sidebar-open={sidebarOpen}
class:sidebar-collapsed={sidebar.collapsed}
style="--sidebar-width: {sidebar.width}px"
>
<Sidebar onnavigate={() => (sidebarOpen = false)} />
<main>
<header class="topbar">
<!-- Two controls, not one: on a phone the sidebar is a drawer that
opens over the page, on a desktop it is a column that folds away.
Same words, different actions, so each is shown only where it
applies. -->
<button
class="menu"
onclick={() => (sidebarOpen = !sidebarOpen)}
@@ -82,6 +91,19 @@
</svg>
</button>
<button
class="fold"
onclick={() => sidebar.toggle()}
aria-label={sidebar.collapsed ? 'Vis sidebjælken' : 'Skjul sidebjælken'}
aria-pressed={sidebar.collapsed}
title={sidebar.collapsed ? 'Vis sidebjælken' : 'Skjul sidebjælken'}
>
<svg viewBox="0 0 24 24" aria-hidden="true">
<rect x="3" y="4" width="18" height="16" rx="2" />
<path d="M9 4v16" />
</svg>
</button>
<button class="search" onclick={() => (paletteOpen = true)}>
<span>Søg</span>
<kbd>⌘K</kbd>
@@ -173,7 +195,32 @@
color: var(--ink-muted);
}
.fold {
display: grid;
width: 32px;
height: 32px;
place-items: center;
border-radius: var(--radius);
color: var(--ink-faint);
transition: color var(--fast) var(--ease);
}
.fold:hover {
color: var(--ink);
}
/* Folded away rather than merely narrow: width 0 with the border gone, so
nothing of it is left to catch the eye. */
.shell.sidebar-collapsed :global(.sidebar) {
width: 0;
padding-left: 0;
padding-right: 0;
border-right: 0;
overflow: hidden;
}
.menu svg,
.fold svg,
.theme svg {
width: 18px;
height: 18px;
@@ -277,6 +324,11 @@
display: grid;
}
/* The drawer is the whole answer here; folding a drawer means nothing. */
.fold {
display: none;
}
.scrim {
display: block;
}
@@ -292,5 +344,15 @@
.shell.sidebar-open :global(.sidebar) {
transform: translateX(0);
}
/* A collapsed desktop sidebar must not follow you to a phone, where the
drawer would then open to nothing. */
.shell.sidebar-collapsed :global(.sidebar) {
width: var(--sidebar-width);
padding-left: max(var(--s3), env(safe-area-inset-left));
padding-right: var(--s3);
border-right: 1px solid var(--line);
overflow-y: auto;
}
}
</style>
+110 -1
View File
@@ -1,7 +1,7 @@
<script>
/** Konto: who you are, your password, and the second factor. */
import { api, humanMessage } from '$lib/api.js';
import { app } from '$lib/stores.svelte.js';
import { app, theme, THEMES } from '$lib/stores.svelte.js';
// --- profile ---------------------------------------------------------------
@@ -204,6 +204,39 @@
</form>
</section>
<section class="panel">
<header>
<h2>Udseende</h2>
<p class="hint">
Gemmes i denne browser. Det er en egenskab ved den skærm, du sidder ved —
en bærbar i solen og en skærm i et mørkt rum vil have hvert sit svar.
</p>
</header>
<div class="themes">
{#each THEMES as option (option.id)}
<button
class="theme-card"
class:chosen={theme.current === option.id}
onclick={() => theme.set(option.id)}
aria-pressed={theme.current === option.id}
>
<!-- data-theme goes on the swatch and not on the card: it redefines
--ink too, and a card wearing a dark theme's ink on a light page
has a name nobody can read. The swatch shows the colours; the
label stays in the page's. -->
<span class="swatch" data-theme={option.id} aria-hidden="true">
<span class="swatch-line"></span>
<span class="swatch-line short"></span>
<span class="swatch-dot"></span>
</span>
<span class="theme-name">{option.name}</span>
<span class="theme-note">{option.note}</span>
</button>
{/each}
</div>
</section>
<section class="panel">
<header>
<h2>Adgangskode</h2>
@@ -353,6 +386,82 @@
border-radius: var(--radius);
}
.themes {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
gap: var(--s3);
}
.theme-card {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: var(--s1);
padding: var(--s3);
border: 1px solid var(--line);
border-radius: var(--radius);
text-align: left;
transition: border-color var(--fast) var(--ease);
}
.theme-card:hover {
border-color: var(--line-strong);
}
.theme-card.chosen {
border-color: var(--accent);
box-shadow: inset 0 0 0 1px var(--accent);
}
/* Painted in the card's own theme rather than the page's — that is the whole
point of putting data-theme on the button. */
.swatch {
width: 100%;
height: 54px;
border-radius: var(--radius-sm);
background: var(--ground);
border: 1px solid var(--line);
padding: var(--s2);
display: flex;
flex-direction: column;
gap: 5px;
justify-content: center;
position: relative;
margin-bottom: var(--s1);
}
.swatch-line {
height: 5px;
width: 70%;
border-radius: var(--radius-full);
background: var(--ink-muted);
}
.swatch-line.short {
width: 45%;
background: var(--ink-faint);
}
.swatch-dot {
position: absolute;
right: var(--s2);
top: var(--s2);
width: 12px;
height: 12px;
border-radius: var(--radius-full);
background: var(--accent);
}
.theme-name {
font-size: var(--text-sm);
color: var(--ink);
}
.theme-note {
font-size: var(--text-xs);
color: var(--ink-faint);
}
.secret {
margin: 0;
padding: var(--s3);
+185 -2
View File
@@ -101,6 +101,61 @@
}
}
// --- sections -------------------------------------------------------------------
let addingSection = $state(false);
let renamingSection = $state(null);
let sectionName = $state('');
async function addSection(event) {
event.preventDefault();
const name = sectionName.trim();
if (!name) return;
addingSection = false;
sectionName = '';
try {
sections = [...sections, await api.createSection(project.id, name)];
} catch (e) {
app.toast(humanMessage(e));
}
}
async function renameSection(event, section) {
event.preventDefault();
const name = sectionName.trim();
renamingSection = null;
if (!name || name === section.name) return;
const previous = sections;
sections = sections.map((s) => (s.id === section.id ? { ...s, name } : s));
try {
await api.updateSection(section.id, { name });
} catch (e) {
sections = previous;
app.toast(humanMessage(e));
}
}
async function removeSection(section) {
const count = open.filter((t) => t.section_id === section.id).length;
const warning = count
? `Slet sektionen "${section.name}"? De ${count} opgaver bliver, men mister deres sektion.`
: `Slet sektionen "${section.name}"?`;
if (!confirm(warning)) return;
const previous = sections;
sections = sections.filter((s) => s.id !== section.id);
try {
await api.deleteSection(section.id);
// The tasks are not deleted with it; they come back unsectioned, and the
// list has to be re-read to show them in the right place.
await app.loadTasks({ project_id: project.id });
} catch (e) {
sections = previous;
app.toast(humanMessage(e));
}
}
async function invite(event) {
event.preventDefault();
inviteError = '';
@@ -249,7 +304,34 @@
{#each sections as section (section.id)}
{@const tasks = open.filter((t) => t.section_id === section.id)}
<section>
<h2>{section.name}</h2>
<div class="section-head">
{#if renamingSection === section.id}
<form onsubmit={(e) => renameSection(e, section)}>
<!-- svelte-ignore a11y_autofocus -->
<input
bind:value={sectionName}
autofocus
aria-label="Sektionens navn"
onblur={() => (renamingSection = null)}
onkeydown={(e) => e.key === 'Escape' && (renamingSection = null)}
/>
</form>
{:else}
<h2>{section.name}</h2>
{#if canEdit}
<button
class="section-action"
onclick={() => {
renamingSection = section.id;
sectionName = section.name;
}}>Omdøb</button
>
<button class="section-action remove" onclick={() => removeSection(section)}>
Slet
</button>
{/if}
{/if}
</div>
<TaskList {tasks} projectId={project.id} sectionId={section.id} {canEdit} />
{#if !tasks.length}
<p class="empty">Tom</p>
@@ -257,7 +339,35 @@
</section>
{/each}
{#if !open.length}
{#if canEdit}
<section class="add-section">
{#if addingSection}
<form onsubmit={addSection}>
<!-- svelte-ignore a11y_autofocus -->
<input
bind:value={sectionName}
autofocus
placeholder="Sektionens navn"
aria-label="Ny sektion"
onblur={() => !sectionName.trim() && (addingSection = false)}
onkeydown={(e) => e.key === 'Escape' && (addingSection = false)}
/>
</form>
{:else}
<button
class="add"
onclick={() => {
addingSection = true;
sectionName = '';
}}
>
+ Tilføj sektion
</button>
{/if}
</section>
{/if}
{#if !open.length && !sections.length}
<p class="clear">
<span class="rune" aria-hidden="true">ᚹ</span>
Ingenting her endnu.
@@ -548,6 +658,79 @@
margin-bottom: var(--s2);
}
.section-head {
display: flex;
align-items: baseline;
gap: var(--s3);
border-bottom: 1px solid var(--line);
margin-bottom: var(--s2);
}
.section-head h2 {
border-bottom: 0;
margin-bottom: 0;
flex: 1;
min-width: 0;
}
/* Hidden until the section is hovered or something in it has focus: a heading
with two buttons permanently beside it stops reading as a heading. */
.section-action {
font-size: var(--text-xs);
color: var(--ink-faint);
padding: 0 var(--s1);
opacity: 0;
transition: opacity var(--fast) var(--ease);
}
.section-head:hover .section-action,
.section-action:focus-visible {
opacity: 1;
}
.section-action:hover {
color: var(--ink);
}
.section-action.remove:hover {
color: var(--danger);
}
.section-head form {
flex: 1;
}
.section-head input,
.add-section input {
width: 100%;
padding: var(--s1) var(--s2);
background: var(--surface-raised);
border: 1px solid var(--line);
border-radius: var(--radius);
font-size: var(--text-sm);
outline: none;
}
.section-head input:focus,
.add-section input:focus {
border-color: var(--accent);
}
.add-section {
margin-top: var(--s5);
}
.add-section .add {
font-size: var(--text-sm);
color: var(--ink-faint);
padding: var(--s2);
transition: color var(--fast) var(--ease);
}
.add-section .add:hover {
color: var(--accent);
}
.empty,
.readonly {
margin: 0;