Unify organizer navigation and add personal widget dashboard
Build and publish container images / images (push) Successful in 12m38s
Release container images / release (push) Successful in 23s

This commit is contained in:
Anya Tokugawa committed 2026-11-04 00:05:16 +09:00
1 parent a9249009f0
commit 6ba30bc9f4
44 files changed
+843 -54

No files matched your search

+3
View File
@@ -60,6 +60,9 @@ func (s *Server) handleCalendarUpcoming(w http.ResponseWriter, r *http.Request,
start = day
}
end := start.AddDate(0, 0, 31)
if r.URL.Query().Get("period") == "day" {
end = start.AddDate(0, 0, 1)
}
for _, c := range cs {
if !selected[c.ID] {
continue
+11
View File
@@ -61,6 +61,17 @@ func TestCalendarUpcomingDefaultsAndBounds(t *testing.T) {
if !strings.Contains(w.Header().Get("Cache-Control"), "no-store") {
t.Fatal("private response cached")
}
w = calendarRequest(s, token, "GET", calendarAPI+"upcoming?period=day", "", "")
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &result) != nil {
t.Fatal(w.Code, w.Body)
}
now := time.Now().In(s.getLocation(domain))
end := time.Date(now.Year(), now.Month(), now.Day()+1, 0, 0, 0, 0, s.getLocation(domain))
for _, event := range result.Events {
if !event.Start.Before(end) {
t.Fatal("tomorrow event in today's widget", event.Start)
}
}
if w = calendarRequest(s, "", "GET", calendarAPI+"upcoming", "", ""); w.Code != 403 {
t.Fatal("anonymous access", w.Code)
}
+4
View File
@@ -98,6 +98,10 @@ func (s *Server) handleConfig(
w http.ResponseWriter,
r *http.Request,
) {
if personalOrganizerSettings(r) {
s.handleOrganizerSettings(w, r)
return
}
domainUUID := s.domainUUIDForRequest(r)
principal := s.requestPrincipal(r)
currentDomain := s.domainForRequest(r)
+1
View File
@@ -22,5 +22,6 @@ func configPanelGroups(locale string, plugins []adapterPlugin) []configPanelGrou
groups[4].Panels = append(groups[4].Panels, configPanelLink{"adapter-" + plugin.ID, plugin.Name})
}
groups = append(groups, configPanelGroup{"extensions", translate(locale, "extension.title"), []configPanelLink{link("extensions", "extension.catalog"), link("diary", "periodical.diary"), link("blog", "periodical.blog")}})
groups = append(groups, configPanelGroup{"organizer", translate(locale, "organizer.title"), []configPanelLink{link("organizer", "organizer.settings")}})
return groups
}
+3
View File
@@ -100,6 +100,9 @@ var mutationPrefixPolicies = []struct {
}
func policyForRequest(r *http.Request) endpointPolicy {
if personalOrganizerSettings(r) {
return endpointPolicy{Name: "organizer.settings", Capability: "read", Target: targetDomain, Resolver: resolveHandler}
}
if taskRoute(r.URL.Path) {
return endpointPolicy{Name: "tasks.handler", Capability: "read", Target: targetDomain, Resolver: resolveHandler}
}
+119
View File
@@ -0,0 +1,119 @@
package server
import (
"net/http"
"strings"
"time"
"pageswiki/internal/store"
)
func personalOrganizerSettings(r *http.Request) bool {
return r.URL.Path == "/-/sys/config" && r.URL.Query().Get("panel") == "organizer" && (r.Method == "GET" || r.Method == "HEAD")
}
func (s *Server) handleOrganizerDashboard(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" && r.Method != "HEAD" {
w.Header().Set("Allow", "GET, HEAD")
w.WriteHeader(405)
return
}
_, active, ok := s.taskReady(w, r)
if !ok {
return
}
domain := s.domainUUIDForRequest(r)
s.renderWithContext(w, r, "organizer_dashboard.gohtml", map[string]any{"TaskWritable": active, "Today": time.Now().In(s.getLocation(domain)).Format("2006-01-02"), "Timezone": s.getTimezoneName(domain)})
}
func (s *Server) handleOrganizerSettings(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "private, no-store")
actor, active := s.calendarActor(r)
if actor == "" {
s.authRequired(w, r)
return
}
s.renderWithContext(w, r, "organizer_settings.gohtml", map[string]any{"TaskWritable": active})
}
func (s *Server) handleDashboardData(w http.ResponseWriter, r *http.Request, actor string, active bool, kind string) {
domain := s.domainUUIDForRequest(r)
if kind == "progress" {
if r.Method != "GET" {
w.Header().Set("Allow", "GET")
w.WriteHeader(405)
return
}
p, err := s.store.DashboardProgress(r.Context(), domain, actor, time.Now().In(s.getLocation(domain)).Format("2006-01-02"))
if err != nil {
taskError(w, err)
return
}
writeEventJSON(w, 200, p)
return
}
if r.Method != "GET" && r.Method != "PUT" {
w.Header().Set("Allow", "GET, PUT")
w.WriteHeader(405)
return
}
p, err := s.store.Dashboard(r.Context(), domain, actor)
if err != nil {
taskError(w, err)
return
}
if r.Method == "PUT" {
if !active {
taskError(w, store.ErrAccessDenied)
return
}
var input struct {
Version int64 `json:"version"`
Widgets []store.DashboardWidget `json:"widgets"`
}
if !taskJSON(w, r, &input) {
return
}
if input.Version != p.Version {
taskError(w, store.ErrTaskConflict)
return
}
// An empty dashboard is valid; nil means the initial default layout.
if input.Widgets == nil {
input.Widgets = []store.DashboardWidget{}
}
p, err = s.store.SaveDashboard(r.Context(), domain, actor, input.Version, input.Widgets)
if err != nil {
taskError(w, err)
return
}
}
writeEventJSON(w, 200, p)
}
func organizerSection(path string) string {
switch {
case path == "/v/plan/dashboard":
return "dashboard"
case strings.HasPrefix(path, "/-/sys/config"):
return "settings"
case path == "/v/plan/contacts":
return "contacts"
case taskRoute(path):
return "tasks"
case calendarRoute(path):
return "calendar"
}
return ""
}
func init() {
for lang, entries := range map[string]map[string]string{
"en": {"organizer.title": "Organizer", "organizer.dashboard": "Dashboard", "organizer.settings": "Personal settings", "organizer.contacts": "Contacts", "organizer.private": "Preferences apply only to you in this Domain. System administration is separate.", "organizer.calendar_defaults": "Default calendars", "organizer.open": "Open"},
"ja": {"organizer.title": "オーガナイザー", "organizer.dashboard": "ダッシュボード", "organizer.settings": "個人設定", "organizer.contacts": "連絡先", "organizer.private": "このドメイン内の自分だけに適用する設定です。システムの管理設定とは別です。", "organizer.calendar_defaults": "既定のカレンダー", "organizer.open": "開く"},
} {
for k, v := range entries {
translations[lang][k] = v
}
}
}
+176
View File
@@ -0,0 +1,176 @@
package server
import (
"context"
"encoding/json"
"net/url"
"pageswiki/internal/store"
"strings"
"testing"
"time"
)
func TestOrganizerDashboardLayoutIsolationAndCAS(t *testing.T) {
s, token, domain, actor := taskFixture(t)
w := taskRequest(s, token, "GET", "dashboard", nil, "")
if w.Code != 200 {
t.Fatal(w.Code, w.Body)
}
var layout struct {
Version int64 `json:"version"`
Widgets []store.DashboardWidget `json:"widgets"`
}
if err := json.Unmarshal(w.Body.Bytes(), &layout); err != nil || len(layout.Widgets) != 6 {
t.Fatal(layout, err)
}
widgets := []store.DashboardWidget{{ID: "tasks", Width: 7, Height: 4, Tab: "review"}}
w = taskRequest(s, token, "PUT", "dashboard", map[string]any{"version": 0, "widgets": widgets}, "")
if w.Code != 200 {
t.Fatal(w.Code, w.Body)
}
if w = taskRequest(s, token, "PUT", "dashboard", map[string]any{"version": 0, "widgets": widgets}, ""); w.Code != 412 {
t.Fatal("stale layout", w.Code)
}
p, err := s.store.TaskPreferences(context.Background(), domain, actor)
if err != nil || p.Version != 0 {
t.Fatal(p, err)
}
// A legacy CLI preferences write must preserve dashboard metadata.
p.Estimate = 90
w = taskRequest(s, token, "PUT", "preferences", p, "")
if w.Code != 200 {
t.Fatal(w.Code, w.Body)
}
p, err = s.store.TaskPreferences(context.Background(), domain, actor)
if err != nil || p.Estimate != 90 {
t.Fatal(p, err)
}
l, err := s.store.Dashboard(context.Background(), domain, actor)
if err != nil || len(l.Widgets) != 1 || l.Version != 1 {
t.Fatal(l, err)
}
// Layout updates cannot postpone the digest scheduler.
if _, err = s.store.DB.Exec(`UPDATE organizer_task_preferences SET next_digest_ms=123 WHERE domain_uuid=? AND owner_uuid=?`, domain, actor); err != nil {
t.Fatal(err)
}
w = taskRequest(s, token, "PUT", "dashboard", map[string]any{"version": l.Version, "widgets": []store.DashboardWidget{}}, "")
if w.Code != 200 {
t.Fatal(w.Code, w.Body)
}
var next int64
if err = s.store.DB.QueryRow(`SELECT next_digest_ms FROM organizer_task_preferences WHERE domain_uuid=? AND owner_uuid=?`, domain, actor).Scan(&next); err != nil || next != 123 {
t.Fatal(next, err)
}
after, err := s.store.TaskPreferences(context.Background(), domain, actor)
if err != nil || after.Version != p.Version || after.Estimate != 90 {
t.Fatal("layout changed mail consent", after, err)
}
w = taskRequest(s, token, "GET", "dashboard", nil, "")
if err = json.Unmarshal(w.Body.Bytes(), &layout); err != nil || len(layout.Widgets) != 0 {
t.Fatal("empty layout reset", layout, err)
}
for _, invalid := range [][]store.DashboardWidget{{{ID: "iframe", Width: 4, Height: 3}}, {{ID: "tasks", Width: 13, Height: 3, Tab: "inbox"}}, {{ID: "tasks", Width: 4, Height: 3, Tab: "secret"}}, {{ID: "progress", Width: 4, Height: 3}, {ID: "progress", Width: 4, Height: 3}}} {
w = taskRequest(s, token, "PUT", "dashboard", map[string]any{"version": layout.Version, "widgets": invalid}, "")
if w.Code != 422 {
t.Fatal("invalid accepted", w.Code, w.Body)
}
}
other, err := s.store.CreatePasswordAccount(domain, "dashboardother", "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", "dashboard", nil, "")
if err = json.Unmarshal(w.Body.Bytes(), &layout); err != nil || layout.Version != 0 || len(layout.Widgets) != 6 {
t.Fatal("owner leakage", layout, err)
}
if err = s.store.SetPrincipalState(domain, actor, "readonly"); err != nil {
t.Fatal(err)
}
token, err = s.store.CreateAuthSession(domain, actor)
if err != nil {
t.Fatal(err)
}
if w = taskRequest(s, token, "PUT", "dashboard", map[string]any{"version": 3, "widgets": widgets}, ""); w.Code != 403 {
t.Fatal("readonly write", w.Code)
}
if w = taskRequest(s, token, "GET", "dashboard", nil, ""); w.Code != 200 {
t.Fatal("readonly read", w.Code)
}
if w = taskRequest(s, "", "GET", "dashboard", nil, ""); w.Code == 200 {
t.Fatal("anonymous dashboard")
}
if err = s.store.SetConfigInDomain(domain, "system_extension_states", `{"organizer.tasks":false}`); err != nil {
t.Fatal(err)
}
if w = taskRequest(s, token, "GET", "dashboard", nil, ""); w.Code != 404 {
t.Fatal("disabled dashboard", w.Code)
}
}
func TestOrganizerPersonalSettingsAreNotAdminAccess(t *testing.T) {
s, _, domain, _ := taskFixture(t)
u, err := s.store.CreatePasswordAccount(domain, "organizer", "long test password", "Organizer", "")
if err != nil {
t.Fatal(err)
}
token, err := s.store.CreateAuthSession(domain, u.UUID)
if err != nil {
t.Fatal(err)
}
w := configRequest(s, token, "GET", "/-/sys/config?panel=organizer", nil)
if w.Code != 200 || !strings.Contains(w.Body.String(), `id="task-productivity"`) {
t.Fatal(w.Code, w.Body)
}
if strings.Contains(w.Body.String(), `id="panel-auth"`) || strings.Contains(w.Body.String(), `id="panel-campus`) {
t.Fatal("admin data in personal settings")
}
if w = configRequest(s, token, "GET", "/-/sys/config?panel=auth", nil); w.Code != 403 {
t.Fatal("admin access", w.Code)
}
if w = configRequest(s, token, "POST", "/-/sys/config?panel=organizer", url.Values{"section": {"home"}}); w.Code != 403 {
t.Fatal("config mutation", w.Code)
}
for path, target := range map[string]string{"/v/plan/tasks/settings": "/-/sys/config?panel=organizer", "/v/plan/tasks/report": "/v/plan/dashboard#activity"} {
w = configRequest(s, token, "GET", path, nil)
if w.Code != 303 || w.Header().Get("Location") != target {
t.Fatal(path, w.Code, w.Header())
}
}
for _, path := range []string{"/v/plan/dashboard", "/v/plan/tasks", "/v/plan/contacts", "/v/plan"} {
w = configRequest(s, token, "GET", path, nil)
if w.Code != 200 || !strings.Contains(w.Body.String(), `class="organizer-nav"`) {
t.Fatal(path, w.Code, w.Body)
}
}
}
func TestOrganizerProgressExactAndPrivate(t *testing.T) {
s, token, domain, actor := taskFixture(t)
today := time.Now().In(s.getLocation(domain)).Format("2006-01-02")
for i, status := range []string{"todo", "done", "cancelled", "done"} {
item := newTaskRecord("task", "Progress test")
item.Status = status
item.PlannedOn = today
item.Archived = i == 3
if _, err := s.store.SaveTask(context.Background(), domain, actor, item, 0); err != nil {
t.Fatal(err)
}
}
w := taskRequest(s, token, "GET", "progress", nil, "")
var p store.DashboardProgress
if err := json.Unmarshal(w.Body.Bytes(), &p); err != nil || w.Code != 200 || p.Total != 2 || p.Done != 1 || p.Date != today {
t.Fatal(w.Code, p, err, w.Body)
}
other, err := s.store.CreatePasswordAccount(domain, "progressother", "long test password", "Other", "")
if err != nil {
t.Fatal(err)
}
p, err = s.store.DashboardProgress(context.Background(), domain, other.UUID, today)
if err != nil || p.Total != 0 {
t.Fatal("progress leak", p, err)
}
}
+7 -3
View File
@@ -38,10 +38,10 @@ func TestProductivityChromium(t *testing.T) {
if e != nil {
t.Fatal(e)
}
path := map[string]string{"contacts": "/v/plan/contacts", "settings": "/v/plan/tasks/settings", "report": "/v/plan/tasks/report", "tasks": "/v/plan/tasks", "home": "/"}[view]
path := map[string]string{"contacts": "/v/plan/contacts", "settings": "/-/sys/config?panel=organizer", "report": "/v/plan/dashboard", "tasks": "/v/plan/tasks", "home": "/"}[view]
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Header.Set("Authorization", "Bearer "+token)
if r.Method == "GET" && r.URL.Path == path {
if r.Method == "GET" && r.URL.RequestURI() == path {
rec := httptest.NewRecorder()
s.withAuthorization(s.mux).ServeHTTP(rec, r)
for k, v := range rec.Header() {
@@ -70,7 +70,11 @@ func TestProductivityChromium(t *testing.T) {
if prefix := os.Getenv("PAGESWIKI_PRODUCTIVITY_SCREENSHOT"); prefix != "" {
shot = prefix + "-" + view + "-" + size + ".png"
}
out, e := exec.CommandContext(ctx, "node", "internal/server/testdata/vim-browser-smoke.mjs", strings.Replace(server.URL, "127.0.0.1", "localhost", 1)+path, t.TempDir(), shot, width, height).CombinedOutput()
command := exec.CommandContext(ctx, "node", "internal/server/testdata/vim-browser-smoke.mjs", strings.Replace(server.URL, "127.0.0.1", "localhost", 1)+path, t.TempDir(), shot, width, height)
if view == "report" && size == "desktop" {
command.Env = append(os.Environ(), "PAGESWIKI_DASHBOARD_DRAG=1")
}
out, e := command.CombinedOutput()
if e != nil {
t.Fatalf("%v: %s", e, out)
}
+2
View File
@@ -67,6 +67,8 @@ func (s *Server) renderWithContext(
w.Header().Add("Vary", "Cookie")
data["CalendarEnabled"] = s.systemExtensionEnabled(domainUUID, "organizer.calendar")
data["TasksEnabled"] = s.systemExtensionEnabled(domainUUID, "organizer.tasks")
data["ContactsEnabled"] = s.systemExtensionEnabled(domainUUID, "organizer.contacts")
data["OrganizerSection"] = organizerSection(r.URL.Path)
if r.URL.Path == "/" {
data["IsHome"] = true
data["BookmarkSections"] = s.bookmarkSections(r)
+8 -2
View File
@@ -58,6 +58,9 @@ func (s *Server) handleTaskProductivity(w http.ResponseWriter, r *http.Request,
return
}
switch kind {
case "dashboard", "progress":
s.handleDashboardData(w, r, actor, active, kind)
return
case "calendar-capture":
if r.Method == "POST" {
if !s.systemExtensionEnabled(domain, "organizer.calendar") {
@@ -263,6 +266,9 @@ func (s *Server) handleTaskProductivity(w http.ResponseWriter, r *http.Request,
}
func (s *Server) handleTaskProductivityPage(w http.ResponseWriter, r *http.Request, active bool) {
view := strings.TrimPrefix(r.URL.Path, "/v/plan/tasks/")
s.renderWithContext(w, r, "task_productivity.gohtml", map[string]any{"Title": "Tasks", "ProductivityView": view, "TaskWritable": active, "Path": r.URL.Path})
if strings.HasSuffix(r.URL.Path, "/settings") {
http.Redirect(w, r, "/-/sys/config?panel=organizer", http.StatusSeeOther)
return
}
http.Redirect(w, r, "/v/plan/dashboard#activity", http.StatusSeeOther)
}
+5 -1
View File
@@ -20,6 +20,9 @@ import (
const tasksAPI = "/_/api/v1/extension/organizer.tasks/"
func taskRoute(p string) bool {
if p == "/v/plan/dashboard" {
return true
}
if contactRoute(p) {
return true
}
@@ -27,6 +30,7 @@ func taskRoute(p string) bool {
}
func (s *Server) registerTaskRoutes() {
s.mux.HandleFunc("/v/plan/dashboard", s.handleOrganizerDashboard)
s.mux.HandleFunc(contactDAV, s.handleContactDAV)
s.mux.HandleFunc(strings.TrimSuffix(contactDAV, "/"), s.handleContactDAV)
s.mux.HandleFunc("/.well-known/carddav", s.handleContactDAV)
@@ -208,7 +212,7 @@ func (s *Server) handleTasksAPI(w http.ResponseWriter, r *http.Request) {
r = r.WithContext(ctx)
domain := s.domainUUIDForRequest(r)
parts := strings.Split(strings.TrimPrefix(r.URL.Path, tasksAPI), "/")
if len(parts) == 1 && (parts[0] == "calendar-capture" || parts[0] == "capture" || parts[0] == "preferences" || parts[0] == "work" || parts[0] == "report") {
if len(parts) == 1 && (parts[0] == "dashboard" || parts[0] == "progress" || parts[0] == "calendar-capture" || parts[0] == "capture" || parts[0] == "preferences" || parts[0] == "work" || parts[0] == "report") {
s.handleTaskProductivity(w, r, actor, active, parts[0])
return
}
+8 -3
View File
@@ -7,10 +7,15 @@ window.addEventListener('load',async()=>{const wait=async(fn)=>{for(let i=0;i<12
window.confirm=()=>true;document.querySelectorAll('.contact-history-row')[1].querySelectorAll('button')[1].click();await wait(()=>document.querySelector('#contacts-list button')?.textContent.includes('ブラウザ'));
const exported=await fetch('/_/api/v1/extension/organizer.contacts/export.vcf').then(r=>r.text());if(!exported.includes('ブラウザ連絡先'))throw Error('Export missing');
document.querySelector('#tasks-dav-open').click();await wait(()=>document.querySelector('#tasks-dav-dialog').open);const dav=document.querySelector('#tasks-dav-dialog');if(getComputedStyle(dav.querySelector('.dav-compat-toggle')).display!=='none')throw Error('CalDAV-only compatibility visible');fill(dav.querySelector('form>input'),'Browser contact client');dav.querySelector('form').requestSubmit();await wait(()=>!dav.querySelector('section').hidden);const credentials=await fetch('/_/api/v1/caldav-credentials').then(r=>r.json());if(credentials.items.length!==1||credentials.items[0].scope!=='contacts')throw Error('Wrong credential scope');dav.querySelector('tbody button').click();await wait(()=>!dav.querySelector('tbody button'));dav.querySelector('header button').click();
}else if(path.endsWith('/settings')){
}else if(path==='/-/sys/config'){
await wait(()=>document.querySelector('[name=due_days]'));fill(document.querySelector('[name=due_days]'),'2');document.querySelector('.productivity-settings').requestSubmit();await wait(()=>document.querySelector('#productivity-status').textContent.includes('保存'));const d=await fetch('/_/api/v1/extension/organizer.tasks/preferences').then(r=>r.json());if(d.preferences.due_days!==2)throw Error('Preferences missing');
}else if(path.endsWith('/report')){
}else if(path==='/v/plan/dashboard'){
await wait(()=>document.querySelectorAll('.productivity-day').length>300);if(!document.querySelector('.productivity-day[data-level="2"]'))throw Error('Seven-point completion missing');
if(document.querySelectorAll('[data-widget]').length!==6)throw Error('Widget registry missing');
const tab=document.querySelector('[data-tab=done]');tab.click();await wait(()=>document.querySelector('#widget-panel-tasks').textContent.includes('Browser work task'));if(location.pathname!=='/v/plan/dashboard'||document.querySelector('#organizer-dashboard iframe'))throw Error('Tab navigation escaped widget');
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');
}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);
@@ -18,5 +23,5 @@ window.addEventListener('load',async()=>{const wait=async(fn)=>{for(let i=0;i<12
}else{
const input=document.querySelector('[data-home-type-search]');fill(input,'add task 検証 cost:2h complexity:3');input.closest('form').requestSubmit();await wait(()=>document.querySelector('.home-command-panel button'));document.querySelector('.home-command-panel button').click();await wait(()=>document.querySelector('.home-command-panel a'));const d=await fetch('/_/api/v1/extension/organizer.tasks/items?q='+encodeURIComponent('検証')).then(r=>r.json());if(d.items[0].estimate_minutes!==120)throw Error('Command cost missing');fill(input,'add cal 会議 from:2026-11-02T09:00 to:2026-11-02T10:00');input.closest('form').requestSubmit();await wait(()=>document.querySelector('.home-command-panel button'));document.querySelector('.home-command-panel button').click();await wait(()=>document.querySelector('.home-command-panel a')?.href.includes('/event/'));
}
if(document.documentElement.scrollWidth>innerWidth+2)throw Error('Page horizontal overflow');document.body.dataset.vimReady='true';
if(document.documentElement.scrollWidth>innerWidth+2)throw Error('Page horizontal overflow: '+[...document.querySelectorAll('body *')].filter(n=>{const r=n.getBoundingClientRect();return r.width&&r.right>innerWidth+2;}).slice(0,15).map(n=>n.tagName+'.'+n.className+':'+Math.round(n.getBoundingClientRect().right)).join(', '));document.body.dataset.vimReady='true';
}catch(e){const n=document.createElement('pre');n.id='error';n.textContent=(e.stack||String(e))+'\n'+(document.querySelector('.home-command-panel')?.textContent||'');document.body.append(n);}});
+14
View File
@@ -44,6 +44,20 @@ try {
if (state.ready) { ready = true; break; }
await delay(200);
}
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};})()`);
const drag=async(from,to)=>{await call('Input.dispatchMouseEvent',{type:'mouseMoved',...from});await call('Input.dispatchMouseEvent',{type:'mousePressed',...from,button:'left',buttons:1,clickCount:1});for(let n=1;n<=8;n++)await call('Input.dispatchMouseEvent',{type:'mouseMoved',x:from.x+(to.x-from.x)*n/8,y:from.y+(to.y-from.y)*n/8,buttons:1});await call('Input.dispatchMouseEvent',{type:'mouseReleased',...to,button:'left',buttons:0,clickCount:1});};
await evaluate(`scrollTo({top:0,behavior:'instant'})`);
const coordinates=await evaluate(`(()=>{const point=s=>{const r=document.querySelector(s).getBoundingClientRect();return {x:r.x+r.width/2,y:r.y+r.height/2};};return {from:point('[data-widget=progress] .widget-drag'),to:point('[data-widget=today] .widget-header')};})()`);await drag(coordinates.from,coordinates.to);
if(await evaluate(`document.querySelector('#dashboard-grid').firstElementChild.dataset.widget`)!=='today')throw Error('Pointer reorder failed: '+JSON.stringify(coordinates));
const grip=await rect('[data-widget=tasks] .widget-resize');await drag(grip,{x:grip.x,y:grip.y-84});
if(await evaluate(`document.querySelector('[data-widget=tasks] [data-size=height]').value`)!=='4')throw Error('Pointer resize failed');
await evaluate(`document.querySelector('#dashboard-controls button:last-child').click()`);
let saved=false;for(let n=0;n<50;n++){if(await evaluate(`document.querySelector('#dashboard-status').textContent.includes('保存しました')`)){saved=true;break;}await delay(100);}if(!saved)throw Error('Pointer layout save failed');
const layout=await evaluate(`fetch('/_/api/v1/extension/organizer.tasks/dashboard').then(r=>r.json())`);if(layout.widgets[0].id!=='today'||layout.widgets.find(w=>w.id==='tasks').height!==4)throw Error('Pointer layout persistence failed');
await evaluate(`document.querySelector('#dashboard-controls button[aria-pressed]').click();scrollTo(0,0)`);
}
if (screenshot) {
const {data} = await call('Page.captureScreenshot', {format: 'png'});
await writeFile(screenshot, Buffer.from(data, 'base64'));