Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5757f06e7a | ||
|
|
5f04fe56bc | ||
|
|
a2a39c4e17 | ||
|
|
fbfc98e217 |
@@ -2477,6 +2477,116 @@ paths:
|
||||
created: { type: integer }
|
||||
"502": { $ref: "#/components/responses/Upstream" }
|
||||
|
||||
/api/v1/notes:
|
||||
get:
|
||||
tags: [notes]
|
||||
summary: Notes — listed, narrowed to a project, or searched.
|
||||
description: >
|
||||
With no parameters: the notes filed under no project, which are the
|
||||
person's own. With `project`: that project's, which needs read access to
|
||||
it. With `q`: a full-text search across every note they can see, matching
|
||||
Danish spelling either way round — "grøn" finds "gron" and the reverse.
|
||||
parameters:
|
||||
- name: q
|
||||
in: query
|
||||
schema: { type: string }
|
||||
- name: project
|
||||
in: query
|
||||
schema: { type: string }
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
notes:
|
||||
type: array
|
||||
items: { $ref: "#/components/schemas/Note" }
|
||||
post:
|
||||
tags: [notes]
|
||||
summary: Write a note.
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/NoteInput" }
|
||||
responses:
|
||||
"201":
|
||||
description: Written
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/Note" }
|
||||
"403": { $ref: "#/components/responses/Forbidden" }
|
||||
|
||||
/api/v1/notes/{noteID}:
|
||||
parameters:
|
||||
- name: noteID
|
||||
in: path
|
||||
required: true
|
||||
schema: { type: string }
|
||||
get:
|
||||
tags: [notes]
|
||||
summary: One note.
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/Note" }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
patch:
|
||||
tags: [notes]
|
||||
summary: Change a note. Every field is optional; what is sent is what changes.
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/NoteInput" }
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/Note" }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
delete:
|
||||
tags: [notes]
|
||||
summary: Put a note in the trash. It can be brought back.
|
||||
responses:
|
||||
"204": { description: Deleted }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
|
||||
/api/v1/notes/linking/{kind}/{targetID}:
|
||||
get:
|
||||
tags: [notes]
|
||||
summary: What has been written about this.
|
||||
description: >
|
||||
The backwards direction. A task's id gives every note that mentions it,
|
||||
a project's name gives every note carrying that #tag.
|
||||
parameters:
|
||||
- name: kind
|
||||
in: path
|
||||
required: true
|
||||
schema: { type: string, enum: [task, note, project] }
|
||||
- name: targetID
|
||||
in: path
|
||||
required: true
|
||||
schema: { type: string }
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
notes:
|
||||
type: array
|
||||
items: { $ref: "#/components/schemas/Note" }
|
||||
"400": { $ref: "#/components/responses/BadRequest" }
|
||||
|
||||
/api/v1/mailboxes:
|
||||
get:
|
||||
tags: [integrations]
|
||||
@@ -3162,6 +3272,34 @@ components:
|
||||
items: { type: string }
|
||||
|
||||
schemas:
|
||||
Note:
|
||||
type: object
|
||||
description: A page of Markdown. The body is the stored form and the exported form.
|
||||
properties:
|
||||
id: { type: string }
|
||||
project_id: { type: string }
|
||||
title: { type: string, description: "Taken from the first line when not given." }
|
||||
body: { type: string, description: Markdown }
|
||||
pinned: { type: boolean }
|
||||
created_at: { type: string, format: date-time }
|
||||
updated_at: { type: string, format: date-time }
|
||||
links:
|
||||
type: array
|
||||
description: What the body points at, read out of the text on the way in.
|
||||
items:
|
||||
type: object
|
||||
properties:
|
||||
kind: { type: string, enum: [task, note, project] }
|
||||
target_id: { type: string }
|
||||
|
||||
NoteInput:
|
||||
type: object
|
||||
properties:
|
||||
project_id: { type: string, description: "Empty files it under no project." }
|
||||
title: { type: string }
|
||||
body: { type: string }
|
||||
pinned: { type: boolean }
|
||||
|
||||
Mailbox:
|
||||
type: object
|
||||
description: One connected mailbox. The password and any token are never returned.
|
||||
|
||||
@@ -101,6 +101,7 @@ func (s *Server) buildMCP() *mcp.Server {
|
||||
}, "task_id", "body"),
|
||||
}, s.mcpAddComment)
|
||||
|
||||
s.registerNoteTools(m)
|
||||
return m
|
||||
}
|
||||
|
||||
@@ -496,3 +497,176 @@ func clamp(value, fallback, max int) int {
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
// --- notes ---------------------------------------------------------------------
|
||||
|
||||
// registerNoteTools adds the note half of the MCP surface.
|
||||
//
|
||||
// Separate from the task tools for one reason worth stating: this is how a note
|
||||
// gets in from somewhere else. Apple Notes has no export worth the name, but a
|
||||
// model running on the machine can read Notes.app and write what it finds through
|
||||
// these — one note at a time, with the text as Markdown. That is a migration
|
||||
// nobody has to build a parser for.
|
||||
func (s *Server) registerNoteTools(m *mcp.Server) {
|
||||
m.Register(mcp.Tool{
|
||||
Name: "search_notes",
|
||||
Description: "Find notes by text. Matches title and body, and is generous about " +
|
||||
"Danish spelling — searching \"gron\" finds \"grøn\", and the other way round. " +
|
||||
"With no query it returns the most recent notes. This is the tool for " +
|
||||
"\"what did I write about the tax return\" or \"find my note on the kitchen\".",
|
||||
InputSchema: mcp.Schema(map[string]any{
|
||||
"text": mcp.Str("Words to look for in the title and body."),
|
||||
"limit": mcp.Int("How many to return. Defaults to 25, maximum 100."),
|
||||
}),
|
||||
}, s.mcpSearchNotes)
|
||||
|
||||
m.Register(mcp.Tool{
|
||||
Name: "create_note",
|
||||
Description: "Write a note. The body is Markdown and is stored as typed — it is " +
|
||||
"also exactly what an export produces, so nothing is converted and nothing " +
|
||||
"is lost. Two things in the text are read out of it and become links: " +
|
||||
"`#Projekt` files the note against that project, so it appears on the " +
|
||||
"project's page without anybody filing it there, and `[[Another note]]` " +
|
||||
"links to a note by its title. Use this to bring notes in from elsewhere — " +
|
||||
"Apple Notes, OneNote, a folder of Markdown — one call per note.",
|
||||
InputSchema: mcp.Schema(map[string]any{
|
||||
"body": mcp.Str("The note as Markdown. #Projekt and [[note]] become links."),
|
||||
"title": mcp.Str("A title. Left out, the first line of the body becomes it."),
|
||||
"project_id": mcp.Str("File it under a project by id. Usually unnecessary — a #tag in the body does the same and is what a person would type."),
|
||||
"pinned": mcp.Bool("Keep it at the top of the list."),
|
||||
}),
|
||||
}, s.mcpCreateNote)
|
||||
|
||||
m.Register(mcp.Tool{
|
||||
Name: "update_note",
|
||||
Description: "Change a note. Only the fields given are changed. Sending `body` " +
|
||||
"replaces the whole text, so read the note first if you mean to add to it — " +
|
||||
"and the links are read again from the new text, so a #tag removed is a link " +
|
||||
"removed.",
|
||||
InputSchema: mcp.Schema(map[string]any{
|
||||
"note_id": mcp.Str("Which note."),
|
||||
"body": mcp.Str("The whole new text, as Markdown."),
|
||||
"title": mcp.Str("A new title."),
|
||||
"pinned": mcp.Bool("Pin it or unpin it."),
|
||||
}),
|
||||
}, s.mcpUpdateNote)
|
||||
}
|
||||
|
||||
func (s *Server) mcpSearchNotes(ctx context.Context, userID string, args json.RawMessage) (any, error) {
|
||||
var params struct {
|
||||
Text string `json:"text"`
|
||||
Limit int `json:"limit"`
|
||||
}
|
||||
_ = json.Unmarshal(args, ¶ms)
|
||||
|
||||
limit := params.Limit
|
||||
if limit <= 0 || limit > 100 {
|
||||
limit = 25
|
||||
}
|
||||
|
||||
var notes []store.Note
|
||||
var err error
|
||||
if strings.TrimSpace(params.Text) == "" {
|
||||
notes, err = s.db.LooseNotes(ctx, userID)
|
||||
} else {
|
||||
notes, err = s.db.SearchNotes(ctx, params.Text, limit)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// The same filter the HTTP surface applies, for the same reason: a search must
|
||||
// not become a way to read what you cannot open.
|
||||
out := make([]map[string]any, 0, len(notes))
|
||||
for _, n := range notes {
|
||||
if !s.mcpMayRead(ctx, &n, userID) {
|
||||
continue
|
||||
}
|
||||
out = append(out, map[string]any{
|
||||
"id": n.ID, "title": n.Title, "body": n.Body,
|
||||
"project_id": n.ProjectID, "updated_at": n.UpdatedAt,
|
||||
})
|
||||
if len(out) >= limit {
|
||||
break
|
||||
}
|
||||
}
|
||||
return map[string]any{"notes": out, "count": len(out)}, nil
|
||||
}
|
||||
|
||||
func (s *Server) mcpMayRead(ctx context.Context, n *store.Note, userID string) bool {
|
||||
if n.ProjectID == "" {
|
||||
return n.CreatedBy == userID
|
||||
}
|
||||
_, err := store.RequireProjectRole(ctx, s.db, n.ProjectID, userID, store.RoleViewer)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func (s *Server) mcpCreateNote(ctx context.Context, userID string, args json.RawMessage) (any, error) {
|
||||
var params struct {
|
||||
Body string `json:"body"`
|
||||
Title string `json:"title"`
|
||||
ProjectID string `json:"project_id"`
|
||||
Pinned bool `json:"pinned"`
|
||||
}
|
||||
_ = json.Unmarshal(args, ¶ms)
|
||||
|
||||
n := &store.Note{
|
||||
CreatedBy: userID,
|
||||
Title: params.Title,
|
||||
Body: params.Body,
|
||||
Pinned: params.Pinned,
|
||||
}
|
||||
if params.ProjectID != "" {
|
||||
if _, err := store.RequireProjectRole(ctx, s.db, params.ProjectID, userID, store.RoleEditor); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
n.ProjectID = params.ProjectID
|
||||
}
|
||||
if err := s.db.SaveNote(ctx, n); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// The links are reported back rather than left silent. A note whose #tag was
|
||||
// misspelt looks identical to one whose tag landed, and in a chat nobody sees
|
||||
// the row that was written.
|
||||
return map[string]any{
|
||||
"id": n.ID, "title": n.Title, "links": n.Links,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Server) mcpUpdateNote(ctx context.Context, userID string, args json.RawMessage) (any, error) {
|
||||
var params struct {
|
||||
NoteID string `json:"note_id"`
|
||||
Body *string `json:"body"`
|
||||
Title *string `json:"title"`
|
||||
Pinned *bool `json:"pinned"`
|
||||
}
|
||||
_ = json.Unmarshal(args, ¶ms)
|
||||
|
||||
n, err := s.db.Note(ctx, params.NoteID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if n == nil || !s.mcpMayRead(ctx, n, userID) {
|
||||
return nil, fmt.Errorf("no such note")
|
||||
}
|
||||
if n.ProjectID != "" {
|
||||
if _, err := store.RequireProjectRole(ctx, s.db, n.ProjectID, userID, store.RoleEditor); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if params.Body != nil {
|
||||
n.Body = *params.Body
|
||||
}
|
||||
if params.Title != nil {
|
||||
n.Title = *params.Title
|
||||
}
|
||||
if params.Pinned != nil {
|
||||
n.Pinned = *params.Pinned
|
||||
}
|
||||
if err := s.db.SaveNote(ctx, n); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{"id": n.ID, "title": n.Title, "links": n.Links}, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/kristianwind/verdande/internal/store"
|
||||
)
|
||||
|
||||
// Notes.
|
||||
//
|
||||
// Access follows the project, because that is where a note lives: a note in a
|
||||
// shared project is readable by everybody who can read the project and writable
|
||||
// by an editor. A note with no project is its author's alone — the same answer a
|
||||
// task in the inbox gets, arrived at the same way rather than by a rule of its own.
|
||||
|
||||
// mayReadNote reports whether this person may see the note, and mayWriteNote
|
||||
// whether they may change it. Split, because a viewer on a shared project can do
|
||||
// the first and not the second.
|
||||
func (s *Server) mayTouchNote(r *http.Request, n *store.Note, role store.Role) bool {
|
||||
user := userFrom(r.Context())
|
||||
if n.ProjectID == "" {
|
||||
return n.CreatedBy == user.ID
|
||||
}
|
||||
_, err := store.RequireProjectRole(r.Context(), s.db, n.ProjectID, user.ID, role)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func (s *Server) handleListNotes(w http.ResponseWriter, r *http.Request) {
|
||||
user := userFrom(r.Context())
|
||||
|
||||
// Searching and listing are the same endpoint, because they answer the same
|
||||
// question with different words. ?q= searches; ?project= narrows; neither gives
|
||||
// the loose ones.
|
||||
if q := strings.TrimSpace(r.URL.Query().Get("q")); q != "" {
|
||||
found, err := s.db.SearchNotes(r.Context(), q, 50)
|
||||
if err != nil {
|
||||
s.internal(w, r, "search notes", err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"notes": s.readable(r, found)})
|
||||
return
|
||||
}
|
||||
|
||||
if projectID := r.URL.Query().Get("project"); projectID != "" {
|
||||
if _, err := store.RequireProjectRole(r.Context(), s.db, projectID, user.ID, store.RoleViewer); err != nil {
|
||||
s.storeError(w, r, "notes in project", err)
|
||||
return
|
||||
}
|
||||
found, err := s.db.NotesInProject(r.Context(), projectID)
|
||||
if err != nil {
|
||||
s.internal(w, r, "notes in project", err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"notes": found})
|
||||
return
|
||||
}
|
||||
|
||||
found, err := s.db.LooseNotes(r.Context(), user.ID)
|
||||
if err != nil {
|
||||
s.internal(w, r, "list notes", err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"notes": found})
|
||||
}
|
||||
|
||||
// readable drops what this person may not see.
|
||||
//
|
||||
// Filtered after the search rather than inside it: FTS5 answers about text, and
|
||||
// teaching the index about roles would put an access rule in a place nobody would
|
||||
// think to look when it was wrong.
|
||||
func (s *Server) readable(r *http.Request, notes []store.Note) []store.Note {
|
||||
out := make([]store.Note, 0, len(notes))
|
||||
for _, n := range notes {
|
||||
if s.mayTouchNote(r, &n, store.RoleViewer) {
|
||||
out = append(out, n)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *Server) handleGetNote(w http.ResponseWriter, r *http.Request) {
|
||||
n, err := s.db.Note(r.Context(), chi.URLParam(r, "noteID"))
|
||||
if err != nil {
|
||||
s.internal(w, r, "get note", err)
|
||||
return
|
||||
}
|
||||
// The same answer for "no such note" and "not yours", so an id cannot be probed.
|
||||
if n == nil || !s.mayTouchNote(r, n, store.RoleViewer) {
|
||||
writeError(w, http.StatusNotFound, CodeNotFound, "no such note")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, n)
|
||||
}
|
||||
|
||||
type noteBody struct {
|
||||
ProjectID *string `json:"project_id"`
|
||||
Title *string `json:"title"`
|
||||
Body *string `json:"body"`
|
||||
Pinned *bool `json:"pinned"`
|
||||
}
|
||||
|
||||
func (s *Server) handleCreateNote(w http.ResponseWriter, r *http.Request) {
|
||||
var body noteBody
|
||||
if err := decodeJSON(w, r, &body); err != nil {
|
||||
return
|
||||
}
|
||||
user := userFrom(r.Context())
|
||||
|
||||
n := &store.Note{CreatedBy: user.ID}
|
||||
if body.ProjectID != nil && *body.ProjectID != "" {
|
||||
if _, err := store.RequireProjectRole(r.Context(), s.db, *body.ProjectID, user.ID, store.RoleEditor); err != nil {
|
||||
s.storeError(w, r, "create note", err)
|
||||
return
|
||||
}
|
||||
n.ProjectID = *body.ProjectID
|
||||
}
|
||||
if body.Title != nil {
|
||||
n.Title = *body.Title
|
||||
}
|
||||
if body.Body != nil {
|
||||
n.Body = *body.Body
|
||||
}
|
||||
if body.Pinned != nil {
|
||||
n.Pinned = *body.Pinned
|
||||
}
|
||||
|
||||
if err := s.db.SaveNote(r.Context(), n); err != nil {
|
||||
s.internal(w, r, "create note", err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, n)
|
||||
}
|
||||
|
||||
func (s *Server) handleUpdateNote(w http.ResponseWriter, r *http.Request) {
|
||||
var body noteBody
|
||||
if err := decodeJSON(w, r, &body); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
n, err := s.db.Note(r.Context(), chi.URLParam(r, "noteID"))
|
||||
if err != nil {
|
||||
s.internal(w, r, "update note", err)
|
||||
return
|
||||
}
|
||||
if n == nil || !s.mayTouchNote(r, n, store.RoleEditor) {
|
||||
writeError(w, http.StatusNotFound, CodeNotFound, "no such note")
|
||||
return
|
||||
}
|
||||
|
||||
if body.ProjectID != nil {
|
||||
// Moving it means being allowed on both sides: you cannot file somebody
|
||||
// else's note into your project, nor yours into theirs.
|
||||
if *body.ProjectID != "" {
|
||||
if _, err := store.RequireProjectRole(r.Context(), s.db, *body.ProjectID,
|
||||
userFrom(r.Context()).ID, store.RoleEditor); err != nil {
|
||||
s.storeError(w, r, "move note", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
n.ProjectID = *body.ProjectID
|
||||
}
|
||||
if body.Title != nil {
|
||||
n.Title = *body.Title
|
||||
}
|
||||
if body.Body != nil {
|
||||
n.Body = *body.Body
|
||||
}
|
||||
if body.Pinned != nil {
|
||||
n.Pinned = *body.Pinned
|
||||
}
|
||||
|
||||
if err := s.db.SaveNote(r.Context(), n); err != nil {
|
||||
s.internal(w, r, "update note", err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, n)
|
||||
}
|
||||
|
||||
func (s *Server) handleDeleteNote(w http.ResponseWriter, r *http.Request) {
|
||||
n, err := s.db.Note(r.Context(), chi.URLParam(r, "noteID"))
|
||||
if err != nil {
|
||||
s.internal(w, r, "delete note", err)
|
||||
return
|
||||
}
|
||||
if n == nil || !s.mayTouchNote(r, n, store.RoleEditor) {
|
||||
writeError(w, http.StatusNotFound, CodeNotFound, "no such note")
|
||||
return
|
||||
}
|
||||
if err := s.db.DeleteNote(r.Context(), n.ID); err != nil {
|
||||
s.internal(w, r, "delete note", err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// handleNotesLinking answers the backwards question for a task or a project:
|
||||
// what has somebody written about this.
|
||||
func (s *Server) handleNotesLinking(w http.ResponseWriter, r *http.Request) {
|
||||
kind := chi.URLParam(r, "kind")
|
||||
if kind != "task" && kind != "project" && kind != "note" {
|
||||
writeError(w, http.StatusBadRequest, CodeValidation, "kind must be task, project or note")
|
||||
return
|
||||
}
|
||||
found, err := s.db.NotesLinking(r.Context(), kind, chi.URLParam(r, "targetID"))
|
||||
if err != nil {
|
||||
s.internal(w, r, "notes linking", err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"notes": s.readable(r, found)})
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// A note in a project is the project's; a note in no project is its author's.
|
||||
// Both answers come from the project's own roles rather than from a rule notes
|
||||
// invented for themselves, which is the point of filing them there.
|
||||
func TestANoteIsNotReadableByJustAnybody(t *testing.T) {
|
||||
ts := newTestServer(t)
|
||||
ts.bootstrap(t)
|
||||
|
||||
resp, body := ts.do(t, "POST", "/api/v1/notes", map[string]any{
|
||||
"body": "Noget privat om #Firma",
|
||||
})
|
||||
if resp.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("create: %d %v", resp.StatusCode, body)
|
||||
}
|
||||
id, _ := body["id"].(string)
|
||||
if id == "" {
|
||||
t.Fatal("no id came back")
|
||||
}
|
||||
|
||||
// The tags were read out of the text on the way in, without being asked for.
|
||||
links, _ := body["links"].([]any)
|
||||
if len(links) != 1 {
|
||||
t.Fatalf("the note recorded %v", body["links"])
|
||||
}
|
||||
|
||||
// Somebody else gets the same answer as for a note that does not exist, so an
|
||||
// id cannot be probed for existence.
|
||||
other := ts.newUser(t, "[email protected]", "Anden")
|
||||
resp, _ = other.do(t, "GET", "/api/v1/notes/"+id, nil)
|
||||
if resp.StatusCode != http.StatusNotFound {
|
||||
t.Errorf("a stranger got %d for somebody else's note, want 404", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// Searching must not become a way to read what you cannot open. The filter is
|
||||
// applied after the index, and this is what says so.
|
||||
func TestSearchDoesNotLeakNotesYouCannotRead(t *testing.T) {
|
||||
ts := newTestServer(t)
|
||||
ts.bootstrap(t)
|
||||
|
||||
if resp, body := ts.do(t, "POST", "/api/v1/notes", map[string]any{
|
||||
"body": "Hemmeligt kodeord til hjemmesiden",
|
||||
}); resp.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("create: %d %v", resp.StatusCode, body)
|
||||
}
|
||||
|
||||
_, mine := ts.do(t, "GET", "/api/v1/notes?q=hemmeligt", nil)
|
||||
if got := len(mine["notes"].([]any)); got != 1 {
|
||||
t.Fatalf("the author found %d of their own notes", got)
|
||||
}
|
||||
|
||||
other := ts.newUser(t, "[email protected]", "Anden")
|
||||
_, theirs := other.do(t, "GET", "/api/v1/notes?q=hemmeligt", nil)
|
||||
if got := len(theirs["notes"].([]any)); got != 0 {
|
||||
t.Errorf("a stranger's search returned %d notes", got)
|
||||
}
|
||||
}
|
||||
|
||||
// The backwards question, which is what makes notes worth linking at all.
|
||||
func TestANoteIsFoundFromTheTaskItMentions(t *testing.T) {
|
||||
ts := newTestServer(t)
|
||||
ts.bootstrap(t)
|
||||
|
||||
_, task := ts.do(t, "POST", "/api/v1/tasks/quick-add", map[string]any{
|
||||
"text": "ring til Anders",
|
||||
})
|
||||
taskID, _ := task["id"].(string)
|
||||
if taskID == "" {
|
||||
t.Fatalf("no task id: %v", task)
|
||||
}
|
||||
|
||||
if resp, _ := ts.do(t, "POST", "/api/v1/notes", map[string]any{
|
||||
"body": "Aftalt at han ringer først, se /opgave/" + taskID,
|
||||
}); resp.StatusCode != http.StatusCreated {
|
||||
t.Fatal("the note was not written")
|
||||
}
|
||||
|
||||
_, found := ts.do(t, "GET", "/api/v1/notes/linking/task/"+taskID, nil)
|
||||
notes, _ := found["notes"].([]any)
|
||||
if len(notes) != 1 {
|
||||
t.Fatalf("%d notes point at the task, want 1", len(notes))
|
||||
}
|
||||
}
|
||||
|
||||
// Editing the text moves the links with it. A link that outlives its mention
|
||||
// claims a connection that is not there.
|
||||
func TestChangingANoteChangesWhatItPointsAt(t *testing.T) {
|
||||
ts := newTestServer(t)
|
||||
ts.bootstrap(t)
|
||||
|
||||
_, note := ts.do(t, "POST", "/api/v1/notes", map[string]any{"body": "Om #Firma"})
|
||||
id, _ := note["id"].(string)
|
||||
|
||||
_, before := ts.do(t, "GET", "/api/v1/notes/linking/project/Firma", nil)
|
||||
if len(before["notes"].([]any)) != 1 {
|
||||
t.Fatal("the first save recorded nothing")
|
||||
}
|
||||
|
||||
if resp, _ := ts.do(t, "PATCH", "/api/v1/notes/"+id, map[string]any{
|
||||
"body": "Om #Regnskab i stedet",
|
||||
}); resp.StatusCode != http.StatusOK {
|
||||
t.Fatal("the note was not changed")
|
||||
}
|
||||
|
||||
_, after := ts.do(t, "GET", "/api/v1/notes/linking/project/Firma", nil)
|
||||
if got := len(after["notes"].([]any)); got != 0 {
|
||||
t.Errorf("%d notes still point at Firma", got)
|
||||
}
|
||||
}
|
||||
@@ -276,6 +276,18 @@ func New(cfg *config.Config, db *store.DB, log *slog.Logger, web fs.FS) *Server
|
||||
// Mailboxes read over IMAP — iCloud, Fastmail, any ordinary host. Each
|
||||
// belongs to the person who connected it, so there is no admin gate
|
||||
// here and no shared registration: the credential is theirs.
|
||||
// Notes. Listing and searching are the same endpoint because they answer
|
||||
// the same question with different words; the backwards one — what has
|
||||
// been written about this task — hangs off the thing being asked about.
|
||||
r.Route("/notes", func(r chi.Router) {
|
||||
r.Get("/", s.handleListNotes)
|
||||
r.Post("/", s.handleCreateNote)
|
||||
r.Get("/linking/{kind}/{targetID}", s.handleNotesLinking)
|
||||
r.Get("/{noteID}", s.handleGetNote)
|
||||
r.Patch("/{noteID}", s.handleUpdateNote)
|
||||
r.Delete("/{noteID}", s.handleDeleteNote)
|
||||
})
|
||||
|
||||
r.Route("/mailboxes", func(r chi.Router) {
|
||||
r.Get("/", s.handleListMailboxes)
|
||||
r.Post("/", s.handleAddMailbox)
|
||||
|
||||
@@ -176,6 +176,14 @@ func (db *DB) NotesInProject(ctx context.Context, projectID string) ([]Note, err
|
||||
projectID)
|
||||
}
|
||||
|
||||
// LooseNotes are the ones filed under no project — a person's own, the way a task
|
||||
// in the inbox is. Nobody else can see them, so there is no role to ask about.
|
||||
func (db *DB) LooseNotes(ctx context.Context, userID string) ([]Note, error) {
|
||||
return db.notesWhere(ctx, `
|
||||
WHERE project_id IS NULL AND created_by = ? AND deleted_at IS NULL
|
||||
ORDER BY pinned DESC, updated_at DESC`, userID)
|
||||
}
|
||||
|
||||
// NotesLinking answers the backwards question: what points at this thing.
|
||||
//
|
||||
// The reason note_links exists. Without it this would mean reading every note's
|
||||
|
||||
+101
-1
@@ -1464,7 +1464,10 @@ test('en opgave lukket ved et uheld kan hentes tilbage', async ({ page }) => {
|
||||
await expect(page.getByText('rens tagrenden', { exact: true })).toBeHidden();
|
||||
|
||||
const sidebar = page.getByRole('navigation', { name: 'Hovedmenu' });
|
||||
await sidebar.getByRole('link', { name: 'Færdige' }).click();
|
||||
// Færdige left the sidebar: it is a rare errand next to four entries read every
|
||||
// day, and it now sits with the other "where did that go" answers.
|
||||
await page.goto('/indstillinger/data');
|
||||
await page.getByRole('link', { name: 'Åbn færdige opgaver' }).click();
|
||||
await expect(page.getByRole('heading', { name: 'Færdige', level: 1 })).toBeVisible();
|
||||
|
||||
const closed = page.locator('.row').filter({ hasText: 'rens tagrenden' });
|
||||
@@ -1900,3 +1903,100 @@ test('tallet ved et projekt er opgaver, og sidebjælken kan foldes med tastature
|
||||
|
||||
expect(trouble).toEqual([]);
|
||||
});
|
||||
|
||||
test('en note kan skrives, findes igen, og peger på det den nævner', async ({ page }) => {
|
||||
const trouble = watchForTrouble(page);
|
||||
await page.goto('/');
|
||||
|
||||
const sidebar = page.getByRole('navigation', { name: 'Hovedmenu' });
|
||||
await sidebar.getByRole('button', { name: 'Nyt projekt' }).click();
|
||||
await sidebar.getByLabel('Projektnavn').fill('Notetesteriet');
|
||||
await sidebar.getByLabel('Projektnavn').press('Enter');
|
||||
await expect(sidebar.getByRole('link', { name: 'Notetesteriet' })).toBeVisible();
|
||||
|
||||
await sidebar.getByRole('link', { name: 'Noter' }).click();
|
||||
await expect(page.getByRole('heading', { name: 'Noter' })).toBeVisible();
|
||||
|
||||
await page.getByRole('button', { name: 'Ny note' }).click();
|
||||
const body = page.getByLabel('Notens tekst');
|
||||
await body.fill('Møde om #Notetesteriet\n\nHan vil gerne have kaffe hver uge.');
|
||||
// Saved on the way out, so there is no Gem-knap to forget.
|
||||
await body.blur();
|
||||
|
||||
// The title comes from the first line, the way Apple Notes does it. Without it
|
||||
// a list of notes is a list of "Uden titel".
|
||||
await expect(page.getByRole('button', { name: /Møde om/ })).toBeVisible();
|
||||
|
||||
// And the #tag was read out of the text, unasked. This is the whole point: it
|
||||
// is the same tag a task carries, so the note can be found from the project.
|
||||
// Scoped to the panel under the editor: the same text is also in the textarea
|
||||
// and in the list preview, which is three of the same thing and none of them
|
||||
// the one being asserted.
|
||||
await expect(page.locator('.link', { hasText: '#Notetesteriet' })).toBeVisible();
|
||||
|
||||
// Findable by a word from the body, and in the other Danish spelling too.
|
||||
await page.getByLabel('Søg i noter').fill('møde');
|
||||
await expect(page.getByRole('button', { name: /Møde om/ })).toBeVisible();
|
||||
await page.getByLabel('Søg i noter').fill('mode');
|
||||
await expect(page.getByRole('button', { name: /Møde om/ })).toBeVisible();
|
||||
|
||||
// It survives a reload, which is the only proof that it was ever written down.
|
||||
await page.reload();
|
||||
await expect(page.getByRole('button', { name: /Møde om/ })).toBeVisible();
|
||||
|
||||
// And the payoff: the note turns up in the project it named, without anybody
|
||||
// filing it there. This is what a #tag being the same tag actually buys.
|
||||
await sidebar.getByRole('link', { name: 'Notetesteriet' }).click();
|
||||
await expect(page.getByRole('heading', { name: 'Notetesteriet' })).toBeVisible();
|
||||
await expect(
|
||||
page.locator('.notes').getByRole('link', { name: /Møde om/ })
|
||||
).toBeVisible();
|
||||
|
||||
expect(trouble).toEqual([]);
|
||||
});
|
||||
|
||||
test('noteeditoren viser formatering, og lagene flugter', async ({ page }) => {
|
||||
const trouble = watchForTrouble(page);
|
||||
await page.goto('/noter');
|
||||
|
||||
await page.getByRole('button', { name: 'Ny note' }).click();
|
||||
const body = page.getByLabel('Notens tekst');
|
||||
await body.fill(
|
||||
'# Overskrift\n\nDette er **fed** og *kursiv* og `kode`.\n\nHandler om #Firma og [[En anden note]].\n- et punkt\n> et citat'
|
||||
);
|
||||
|
||||
// The marks are still there — this is a mirror, not a renderer — but they are
|
||||
// drawn as what they mean.
|
||||
const mirror = page.locator('.mirror');
|
||||
await expect(mirror.locator('.bold')).toHaveText('**fed**');
|
||||
await expect(mirror.locator('.italic')).toHaveText('*kursiv*');
|
||||
await expect(mirror.locator('.code')).toHaveText('`kode`');
|
||||
await expect(mirror.locator('.tag')).toHaveText('#Firma');
|
||||
await expect(mirror.locator('.wikilink')).toHaveText('[[En anden note]]');
|
||||
await expect(mirror.locator('.h1')).toContainText('Overskrift');
|
||||
|
||||
// The whole risk of the technique: two layers that must line up character for
|
||||
// character. If they drift, the formatting slides away from the text as the
|
||||
// note grows, and it is unusable — so this measures rather than trusts.
|
||||
const drift = await page.evaluate(() => {
|
||||
const ta = document.querySelector('.paper textarea');
|
||||
const mi = document.querySelector('.paper .mirror');
|
||||
const a = getComputedStyle(ta), b = getComputedStyle(mi);
|
||||
return {
|
||||
font: a.fontSize === b.fontSize && a.fontFamily === b.fontFamily,
|
||||
line: a.lineHeight === b.lineHeight,
|
||||
wrap: a.whiteSpace === b.whiteSpace,
|
||||
padding: a.paddingTop === b.paddingTop && a.paddingLeft === b.paddingLeft,
|
||||
// And the rendered height, which is what actually proves it: the same text
|
||||
// laid out twice has to take the same room.
|
||||
heights: Math.abs(ta.scrollHeight - mi.scrollHeight)
|
||||
};
|
||||
});
|
||||
expect(drift.font, 'skrifttypen er ikke ens').toBe(true);
|
||||
expect(drift.line, 'linjehøjden er ikke ens').toBe(true);
|
||||
expect(drift.wrap, 'ombrydningen er ikke ens').toBe(true);
|
||||
expect(drift.padding, 'polstringen er ikke ens').toBe(true);
|
||||
expect(drift.heights, 'lagene fylder ikke det samme').toBeLessThanOrEqual(2);
|
||||
|
||||
expect(trouble).toEqual([]);
|
||||
});
|
||||
|
||||
@@ -360,6 +360,18 @@ export const api = {
|
||||
authorizeGmail: () => post('/gmail/authorize'),
|
||||
syncGmail: () => post('/gmail/sync'),
|
||||
|
||||
// Notes. Listing and searching are one endpoint because they answer the same
|
||||
// question with different words.
|
||||
notes: (params = {}) => {
|
||||
const q = new URLSearchParams(Object.entries(params).filter(([, v]) => v)).toString();
|
||||
return get('/notes' + (q ? `?${q}` : ''));
|
||||
},
|
||||
note: (id) => get(`/notes/${id}`),
|
||||
createNote: (body) => post('/notes', body),
|
||||
updateNote: (id, body) => patch(`/notes/${id}`, body),
|
||||
deleteNote: (id) => del(`/notes/${id}`),
|
||||
notesLinking: (kind, targetId) => get(`/notes/linking/${kind}/${encodeURIComponent(targetId)}`),
|
||||
|
||||
// Mailboxes read over IMAP. Each belongs to the person who connected it, so
|
||||
// there is no instance-wide registration behind these the way Gmail has one.
|
||||
mailboxes: () => get('/mailboxes'),
|
||||
|
||||
@@ -369,19 +369,27 @@
|
||||
{t('nav.delegated')}
|
||||
</a>
|
||||
{/if}
|
||||
<!-- After the three views of what is left, because it is the one that is not
|
||||
about what is left. It earns a permanent place rather than a toggle in
|
||||
each view: somebody looking for a task they closed by mistake does not
|
||||
know which view they closed it in. -->
|
||||
<a href="/faerdige" class:active={current === '/faerdige'} onclick={onnavigate}>
|
||||
<span class="dot" aria-hidden="true"></span>
|
||||
{t('done.title')}
|
||||
</a>
|
||||
<!-- Færdige is not in this list any more. It used to sit here on the argument
|
||||
that somebody hunting a task they closed by mistake does not know which
|
||||
view they closed it in — which is true, and is also a rare errand next to
|
||||
four entries that are read every day. It lives under Settings → Data, with
|
||||
the trash, where the other "where did that go" questions are answered. -->
|
||||
{#if app.inbox}
|
||||
{@render projectRow(app.inbox, false)}
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Notes stand apart, with a rule above them.
|
||||
They are not a fourth way of looking at the same tasks, which is what
|
||||
everything above is; they are the other half of the program. Sitting in that
|
||||
run made them read as one more filter. -->
|
||||
<div class="apart">
|
||||
<a href="/noter" class:active={current === '/noter'} onclick={onnavigate}>
|
||||
<span class="dot" aria-hidden="true"></span>
|
||||
{t('notes.title')}
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<!-- One row for every project the sidebar shows — your own, the Inbox and the
|
||||
shared ones — because all three are somewhere a task can be dropped, and
|
||||
three copies of that would be three chances to fix a bug in two of them.
|
||||
@@ -863,6 +871,17 @@
|
||||
gap: 1px;
|
||||
}
|
||||
|
||||
/* A rule and a little air, which is the whole of "separate". Notes are the other
|
||||
half of the program, not a fifth way of looking at the same tasks. */
|
||||
.apart {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1px;
|
||||
margin: var(--s3) 0;
|
||||
padding-top: var(--s3);
|
||||
border-top: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.group-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -16,6 +16,19 @@
|
||||
*/
|
||||
export const da = {
|
||||
// --- the shell ---------------------------------------------------------------
|
||||
'notes.title': 'Noter',
|
||||
'notes.new': 'Ny note',
|
||||
'notes.search': 'Søg i noter',
|
||||
'notes.body': 'Notens tekst',
|
||||
'notes.placeholder': 'Skriv. #projekt og [[en anden note]] bliver til henvisninger.',
|
||||
'notes.untitled': 'Uden titel',
|
||||
'notes.noneYet': 'Ingen noter endnu.',
|
||||
'notes.noneFound': 'Ingen noter matcher.',
|
||||
'notes.pickOne': 'Vælg en note, eller lav en ny.',
|
||||
'notes.saving': 'Gemmer …',
|
||||
'notes.saved': 'Gemt',
|
||||
'notes.delete': 'Slet',
|
||||
'notes.deleteNote': 'Slet "{name}"? Den kan hentes tilbage fra papirkurven.',
|
||||
'nav.today': 'I dag',
|
||||
'nav.upcoming': 'Kommende',
|
||||
'nav.delegated': 'Venter på andre',
|
||||
@@ -305,6 +318,8 @@ export const da = {
|
||||
'data.csvFile': 'CSV-fil',
|
||||
'data.importing': 'Importerer …',
|
||||
'data.openProject': 'Åbn projektet',
|
||||
'data.doneHint': 'Alt du har lukket, nyeste først. Lukkede du noget ved en fejl, ligger det her — og kan åbnes igen.',
|
||||
'data.openDone': 'Åbn færdige opgaver',
|
||||
'data.trash': 'Papirkurv',
|
||||
'data.trashEmpty': 'Papirkurven er tom.',
|
||||
'data.restore': 'Hent tilbage',
|
||||
|
||||
@@ -12,6 +12,19 @@
|
||||
*/
|
||||
export const en = {
|
||||
// --- the shell ---------------------------------------------------------------
|
||||
'notes.title': 'Notes',
|
||||
'notes.new': 'New note',
|
||||
'notes.search': 'Search notes',
|
||||
'notes.body': "The note's text",
|
||||
'notes.placeholder': 'Write. #project and [[another note]] become references.',
|
||||
'notes.untitled': 'Untitled',
|
||||
'notes.noneYet': 'No notes yet.',
|
||||
'notes.noneFound': 'No notes match.',
|
||||
'notes.pickOne': 'Pick a note, or write a new one.',
|
||||
'notes.saving': 'Saving …',
|
||||
'notes.saved': 'Saved',
|
||||
'notes.delete': 'Delete',
|
||||
'notes.deleteNote': 'Delete "{name}"? It can be brought back from the trash.',
|
||||
'nav.today': 'Today',
|
||||
'nav.upcoming': 'Upcoming',
|
||||
'nav.delegated': 'Waiting on others',
|
||||
@@ -300,6 +313,8 @@ export const en = {
|
||||
'data.csvFile': 'CSV file',
|
||||
'data.importing': 'Importing …',
|
||||
'data.openProject': 'Open the project',
|
||||
'data.doneHint': 'Everything you have closed, newest first. Closed something by mistake and it is here — and can be opened again.',
|
||||
'data.openDone': 'Open finished tasks',
|
||||
'data.trash': 'Trash',
|
||||
'data.trashEmpty': 'The trash is empty.',
|
||||
'data.restore': 'Restore',
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* Just enough Markdown to see what you are writing.
|
||||
*
|
||||
* Not a renderer: the output is the same text, in the same order, with parts
|
||||
* wrapped so they can be styled. That matters because it sits behind a textarea
|
||||
* and has to line up with it character for character — a renderer that dropped
|
||||
* the `**` or reflowed a list would drift out of alignment on the first bold word.
|
||||
*
|
||||
* So the marks stay, dimmed. Obsidian hides them except in the line the cursor is
|
||||
* in; dimming them always is simpler, does not move text under the cursor as it
|
||||
* travels, and still lets you read a document at a glance. It is a smaller idea
|
||||
* that survives contact with a textarea.
|
||||
*/
|
||||
|
||||
const INLINE = [
|
||||
// Order matters: the longer fence first, or `**bold**` is read as two italics.
|
||||
{ kind: 'code', re: /`([^`\n]+)`/g },
|
||||
{ kind: 'bold', re: /\*\*([^*\n]+)\*\*/g },
|
||||
{ kind: 'italic', re: /\*([^*\n]+)\*/g },
|
||||
{ kind: 'tag', re: /(?:^|(?<=\s))#[\p{L}\p{N}_-]{1,64}/gu },
|
||||
{ kind: 'wikilink', re: /\[\[[^\]\n]{1,200}\]\]/g }
|
||||
];
|
||||
|
||||
/**
|
||||
* segmentsOf splits one line into pieces, each with the kind it should be drawn
|
||||
* as. A piece with no kind is ordinary text.
|
||||
*/
|
||||
function inlineSegments(line) {
|
||||
const marks = [];
|
||||
|
||||
// Each pass reads a copy with the earlier passes' characters blanked out.
|
||||
//
|
||||
// Skipping overlaps after the fact is not enough, and the failure is subtle:
|
||||
// after `**fed**` is claimed as bold, a plain overlap check still lets the
|
||||
// italic pass start at the leftover `*` and run to the next one — swallowing
|
||||
// " og " and leaving the actual italic word unmarked. Blanking means a later
|
||||
// pass cannot see the characters at all.
|
||||
let masked = line;
|
||||
const blank = (start, end) =>
|
||||
(masked = masked.slice(0, start) + '\u0000'.repeat(end - start) + masked.slice(end));
|
||||
|
||||
for (const { kind, re } of INLINE) {
|
||||
re.lastIndex = 0;
|
||||
let m;
|
||||
while ((m = re.exec(masked))) {
|
||||
marks.push({ kind, start: m.index, end: m.index + m[0].length });
|
||||
}
|
||||
for (const mark of marks) blank(mark.start, mark.end);
|
||||
}
|
||||
marks.sort((a, b) => a.start - b.start);
|
||||
|
||||
const out = [];
|
||||
let at = 0;
|
||||
for (const mark of marks) {
|
||||
if (mark.start > at) out.push({ text: line.slice(at, mark.start) });
|
||||
out.push({ text: line.slice(mark.start, mark.end), kind: mark.kind });
|
||||
at = mark.end;
|
||||
}
|
||||
if (at < line.length) out.push({ text: line.slice(at) });
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* linesOf turns a body into lines, each with a block kind and its inline pieces.
|
||||
* Every line is returned, blank ones included, or the mirror would be one line
|
||||
* short of the textarea for every empty line in the note.
|
||||
*/
|
||||
export function linesOf(body) {
|
||||
return body.split('\n').map((line) => {
|
||||
const heading = /^(#{1,6})\s/.exec(line);
|
||||
if (heading) {
|
||||
return { block: `h${heading[1].length}`, parts: inlineSegments(line) };
|
||||
}
|
||||
if (/^\s*[-*+]\s/.test(line)) return { block: 'list', parts: inlineSegments(line) };
|
||||
if (/^\s*\d+\.\s/.test(line)) return { block: 'list', parts: inlineSegments(line) };
|
||||
if (/^\s*>\s?/.test(line)) return { block: 'quote', parts: inlineSegments(line) };
|
||||
return { block: 'p', parts: inlineSegments(line) };
|
||||
});
|
||||
}
|
||||
@@ -225,6 +225,19 @@
|
||||
{/if}
|
||||
</section>
|
||||
|
||||
<!-- Færdige used to be a permanent entry in the sidebar. It is a rare errand next
|
||||
to the four that are read every day, and it belongs with the other "where did
|
||||
that go" questions rather than above them. -->
|
||||
<section class="panel">
|
||||
<header>
|
||||
<h2>{t('done.title')}</h2>
|
||||
<p class="hint">{t('data.doneHint')}</p>
|
||||
</header>
|
||||
<div class="row">
|
||||
<a class="ghost" href="/faerdige">{t('data.openDone')}</a>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<header>
|
||||
<h2>{t('data.trash')}</h2>
|
||||
|
||||
@@ -0,0 +1,426 @@
|
||||
<script>
|
||||
/**
|
||||
* Notes.
|
||||
*
|
||||
* A list on the left, the note itself on the right. Not a grid of cards: a note
|
||||
* is read by its first line far more often than by its whole self, and a list
|
||||
* shows twenty of those where a grid shows six.
|
||||
*
|
||||
* Markdown in a plain textarea for now. The live preview — where the marks show
|
||||
* only in the line the cursor is in — is the next piece and the expensive one;
|
||||
* this is the shape it will sit inside, and everything else is already true
|
||||
* without it.
|
||||
*/
|
||||
import { api, humanMessage } from '$lib/api.js';
|
||||
import { app } from '$lib/stores.svelte.js';
|
||||
import { t } from '$lib/i18n.svelte.js';
|
||||
import { linesOf } from '$lib/markdown.js';
|
||||
|
||||
let notes = $state([]);
|
||||
let selected = $state(null);
|
||||
let query = $state('');
|
||||
let status = $state('loading');
|
||||
let saving = $state(false);
|
||||
|
||||
// The text being edited, kept apart from the note it came from so a save that
|
||||
// arrives late cannot overwrite what has been typed since.
|
||||
let draft = $state('');
|
||||
let timer;
|
||||
|
||||
$effect(() => {
|
||||
load(query);
|
||||
});
|
||||
|
||||
async function load(q) {
|
||||
try {
|
||||
notes = (await api.notes(q ? { q } : {})).notes ?? [];
|
||||
status = 'ready';
|
||||
if (selected && !notes.some((n) => n.id === selected.id)) open(notes[0] ?? null);
|
||||
} catch (e) {
|
||||
status = 'failed';
|
||||
app.toast(humanMessage(e));
|
||||
}
|
||||
}
|
||||
|
||||
function open(note) {
|
||||
clearTimeout(timer);
|
||||
selected = note;
|
||||
draft = note?.body ?? '';
|
||||
}
|
||||
|
||||
async function create() {
|
||||
try {
|
||||
const note = await api.createNote({ body: '' });
|
||||
notes = [note, ...notes];
|
||||
open(note);
|
||||
document.querySelector('.editor textarea')?.focus();
|
||||
} catch (e) {
|
||||
app.toast(humanMessage(e));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Saved as you stop typing rather than on a button.
|
||||
*
|
||||
* A note is the one place in this program where an hour of writing can be lost
|
||||
* to one mis-click, and a Gem-knap is a button that exists to be forgotten. The
|
||||
* delay is long enough that a sentence is one save and not twenty.
|
||||
*/
|
||||
function typed() {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(save, 700);
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (!selected) return;
|
||||
const id = selected.id;
|
||||
const body = draft;
|
||||
saving = true;
|
||||
try {
|
||||
const saved = await api.updateNote(id, { body });
|
||||
notes = notes.map((n) => (n.id === id ? saved : n));
|
||||
// Only if it is still the one on screen: switching notes mid-save must not
|
||||
// drag the previous one's title back onto this one.
|
||||
if (selected?.id === id) selected = saved;
|
||||
} catch (e) {
|
||||
app.toast(humanMessage(e));
|
||||
} finally {
|
||||
saving = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(note) {
|
||||
if (!confirm(t('notes.deleteNote', { name: note.title || t('notes.untitled') }))) return;
|
||||
try {
|
||||
await api.deleteNote(note.id);
|
||||
notes = notes.filter((n) => n.id !== note.id);
|
||||
if (selected?.id === note.id) open(notes[0] ?? null);
|
||||
} catch (e) {
|
||||
app.toast(humanMessage(e));
|
||||
}
|
||||
}
|
||||
|
||||
// What the note points at, for the panel under the editor.
|
||||
let links = $derived(selected?.links ?? []);
|
||||
|
||||
// The styled twin of what is in the textarea. Recomputed on every keystroke,
|
||||
// which sounds expensive and is not: it is a split and a handful of regexes
|
||||
// over a page of text, and it runs in the same frame as the character that
|
||||
// caused it.
|
||||
let lines = $derived(linesOf(draft));
|
||||
</script>
|
||||
|
||||
<svelte:head><title>{t('notes.title')} · verdande</title></svelte:head>
|
||||
|
||||
<div class="notes">
|
||||
<aside>
|
||||
<div class="head">
|
||||
<h1>{t('notes.title')}</h1>
|
||||
<button class="new" onclick={create} aria-label={t('notes.new')}>+</button>
|
||||
</div>
|
||||
|
||||
<input
|
||||
class="search"
|
||||
type="search"
|
||||
bind:value={query}
|
||||
placeholder={t('notes.search')}
|
||||
aria-label={t('notes.search')}
|
||||
/>
|
||||
|
||||
{#if status === 'loading'}
|
||||
<p class="hint">{t('history.loading')}</p>
|
||||
{:else if !notes.length}
|
||||
<p class="hint">{query ? t('notes.noneFound') : t('notes.noneYet')}</p>
|
||||
{:else}
|
||||
<ul>
|
||||
{#each notes as note (note.id)}
|
||||
<li>
|
||||
<button class="row" class:on={selected?.id === note.id} onclick={() => open(note)}>
|
||||
<strong>{note.title || t('notes.untitled')}</strong>
|
||||
<span class="preview">{note.body.slice(0, 80)}</span>
|
||||
</button>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
</aside>
|
||||
|
||||
<section class="editor">
|
||||
{#if selected}
|
||||
<!-- The mirror sits behind the textarea and must match it exactly: same font,
|
||||
same size, same padding, same wrapping. Any difference shows up as
|
||||
formatting that drifts away from the text as the note grows.
|
||||
|
||||
A contenteditable would let the text be styled directly and would also
|
||||
break undo, autocorrect and IME input — a bad trade in the one place in
|
||||
this program where somebody writes for half an hour at a stretch. -->
|
||||
<div class="paper">
|
||||
<div class="mirror" aria-hidden="true">
|
||||
{#each lines as line}
|
||||
<div class={line.block}>
|
||||
{#each line.parts as part}
|
||||
{#if part.kind}<span class={part.kind}>{part.text}</span>{:else}{part.text}{/if}
|
||||
{/each}{#if !line.parts.length} {/if}
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<textarea
|
||||
bind:value={draft}
|
||||
oninput={typed}
|
||||
onblur={save}
|
||||
spellcheck="true"
|
||||
aria-label={t('notes.body')}
|
||||
placeholder={t('notes.placeholder')}
|
||||
></textarea>
|
||||
</div>
|
||||
|
||||
<footer>
|
||||
<span class="hint">{saving ? t('notes.saving') : t('notes.saved')}</span>
|
||||
{#if links.length}
|
||||
<span class="links">
|
||||
{#each links as link}
|
||||
<span class="link">{link.kind === 'project' ? '#' : ''}{link.target_id}</span>
|
||||
{/each}
|
||||
</span>
|
||||
{/if}
|
||||
<button class="remove" onclick={() => remove(selected)}>{t('notes.delete')}</button>
|
||||
</footer>
|
||||
{:else}
|
||||
<p class="empty">{t('notes.pickOne')}</p>
|
||||
{/if}
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.notes {
|
||||
/* Air above the heading, so it does not sit against the top bar. */
|
||||
padding-top: var(--s3);
|
||||
display: grid;
|
||||
grid-template-columns: minmax(220px, 300px) 1fr;
|
||||
gap: var(--s4);
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
aside {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--s2);
|
||||
min-height: 0;
|
||||
border-right: 1px solid var(--line);
|
||||
padding-right: var(--s3);
|
||||
}
|
||||
|
||||
.head {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: var(--text-xl);
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.new {
|
||||
font-size: var(--text-lg);
|
||||
color: var(--ink-faint);
|
||||
padding: 0 var(--s2);
|
||||
}
|
||||
|
||||
.new:hover {
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
.search {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
ul {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
overflow-y: auto;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.row {
|
||||
display: block;
|
||||
width: 100%;
|
||||
text-align: left;
|
||||
padding: var(--s2);
|
||||
border-radius: var(--radius);
|
||||
color: var(--ink-muted);
|
||||
}
|
||||
|
||||
.row:hover {
|
||||
background: var(--surface);
|
||||
}
|
||||
|
||||
.row.on {
|
||||
background: var(--surface-raised);
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
.row strong {
|
||||
display: block;
|
||||
font-size: var(--text-sm);
|
||||
font-weight: 560;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.preview {
|
||||
display: block;
|
||||
font-size: var(--text-xs);
|
||||
color: var(--ink-faint);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.editor {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
/* Everything below exists to keep two layers in lockstep. The shared rules are
|
||||
set on both at once on purpose: a font-size on one and not the other is a
|
||||
whole line of drift by the bottom of a long note. */
|
||||
.paper {
|
||||
position: relative;
|
||||
flex: 1;
|
||||
min-height: 50vh;
|
||||
}
|
||||
|
||||
.paper textarea,
|
||||
.paper .mirror {
|
||||
font: inherit;
|
||||
font-size: var(--text-base, 1rem);
|
||||
line-height: 1.6;
|
||||
padding: var(--s2) 0;
|
||||
border: 0;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: break-word;
|
||||
word-break: normal;
|
||||
tab-size: 4;
|
||||
}
|
||||
|
||||
textarea {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
resize: none;
|
||||
background: none;
|
||||
/* Transparent, so what is read is the mirror underneath. The caret keeps its
|
||||
own colour or there would be nothing to type against. */
|
||||
color: transparent;
|
||||
caret-color: var(--ink);
|
||||
}
|
||||
|
||||
textarea::selection {
|
||||
background: var(--accent);
|
||||
color: var(--accent-ink);
|
||||
}
|
||||
|
||||
textarea:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.mirror {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
pointer-events: none;
|
||||
color: var(--ink);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* Headings change weight and colour, never size: a larger font would take more
|
||||
lines than the textarea does and everything below it would slide. */
|
||||
.mirror .h1,
|
||||
.mirror .h2,
|
||||
.mirror .h3,
|
||||
.mirror .h4,
|
||||
.mirror .h5,
|
||||
.mirror .h6 {
|
||||
font-weight: 620;
|
||||
}
|
||||
|
||||
.mirror .h1 {
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
.mirror .quote {
|
||||
color: var(--ink-muted);
|
||||
}
|
||||
|
||||
.mirror .bold {
|
||||
font-weight: 620;
|
||||
}
|
||||
|
||||
.mirror .italic {
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.mirror .code {
|
||||
font-family: var(--mono, ui-monospace, monospace);
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.mirror .tag,
|
||||
.mirror .wikilink {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--s3);
|
||||
padding-top: var(--s2);
|
||||
border-top: 1px solid var(--line);
|
||||
font-size: var(--text-xs);
|
||||
}
|
||||
|
||||
.links {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--s1);
|
||||
}
|
||||
|
||||
.link {
|
||||
color: var(--ink-muted);
|
||||
background: var(--surface);
|
||||
border-radius: var(--radius-sm);
|
||||
padding: 0 var(--s1);
|
||||
font-family: var(--mono, ui-monospace, monospace);
|
||||
}
|
||||
|
||||
.remove {
|
||||
margin-left: auto;
|
||||
color: var(--ink-faint);
|
||||
}
|
||||
|
||||
.remove:hover {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.empty,
|
||||
.hint {
|
||||
color: var(--ink-faint);
|
||||
font-size: var(--text-sm);
|
||||
}
|
||||
|
||||
@media (max-width: 700px) {
|
||||
.notes {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
aside {
|
||||
border-right: 0;
|
||||
padding-right: 0;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -43,6 +43,23 @@
|
||||
load(id);
|
||||
});
|
||||
|
||||
// Notes that mention this project. Looked up by name rather than by id, because
|
||||
// a #tag is written by hand and a person types the name — the same string the
|
||||
// quick-add parser reads out of a task.
|
||||
let notes = $state([]);
|
||||
|
||||
$effect(() => {
|
||||
const name = project?.name;
|
||||
if (!name) {
|
||||
notes = [];
|
||||
return;
|
||||
}
|
||||
api
|
||||
.notesLinking('project', name)
|
||||
.then((r) => (notes = r.notes ?? []))
|
||||
.catch(() => (notes = []));
|
||||
});
|
||||
|
||||
async function load(projectId) {
|
||||
if (!projectId) return;
|
||||
status = 'loading';
|
||||
@@ -793,6 +810,24 @@
|
||||
{#if project.role === 'viewer'}
|
||||
<p class="readonly">{t('project.readOnly')}</p>
|
||||
{/if}
|
||||
<!-- What has been written about this project, which is the payoff for a #tag
|
||||
in a note being the same tag a task carries: nobody files anything here,
|
||||
it turns up because somebody mentioned the project while writing. -->
|
||||
{#if notes.length}
|
||||
<section class="notes">
|
||||
<h2>{t('notes.title')}</h2>
|
||||
<ul>
|
||||
{#each notes as note (note.id)}
|
||||
<li>
|
||||
<a href="/noter?note={note.id}">
|
||||
<strong>{note.title || t('notes.untitled')}</strong>
|
||||
<span>{note.body.slice(0, 90)}</span>
|
||||
</a>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
</section>
|
||||
{/if}
|
||||
{:else if status === 'loading'}
|
||||
<!-- Deliberately blank, as on first load elsewhere: a spinner for a request
|
||||
that usually resolves in 30ms is a flash of anxiety, not feedback. -->
|
||||
@@ -809,6 +844,53 @@
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.notes {
|
||||
margin-top: var(--s4);
|
||||
padding-top: var(--s3);
|
||||
border-top: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.notes h2 {
|
||||
font-size: var(--text-xs);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
color: var(--ink-faint);
|
||||
margin-bottom: var(--s2);
|
||||
}
|
||||
|
||||
.notes ul {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1px;
|
||||
}
|
||||
|
||||
.notes a {
|
||||
display: block;
|
||||
padding: var(--s2);
|
||||
border-radius: var(--radius);
|
||||
color: var(--ink-muted);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.notes a:hover {
|
||||
background: var(--surface);
|
||||
}
|
||||
|
||||
.notes strong {
|
||||
display: block;
|
||||
font-size: var(--text-sm);
|
||||
font-weight: 560;
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
.notes span {
|
||||
font-size: var(--text-xs);
|
||||
color: var(--ink-faint);
|
||||
}
|
||||
|
||||
/* Recessed, because it is a record rather than a plan. The rows keep their own
|
||||
completed styling; this is about the section around them. */
|
||||
.done {
|
||||
|
||||
Reference in New Issue
Block a user