feat(tasks): add keyboard index and productivity dashboard improvements
This commit is contained in:
1 parent
02edb51b8a
commit
667776e43f
44 files changed
+1224
-138
No files matched your search
@@ -3,6 +3,7 @@ package grammaratur
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
@@ -18,11 +19,71 @@ func HTMLToMarkdownAuthoring(source string) (string, error) {
|
||||
return "", err
|
||||
}
|
||||
if htmlStructure(source) != htmlStructure(MarkdownToHTML(converted)) {
|
||||
return rawHTMLBlock(source), nil
|
||||
// Protect only the blocks which cannot round-trip. One custom component
|
||||
// must not turn the headings, lists and paragraphs around it into HTML.
|
||||
blocks, ok := authoringBlocks(source)
|
||||
if !ok {
|
||||
return rawHTMLBlock(source), nil
|
||||
}
|
||||
var parts []string
|
||||
for _, raw := range blocks {
|
||||
if strings.TrimSpace(raw) == "" {
|
||||
continue
|
||||
}
|
||||
md, e := HTMLToMarkdown(raw)
|
||||
if e != nil || htmlStructure(raw) != htmlStructure(MarkdownToHTML(md)) {
|
||||
md = rawHTMLBlock(raw)
|
||||
}
|
||||
parts = append(parts, md)
|
||||
}
|
||||
mixed := strings.Join(parts, "\n\n")
|
||||
// Includes head content, comments outside body and fragment edge cases.
|
||||
if htmlStructure(source) != htmlStructure(MarkdownAuthoringHTML(mixed)) {
|
||||
return rawHTMLBlock(source), nil
|
||||
}
|
||||
return mixed, nil
|
||||
}
|
||||
return converted, nil
|
||||
}
|
||||
|
||||
// Token boundaries retain the exact source of protected components (including
|
||||
// attribute quoting and void-element syntax). Never serialize the parsed DOM
|
||||
// back over their source. Malformed/implicit nesting uses whole-document fallback.
|
||||
func authoringBlocks(source string) ([]string, bool) {
|
||||
z := html.NewTokenizer(strings.NewReader(source))
|
||||
var stack, blocks []string
|
||||
start, offset := 0, 0
|
||||
for {
|
||||
kind := z.Next()
|
||||
if kind == html.ErrorToken {
|
||||
return blocks, z.Err() == io.EOF && len(stack) == 0 && offset == len(source)
|
||||
}
|
||||
offset += len(z.Raw())
|
||||
switch kind {
|
||||
case html.StartTagToken:
|
||||
name, _ := z.TagName()
|
||||
switch string(name) {
|
||||
case "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr":
|
||||
default:
|
||||
stack = append(stack, string(name))
|
||||
}
|
||||
case html.EndTagToken:
|
||||
name, _ := z.TagName()
|
||||
if len(stack) == 0 || stack[len(stack)-1] != string(name) {
|
||||
return nil, false
|
||||
}
|
||||
stack = stack[:len(stack)-1]
|
||||
}
|
||||
if len(stack) == 0 {
|
||||
blocks = append(blocks, source[start:offset])
|
||||
start = offset
|
||||
if len(blocks) > 1024 {
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// {=html} is an explicit authoring fence, not an ordinary code sample. The
|
||||
// closing delimiter is longer than any run in the source, so arbitrary HTML
|
||||
// (including Markdown examples) cannot accidentally terminate it.
|
||||
@@ -110,6 +171,12 @@ func htmlStructure(source string) string {
|
||||
literal = literal || n.Data == "pre" || n.Data == "code" || n.Data == "script" || n.Data == "style"
|
||||
data := n.Data
|
||||
if n.Type == html.TextNode && !literal {
|
||||
if strings.TrimSpace(data) == "" && n.Parent != nil {
|
||||
switch n.Parent.Data {
|
||||
case "ul", "ol", "table", "thead", "tbody", "tfoot", "tr":
|
||||
return
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(data) == "" && (n.Parent == nil || n.Parent.Data == "body" || n.Parent.Data == "html") {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -65,3 +65,19 @@ func TestAuthoringWhitespaceComparisonIsConservative(t *testing.T) {
|
||||
t.Fatal("word boundaries ignored")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthoringPartialMarkdownRecovery(t *testing.T) {
|
||||
source := `<h1>Title</h1><p>Some <strong>bold</strong> text.</p><figure data-x="keep"><img src="/image"><figcaption>Caption</figcaption></figure><ul><li>First</li><li>Second</li></ul>`
|
||||
md, err := HTMLToMarkdownAuthoring(source)
|
||||
if err != nil || !strings.HasPrefix(md, "# Title") || !strings.Contains(md, "**bold**") || strings.Count(md, "{=html}") != 1 || !strings.Contains(md, "- First") {
|
||||
t.Fatalf("markdown not recovered: %q %v", md, err)
|
||||
}
|
||||
if htmlStructure(source) != htmlStructure(MarkdownAuthoringHTML(md)) {
|
||||
t.Fatal("HTML lost during partial conversion")
|
||||
}
|
||||
protected := `<figure data-x='original'><img src=/image><figcaption>Caption</figcaption></figure>`
|
||||
md, err = HTMLToMarkdownAuthoring("<h1>Title</h1>" + protected + "<p>Tail</p>")
|
||||
if err != nil || !strings.Contains(MarkdownAuthoringHTML(md), protected) || !strings.HasPrefix(md, "# Title") {
|
||||
t.Fatalf("protected bytes changed: %q %v", md, err)
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
@@ -321,13 +320,6 @@ func (s *Server) renderAuthPage(w http.ResponseWriter, r *http.Request, data map
|
||||
transparency := s.homeGlassTransparency(domainUUID)
|
||||
data["HomeGlassTransparency"] = transparency
|
||||
data["HomeGlassOpacity"] = 100 - transparency
|
||||
configured, opacity := s.homeWallpaperConfig(domainUUID)
|
||||
data["HomeWallpaperOpacity"] = strconv.FormatFloat(float64(opacity)/100, 'f', 2, 64)
|
||||
if configured != "" {
|
||||
// Only the administrator-selected login wallpaper is exposed; the
|
||||
// request cannot choose an arbitrary document address.
|
||||
data["HomeWallpaperURL"] = "/_/auth/wallpaper"
|
||||
w.Header().Set("Cache-Control", "private, no-store")
|
||||
}
|
||||
// Login has no wallpaper: private home images must not become public.
|
||||
s.renderWithContext(w, r, "auth.gohtml", data)
|
||||
}
|
||||
@@ -72,6 +72,15 @@ func TestCalendarUpcomingDefaultsAndBounds(t *testing.T) {
|
||||
t.Fatal("tomorrow event in today's widget", event.Start)
|
||||
}
|
||||
}
|
||||
w = calendarRequest(s, token, "GET", calendarAPI+"upcoming?period=day&date="+end.Format("2006-01-02"), "", "")
|
||||
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &result) != nil {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
for _, event := range result.Events {
|
||||
if !event.Start.Before(end.AddDate(0, 0, 1)) || !event.End.After(end) {
|
||||
t.Fatal("event outside tomorrow", event.Start, event.End)
|
||||
}
|
||||
}
|
||||
if w = calendarRequest(s, "", "GET", calendarAPI+"upcoming", "", ""); w.Code != 403 {
|
||||
t.Fatal("anonymous access", w.Code)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"math/big"
|
||||
"mime"
|
||||
@@ -9,7 +8,6 @@ import (
|
||||
pathpkg "path"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
@@ -23,75 +21,16 @@ type homeWallpaperView struct {
|
||||
Key string
|
||||
}
|
||||
|
||||
// configuredLoginWallpaper returns only the image selected by the Domain
|
||||
// administrator as the home/login wallpaper. It intentionally does not use
|
||||
// the requesting principal's document permissions: choosing an image as the
|
||||
// login wallpaper makes that one image public on the sign-in surface.
|
||||
func (s *Server) configuredLoginWallpaper(domainUUID string) *store.Revision {
|
||||
configured, _ := s.homeWallpaperConfig(domainUUID)
|
||||
if configured == "" {
|
||||
return nil
|
||||
}
|
||||
if objectUUID, err := s.store.ResolvePathInDomain(domainUUID, configured); err == nil {
|
||||
revision, revisionErr := s.store.GetLatestRevisionForLanguages(objectUUID, []string{s.getLocale(domainUUID), "und"})
|
||||
if revisionErr == nil && imageContentType(revision.ContentType) {
|
||||
return revision
|
||||
}
|
||||
}
|
||||
entries, err := s.store.ListBrowserEntriesInDomain(domainUUID, configured)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
candidates := make([]store.BrowserEntry, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
if !entry.IsDir && entry.RevisionUUID != "" && imageContentType(entry.ContentType) {
|
||||
candidates = append(candidates, entry)
|
||||
}
|
||||
}
|
||||
if len(candidates) == 0 {
|
||||
return nil
|
||||
}
|
||||
index := 0
|
||||
if value, randomErr := rand.Int(rand.Reader, big.NewInt(int64(len(candidates)))); randomErr == nil {
|
||||
index = int(value.Int64())
|
||||
}
|
||||
revision, err := s.store.GetRevision(candidates[index].RevisionUUID)
|
||||
if err != nil || !imageContentType(revision.ContentType) {
|
||||
return nil
|
||||
}
|
||||
return revision
|
||||
}
|
||||
|
||||
// Legacy route retained as a deliberate 404. Home wallpapers are never
|
||||
// published to unauthenticated clients through the sign-in screen.
|
||||
func (s *Server) handleAuthWallpaper(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet && r.Method != http.MethodHead {
|
||||
w.Header().Set("Allow", "GET, HEAD")
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
revision := s.configuredLoginWallpaper(s.domainUUIDForRequest(r))
|
||||
if revision == nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
contentType := revision.ContentType
|
||||
mediaType, _, err := mime.ParseMediaType(contentType)
|
||||
if err != nil || !strings.HasPrefix(strings.ToLower(mediaType), "image/") {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
filename := strings.TrimSpace(revision.Filename)
|
||||
if filename == "" {
|
||||
filename = "wallpaper"
|
||||
}
|
||||
w.Header().Set("Cache-Control", "private, no-store")
|
||||
w.Header().Set("Content-Type", contentType)
|
||||
w.Header().Set("Content-Disposition", mime.FormatMediaType("inline", map[string]string{"filename": filename}))
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("ETag", `"`+revision.DocumentHash+`"`)
|
||||
if strings.EqualFold(mediaType, "image/svg+xml") {
|
||||
w.Header().Set("Content-Security-Policy", "default-src 'none'; sandbox")
|
||||
}
|
||||
http.ServeContent(w, r, filename, time.UnixMilli(revision.CreatedAtMS), bytes.NewReader([]byte(revision.Body)))
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
|
||||
func normalizePickerPath(raw string) (string, bool) {
|
||||
@@ -135,7 +74,8 @@ func (s *Server) homeWallpaperConfig(domainUUID string) (string, int) {
|
||||
|
||||
func (s *Server) homeWallpaperForRequest(r *http.Request) homeWallpaperView {
|
||||
domainUUID := s.domainUUIDForRequest(r)
|
||||
configured, opacity := s.homeWallpaperConfig(domainUUID)
|
||||
p := s.appearanceForRequest(r)
|
||||
configured, opacity := p.Path, p.Opacity
|
||||
view := homeWallpaperView{Path: configured, Opacity: strconv.FormatFloat(float64(opacity)/100, 'f', 2, 64)}
|
||||
if configured == "" {
|
||||
return view
|
||||
|
||||
@@ -22,7 +22,7 @@ func saveWallpaperFixture(t *testing.T, s *Server, domain, path, contentType str
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthPageUsesConfiguredWallpaperAndGlass(t *testing.T) {
|
||||
func TestAuthPageDoesNotPublishHomeWallpaper(t *testing.T) {
|
||||
s, _, domain := configFixture(t)
|
||||
s.mux.HandleFunc("/_/auth/", s.handleAuth)
|
||||
saveWallpaperFixture(t, s, domain, "/wallpapers/login.jpg", "image/jpeg")
|
||||
@@ -46,8 +46,6 @@ func TestAuthPageUsesConfiguredWallpaperAndGlass(t *testing.T) {
|
||||
for _, expected := range []string{
|
||||
`class="auth-page"`,
|
||||
`--home-glass-opacity:53%`,
|
||||
`class="home-wallpaper" src="/_/auth/wallpaper"`,
|
||||
`style="opacity:0.41"`,
|
||||
`/static/css/auth.css?v=1`,
|
||||
`class="auth-provider-button"`,
|
||||
`OpenID Connectでログイン`,
|
||||
@@ -56,10 +54,13 @@ func TestAuthPageUsesConfiguredWallpaperAndGlass(t *testing.T) {
|
||||
t.Fatalf("auth page missing %q: status=%d body=%s", expected, response.Code, body)
|
||||
}
|
||||
}
|
||||
if strings.Contains(body, `class="home-wallpaper"`) || strings.Contains(body, `/_/auth/wallpaper`) {
|
||||
t.Fatal("private home wallpaper exposed at login")
|
||||
}
|
||||
|
||||
wallpaper := httptest.NewRecorder()
|
||||
s.withAuthorization(s.mux).ServeHTTP(wallpaper, httptest.NewRequest(http.MethodGet, "http://localhost/_/auth/wallpaper?path=/private/ignored", nil))
|
||||
if wallpaper.Code != http.StatusOK || wallpaper.Body.String() != "fixture" || wallpaper.Header().Get("Content-Type") != "image/jpeg" || wallpaper.Header().Get("X-Content-Type-Options") != "nosniff" {
|
||||
if wallpaper.Code != http.StatusNotFound || wallpaper.Body.String() == "fixture" {
|
||||
t.Fatalf("login wallpaper: status=%d type=%q body=%q", wallpaper.Code, wallpaper.Header().Get("Content-Type"), wallpaper.Body.String())
|
||||
}
|
||||
|
||||
|
||||
@@ -239,7 +239,7 @@ var translations = map[string]map[string]string{
|
||||
"home.palette_brightness": "Light and dark",
|
||||
"home.palette_preserve": "Keep the current theme brightness",
|
||||
"home.palette_auto": "Choose from the displayed wallpaper",
|
||||
"home.palette_help": "Applies only to the home page and its dialogs. Warning colors are preserved. If extraction fails, the selected theme remains. Shared by this domain.",
|
||||
"home.palette_help": "Applies only to the home page and its dialogs. Warning colors are preserved. If extraction fails, the selected theme remains.",
|
||||
"home.glass_transparency": "Glass transparency (%)",
|
||||
"home.glass_help": "Controls the shared transparency of the home search, menus, suggestions, cards, and dialogs. Higher values are more transparent.",
|
||||
"picker.open": "Browse PagesWiki",
|
||||
@@ -1019,7 +1019,7 @@ var translations = map[string]map[string]string{
|
||||
"home.palette_brightness": "明暗",
|
||||
"home.palette_preserve": "現在のテーマの明暗を維持",
|
||||
"home.palette_auto": "表示中の壁紙から自動判定",
|
||||
"home.palette_help": "トップ画面とその上のダイアログにのみ適用します。警告色は変更しません。色を抽出できない場合は選択中のテーマを維持します。このドメインで共通の設定です。",
|
||||
"home.palette_help": "トップ画面とその上のダイアログにのみ適用します。警告色は変更しません。色を抽出できない場合は選択中のテーマを維持します。",
|
||||
"home.glass_transparency": "グラスの透明度(%)",
|
||||
"home.glass_help": "トップ画面の検索、メニュー、サジェスト、カード、ダイアログに共通の透明度です。数値を上げるほど背景が透けます。",
|
||||
"picker.open": "PagesWikiから選択",
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
)
|
||||
|
||||
func personalOrganizerSettings(r *http.Request) bool {
|
||||
return r.URL.Path == "/-/sys/config" && r.URL.Query().Get("panel") == "organizer" && (r.Method == "GET" || r.Method == "HEAD")
|
||||
return r.URL.Path == "/-/sys/config" && r.URL.Query().Get("panel") == "organizer" && (r.Method == "GET" || r.Method == "HEAD" || r.Method == "POST" && r.URL.Query().Get("section") == "appearance")
|
||||
}
|
||||
|
||||
func (s *Server) handleOrganizerDashboard(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -33,7 +33,13 @@ func (s *Server) handleOrganizerSettings(w http.ResponseWriter, r *http.Request)
|
||||
s.authRequired(w, r)
|
||||
return
|
||||
}
|
||||
s.renderWithContext(w, r, "organizer_settings.gohtml", map[string]any{"TaskWritable": active})
|
||||
if r.Method == "POST" {
|
||||
s.savePersonalAppearance(w, r, actor, active)
|
||||
return
|
||||
}
|
||||
data := s.appearanceData(r)
|
||||
data["TaskWritable"] = active
|
||||
s.renderWithContext(w, r, "organizer_settings.gohtml", data)
|
||||
}
|
||||
|
||||
func (s *Server) handleDashboardData(w http.ResponseWriter, r *http.Request, actor string, active bool, kind string) {
|
||||
@@ -110,6 +116,12 @@ func organizerSection(path string) string {
|
||||
}
|
||||
|
||||
func init() {
|
||||
translations["en"]["home.domain_appearance_defaults"] = "Appearance defaults (personal settings take precedence)"
|
||||
translations["ja"]["home.domain_appearance_defaults"] = "外観の初期値(個人設定を優先)"
|
||||
translations["en"]["home.personal_wallpaper"] = "Personal wallpaper Path (empty: none)"
|
||||
translations["ja"]["home.personal_wallpaper"] = "個人の壁紙Path(空欄:なし)"
|
||||
translations["en"]["home.personal_opacity"] = "Wallpaper opacity (%)"
|
||||
translations["ja"]["home.personal_opacity"] = "壁紙の不透明度(%)"
|
||||
translations["en"]["task.work_history"] = "Work history"
|
||||
translations["ja"]["task.work_history"] = "作業記録"
|
||||
for lang, entries := range map[string]map[string]string{
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// Personal appearance is separate from domain defaults and from organizer mail
|
||||
// preferences. It never makes the selected documents publicly readable.
|
||||
type personalAppearance struct {
|
||||
Version int64
|
||||
Path string
|
||||
Opacity int
|
||||
Glass int
|
||||
Palette homePaletteSettings
|
||||
}
|
||||
|
||||
func (s *Server) appearanceForRequest(r *http.Request) personalAppearance {
|
||||
domain := s.domainUUIDForRequest(r)
|
||||
path, opacity := s.homeWallpaperConfig(domain)
|
||||
p := personalAppearance{Path: path, Opacity: opacity, Glass: s.homeGlassTransparency(domain), Palette: s.homePalette(domain)}
|
||||
principal := s.requestPrincipal(r)
|
||||
if principal == nil {
|
||||
return p
|
||||
}
|
||||
var raw string
|
||||
var version int64
|
||||
if s.store.DB.QueryRowContext(r.Context(), `SELECT version,data FROM personal_appearance WHERE domain_uuid=? AND owner_uuid=?`, domain, principal.UUID).Scan(&version, &raw) == nil {
|
||||
var saved personalAppearance
|
||||
if json.Unmarshal([]byte(raw), &saved) == nil {
|
||||
saved.Version = version
|
||||
return saved
|
||||
}
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func (s *Server) appearanceData(r *http.Request) map[string]any {
|
||||
p := s.appearanceForRequest(r)
|
||||
return map[string]any{"AppearanceVersion": p.Version, "HomeWallpaperPath": p.Path, "HomeWallpaperPercent": p.Opacity, "HomeGlassTransparency": p.Glass, "HomePalette": p.Palette}
|
||||
}
|
||||
|
||||
func (s *Server) savePersonalAppearance(w http.ResponseWriter, r *http.Request, actor string, active bool) {
|
||||
if !active || s.store.ReadOnly {
|
||||
http.Error(w, "forbidden", 403)
|
||||
return
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 16384)
|
||||
if r.ParseForm() != nil {
|
||||
http.Error(w, "invalid form", 400)
|
||||
return
|
||||
}
|
||||
domain := s.domainUUIDForRequest(r)
|
||||
p := s.appearanceForRequest(r)
|
||||
version, err := strconv.ParseInt(r.FormValue("version"), 10, 64)
|
||||
if err != nil || version < 0 {
|
||||
http.Error(w, "invalid version", 400)
|
||||
return
|
||||
}
|
||||
if p.Version != version {
|
||||
http.Error(w, "Settings changed elsewhere; reload before saving.", 409)
|
||||
return
|
||||
}
|
||||
if p.Glass, err = normalizeHomeGlassTransparency(r.FormValue("home_glass_transparency")); err != nil {
|
||||
http.Error(w, "invalid transparency", 400)
|
||||
return
|
||||
}
|
||||
if p.Palette, err = s.parseHomePalette(domain, r.Form); err != nil {
|
||||
http.Error(w, "invalid palette", 400)
|
||||
return
|
||||
}
|
||||
if r.Form.Has("home_wallpaper_path") {
|
||||
var ok bool
|
||||
p.Path, ok = normalizePickerPath(r.FormValue("home_wallpaper_path"))
|
||||
if !ok {
|
||||
http.Error(w, "invalid Path", 400)
|
||||
return
|
||||
}
|
||||
if p.Path != "" && !s.requestCanReadPath(r, p.Path) {
|
||||
http.Error(w, "Path not readable", 403)
|
||||
return
|
||||
}
|
||||
}
|
||||
if r.Form.Has("home_wallpaper_opacity") {
|
||||
p.Opacity, err = strconv.Atoi(r.FormValue("home_wallpaper_opacity"))
|
||||
if err != nil || p.Opacity < 0 || p.Opacity > 100 {
|
||||
http.Error(w, "invalid opacity", 400)
|
||||
return
|
||||
}
|
||||
}
|
||||
p.Version = version + 1
|
||||
raw, _ := json.Marshal(p)
|
||||
result, err := s.store.DB.ExecContext(r.Context(), `INSERT INTO personal_appearance(domain_uuid,owner_uuid,version,data) SELECT ?,?,?,? WHERE ?=0 ON CONFLICT(domain_uuid,owner_uuid) DO NOTHING`, domain, actor, p.Version, string(raw), version)
|
||||
if err == nil {
|
||||
var n int64
|
||||
n, err = result.RowsAffected()
|
||||
if err == nil && n == 0 {
|
||||
result, err = s.store.DB.ExecContext(r.Context(), `UPDATE personal_appearance SET version=?,data=? WHERE domain_uuid=? AND owner_uuid=? AND version=?`, p.Version, string(raw), domain, actor, version)
|
||||
if err == nil {
|
||||
n, err = result.RowsAffected()
|
||||
if n == 0 {
|
||||
err = sql.ErrNoRows
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
http.Error(w, "Settings changed elsewhere; reload before saving.", 409)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
http.Error(w, "Unable to save settings", 500)
|
||||
return
|
||||
}
|
||||
if r.Header.Get("Accept") == "application/json" {
|
||||
writeEventJSON(w, 200, map[string]any{"version": p.Version})
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, "/-/sys/config?panel=organizer#appearance", http.StatusSeeOther)
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPersonalAppearanceIsolationAndCAS(t *testing.T) {
|
||||
s, admin, domain := configFixture(t)
|
||||
p, err := s.store.CreatePasswordAccount(domain, "appearanceuser", "long test password", "Member", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
token, err := s.store.CreateAuthSession(domain, p.UUID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
endpoint := "/-/sys/config?panel=organizer§ion=appearance"
|
||||
form := url.Values{"version": {"0"}, "home_wallpaper_path": {""}, "home_wallpaper_opacity": {"50"}, "home_glass_transparency": {"71"}, "home_palette_mode": {"accent"}, "home_palette_strength": {"55"}, "home_palette_brightness": {"preserve"}}
|
||||
w := configRequest(s, token, "POST", endpoint, form)
|
||||
if w.Code != 303 || w.Header().Get("Location") != "/-/sys/config?panel=organizer#appearance" {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
if w = configRequest(s, token, "POST", endpoint, form); w.Code != 409 {
|
||||
t.Fatal("stale write", w.Code, w.Body)
|
||||
}
|
||||
w = configRequest(s, token, "GET", "/-/sys/config?panel=organizer", nil)
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), `name="home_glass_transparency" type="number" min="0" max="85" value="71"`) {
|
||||
t.Fatal("personal value missing", w.Code, w.Body)
|
||||
}
|
||||
w = configRequest(s, admin, "GET", "/-/sys/config?panel=organizer", nil)
|
||||
if w.Code != 200 || strings.Contains(w.Body.String(), `max="85" value="71"`) {
|
||||
t.Fatal("owner leakage", w.Code)
|
||||
}
|
||||
raw, _ := s.store.GetConfigInDomain(domain, "home_glass_transparency")
|
||||
if raw == "71" {
|
||||
t.Fatal("changed domain settings")
|
||||
}
|
||||
if w = configRequest(s, "", "POST", endpoint, form); w.Code == 303 && w.Header().Get("Location") == "/-/sys/config?panel=organizer#appearance" {
|
||||
t.Fatal("anonymous write")
|
||||
}
|
||||
if err = s.store.SetPrincipalState(domain, p.UUID, "readonly"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
token, err = s.store.CreateAuthSession(domain, p.UUID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
form.Set("version", "1")
|
||||
if w = configRequest(s, token, "POST", endpoint, form); w.Code != 403 {
|
||||
t.Fatal("readonly write", w.Code)
|
||||
}
|
||||
}
|
||||
@@ -74,23 +74,27 @@ func (s *Server) renderWithContext(
|
||||
if r.URL.Path == "/" {
|
||||
data["IsHome"] = true
|
||||
data["BookmarkSections"] = s.bookmarkSections(r)
|
||||
canConfigureHome := s.canManageAssets(r)
|
||||
if controlled, err := s.store.DomainEntryControlled(domainUUID); err != nil || controlled {
|
||||
canConfigureHome = false
|
||||
_, canConfigureHome := s.calendarActor(r)
|
||||
if s.requestPrincipal(r) != nil {
|
||||
w.Header().Set("Cache-Control", "private, no-store")
|
||||
}
|
||||
data["CanManageBookmarks"] = s.canManageAssets(r)
|
||||
data["CanConfigureHome"] = canConfigureHome
|
||||
transparency := s.homeGlassTransparency(domainUUID)
|
||||
appearance := s.appearanceForRequest(r)
|
||||
for k, v := range s.appearanceData(r) {
|
||||
data[k] = v
|
||||
}
|
||||
transparency := appearance.Glass
|
||||
data["HomeGlassTransparency"] = transparency
|
||||
data["HomeGlassOpacity"] = 100 - transparency
|
||||
wallpaper := s.homeWallpaperForRequest(r)
|
||||
data["HomeWallpaperURL"] = wallpaper.URL
|
||||
data["HomeWallpaperOpacity"] = wallpaper.Opacity
|
||||
data["HomeWallpaperKey"] = wallpaper.Key
|
||||
data["HomePalette"] = s.homePalette(domainUUID)
|
||||
data["HomePalette"] = appearance.Palette
|
||||
data["HomePaletteDomain"] = domainUUID
|
||||
if wallpaper.URL != "" {
|
||||
w.Header().Set("Cache-Control", "private, no-cache")
|
||||
w.Header().Set("Cache-Control", "private, no-store")
|
||||
}
|
||||
if data["CanManageBookmarks"] == true {
|
||||
data["ManagedBookmarks"] = s.managedBookmarks(domainUUID)
|
||||
|
||||
@@ -77,9 +77,14 @@ func TestBookmarkAndVimSettingsChromium(t *testing.T) {
|
||||
if len(items) != 2 || items[0].Kind != "section" || !items[0].Children || items[0].Href != "/docs" || items[1].Label != "Reference" {
|
||||
t.Fatalf("saved bookmarks: %#v", items)
|
||||
}
|
||||
if got := s.homeGlassTransparency(domain); got != 57 {
|
||||
r := httptest.NewRequest("GET", "http://localhost/", nil)
|
||||
r.Header.Set("Authorization", "Bearer "+token)
|
||||
if got := s.appearanceForRequest(r).Glass; got != 57 {
|
||||
t.Fatalf("saved glass transparency: %d", got)
|
||||
}
|
||||
if s.homeGlassTransparency(domain) == 57 {
|
||||
t.Fatal("personal appearance changed domain defaults")
|
||||
}
|
||||
vim := s.domainVimSettings(domain)
|
||||
if !vim.Enabled || vim.Vimrc != "set tabstop=3\n" || vim.ColorName != "uploaded.vim" || !strings.Contains(vim.Colorscheme, "Normal") {
|
||||
t.Fatalf("saved vim: %#v", vim)
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestTaskIndexChromium(t *testing.T) {
|
||||
if os.Getenv("PAGESWIKI_BROWSER_TEST") != "1" {
|
||||
t.Skip("opt-in Chromium")
|
||||
}
|
||||
for _, width := range []string{"1440", "390"} {
|
||||
t.Run(width, func(t *testing.T) {
|
||||
s, token, domain, actor := taskFixture(t)
|
||||
for i, title := range []string{"**Alpha**", "Beta", "Gamma"} {
|
||||
task := newTaskRecord("task", title)
|
||||
if i < 2 {
|
||||
project, err := s.store.SaveTask(context.Background(), domain, actor, newTaskRecord("project", "Project "+title), 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task.ProjectUUID = project.UUID
|
||||
}
|
||||
if i == 1 {
|
||||
task.Status = "doing"
|
||||
}
|
||||
if _, err := s.store.SaveTask(context.Background(), domain, actor, task, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
script, err := os.ReadFile("internal/server/testdata/task-index.js")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
r.Host = "localhost"
|
||||
r.Header.Set("Authorization", "Bearer "+token)
|
||||
if r.URL.Path == "/v/plan/tasks/index" {
|
||||
rec := httptest.NewRecorder()
|
||||
s.withAuthorization(s.mux).ServeHTTP(rec, r)
|
||||
for k, v := range rec.Header() {
|
||||
w.Header()[k] = v
|
||||
}
|
||||
w.WriteHeader(rec.Code)
|
||||
w.Write([]byte(strings.Replace(rec.Body.String(), "</body>", browserFixtureScript(rec.Header(), script)+"</body>", 1)))
|
||||
return
|
||||
}
|
||||
s.withAuthorization(s.mux).ServeHTTP(w, r)
|
||||
}))
|
||||
defer server.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, "node", "internal/server/testdata/vim-browser-smoke.mjs", strings.Replace(server.URL, "127.0.0.1", "localhost", 1)+"/v/plan/tasks/index", t.TempDir(), "/tmp/pages-task-index-"+width+".png", width, "900")
|
||||
cmd.Env = append(os.Environ(), "PAGESWIKI_TASK_INDEX_BROWSER=1")
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("browser %v: %s", err, out)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/url"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
func TestTaskIndexFilteringSortingPagination(t *testing.T) {
|
||||
s, token, domain, actor := taskFixture(t)
|
||||
today := time.Now().In(s.getLocation(domain)).Format("2006-01-02")
|
||||
project, err := s.store.SaveTask(context.Background(), domain, actor, newTaskRecord("project", "Index project"), 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
page, err := s.store.CreatePageAtPathInDomain(domain, "/index-related")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i, title := range []string{"Alpha release", "Beta release", "Gamma", "Delta"} {
|
||||
task := newTaskRecord("task", title)
|
||||
task.DueOn = []string{"2020-01-01", "2020-01-01", "2099-01-01", ""}[i]
|
||||
if i == 0 {
|
||||
task.Status = "doing"
|
||||
task.Priority = 3
|
||||
task.References = []string{"/files/ref.pdf"}
|
||||
task.ProjectUUID = project.UUID
|
||||
task.PageUUID = page
|
||||
task.StartOn = "2019-01-01"
|
||||
task.PlannedOn = today
|
||||
task.ReviewOn = today
|
||||
}
|
||||
if i == 2 {
|
||||
task.Status = "done"
|
||||
}
|
||||
if i == 3 {
|
||||
task.Archived = true
|
||||
}
|
||||
if _, err = s.store.SaveTask(context.Background(), domain, actor, task, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
type result struct {
|
||||
Items []store.TaskRecord
|
||||
Next string
|
||||
}
|
||||
get := func(filter, sort, order, project, before string, limit int) result {
|
||||
t.Helper()
|
||||
q := url.Values{"view": {"index"}, "filter": {filter}, "sort": {sort}, "order": {order}, "project": {project}, "before": {before}, "limit": {"1"}}
|
||||
if limit > 1 {
|
||||
q.Set("limit", "100")
|
||||
}
|
||||
w := taskRequest(s, token, "GET", "items?"+q.Encode(), nil, "")
|
||||
var d result
|
||||
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &d) != nil {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
return d
|
||||
}
|
||||
first := get("~active", "title", "asc", "", "", 1)
|
||||
if len(first.Items) != 1 || first.Items[0].Title != "Alpha release" || first.Next == "" {
|
||||
t.Fatal(first)
|
||||
}
|
||||
second := get("~active", "title", "asc", "", first.Next, 1)
|
||||
if len(second.Items) != 1 || second.Items[0].Title != "Beta release" || second.Next != "" {
|
||||
t.Fatal(second)
|
||||
}
|
||||
reverse := get("~active", "title", "desc", "", "", 100)
|
||||
if len(reverse.Items) != 2 || reverse.Items[0].Title != "Beta release" {
|
||||
t.Fatal(reverse)
|
||||
}
|
||||
cases := map[string]string{`~s "Alpha release" ~doing ~overdue ~priority 3 ~attachment`: "Alpha release", `~due <=today !~doing ~active`: "Beta release", `~done !~overdue`: "Gamma", `~archived ~due none`: "Delta", `~s release ~due <` + today + ` ~doing`: "Alpha release"}
|
||||
for filter, title := range cases {
|
||||
r := get(filter, "due", "asc", "", "", 100)
|
||||
if len(r.Items) != 1 || r.Items[0].Title != title {
|
||||
t.Fatal(filter, r)
|
||||
}
|
||||
}
|
||||
for _, filter := range []string{"~wiki", "~start <=2020-01-01 ~planned today ~review =today"} {
|
||||
r := get(filter, "due", "asc", "", "", 100)
|
||||
if len(r.Items) != 1 || r.Items[0].Title != "Alpha release" {
|
||||
t.Fatal(filter, r)
|
||||
}
|
||||
}
|
||||
for _, key := range []string{"due", "planned", "title", "status", "priority", "created", "updated"} {
|
||||
a := get("~active", key, "asc", "", "", 1)
|
||||
b := get("~active", key, "asc", "", a.Next, 1)
|
||||
rev := get("~active", key, "desc", "", "", 100)
|
||||
if a.Next == "" || len(b.Items) != 1 || b.Items[0].UUID == a.Items[0].UUID || len(rev.Items) != 2 || rev.Items[0].UUID != b.Items[0].UUID {
|
||||
t.Fatal("unstable sort", key, a, b, rev)
|
||||
}
|
||||
}
|
||||
if r := get("~active", "due", "asc", "none", "", 100); len(r.Items) != 1 || r.Items[0].Title != "Beta release" {
|
||||
t.Fatal(r)
|
||||
}
|
||||
if r := get("", "due", "asc", project.UUID, "", 100); len(r.Items) != 1 || r.Items[0].Title != "Alpha release" {
|
||||
t.Fatal(r)
|
||||
}
|
||||
for _, filter := range []string{`~unknown`, `~s`, `~s "unfinished`, `~due 2026-02-30`, `~priority 8`, `~bucket whatever`} {
|
||||
w := taskRequest(s, token, "GET", "items?view=index&filter="+url.QueryEscape(filter), nil, "")
|
||||
if w.Code != 422 {
|
||||
t.Fatal("invalid accepted", filter, w.Code)
|
||||
}
|
||||
}
|
||||
if w := taskRequest(s, token, "GET", "items?view=index&sort=title%3BDROP+TABLE+organizer_items", nil, ""); w.Code != 422 {
|
||||
t.Fatal(w.Code)
|
||||
}
|
||||
if w := configRequest(s, token, "GET", "/v/plan/tasks/index", nil); w.Code != 200 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
other, err := s.store.CreatePasswordAccount(domain, "indexother", "long test password", "Other", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
otherToken, err := s.store.CreateAuthSession(domain, other.UUID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
w := taskRequest(s, otherToken, "GET", "items?view=index&before="+first.Next, nil, "")
|
||||
var empty result
|
||||
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &empty) != nil || len(empty.Items) != 0 {
|
||||
t.Fatal("cross-owner leakage", w.Code, w.Body)
|
||||
}
|
||||
if err = s.store.SetPrincipalState(domain, actor, "readonly"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
readonlyToken, err := s.store.CreateAuthSession(domain, actor)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w = taskRequest(s, readonlyToken, "GET", "items?view=index", nil, ""); w.Code != 200 {
|
||||
t.Fatal("readonly read", w.Code)
|
||||
}
|
||||
item := first.Items[0]
|
||||
item.Status = "done"
|
||||
if w = taskRequest(s, readonlyToken, "PUT", "items/"+item.UUID, item, `"1"`); w.Code != 403 {
|
||||
t.Fatal("readonly mutation", w.Code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTaskReferencesRoundTripAndLegacyUpdate(t *testing.T) {
|
||||
s, token, domain, actor := taskFixture(t)
|
||||
task := newTaskRecord("task", "**Bold** and `code`")
|
||||
task.References = []string{"https://example.test/doc", "/files/資料.pdf"}
|
||||
w := taskRequest(s, token, "POST", "items", task, "")
|
||||
if w.Code != 201 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
task.References = nil
|
||||
task.Title = "Updated"
|
||||
w = taskRequest(s, token, "PUT", "items/"+task.UUID, task, `"1"`)
|
||||
if w.Code != 200 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
got, err := s.store.GetTask(context.Background(), domain, actor, task.UUID)
|
||||
if err != nil || len(got.References) != 2 {
|
||||
t.Fatal(got, err)
|
||||
}
|
||||
raw, _ := json.Marshal(got)
|
||||
var body map[string]any
|
||||
json.Unmarshal(raw, &body)
|
||||
body["references"] = []string{}
|
||||
w = taskRequest(s, token, "PUT", "items/"+task.UUID, body, `"2"`)
|
||||
if w.Code != 200 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
got, err = s.store.GetTask(context.Background(), domain, actor, task.UUID)
|
||||
if err != nil || len(got.References) != 0 {
|
||||
t.Fatal("references not cleared", got, err)
|
||||
}
|
||||
for _, ref := range []string{"javascript:alert(1)", "data:text/html,hi", "//evil.test/x", "/\\evil.test/x", "https://user:pass@example.test", "https://example.test/\nheader"} {
|
||||
bad := newTaskRecord("task", "bad")
|
||||
bad.References = []string{ref}
|
||||
if w = taskRequest(s, token, "POST", "items", bad, ""); w.Code != 422 {
|
||||
t.Fatal("unsafe reference accepted", ref, w.Code)
|
||||
}
|
||||
}
|
||||
widgets := []map[string]any{{"id": "tomorrow-schedule", "width": 6, "height": 4}, {"id": "commands", "width": 6, "height": 3}}
|
||||
if w = taskRequest(s, token, "PUT", "dashboard", map[string]any{"version": 0, "widgets": widgets}, ""); w.Code != 200 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
@@ -146,7 +146,7 @@ func (s *Server) handleTaskPage(w http.ResponseWriter, r *http.Request) {
|
||||
selectedDate, view = d.Format("2006-01-02"), "day"
|
||||
}
|
||||
switch view {
|
||||
case "inbox", "backlog", "someday", "review", "done", "archived", "carryover", "day":
|
||||
case "inbox", "backlog", "someday", "review", "done", "archived", "carryover", "day", "index":
|
||||
case "tomorrow":
|
||||
selectedDate = time.Now().In(s.getLocation(domain)).AddDate(0, 0, 1).Format("2006-01-02")
|
||||
view = "day"
|
||||
@@ -315,7 +315,7 @@ func (s *Server) handleTasksAPI(w http.ResponseWriter, r *http.Request) {
|
||||
selected = q.Get("date")
|
||||
}
|
||||
hierarchy := q.Get("hierarchy") == "1"
|
||||
items, next, err := s.store.ListTasks(ctx, domain, actor, store.TaskQuery{Kind: kind, View: view, Project: q.Get("project"), Parent: q.Get("parent"), Search: q.Get("q"), Today: selected, Before: q.Get("before"), Limit: limit, Hierarchy: hierarchy})
|
||||
items, next, err := s.store.ListTasks(ctx, domain, actor, store.TaskQuery{Kind: kind, View: view, Project: q.Get("project"), Parent: q.Get("parent"), Search: q.Get("q"), Today: selected, Before: q.Get("before"), Limit: limit, Hierarchy: hierarchy, Filter: q.Get("filter"), Sort: q.Get("sort"), Order: q.Get("order")})
|
||||
if err != nil {
|
||||
taskError(w, err)
|
||||
return
|
||||
|
||||
+23
-1
@@ -8,7 +8,8 @@ window.addEventListener('load',async()=>{const wait=async(fn)=>{for(let i=0;i<12
|
||||
const prefs=await fetch(api+'preferences').then(r=>r.json());const saved=await fetch(api+'preferences',{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify({...prefs.preferences,notify_due:true,notify_planned:true,reminder_time:'10:35'})});if(!saved.ok)throw Error('Preferences save failed');
|
||||
document.querySelector('#tasks-new').click();await wait(()=>input('page_path'));
|
||||
if(input('notify_due').checked||input('notify_planned').checked)throw Error('Undated task enabled reminders');
|
||||
fill(input('title'),'タスク編集のレイアウト確認');fill(input('notes'),'主要項目を左右に整理。日付と通知をまとめて設定します。');
|
||||
fill(input('title'),'**タスク編集のレイアウト確認**');fill(input('notes'),'主要項目を左右に整理。日付と通知をまとめて設定します。');
|
||||
fill(input('references'),'https://example.test/doc\n/files/資料.pdf');
|
||||
fill(input('planned_on'),'2030-01-01');fill(input('due_on'),'2030-01-02');
|
||||
if(!input('notify_due').checked||!input('notify_planned').checked||input('reminder_time').value!=='10:35')throw Error('Dated defaults missing');
|
||||
input('notify_due').click();fill(input('due_on'),'2030-01-03');if(input('notify_due').checked)throw Error('Explicit reminder choice overwritten');
|
||||
@@ -18,6 +19,9 @@ window.addEventListener('load',async()=>{const wait=async(fn)=>{for(let i=0;i<12
|
||||
if(task.status!=='doing'||task.bucket!=='backlog'||task.complexity!==4||!task.notify_planned||task.notify_due||task.reminder_time!=='10:35')throw Error('Editor fields not persisted');
|
||||
await wait(()=>document.querySelector('[data-task-id="'+task.uuid+'"] [data-action=detail]'));document.querySelector('[data-task-id="'+task.uuid+'"] [data-action=detail]').click();await wait(()=>input('page_path'));
|
||||
if(input('notify_due').checked)throw Error('Defaults changed existing task');
|
||||
if(task.references?.length!==2||input('references').value!=='https://example.test/doc\n/files/資料.pdf')throw Error('Task references lost');
|
||||
const preview=document.querySelector('.task-title-preview');if(!preview?.querySelector('strong')||getComputedStyle(preview).display==='none'||preview.getBoundingClientRect().height<10)throw Error('Markdown title preview missing');
|
||||
const safe=document.createElement('div');PagesTaskPresentation.render(safe,'<img src=x onerror=alert(1)> [bad](javascript:alert) **safe**');if(safe.querySelector('img,a')||!safe.querySelector('strong'))throw Error('Unsafe task Markdown');
|
||||
if(form.querySelector('.task-editor-advanced').open)throw Error('Advanced section should start collapsed');
|
||||
const fields=document.querySelector('#tasks-fields'),rect=dialog.getBoundingClientRect();
|
||||
if(rect.width>innerWidth+1||rect.height>innerHeight+1||fields.scrollWidth>fields.clientWidth+1)throw Error('Editor overflow');
|
||||
@@ -46,6 +50,24 @@ window.addEventListener('load',async()=>{const wait=async(fn)=>{for(let i=0;i<12
|
||||
document.querySelector('#dashboard-controls button[aria-pressed]').click();const width=document.querySelector('[data-widget=tasks] [data-size=width]');width.value='6';width.dispatchEvent(new Event('change'));const height=document.querySelector('[data-widget=tasks] [data-size=height]');height.value='5';height.dispatchEvent(new Event('change'));
|
||||
document.querySelector('[data-widget=tasks] .widget-arrange button').click();document.querySelector('#dashboard-controls button:last-child').click();await wait(()=>document.querySelector('#dashboard-status').textContent.includes('保存しました'));const layout=await fetch('/_/api/v1/extension/organizer.tasks/dashboard').then(r=>r.json());if(layout.widgets[2].id!=='tasks'||layout.widgets[2].width!==6||layout.widgets[2].height!==5||layout.widgets[2].tab!=='done')throw Error('Layout did not persist');
|
||||
if(!document.querySelector('.organizer-nav a[href="/v/plan/contacts"]')||!document.querySelector('.organizer-nav a[aria-current="page"]'))throw Error('Shared navigation missing');
|
||||
const add=document.querySelector('#dashboard-controls select');
|
||||
for(const id of ['commands','tomorrow-schedule']){add.value=id;add.dispatchEvent(new Event('change'));}
|
||||
await wait(()=>document.querySelector('.dashboard-command'));
|
||||
const command=document.querySelector('.dashboard-command'),commandInput=command.querySelector('input'),api='/_/api/v1/extension/organizer.tasks/';
|
||||
const run=async text=>{fill(commandInput,text);command.requestSubmit();await wait(()=>!command.querySelector('button').disabled);if(commandInput.value)throw Error('Command failed: '+command.parentElement.textContent);};
|
||||
await run('add task **Command fixture**');
|
||||
let items=await fetch(api+'items?q=Command%20fixture').then(r=>r.json());const id=items.items[0].uuid;
|
||||
fill(commandInput,'today Command');await wait(()=>document.querySelector('#dashboard-command-tasks option'));if(!document.querySelector('#dashboard-command-tasks option').value.includes(id))throw Error('Command task suggestions missing');
|
||||
await run('today '+id);let item=await fetch(api+'items/'+id).then(r=>r.json());if(item.item.planned_on!==document.querySelector('#organizer-dashboard').dataset.today)throw Error('Today command failed');
|
||||
await run('tomorrow '+id);await run('due '+id+' 2030-12-31');item=await fetch(api+'items/'+id).then(r=>r.json());if(item.item.due_on!=='2030-12-31')throw Error('Due command failed');
|
||||
await wait(()=>document.querySelector('[data-widget=tomorrow] strong'));
|
||||
window.confirm=()=>false;fill(commandInput,'delete '+id);command.requestSubmit();await wait(()=>!command.querySelector('button').disabled);if(!(await fetch(api+'items/'+id)).ok)throw Error('Unconfirmed deletion');
|
||||
window.confirm=()=>true;await run('delete '+id);if((await fetch(api+'items/'+id)).status!==404)throw Error('Deletion failed');
|
||||
const date=new Date(document.querySelector('#organizer-dashboard').dataset.today+'T12:00:00Z');date.setUTCDate(date.getUTCDate()+1);const day=date.toISOString().slice(0,10),calAPI='/_/api/v1/extension/organizer.calendar/';
|
||||
const calendars=await fetch(calAPI+'calendars').then(r=>r.json());const calendar=(calendars.calendars||calendars.items)[0];
|
||||
const response=await fetch(calAPI+'calendars/'+calendar.id+'/events',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({summary:'Tomorrow visual fixture',start:day+'T03:00:00Z',end:day+'T04:00:00Z'})});if(!response.ok)throw Error('Event fixture failed');
|
||||
document.querySelector('#dashboard-controls button').click();await wait(()=>document.querySelector('[data-widget=tomorrow-schedule] .agenda-event'));
|
||||
if(!document.querySelector('[data-widget=tomorrow-schedule]').textContent.includes('Tomorrow visual fixture'))throw Error('Tomorrow schedule missing');
|
||||
}else if(path==='/v/plan/tasks'){
|
||||
const prefs=await fetch('/_/api/v1/extension/organizer.tasks/preferences').then(r=>r.json());await fetch('/_/api/v1/extension/organizer.tasks/preferences',{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify({...prefs.preferences,due_days:2,estimate_minutes:60})});
|
||||
await wait(()=>document.querySelector('#tasks-quick-title'));fill(document.querySelector('#tasks-quick-title'),'Recording task');document.querySelector('#tasks-capture').requestSubmit();await wait(()=>document.querySelector('[data-action=work]'));document.querySelector('[data-action=work]').click();await wait(()=>document.querySelector('.task-work-bar a').textContent.includes('Recording task'));document.querySelector('.task-work-bar button').click();await wait(()=>document.querySelector('.task-work-bar').hidden);
|
||||
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
window.addEventListener('load',async()=>{
|
||||
const wait=async fn=>{for(let n=0;n<120;n++){if(fn())return;await new Promise(r=>setTimeout(r,50));}throw Error('Timed out: '+fn);};
|
||||
const assert=(ok,msg)=>{if(!ok)throw Error(msg);},key=(k,ctrl=false)=>document.activeElement.dispatchEvent(new KeyboardEvent('keydown',{key:k,ctrlKey:ctrl,bubbles:true,cancelable:true}));
|
||||
const rows=()=>[...document.querySelectorAll('.task-index-grid tbody tr')],selected=()=>document.querySelector('.task-index-grid tr[aria-selected=true]'),api='/_/api/v1/extension/organizer.tasks/';
|
||||
try{
|
||||
const grid=document.querySelector('.task-index-grid'),form=document.querySelector('.task-index-filter'),filter=form.querySelector('input'),sort=form.querySelector('select');
|
||||
const ready=()=>grid.getAttribute('aria-busy')!=='true';
|
||||
await wait(()=>ready()&&rows().length===3&&document.querySelectorAll('.task-index-projects button').length===4);
|
||||
grid.focus();key('o');assert(document.activeElement===sort,'o did not focus sort');sort.value='title';sort.dispatchEvent(new Event('change'));await wait(ready);key('Escape');
|
||||
rows()[0].click();const first=selected().dataset.task;key('j');assert(selected().dataset.task!==first,'j failed');key('k');assert(selected().dataset.task===first,'k failed');assert(rows()[0].querySelector('strong'),'Markdown subject lost');
|
||||
key('l');assert(document.activeElement===filter,'l did not focus limit');filter.value='~s Beta ~doing';form.requestSubmit();await wait(()=>ready()&&rows().length===1);const beta=selected().dataset.task;
|
||||
filter.focus();key('d');let item=await fetch(api+'items/'+beta).then(r=>r.json());assert(item.item.status==='doing','Shortcut fired while typing');
|
||||
const changed=await fetch(api+'items/'+beta,{method:'PUT',headers:{'Content-Type':'application/json','If-Match':'"'+item.item.version+'"'},body:JSON.stringify({...item.item,notes:'Changed in another client'})});assert(changed.ok,'Concurrent update fixture failed');
|
||||
key('Escape');key('d');await wait(()=>document.querySelector('#tasks-status').textContent.includes('別の画面で更新'));
|
||||
item=await fetch(api+'items/'+beta).then(r=>r.json());assert(item.item.status==='doing'&&item.item.notes==='Changed in another client','Stale completion overwrote another client');
|
||||
form.requestSubmit();await wait(ready);key('d');await wait(()=>ready()&&rows().length===0);item=await fetch(api+'items/'+beta).then(r=>r.json());assert(item.item.status==='done'&&item.item.notes==='Changed in another client','d did not preserve full task data');
|
||||
filter.value='~unknown';form.requestSubmit();await wait(()=>ready()&&document.querySelector('#tasks-status').textContent.includes('不正'));assert(form.querySelector('input').value==='~unknown','Invalid filter lost');
|
||||
filter.value='~active';form.requestSubmit();await wait(()=>ready()&&rows().length===2);grid.focus();key('j',true);await wait(()=>ready()&&rows().length===1);assert(document.querySelector('.task-index-projects [aria-current=true]').dataset.project==='none','Ctrl+j did not switch project');
|
||||
key('k',true);await wait(()=>ready()&&rows().length===2);key('O');await wait(ready);assert(rows()[0].textContent.includes('Gamma'),'Reverse sort failed');
|
||||
grid.focus();key('?');const help=document.querySelector('.task-index-help');assert(help.open,'Help missing');const previous=selected().dataset.task;key('j');assert(selected().dataset.task===previous,'Shortcut fired through modal');help.querySelector('button').click();
|
||||
key('m');await wait(()=>document.querySelector('#tasks-dialog').open&&document.querySelector('#tasks-form [name=page_path]'));key('j');assert(selected().dataset.task===previous,'Shortcut fired through editor');document.querySelector('#tasks-close').click();
|
||||
const projectButton=[...document.querySelectorAll('.task-index-projects button')].find(b=>b.dataset.project&&b.dataset.project!=='none');projectButton.click();await wait(ready);const project=projectButton.dataset.project;grid.focus();key('c');
|
||||
await wait(()=>document.querySelector('#tasks-dialog').open&&document.querySelector('#tasks-form [name=project_uuid]')?.value===project);const title=document.querySelector('#tasks-form [name=title]');title.value='Created from index';title.dispatchEvent(new Event('input',{bubbles:true}));document.querySelector('#tasks-form').requestSubmit();await wait(()=>!document.querySelector('#tasks-dialog').open&&ready()&&rows().some(row=>row.textContent.includes('Created from index')));
|
||||
rows().find(row=>row.textContent.includes('Created from index')).click();const created=selected().dataset.task;key('w');await wait(()=>document.querySelector('#tasks-status').textContent.includes('関連Wikiページはありません'));
|
||||
key('s');await wait(()=>document.querySelector('#tasks-focus').dataset.state==='running');const session=await fetch(api+'focus').then(r=>r.json());assert(session.item.task_uuid===created,'Pomodoro attached to wrong task');
|
||||
assert(document.documentElement.scrollWidth<=innerWidth+2,'Page overflow');assert(!document.querySelector('#tasks-list input'),'Index must not be an inline form');
|
||||
document.body.dataset.vimReady='true';
|
||||
}catch(e){const p=document.createElement('pre');p.id='error';p.textContent=e.stack;document.body.append(p);}
|
||||
});
|
||||
@@ -44,6 +44,15 @@ try {
|
||||
if (state.ready) { ready = true; break; }
|
||||
await delay(200);
|
||||
}
|
||||
if(ready && process.env.PAGESWIKI_TASK_INDEX_BROWSER==='1'){
|
||||
const evaluate=async expression=>{const r=await call('Runtime.evaluate',{expression,returnByValue:true,awaitPromise:true});if(r.exceptionDetails)throw Error(JSON.stringify(r.exceptionDetails));return r.result.value;};
|
||||
const key=async(key,modifiers=0)=>{await call('Input.dispatchKeyEvent',{type:'keyDown',key,code:'Key'+key.toUpperCase(),modifiers});await call('Input.dispatchKeyEvent',{type:'keyUp',key,code:'Key'+key.toUpperCase(),modifiers});};
|
||||
await evaluate(`document.querySelector('.task-index-projects button').click();new Promise((resolve,reject)=>{let n=0;const id=setInterval(()=>{if(document.querySelector('.task-index-grid').getAttribute('aria-busy')!=='true'){clearInterval(id);document.querySelector('.task-index-grid tbody tr').click();resolve();}else if(++n>100){clearInterval(id);reject(Error('index loading'));}},30);})`);
|
||||
const selected=()=>evaluate(`document.querySelector('.task-index-grid tr[aria-selected=true]').dataset.task`);
|
||||
const before=await selected();await key('j');if(await selected()===before)throw Error('Native j did not move');await key('k');if(await selected()!==before)throw Error('Native k did not move');
|
||||
await key('j',2);if(await evaluate(`document.querySelector('.task-index-projects [aria-current=true]').dataset.project`)!=='none')throw Error('Native Ctrl+j did not switch project');await key('k',2);
|
||||
await evaluate(`new Promise(resolve=>{const id=setInterval(()=>{if(document.querySelector('.task-index-grid').getAttribute('aria-busy')!=='true'){clearInterval(id);resolve();}},30)})`);
|
||||
}
|
||||
if(ready && process.env.PAGESWIKI_DASHBOARD_DRAG==='1'){
|
||||
const evaluate=async expression=>{const r=await call('Runtime.evaluate',{expression,returnByValue:true,awaitPromise:true});if(r.exceptionDetails)throw Error(JSON.stringify(r.exceptionDetails));return r.result.value;};
|
||||
const rect=async selector=>evaluate(`(()=>{const n=document.querySelector(${JSON.stringify(selector)});n.scrollIntoView({block:'center',behavior:'instant'});const r=n.getBoundingClientRect();return {x:r.x+r.width/2,y:r.y+r.height/2};})()`);
|
||||
|
||||
@@ -3,6 +3,11 @@ package store
|
||||
import "database/sql"
|
||||
|
||||
func (s *Store) EnsureConfigTable() error {
|
||||
if _, err := s.DB.Exec(`CREATE TABLE IF NOT EXISTS personal_appearance (
|
||||
domain_uuid TEXT NOT NULL, owner_uuid TEXT NOT NULL, version INTEGER NOT NULL,
|
||||
data TEXT NOT NULL, PRIMARY KEY(domain_uuid,owner_uuid))`); err != nil {
|
||||
return err
|
||||
}
|
||||
domain, err := s.GetDefaultDomain()
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -21,13 +21,13 @@ func DefaultDashboard() []DashboardWidget {
|
||||
}
|
||||
|
||||
func ValidateDashboard(items []DashboardWidget) error {
|
||||
if len(items) > 7 {
|
||||
if len(items) > 9 {
|
||||
return ErrTaskInvalid
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, item := range items {
|
||||
switch item.ID {
|
||||
case "progress", "today", "tomorrow", "tasks", "schedule", "activity", "feeds":
|
||||
case "progress", "today", "tomorrow", "tasks", "schedule", "tomorrow-schedule", "commands", "activity", "feeds":
|
||||
default:
|
||||
return ErrTaskInvalid
|
||||
}
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
// A small AND-only query language. Values are always bound parameters; neither
|
||||
// filter text nor sort names can become SQL identifiers or expressions.
|
||||
func taskIndexFilter(source, today string) (string, []any, error) {
|
||||
if len(source) > 1000 {
|
||||
return "", nil, ErrTaskInvalid
|
||||
}
|
||||
tokens, err := taskFilterTokens(source)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
parts := []string{}
|
||||
args := []any{}
|
||||
archived := false
|
||||
for i := 0; i < len(tokens); i++ {
|
||||
token := tokens[i]
|
||||
neg := strings.HasPrefix(token, "!")
|
||||
if neg {
|
||||
token = strings.TrimPrefix(token, "!")
|
||||
}
|
||||
clause := ""
|
||||
value := func() (string, error) {
|
||||
i++
|
||||
if i >= len(tokens) || tokens[i] == "" {
|
||||
return "", ErrTaskInvalid
|
||||
}
|
||||
return tokens[i], nil
|
||||
}
|
||||
switch token {
|
||||
case "~active":
|
||||
clause = `status NOT IN ('done','cancelled')`
|
||||
case "~todo", "~doing", "~done", "~cancelled":
|
||||
clause = `status=?`
|
||||
args = append(args, strings.TrimPrefix(token, "~"))
|
||||
case "~overdue":
|
||||
clause = `due_on!='' AND due_on<? AND status NOT IN ('done','cancelled')`
|
||||
args = append(args, today)
|
||||
case "~wiki":
|
||||
clause = `COALESCE(json_extract(data,'$.page_uuid'),'')!=''`
|
||||
case "~attachment":
|
||||
clause = `COALESCE(json_array_length(data,'$.references'),0)>0`
|
||||
case "~archived":
|
||||
clause = `archived=1`
|
||||
if !neg {
|
||||
archived = true
|
||||
}
|
||||
case "~s":
|
||||
v, e := value()
|
||||
if e != nil {
|
||||
return "", nil, e
|
||||
}
|
||||
clause = `instr(lower(title),lower(?))>0`
|
||||
args = append(args, v)
|
||||
case "~bucket":
|
||||
v, e := value()
|
||||
if e != nil || (v != "inbox" && v != "backlog" && v != "someday") {
|
||||
return "", nil, ErrTaskInvalid
|
||||
}
|
||||
clause = `bucket=?`
|
||||
args = append(args, v)
|
||||
case "~priority":
|
||||
v, e := value()
|
||||
n, e2 := strconv.Atoi(v)
|
||||
if e != nil || e2 != nil || n < 0 || n > 3 {
|
||||
return "", nil, ErrTaskInvalid
|
||||
}
|
||||
clause = `COALESCE(json_extract(data,'$.priority'),0)=?`
|
||||
args = append(args, n)
|
||||
case "~due", "~planned", "~start", "~review":
|
||||
v, e := value()
|
||||
if e != nil {
|
||||
return "", nil, e
|
||||
}
|
||||
op := "="
|
||||
for _, prefix := range []string{"<=", ">=", "<", ">", "="} {
|
||||
if strings.HasPrefix(v, prefix) {
|
||||
op = prefix
|
||||
v = strings.TrimPrefix(v, prefix)
|
||||
break
|
||||
}
|
||||
}
|
||||
column := map[string]string{"~due": "due_on", "~planned": "planned_on", "~start": "COALESCE(json_extract(data,'$.start_on'),'')", "~review": "review_on"}[token]
|
||||
if v == "none" {
|
||||
if op != "=" {
|
||||
return "", nil, ErrTaskInvalid
|
||||
}
|
||||
clause = column + "=''"
|
||||
break
|
||||
}
|
||||
if v == "today" {
|
||||
v = today
|
||||
}
|
||||
if v == "tomorrow" {
|
||||
day, _ := time.Parse("2006-01-02", today)
|
||||
v = day.AddDate(0, 0, 1).Format("2006-01-02")
|
||||
}
|
||||
if v == "" || !validTaskDate(v) {
|
||||
return "", nil, ErrTaskInvalid
|
||||
}
|
||||
clause = column + "!='' AND " + column + op + "?"
|
||||
args = append(args, v)
|
||||
default:
|
||||
if strings.HasPrefix(token, "~") || token == "" {
|
||||
return "", nil, ErrTaskInvalid
|
||||
}
|
||||
clause = `instr(lower(title),lower(?))>0`
|
||||
args = append(args, token)
|
||||
}
|
||||
if neg {
|
||||
clause = "NOT (" + clause + ")"
|
||||
}
|
||||
parts = append(parts, "("+clause+")")
|
||||
}
|
||||
if !archived {
|
||||
parts = append(parts, "archived=0")
|
||||
}
|
||||
return strings.Join(parts, " AND "), args, nil
|
||||
}
|
||||
|
||||
func taskFilterTokens(source string) ([]string, error) {
|
||||
var tokens []string
|
||||
var word strings.Builder
|
||||
var quote rune
|
||||
escaped, started := false, false
|
||||
for _, r := range source {
|
||||
if unicode.IsControl(r) && !unicode.IsSpace(r) {
|
||||
return nil, ErrTaskInvalid
|
||||
}
|
||||
if escaped {
|
||||
word.WriteRune(r)
|
||||
escaped = false
|
||||
started = true
|
||||
continue
|
||||
}
|
||||
if r == '\\' {
|
||||
escaped = true
|
||||
started = true
|
||||
continue
|
||||
}
|
||||
if quote != 0 {
|
||||
if r == quote {
|
||||
quote = 0
|
||||
} else {
|
||||
word.WriteRune(r)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if r == '\'' || r == '"' {
|
||||
quote = r
|
||||
started = true
|
||||
continue
|
||||
}
|
||||
if unicode.IsSpace(r) {
|
||||
if started {
|
||||
tokens = append(tokens, word.String())
|
||||
word.Reset()
|
||||
started = false
|
||||
}
|
||||
continue
|
||||
}
|
||||
word.WriteRune(r)
|
||||
started = true
|
||||
}
|
||||
if quote != 0 || escaped {
|
||||
return nil, ErrTaskInvalid
|
||||
}
|
||||
if started {
|
||||
tokens = append(tokens, word.String())
|
||||
}
|
||||
if len(tokens) > 64 {
|
||||
return nil, ErrTaskInvalid
|
||||
}
|
||||
return tokens, nil
|
||||
}
|
||||
|
||||
func taskIndexOrder(key string) string {
|
||||
return map[string]string{"": "COALESCE(NULLIF(due_on,''),'9999-99-99')", "due": "COALESCE(NULLIF(due_on,''),'9999-99-99')", "planned": "COALESCE(NULLIF(planned_on,''),'9999-99-99')", "title": "lower(title)", "status": "status", "priority": "COALESCE(json_extract(data,'$.priority'),0)", "created": "created_at_ms", "updated": "updated_at_ms"}[key]
|
||||
}
|
||||
+61
-5
@@ -5,6 +5,7 @@ import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
@@ -24,6 +25,7 @@ type TaskRecord struct {
|
||||
Kind string `json:"kind"`
|
||||
Title string `json:"title"`
|
||||
Notes string `json:"notes"`
|
||||
References []string `json:"references,omitempty"`
|
||||
NotesSubpath string `json:"notes_subpath,omitempty"`
|
||||
ProjectUUID string `json:"project_uuid"`
|
||||
ParentUUID string `json:"parent_uuid,omitempty"`
|
||||
@@ -51,6 +53,7 @@ type TaskRecord struct {
|
||||
}
|
||||
|
||||
type TaskQuery struct {
|
||||
Filter, Sort, Order string
|
||||
Kind, View, Project, Search, Today, Before string
|
||||
Parent string
|
||||
Hierarchy bool
|
||||
@@ -117,6 +120,22 @@ func validTaskDate(v string) bool {
|
||||
}
|
||||
|
||||
func validateTask(item *TaskRecord) error {
|
||||
if len(item.References) > 20 {
|
||||
return ErrTaskInvalid
|
||||
}
|
||||
for _, ref := range item.References {
|
||||
u, err := url.Parse(ref)
|
||||
if err != nil || len(ref) > 4096 || strings.ContainsAny(ref, "\\\r\n\x00\t ") || u.User != nil || !utf8.ValidString(ref) {
|
||||
return ErrTaskInvalid
|
||||
}
|
||||
if u.Scheme == "http" || u.Scheme == "https" {
|
||||
if u.Hostname() == "" {
|
||||
return ErrTaskInvalid
|
||||
}
|
||||
} else if u.Scheme != "" || u.Host != "" || !strings.HasPrefix(ref, "/") || strings.HasPrefix(ref, "//") {
|
||||
return ErrTaskInvalid
|
||||
}
|
||||
}
|
||||
if item.Complexity < 0 || item.Complexity > 5 {
|
||||
return ErrTaskInvalid
|
||||
}
|
||||
@@ -262,6 +281,11 @@ func (s *Store) saveTask(ctx context.Context, domain, actor string, item TaskRec
|
||||
if err = json.Unmarshal([]byte(oldJSON), &old); err != nil {
|
||||
return TaskRecord{}, err
|
||||
}
|
||||
// Older CLI/DAV clients omit this optional field. An explicit [] clears
|
||||
// references; omission must not erase attachments during unrelated edits.
|
||||
if expected > 0 && item.References == nil {
|
||||
item.References = old.References
|
||||
}
|
||||
if expected == 0 { // Safe retry of a create with the same client-generated UUID.
|
||||
candidate := item
|
||||
candidate.Version, candidate.CreatedMS, candidate.UpdatedMS, candidate.CompletedMS = old.Version, old.CreatedMS, old.UpdatedMS, old.CompletedMS
|
||||
@@ -408,6 +432,13 @@ func (s *Store) ListTasks(ctx context.Context, domain, actor string, query TaskQ
|
||||
if query.Limit < 1 || query.Limit > 100 {
|
||||
query.Limit = 60
|
||||
}
|
||||
index := query.View == "index"
|
||||
if index && (query.Kind != "task" || query.Hierarchy || taskIndexOrder(query.Sort) == "" || (query.Order != "" && query.Order != "asc" && query.Order != "desc")) {
|
||||
return nil, "", ErrTaskInvalid
|
||||
}
|
||||
if !index && (query.Filter != "" || query.Sort != "" || query.Order != "") {
|
||||
return nil, "", ErrTaskInvalid
|
||||
}
|
||||
q := `SELECT data FROM organizer_items WHERE domain_uuid=? AND owner_uuid=? AND kind=?`
|
||||
args := []any{domain, actor, query.Kind}
|
||||
hierarchy := query.Hierarchy && query.Kind == "task" && query.View != "family"
|
||||
@@ -420,7 +451,14 @@ func (s *Store) ListTasks(ctx context.Context, domain, actor string, query TaskQ
|
||||
WHERE i.domain_uuid=? AND i.owner_uuid=?
|
||||
) SELECT data FROM task_rows WHERE kind=?`
|
||||
}
|
||||
if query.View == "family" {
|
||||
if index {
|
||||
filter, values, err := taskIndexFilter(query.Filter, query.Today)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
q += " AND " + filter
|
||||
args = append(args, values...)
|
||||
} else if query.View == "family" {
|
||||
if query.Parent == "" || query.Kind != "task" {
|
||||
return nil, "", ErrTaskInvalid
|
||||
}
|
||||
@@ -438,7 +476,11 @@ func (s *Store) ListTasks(ctx context.Context, domain, actor string, query TaskQ
|
||||
}
|
||||
if query.Project != "" {
|
||||
q += ` AND project_uuid=?`
|
||||
args = append(args, query.Project)
|
||||
project := query.Project
|
||||
if index && project == "none" {
|
||||
project = ""
|
||||
}
|
||||
args = append(args, project)
|
||||
}
|
||||
if query.Kind == "task" {
|
||||
switch query.View {
|
||||
@@ -462,7 +504,7 @@ func (s *Store) ListTasks(ctx context.Context, domain, actor string, query TaskQ
|
||||
case "all":
|
||||
q += ` AND status NOT IN ('done','cancelled')`
|
||||
case "archived":
|
||||
case "family":
|
||||
case "family", "index":
|
||||
default:
|
||||
return nil, "", ErrTaskInvalid
|
||||
}
|
||||
@@ -472,7 +514,15 @@ func (s *Store) ListTasks(ctx context.Context, domain, actor string, query TaskQ
|
||||
args = append(args, query.Search)
|
||||
}
|
||||
if query.Before != "" {
|
||||
if hierarchy {
|
||||
if index {
|
||||
comparison := ">"
|
||||
if query.Order == "desc" {
|
||||
comparison = "<"
|
||||
}
|
||||
key := taskIndexOrder(query.Sort)
|
||||
q += " AND (" + key + ",uuid)" + comparison + "(SELECT " + key + ",uuid FROM organizer_items WHERE domain_uuid=? AND owner_uuid=? AND kind='task' AND uuid=?)"
|
||||
args = append(args, domain, actor, query.Before)
|
||||
} else if hierarchy {
|
||||
// A separate indexed cursor lookup keeps the wide task_rows CTE
|
||||
// single-use, avoiding materialization of every private JSON body.
|
||||
var familyCreated, created int64
|
||||
@@ -494,7 +544,13 @@ func (s *Store) ListTasks(ctx context.Context, domain, actor string, query TaskQ
|
||||
args = append(args, domain, actor, query.Before)
|
||||
}
|
||||
}
|
||||
if hierarchy {
|
||||
if index {
|
||||
direction := "ASC"
|
||||
if query.Order == "desc" {
|
||||
direction = "DESC"
|
||||
}
|
||||
q += " ORDER BY " + taskIndexOrder(query.Sort) + " " + direction + ",uuid " + direction + " LIMIT ?"
|
||||
} else if hierarchy {
|
||||
q += ` ORDER BY family_created DESC,family_uuid DESC,family_head DESC,created_at_ms DESC,uuid DESC LIMIT ?`
|
||||
} else {
|
||||
q += ` ORDER BY created_at_ms DESC,uuid DESC LIMIT ?`
|
||||
|
||||
Reference in new issue
Block a user