diff --git a/e2e/agenda-window.spec.ts b/e2e/agenda-window.spec.ts index 85a0789e..6c2391a8 100644 --- a/e2e/agenda-window.spec.ts +++ b/e2e/agenda-window.spec.ts @@ -6,6 +6,7 @@ test.use({ timezoneId: "UTC", reducedMotion: "reduce" }); test("a dense agenda keeps day totals, row focus and collapse while scrolling", async ({ page, }) => { + test.setTimeout(90_000); await page.clock.setFixedTime(new Date("2026-11-04T12:00:00Z")); await page.goto( "views/TaskNotes%2FViews%2Fupcoming.base%23upcoming?demo=10000", @@ -14,7 +15,10 @@ test("a dense agenda keeps day totals, row focus and collapse while scrolling", const groups = lead.locator(".agenda-row-group"); const toggle = lead.getByRole("button", { name: /^Overdue \d+$/ }); const titles = page.locator(".tnc-item--list .task-row-title"); - await expect(titles.first()).toBeVisible(); + // Cold admission seeds 10k records before the calendar can mount a pool. + await expect(groups.first().locator(".task-row-title").first()).toBeVisible({ + timeout: 30_000, + }); expect(await groups.count()).toBeGreaterThan(100); expect(await titles.count()).toBeLessThan(160); diff --git a/scripts/bench-first-paint.mjs b/scripts/bench-first-paint.mjs index 9ce5e6f3..ae2d2309 100644 --- a/scripts/bench-first-paint.mjs +++ b/scripts/bench-first-paint.mjs @@ -1,4 +1,4 @@ -/* global window, requestAnimationFrame */ +/* global document, window, requestAnimationFrame */ // First usable task row in the local SDK protocol fixture. import { chromium } from "@playwright/test"; import assert from "node:assert/strict"; @@ -8,6 +8,7 @@ const origins = ( ).map((url) => new URL(url)); for (const origin of origins) assert.ok(["localhost", "127.0.0.1"].includes(origin.hostname)); +const size = Number(process.env.TASKNOTES_BENCH_TASKS ?? 10000); const browser = await chromium.launch(); const results = Object.fromEntries( origins.map(({ origin }) => [origin, { cold: [], warm: [] }]), @@ -22,9 +23,10 @@ async function openCollection(origin) { }); const page = await context.newPage(); page.setDefaultTimeout(60_000); - await page.addInitScript(() => { + await page.clock.setFixedTime(new Date("2026-11-04T12:00:00Z")); + await page.addInitScript((size) => { window.__TASKNOTES_NEXT_SMOKE__ = { - records: Array.from({ length: 10_000 }, (_, index) => ({ + records: Array.from({ length: size }, (_, index) => ({ path: `Tasks/T${index}.md`, frontmatter: { type: "task", @@ -38,7 +40,7 @@ async function openCollection(origin) { body: "Task detail. ".repeat(80), })), }; - }); + }, size); for (const mode of ["cold", "warm"]) { await page.goto(origin.href); const open = page.getByRole("button", { @@ -46,31 +48,30 @@ async function openCollection(origin) { }); await open.waitFor(); // Include seeding, SDK open, React commit and a paint opportunity. - await open.evaluate((button) => { - performance.mark("fixture-open"); - button.click(); - }); - await page.locator(".task-row-title").first().waitFor(); - samples[mode].push( - await page.evaluate(async () => { - await new Promise((resolve) => - requestAnimationFrame(() => requestAnimationFrame(resolve)), - ); - return Math.round( - performance.measure("first task", "fixture-open").duration, - ); - }), + const start = performance.now(); + await open.evaluate((button) => button.click()); + await page.waitForFunction( + () => + document.querySelector(".task-row-title")?.getBoundingClientRect() + .height > 0, + ); + await page.evaluate( + () => + new Promise((done) => + requestAnimationFrame(() => requestAnimationFrame(done)), + ), ); + samples[mode].push(Math.round(performance.now() - start)); } await context.close(); } try { - for (let round = 0; round < 5; round++) { + for (let round = 0; round < 7; round++) { for (const origin of round % 2 ? [...origins].reverse() : origins) await openCollection(origin); console.log(JSON.stringify({ round, results })); } - console.log(JSON.stringify({ chromium: browser.version(), results })); + console.log(JSON.stringify({ size, chromium: browser.version(), results })); } finally { await browser.close(); } diff --git a/scripts/bench-task-workflow.mjs b/scripts/bench-task-workflow.mjs new file mode 100644 index 00000000..77f20eb3 --- /dev/null +++ b/scripts/bench-task-workflow.mjs @@ -0,0 +1,217 @@ +/* global document, history, location, dispatchEvent, PopStateEvent, requestAnimationFrame */ +// Pass two loopback e2e previews to alternate the order of paired builds. +import assert from "node:assert/strict"; +import { chromium } from "@playwright/test"; + +const origins = process.argv.slice(2).map((url) => new URL(url)); +assert.ok( + origins.length && + origins.every((url) => ["127.0.0.1", "localhost"].includes(url.hostname)), +); +const browser = await chromium.launch(); +const rounds = Number(process.env.TASKNOTES_BENCH_ROUNDS ?? 7); +const results = {}; +const view = (slug) => + "/views/" + encodeURIComponent("TaskNotes/Views/" + slug + ".base#" + slug); + +async function sample(origin, size) { + const context = await browser.newContext({ + viewport: { width: 1280, height: 800 }, + timezoneId: "UTC", + locale: "en-US", + reducedMotion: "reduce", + serviceWorkers: "block", + }); + const page = await context.newPage(); + page.setDefaultTimeout(30000); + await page.clock.setFixedTime(new Date("2026-11-04T12:00:00Z")); + const samples = {}; + const ready = (selector) => + page.waitForFunction( + (selector) => + document.querySelector(selector)?.getBoundingClientRect().height > 0, + selector, + ); + async function measure(name, act) { + try { + const start = performance.now(); + await act(); + await page.evaluate( + () => + new Promise((done) => + requestAnimationFrame(() => requestAnimationFrame(done)), + ), + ); + samples[name] = Math.round(performance.now() - start); + } catch (cause) { + throw new Error(name, { cause }); + } + } + async function go(path, selector) { + await page.evaluate((next) => { + history.pushState(null, "", next + location.search); + dispatchEvent(new PopStateEvent("popstate")); + }, path); + await ready(selector); + } + try { + for (const mode of ["cold", "warm"]) { + await measure(mode + " open", async () => { + await page.goto(new URL("?demo=" + size, origin).href); + await ready(".task-row-title"); + }); + for (const [name, path, selector] of [ + ["Upcoming", view("upcoming"), ".tnc-list-lead .task-row-title"], + ["Calendar", view("calendar"), ".tnc-dg .tnc-item"], + ["Tasks", view("inbox"), ".task-list-view .task-row-title"], + ["Projects", view("projects"), ".project-group .task-row"], + ["Kanban", view("work-board"), ".kanban-card"], + ["Scratchpad", "/scratchpad", ".scratchpad-document-stream"], + ["Search", "/search", ".browse-fields"], + ["Today", view("today"), ".task-row-title"], + ]) + await measure(mode + " " + name, () => go(path, selector)); + + const prefix = mode + " "; + const project = page.locator( + '.navigation-project-section button[aria-label^="Operations "] small', + ); + const count = Number(await project.textContent()); + const title = "Workflow capture " + mode; + await page + .getByRole("button", { name: "New task", exact: true }) + .filter({ visible: true }) + .click(); + const input = page + .getByRole("textbox", { name: "New task title" }) + .filter({ visible: true }) + .last(); + await input.fill(title + " +Operations #workflowtag today"); + await measure(prefix + "capture + project count", async () => { + await input.press("Enter"); + await page.waitForFunction( + (n) => + document.querySelector( + '.navigation-project-section button[aria-label^="Operations "] small', + )?.textContent === String(n), + count + 1, + ); + }); + await go("/search", "#task-search"); + const search = page.getByRole("searchbox", { name: "Search tasks" }); + const row = page + .locator(".search-results .task-row-title") + .filter({ hasText: title }); + await measure(prefix + "title filter", async () => { + await search.fill(title); + await row.waitFor(); + }); + await search.fill(""); + await page.locator(".browse-fields").waitFor(); + await measure(prefix + "tag filter", async () => { + await search.fill("workflowtag"); + await row.waitFor(); + await page.locator(".search-result-count").waitFor(); + }); + const editor = page.getByRole("textbox", { + name: "Task title", + exact: true, + }); + await measure(prefix + "open detail", async () => { + await row.click(); + await editor.waitFor(); + }); + const edited = title + " edited"; + await measure(prefix + "edit, save + reopen", async () => { + await editor.fill(edited); + await editor.blur(); + await page + .getByRole("button", { name: "Close task details", exact: true }) + .click(); + await page + .getByRole("button", { name: edited, exact: true }) + .first() + .click(); + await page.waitForFunction( + (value) => document.querySelector("#task-title")?.value === value, + edited, + ); + }); + await page + .getByRole("button", { name: "Close task details", exact: true }) + .click(); + const complete = page + .getByRole("button", { name: edited, exact: true }) + .first(); + await complete.focus(); + await measure(prefix + "complete + project count", async () => { + await page.keyboard.press("x"); + await page.waitForFunction( + (n) => + document.querySelector( + '.navigation-project-section button[aria-label^="Operations "] small', + )?.textContent === String(n), + count, + ); + }); + await go(view("upcoming"), ".tnc-list-lead .task-row-title"); + const lead = page.locator(".tnc-list-lead"); + const group = lead.locator(".agenda-row-group").nth(80); + const destination = + size === 10000 + ? group + : page.locator(".tnc-list-section[data-date]").last(); + await measure(prefix + "agenda scroll", async () => { + await destination.scrollIntoViewIfNeeded(); + if (size === 10000) + await group.locator(".task-row-title").first().waitFor(); + }); + const source = lead.getByRole("button", { + name: "Book the project room", + exact: true, + }); + if (size === 10000) + await lead + .locator(".agenda-row-group") + .first() + .evaluate((el) => el.scrollIntoView({ block: "start" })); + else await lead.getByRole("heading").scrollIntoViewIfNeeded(); + await source.evaluate((el) => el.scrollIntoView({ block: "center" })); + const day = await page + .locator(".tnc-strip-day[aria-current=date] + button") + .getAttribute("data-date"); + const target = page.locator(`.tnc-strip-day[data-date="${day}"]`); + await measure(prefix + "agenda drag", async () => { + await source.dragTo(target, { + sourcePosition: { x: 20, y: 16 }, + steps: 13, + }); + await source.waitFor({ state: "hidden" }); + await target.click(); + await page + .locator('.tnc-list-section[data-date="' + day + '"]') + .getByRole("button", { name: "Book the project room", exact: true }) + .waitFor(); + }); + } + return samples; + } finally { + await context.close(); + } +} +try { + for (let round = 0; round < rounds; round++) + for (const size of [60, 10000]) + for (const origin of round % 2 ? [...origins].reverse() : origins) { + const samples = await sample(origin, size); + const group = ((results[origin.origin] ??= {})[size] ??= {}); + for (const [key, value] of Object.entries(samples)) + (group[key] ??= []).push(value); + console.error( + JSON.stringify({ round, origin: origin.origin, size, samples }), + ); + } + console.log(JSON.stringify({ chromium: browser.version(), results })); +} finally { + await browser.close(); +} diff --git a/src/app/task-calendar-view.test.tsx b/src/app/task-calendar-view.test.tsx index 6ecc336f..bb3b949b 100644 --- a/src/app/task-calendar-view.test.tsx +++ b/src/app/task-calendar-view.test.tsx @@ -785,6 +785,26 @@ describe("shared agenda", () => { }); }); + it.each([ + { days: 1, scheduled: "2026-07-04", included: true }, + { days: 1, scheduled: "2026-07-05", included: false }, + { days: 20, scheduled: "2026-07-20", included: true }, + ])( + "projects the initial $days-day agenda and its strip through the correct end ($scheduled)", + ({ days, scheduled, included }) => { + const current = execution(scheduled); + current.view.presentation!.options = { + calendarView: "listWeek", + listDayCount: days, + }; + // July 1 is a Wednesday in the helper's Sunday-first view. + renderCalendar(current, vi.fn()); + expect(items().some((item) => item.id === "scheduled-one")).toBe( + included, + ); + }, + ); + it("mounts ordinary task controls without a surrounding calendar button", async () => { const current = execution("2026-07-24T09:30"); current.view.presentation!.options.calendarView = "listWeek"; diff --git a/src/app/task-calendar-view.tsx b/src/app/task-calendar-view.tsx index 7ded09db..25c3fa3e 100644 --- a/src/app/task-calendar-view.tsx +++ b/src/app/task-calendar-view.tsx @@ -242,8 +242,12 @@ export function TaskCalendarView({ }, [locale]); const { configuration, materializeOccurrence } = useRepository(); const { timezone } = calendarContext(configuration); + const listDayCount = numberOption( + execution.view.presentation?.options.listDayCount, + 7, + ); const [range, setRange] = useState(() => - initialRange(selected, mode, timezone, preferences.firstDay), + initialRange(selected, mode, timezone, preferences.firstDay, listDayCount), ); useCalendarPosition(rootRef, mode, phone, selected, range.start.getTime()); useCalendarPreviews(rootRef, (day) => { @@ -980,10 +984,7 @@ export function TaskCalendarView({ execution.view.presentation?.options.customDayCount, 3, )} - listDayCount={numberOption( - execution.view.presentation?.options.listDayCount, - 7, - )} + listDayCount={listDayCount} listAgenda={agenda} listRowPool={(container, create) => agendaRowWindow( @@ -1611,6 +1612,7 @@ function initialRange( mode: CalendarMode, timezone: string, firstDay: number, + listDayCount: number, ): { start: Date; end: Date } { const date = dateFromStorage(selected) ?? new Date(); const midnight = (year: number, month: number, day: number) => @@ -1622,6 +1624,19 @@ function initialRange( start: midnight(date.getFullYear(), 0, 1), end: midnight(date.getFullYear() + 1, 0, 1), }; + if (mode === "listWeek") { + // The list starts on its anchor. Include the end of the visible date + // strip just as onRangeChange does, including for short custom lists. + const first = parseDay(selected)!; + const end = Math.max( + first + listDayCount, + startOfWeek(first, firstDay) + 7, + ); + return { + start: new Date(calendarDateToInstant(selected, timezone)), + end: new Date(calendarDateToInstant(formatDay(end), timezone)), + }; + } if (mode === "dayGridMonth") { const first = startOfWeek( startOfMonth(parseDay(todayString(date))!), diff --git a/src/app/use-calendar-agenda.ts b/src/app/use-calendar-agenda.ts index d23ea83d..fcdf132a 100644 --- a/src/app/use-calendar-agenda.ts +++ b/src/app/use-calendar-agenda.ts @@ -71,22 +71,15 @@ export function useCalendarAgenda({ setSlots(new Map(mountedSlots.current)); }); } - const [stripRange, setStripRange] = useState(() => { - const start = new Date(); - const end = new Date(start); - end.setDate(end.getDate() + 7); - return { start, end }; - }); - // Count the actual days shown in the strip, including past weeks. Widening - // the main agenda projection instead would suppress its overdue-on-today - // entries. No second expansion is needed while using a grid layout. - const stripExecution = useMemo( - () => (enabled ? execution : { ...execution, rows: [] }), - [enabled, execution], - ); + // The strip owns its week (or expanded month). Its first DOM measurement + // supplies the range, including past days omitted from the main agenda. + const [stripRange, setStripRange] = useState<{ + start: Date; + end: Date; + } | null>(null); const entries = useCalendarEntries( - stripExecution, - stripRange, + execution, + enabled ? stripRange : null, identityTasks, configuration, display, @@ -137,7 +130,7 @@ export function useCalendarAgenda({ ? new Date(calendarDateToInstant(todayString(endDay), zone)) : endDay; setStripRange((current) => - current.start.getTime() === start.getTime() && + current?.start.getTime() === start.getTime() && current.end.getTime() === end.getTime() ? current : { start, end }, @@ -283,12 +276,15 @@ export function useCalendarAgenda({ }; }, [root, calendar, enabled, items, locale, entries, selected, zone]); - const lastShown = new Date(stripRange.end); - lastShown.setDate(lastShown.getDate() - 1); - const stripTitle = new Intl.DateTimeFormat(locale, { - month: "short", - day: "numeric", - }).formatRange(stripRange.start, lastShown); + const stripTitle = useMemo(() => { + if (!stripRange) return ""; + const lastShown = new Date(stripRange.end); + lastShown.setDate(lastShown.getDate() - 1); + return new Intl.DateTimeFormat(locale, { + month: "short", + day: "numeric", + }).formatRange(stripRange.start, lastShown); + }, [stripRange, locale]); const [expanded, setExpanded] = useState(false); useEffect(() => { const host = root.current; diff --git a/src/app/use-calendar-entries.ts b/src/app/use-calendar-entries.ts index ab6830aa..df754d8b 100644 --- a/src/app/use-calendar-entries.ts +++ b/src/app/use-calendar-entries.ts @@ -1,6 +1,7 @@ import { useEffect, useMemo } from "react"; import { AppCalendarEntryIndex, + type CalendarEntry, calendarContext, calendarSettings, } from "../domain/calendar-events"; @@ -13,7 +14,7 @@ const noMaterializations: readonly TaskSummary[] = []; export function useCalendarEntries( execution: TaskViewExecution, - range: { start: Date; end: Date }, + range: { start: Date; end: Date } | null, identityTasks: readonly TaskSummary[], configuration: TaskCollectionConfiguration, display: CalendarSettings, @@ -33,6 +34,7 @@ export function useCalendarEntries( [identityTasks], ); return useMemo(() => { + if (!range) return new Map(); const context = calendarContext(configuration); return index.entries( execution, diff --git a/src/app/use-calendar-position.test.tsx b/src/app/use-calendar-position.test.tsx index 0f157d4e..77ead20a 100644 --- a/src/app/use-calendar-position.test.tsx +++ b/src/app/use-calendar-position.test.tsx @@ -52,10 +52,13 @@ it("reanchors the selected agenda section when detail changes the pane width in ); act(() => resize()); expect(section.scrollIntoView).not.toHaveBeenCalled(); - bounds(root.current, 0, 0, 550, 700); + bounds(root.current, 0, 180, 800, 700); + act(() => resize()); + expect(section.scrollIntoView).not.toHaveBeenCalled(); + bounds(root.current, 0, -250, 550, 700); act(() => resize()); expect(section.scrollIntoView).toHaveBeenCalledWith({ block: "start" }); - bounds(root.current, 0, 0, 900, 700); + bounds(root.current, 0, -250, 900, 700); act(() => resize()); expect(section.scrollIntoView).toHaveBeenCalledTimes(2); }); diff --git a/src/app/use-calendar-position.ts b/src/app/use-calendar-position.ts index d5bb6989..6e2db6bb 100644 --- a/src/app/use-calendar-position.ts +++ b/src/app/use-calendar-position.ts @@ -17,10 +17,13 @@ export function useCalendarPosition( let width = root.getBoundingClientRect().width; let frame = 0; const observer = new ResizeObserver(() => { - const nextWidth = root.getBoundingClientRect().width; - if (nextWidth === width) return; - width = nextWidth; + const bounds = root.getBoundingClientRect(); + if (bounds.width === width) return; + width = bounds.width; cancelAnimationFrame(frame); + // The sidebar can settle after the first agenda paint. Keep the start + // of the agenda visible until the user has scrolled into its days. + if (bounds.top >= 0) return; frame = requestAnimationFrame(() => { root .querySelector(`.tnc-list-day[data-date="${selected}"]`) diff --git a/src/domain/runtime-timezone.test.ts b/src/domain/runtime-timezone.test.ts new file mode 100644 index 00000000..e389da02 --- /dev/null +++ b/src/domain/runtime-timezone.test.ts @@ -0,0 +1,18 @@ +import { afterEach, expect, it, vi } from "vitest"; +import { runtimeTimezone } from "./runtime-timezone"; + +afterEach(() => vi.restoreAllMocks()); + +it("shares the device timezone during a batch and detects travel on the next turn", async () => { + await Promise.resolve(); + const resolved = new Intl.DateTimeFormat().resolvedOptions(); + const options = vi + .spyOn(Intl.DateTimeFormat.prototype, "resolvedOptions") + .mockReturnValueOnce({ ...resolved, timeZone: "Australia/Melbourne" }) + .mockReturnValueOnce({ ...resolved, timeZone: "Europe/Paris" }); + expect(runtimeTimezone()).toBe("Australia/Melbourne"); + expect(runtimeTimezone()).toBe("Australia/Melbourne"); + expect(options).toHaveBeenCalledTimes(1); + await Promise.resolve(); + expect(runtimeTimezone()).toBe("Europe/Paris"); +}); diff --git a/src/domain/runtime-timezone.ts b/src/domain/runtime-timezone.ts index 558ca03c..04ed9ae1 100644 --- a/src/domain/runtime-timezone.ts +++ b/src/domain/runtime-timezone.ts @@ -1,5 +1,8 @@ +let currentTimezone: string | undefined; + /** Return the current runtime's canonical IANA timezone. */ export function runtimeTimezone(): string { + if (currentTimezone) return currentTimezone; const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone; if ( !timezone || @@ -16,6 +19,12 @@ export function runtimeTimezone(): string { `runtime_timezone_invalid: This device reported an invalid timezone (${timezone}).`, ); } + // A synchronous batch of floating dates shares one device zone. Resolve it + // again on the next turn so a resumed or travelling device sees its new zone. + currentTimezone = timezone; + queueMicrotask(() => { + currentTimezone = undefined; + }); return timezone; }