From 0768afe3d334b684f47433027f31516e453c9c95 Mon Sep 17 00:00:00 2001 From: callumalpass Date: Sat, 28 Nov 2026 20:19:15 +1100 Subject: [PATCH] Window Projects globally and reduce recurring view work --- benchmarks/recurrence-scale.test.ts | 119 ++++++ e2e/phone.spec.ts | 10 +- e2e/projects-window.spec.ts | 68 ++++ package.json | 1 + scripts/bench-projects.mjs | 69 ++++ src/app/calendar-event-presentation.ts | 2 +- src/app/calendar-items.ts | 13 +- src/app/keyboard-shortcuts.ts | 12 + src/app/views/projects-view.tsx | 493 ++++++++++++++++--------- src/components/bounded-list.tsx | 161 ++++++-- src/domain/task-occurrence.ts | 38 ++ src/domain/today-summary.test.ts | 47 +++ src/domain/today-summary.ts | 7 +- src/domain/view-values.ts | 29 +- src/styles/03-task-rows.css | 1 + src/styles/10-lists-and-boards.css | 20 +- src/styles/11-calendar.css | 2 +- src/test/demo-entry-fixture.tsx | 22 +- 18 files changed, 887 insertions(+), 227 deletions(-) create mode 100644 benchmarks/recurrence-scale.test.ts create mode 100644 e2e/projects-window.spec.ts create mode 100644 scripts/bench-projects.mjs diff --git a/benchmarks/recurrence-scale.test.ts b/benchmarks/recurrence-scale.test.ts new file mode 100644 index 00000000..5c338895 --- /dev/null +++ b/benchmarks/recurrence-scale.test.ts @@ -0,0 +1,119 @@ +import { afterEach, expect, it, vi } from "vitest"; +import { calendarItems } from "../src/app/calendar-items"; +import { DemoTaskRepository } from "../src/demo/demo-task-repository"; +import { calendarEvents } from "../src/domain/calendar-events"; +import { + projectTodayTasks, + taskOccurrencesBetween, +} from "../src/domain/task-occurrence"; +import { summarizeToday } from "../src/domain/today-summary"; + +afterEach(() => vi.useRealTimers()); + +it.runIf(process.env.TASKNOTES_BENCH_FORMATTING === "1")( + "measures Today, Inbox and Calendar projections with 10,000 recurring tasks", + async () => { + const now = "2026-11-04T12:00:00Z"; + const today = now.slice(0, 10); + vi.useFakeTimers({ toFake: ["Date"] }); + vi.setSystemTime(new Date(now)); + const repository = new DemoTaskRepository(1, undefined, { + tasks: (model) => + Array.from({ length: 12_000 }, (_, index) => + model.create( + { + title: `Series ${index}`, + scheduled: index < 8_000 ? "2026-10-05" : undefined, + recurrence: + index >= 10_000 + ? undefined + : index % 2 + ? "FREQ=WEEKLY;BYDAY=MO,WE,FR" + : "FREQ=DAILY", + }, + { + id: `series-${index}`, + now: new Date(Date.parse(now) - index * 3_600_000).toISOString(), + }, + ), + ), + scratchpads: () => [], + }); + const configuration = await repository.taskConfiguration(); + const views = (await repository.listViews()).flatMap((doc) => doc.views); + const calendar = views.find((view) => view.id === "calendar")!; + const inbox = views.find((view) => view.id === "inbox")!; + const execution = await repository.executeView(calendar); + const tasks = await repository.listSummaries({ + status: "all", + limit: 50_000, + }); + const start = new Date("2026-10-25T00:00:00Z"); + const end = new Date("2026-12-06T00:00:00Z"); + const samples = { + todaySummary: [] as number[], + todayOccurrences: [] as number[], + inboxView: [] as number[], + rruleDateExpansion: [] as number[], + calendarOccurrences: [] as number[], + calendarProjection: [] as number[], + }; + let counts = {}; + for (let round = 0; round <= 7; round++) { + const measure = async ( + key: keyof typeof samples, + operation: () => T | Promise, + ) => { + const since = performance.now(); + const result = await operation(); + if (round) samples[key].push(Math.round(performance.now() - since)); + return result; + }; + const summary = await measure("todaySummary", () => + summarizeToday(tasks, today), + ); + const todayRows = await measure("todayOccurrences", () => + projectTodayTasks(tasks, "2026-10-05", today, 100), + ); + const inboxRows = await measure("inboxView", () => + repository.executeView(inbox), + ); + const recurring = tasks.filter((task) => task.recurrence); + await measure("rruleDateExpansion", () => + recurring.reduce( + (total, task) => + total + + taskOccurrencesBetween(task, "2026-10-25", "2026-12-05").length, + 0, + ), + ); + const calendarRows = await measure("calendarOccurrences", () => + calendarEvents(execution, start, end, tasks, {}, configuration), + ); + const items = await measure( + "calendarProjection", + () => + calendarItems(calendarRows, execution, "title", configuration).items, + ); + counts = { + next: summary.next?.date, + today: todayRows.totalCount, + inbox: inboxRows.totalCount, + calendar: items.length, + }; + expect(recurring).toHaveLength(10_000); + expect(tasks).toHaveLength(12_000); + expect(summary.next?.date).toBe("2026-11-05"); + expect(inboxRows.totalCount).toBe(2_000); + expect(items.length).toBeGreaterThan(100_000); + } + const medianMs = Object.fromEntries( + Object.entries(samples).map(([key, values]) => [ + key, + [...values].sort((a, b) => a - b)[3], + ]), + ); + console.log(JSON.stringify({ counts, medianMs, samples })); + }, + 180_000, +); diff --git a/e2e/phone.spec.ts b/e2e/phone.spec.ts index d012c020..468384a4 100644 --- a/e2e/phone.spec.ts +++ b/e2e/phone.spec.ts @@ -191,9 +191,17 @@ test("touch month selection consumes its compatibility click, not the next inten page, }) => { await page.emulateMedia({ colorScheme: "dark" }); - await page.setViewportSize({ width: 412, height: 713 }); + await page.setViewportSize({ width: 360, height: 713 }); await page.clock.setFixedTime(new Date("2026-11-06T10:00:00")); await page.goto(route("calendar")); + for (const name of ["Previous period", "Next period"]) { + const bounds = await page + .getByRole("button", { name, exact: true }) + .boundingBox(); + expect(bounds?.width).toBeGreaterThanOrEqual(44); + expect(bounds?.height).toBeGreaterThanOrEqual(44); + } + await expectNoHorizontalOverflow(page); const day = page.locator('.tnc-dg-day[data-date="2026-11-06"]'); await expect(day).toBeVisible(); await day.tap(); diff --git a/e2e/projects-window.spec.ts b/e2e/projects-window.spec.ts new file mode 100644 index 00000000..e4337bd8 --- /dev/null +++ b/e2e/projects-window.spec.ts @@ -0,0 +1,68 @@ +import { expect, test } from "./local-test"; + +test("Projects windows 125 groups and keeps offscreen jumps and row navigation", async ({ + page, +}) => { + test.setTimeout(90_000); + await page.goto( + `views/${encodeURIComponent("TaskNotes/Views/projects.base#projects")}?demo=projects-scale`, + ); + const project = (number: string) => + page.getByRole("button", { + name: `Project ${number} 80 tasks`, + exact: true, + }); + const task = (name: string) => + page.getByRole("button", { name: `Task ${name}`, exact: true }); + const rows = page.locator(".project-group .task-row"); + await expect(task("001-01")).toBeVisible({ timeout: 30_000 }); + expect(await rows.count()).toBeLessThan(100); + await expect(project("125")).toHaveCount(0); + + const jump = page.getByRole("combobox", { name: "Jump to project" }); + await jump.click(); + await page + .getByRole("option", { name: "Project 125 (80)", exact: true }) + .click(); + const last = project("125"); + await expect(last).toBeFocused(); + await expect(last).toBeInViewport(); + const controlsId = await last.getAttribute("aria-controls"); + expect(controlsId).toMatch(/^\S+$/); + const controlled = page.locator(`[id="${controlsId}"]`); + await expect( + controlled.getByRole("button", { name: "Task 125-01", exact: true }), + ).toBeVisible(); + await last.press("Enter"); + await expect(last).toHaveAttribute("aria-expanded", "false"); + await expect(controlled).toBeHidden(); + await last.press("Enter"); + await expect(last).toHaveAttribute("aria-expanded", "true"); + await expect(task("125-01")).toBeVisible(); + + await task("125-01").focus(); + await task("125-01").press("ArrowUp"); + await expect(task("124-80")).toBeFocused(); + await task("124-80").press("Shift+ArrowDown"); + await expect(task("125-01")).toBeFocused(); + await expect(page.locator(".bulk-actions")).toContainText("2 selected"); + await page.keyboard.press("Escape"); + + // A retained row must navigate to its true neighbour after a long scroll. + await page.evaluate(() => window.scrollTo(0, 0)); + await expect(task("001-01")).toBeInViewport(); + await expect(task("125-02")).toHaveCount(0); + await page.keyboard.press("ArrowDown"); + await expect(task("125-02")).toBeFocused(); + await expect(task("125-02")).toBeInViewport(); + expect(await rows.count()).toBeLessThan(100); + + await task("125-02").press("Enter"); + await expect(page.getByRole("textbox", { name: "Task title" })).toHaveValue( + "Task 125-02", + ); + await page.getByRole("button", { name: "Next task", exact: true }).click(); + await expect(page.getByRole("textbox", { name: "Task title" })).toHaveValue( + "Task 125-03", + ); +}); diff --git a/package.json b/package.json index 9a378e84..50b7733d 100644 --- a/package.json +++ b/package.json @@ -44,6 +44,7 @@ "test:watch": "vitest", "bench:view-formatting": "TASKNOTES_BENCH_FORMATTING=1 vitest run benchmarks/view-formatting.test.ts benchmarks/view-entry.test.ts", "bench:view-interactions": "TASKNOTES_BENCH_INTERACTIONS=1 vitest run benchmarks/view-interactions.test.ts", + "bench:recurrence": "TASKNOTES_BENCH_FORMATTING=1 vitest run benchmarks/recurrence-scale.test.ts", "bench:collections": "tsc -p benchmarks/tsconfig.json && vitest run --config benchmarks/vitest.config.ts", "test:e2e": "playwright test", "test:e2e:connect": "playwright test --config playwright.dogfood.config.ts", diff --git a/scripts/bench-projects.mjs b/scripts/bench-projects.mjs new file mode 100644 index 00000000..75d41207 --- /dev/null +++ b/scripts/bench-projects.mjs @@ -0,0 +1,69 @@ +/* global history, location, PopStateEvent, dispatchEvent, requestAnimationFrame */ +import assert from "node:assert/strict"; +import { performance } from "node:perf_hooks"; +import { chromium } from "@playwright/test"; + +const origin = new URL(process.argv[2] ?? "http://127.0.0.1:4173"); +assert.ok(["localhost", "127.0.0.1"].includes(origin.hostname)); +const browser = await chromium.launch(); +try { + const context = await browser.newContext({ + viewport: { width: 1280, height: 800 }, + locale: "en-US", + timezoneId: "UTC", + reducedMotion: "reduce", + serviceWorkers: "block", + }); + await context.route("**/*", (route) => + new URL(route.request().url()).origin === origin.origin + ? route.continue() + : route.abort(), + ); + const page = await context.newPage(); + await page.clock.setFixedTime(new Date("2026-11-04T12:00:00Z")); + await page.goto(new URL("/search?demo=projects-scale", origin).href); + const search = page.getByRole("searchbox", { name: "Search tasks" }); + const projects = + "/views/" + encodeURIComponent("TaskNotes/Views/projects.base#projects"); + const go = (path) => + page.evaluate((next) => { + history.pushState(null, "", next + location.search); + dispatchEvent(new PopStateEvent("popstate")); + }, path); + const samples = []; + for (let round = 0; round <= 7; round++) { + await go("/search"); + await search.waitFor(); + const start = performance.now(); + await go(projects); + await page + .locator(".project-group .task-row") + .first() + .waitFor({ timeout: 60_000 }); + await page.evaluate( + () => + new Promise((done) => + requestAnimationFrame(() => requestAnimationFrame(done)), + ), + ); + const ms = Math.round(performance.now() - start); + const rows = await page.locator(".project-group .task-row").count(); + if (round) samples.push({ ms, rows }); + } + const median = (key) => + samples.map((sample) => sample[key]).sort((a, b) => a - b)[3]; + console.log( + JSON.stringify( + { + chromium: browser.version(), + medianMs: median("ms"), + medianRows: median("rows"), + samples, + }, + null, + 2, + ), + ); +} finally { + await browser.close(); +} diff --git a/src/app/calendar-event-presentation.ts b/src/app/calendar-event-presentation.ts index 464cb2b9..28ca4e6c 100644 --- a/src/app/calendar-event-presentation.ts +++ b/src/app/calendar-event-presentation.ts @@ -14,7 +14,7 @@ export interface CalendarPriorityMarker { * completed work stays unmarked so titles keep the room. */ export function calendarPriorityMarker( - task: TaskSummary, + task: Pick, configuration: TaskCollectionConfiguration, ): CalendarPriorityMarker | undefined { if (task.completed || !task.priority || task.priority === "none") return; diff --git a/src/app/calendar-items.ts b/src/app/calendar-items.ts index d5731b5e..3a0d2c59 100644 --- a/src/app/calendar-items.ts +++ b/src/app/calendar-items.ts @@ -7,7 +7,7 @@ import { calendarItem, type CalendarEntry, } from "../domain/calendar-events"; -import { occurrenceTask, type TaskOccurrence } from "../domain/task-occurrence"; +import { type TaskOccurrence } from "../domain/task-occurrence"; import type { TaskCollectionConfiguration } from "../domain/task-configuration"; import type { TaskViewExecution } from "../domain/view"; import { @@ -114,9 +114,11 @@ export function calendarItems( const neutral = entry.modelEntry; if (seen.has(neutral.id)) continue; seen.add(neutral.id); - const displayed = entry.occurrence - ? occurrenceTask(entry.occurrence) - : entry.task; + const displayed = { + completed: entry.occurrence?.completed ?? entry.task.completed, + priority: entry.task.priority, + timezone: entry.task.timezone, + }; const tracked = neutral.type === "timeEntry"; const marker = tracked ? undefined @@ -172,7 +174,8 @@ export function calendarItems( details, ...(tracked ? { kind: "Tracked time" } - : neutral.type === "due" && displayed.scheduled + : neutral.type === "due" && + (entry.occurrence || entry.task.scheduled) ? { kind: "Due" } : {}), recurring: Boolean(neutral.recurringKind), diff --git a/src/app/keyboard-shortcuts.ts b/src/app/keyboard-shortcuts.ts index 7c73dbe0..05aa0877 100644 --- a/src/app/keyboard-shortcuts.ts +++ b/src/app/keyboard-shortcuts.ts @@ -1,3 +1,4 @@ +import { FOCUS_ADJACENT_TASK } from "../components/bounded-list"; import { t } from "@lingui/core/macro"; import { hasOpenOverlay } from "../components/overlays/overlay-stack"; import { todayString } from "../domain/task"; @@ -240,6 +241,17 @@ export function focusAdjacentTaskRow( const current = active?.closest(ROW_SELECTOR) ?? null; const region = current?.closest("#main-content, .detail-inspector") ?? main ?? document; + if ( + current && + !current.dispatchEvent( + new CustomEvent(FOCUS_ADJACENT_TASK, { + bubbles: true, + cancelable: true, + detail: direction, + }), + ) + ) + return true; const rows = taskRowsIn(region); if (!rows.length) return false; if (!current || !rows.includes(current)) { diff --git a/src/app/views/projects-view.tsx b/src/app/views/projects-view.tsx index 9532007f..29bb372e 100644 --- a/src/app/views/projects-view.tsx +++ b/src/app/views/projects-view.tsx @@ -3,13 +3,25 @@ import { t as translate } from "@lingui/core/macro"; import { useLingui, Trans } from "@lingui/react/macro"; import { countLabel } from "../../i18n/default-labels"; import { ChevronLeft, ChevronRight, Plus } from "lucide-react"; -import { useContext, useEffect, useEffectEvent, useId, useState } from "react"; +import { + useCallback, + useContext, + useEffect, + useEffectEvent, + useId, + useMemo, + useRef, + useState, +} from "react"; import { sectionCollapsed, saveSectionCollapsed, } from "../../application/section-preferences"; -import { BoundedList } from "../../components/bounded-list"; +import { + BoundedList, + type BoundedListHandle, +} from "../../components/bounded-list"; import { TaskRow } from "../../components/task-row"; import { TaskNotesSelect } from "../../components/tasknotes-controls"; import { @@ -33,9 +45,29 @@ import { import { projectLabel } from "../../domain/project-shortcuts"; import type { TaskSummary } from "../../domain/task"; -import type { TaskViewExecution } from "../../domain/view"; +import type { ViewProps } from "./view-props"; + +type Project = { + key: string; + label: string; + path?: string; + value: string; + tasks: TaskSummary[]; +}; + +type ProjectEntry = { + key: string; + project: Project; + headerIndex: number; + index: number; + task?: TaskSummary; +}; -const taskId = (task: TaskSummary) => task.id; +const projectHeadingKey = (key: string) => `heading:${key}`; +const entryKey = (entry: ProjectEntry) => entry.key; +const entryTaskId = (entry: ProjectEntry) => entry.task?.id; +const entryEstimate = (entry: ProjectEntry) => + entry.task ? 48 : entry.index ? 87 : 57; export function ProjectsView({ execution, @@ -46,105 +78,64 @@ export function ProjectsView({ onCreate, onOpen, onToggle, -}: { - execution: TaskViewExecution; +}: ViewProps & { sectionScope?: string; projectsField: string; linkWriteFormat: "wikilink" | "markdown"; tasks: readonly TaskSummary[]; onCreate(value: string, label: string): void; - onOpen(task: TaskSummary, occurrenceDate?: string): void; - onToggle(task: TaskSummary, occurrenceDate?: string): void; }) { const { t } = useLingui(); const id = useId(); + const list = useRef(null); const [collapsed, setCollapsed] = useState>({}); - const preferenceKey = (key: string) => - sectionScope - ? JSON.stringify([sectionScope, execution.view.key, "project", key]) - : undefined; + const preferenceKey = useCallback( + (key: string) => + sectionScope + ? JSON.stringify([sectionScope, execution.view.key, "project", key]) + : undefined, + [sectionScope, execution.view.key], + ); const collapse = (key: string, value: boolean) => { setCollapsed((current) => ({ ...current, [key]: value })); saveSectionCollapsed(preferenceKey(key), value); }; // A just-completed task stays in its project until its row has folded. const holds = useContext(TaskCompletionHoldsContext); - const departing = new Map( - tasks - .filter((task) => task.completed && holds.has(task.id)) - .map((task) => [task.id, holds.get(task.id) ?? null]), + const departing = useMemo( + () => + new Map( + tasks + .filter((task) => task.completed && holds.has(task.id)) + .map((task) => [task.id, holds.get(task.id) ?? null]), + ), + [tasks, holds], ); const activeTasks = useHeldOrder( - tasks.filter( - (task) => (!task.completed || departing.has(task.id)) && !task.archived, + useMemo( + () => + tasks.filter( + (task) => + (!task.completed || departing.has(task.id)) && !task.archived, + ), + [tasks, departing], ), departing.size > 0, ); - const records = indexProjectRecords( - (execution.records ?? []).map(({ record }) => record), + const ordered = useMemo( + () => + groupProjects( + activeTasks, + (execution.records ?? []).map(({ record }) => record), + projectsField, + linkWriteFormat, + ), + [activeTasks, execution.records, projectsField, linkWriteFormat], ); - const groups = new Map< - string, - { - label: string; - path?: string; - value: string; - tasks: Map; - } - >(); - - for (const task of activeTasks) { - const values = task.projects.length - ? task.projects - : listStrings(task.frontmatter[projectsField]); - for (const value of values) { - const target = linkTarget(value); - const normalizedTarget = target.toLocaleLowerCase(); - const matches = normalizedTarget.includes("/") - ? (records.byPath.get(normalizedTarget) ?? []) - : (records.byBasename.get(normalizedTarget) ?? []); - if (matches.length) { - for (const record of matches) { - const key = `record:${record.path.toLocaleLowerCase()}`; - const group = groups.get(key) ?? { - label: record.label, - path: record.path, - value: recordCompletion(record, linkWriteFormat).value, - tasks: new Map(), - }; - if (!group.tasks.has(task.id)) group.tasks.set(task.id, task); - groups.set(key, group); - } - continue; - } - const key = `link:${target.toLocaleLowerCase()}`; - const group = groups.get(key) ?? { - label: linkLabel(value) ?? target.split("/").at(-1) ?? value, - value, - tasks: new Map(), - }; - if (!group.tasks.has(task.id)) group.tasks.set(task.id, task); - groups.set(key, group); - } - } - - const ordered = [...groups.entries()] - .map(([key, project]) => { - const tasks = [...project.tasks.values()]; - return { - key, - ...project, - tasks, - count: departing.size - ? tasks.filter((task) => !departing.has(task.id)).length - : tasks.length, - }; - }) - .sort( - (left, right) => - left.label.localeCompare(right.label) || - (left.path ?? "").localeCompare(right.path ?? ""), - ); + const count = (project: Project) => + departing.size + ? project.tasks.filter((task) => !departing.has(task.id)).length + : project.tasks.length; const focusedLabel = useFocusedProject(); const findProject = (label: string | null) => label @@ -157,7 +148,64 @@ export function ProjectsView({ ) : undefined; const focused = findProject(focusedLabel); - const shown = focused ? [focused] : ordered; + const shown = useMemo( + () => (focused ? [focused] : ordered), + [focused, ordered], + ); + const expanded = useMemo( + () => + new Set( + shown + .filter( + ({ key }) => + !(collapsed[key] ?? sectionCollapsed(preferenceKey(key))), + ) + .map(({ key }) => key), + ), + [shown, collapsed, preferenceKey], + ); + const groupIds = useMemo( + () => new Map(ordered.map(({ key }, index) => [key, `${id}-${index}`])), + [id, ordered], + ); + const windowed = + shown.reduce((total, project) => total + project.tasks.length, 0) > 100; + const entries = useMemo(() => { + if (!windowed) return []; + const result: ProjectEntry[] = []; + for (const [index, project] of shown.entries()) { + const headerIndex = result.length; + result.push({ + key: projectHeadingKey(project.key), + project, + headerIndex, + index, + }); + if (!expanded.has(project.key)) continue; + for (const task of project.tasks) + result.push({ + key: JSON.stringify([project.key, task.id]), + project, + headerIndex, + index, + task, + }); + } + return result; + }, [expanded, shown, windowed]); + const relatedIndices = useCallback( + (index: number) => [entries[index].headerIndex], + [entries], + ); + const visibleTasks = useMemo( + () => + shown.flatMap((project) => + expanded.has(project.key) + ? project.tasks.filter((task) => !departing.has(task.id)) + : [], + ), + [departing, expanded, shown], + ); const focusProject = (label: string | null) => { const project = findProject(label); if (!project) return false; @@ -167,13 +215,20 @@ export function ProjectsView({ return true; }; const jumpTo = (label: string | null) => { - const index = ordered.findIndex((project) => project.label === label); - const project = ordered[index]; + const project = ordered.find((project) => project.label === label); if (!project) return; collapse(project.key, false); + if (list.current) { + list.current.reveal( + projectHeadingKey(project.key), + ".project-toggle", + "start", + ); + return; + } // The jump picker returns focus to itself after onChange, so wait a frame. requestAnimationFrame(() => { - const heading = document.getElementById(`${id}-${index}`); + const heading = document.getElementById(groupIds.get(project.key)!); heading?.querySelector("button")?.focus({ preventScroll: true }); heading?.scrollIntoView({ block: "start" }); }); @@ -206,14 +261,67 @@ export function ProjectsView({

); + const renderTask = (task: TaskSummary, project: Project) => ( + + onOpen( + target, + occurrence, + visibleTasks.map(({ id }) => ({ id })), + ) + } + onToggle={onToggle} + /> + ); + const renderHeading = ( + project: Project, + isExpanded: boolean, + listId: string, + ) => { + const taskCount = count(project); + return ( +
+
+

+ +

+ {project.path ? {project.path} : null} +
+ +
+ ); + }; + const listId = (key: string) => `${groupIds.get(key)}-tasks`; + return ( - - (collapsed[project.key] ?? sectionCollapsed(preferenceKey(project.key))) - ? [] - : project.tasks.filter((task) => !departing.has(task.id)), - )} - > +
{focused ? ( - - {project.path ? {project.path} : null} -
- - - - - ); - })} + {expanded.has(project.key) && + project.tasks.map((task) => renderTask(task, project))} + + + )) + )} +
); } +function groupProjects( + activeTasks: readonly TaskSummary[], + records: readonly CollectionRecord[], + projectsField: string, + linkWriteFormat: "wikilink" | "markdown", +): Project[] { + const projectRecords = indexProjectRecords(records); + const groups = new Map< + string, + { + label: string; + path?: string; + value: string; + tasks: Map; + } + >(); + + for (const task of activeTasks) { + const values = task.projects.length + ? task.projects + : listStrings(task.frontmatter[projectsField]); + for (const value of values) { + const target = linkTarget(value); + const normalizedTarget = target.toLocaleLowerCase(); + const matches = normalizedTarget.includes("/") + ? (projectRecords.byPath.get(normalizedTarget) ?? []) + : (projectRecords.byBasename.get(normalizedTarget) ?? []); + if (matches.length) { + for (const record of matches) { + const key = `record:${record.path.toLocaleLowerCase()}`; + const group = groups.get(key) ?? { + label: record.label, + path: record.path, + value: recordCompletion(record, linkWriteFormat).value, + tasks: new Map(), + }; + if (!group.tasks.has(task.id)) group.tasks.set(task.id, task); + groups.set(key, group); + } + continue; + } + const key = `link:${target.toLocaleLowerCase()}`; + const group = groups.get(key) ?? { + label: linkLabel(value) ?? target.split("/").at(-1) ?? value, + value, + tasks: new Map(), + }; + if (!group.tasks.has(task.id)) group.tasks.set(task.id, task); + groups.set(key, group); + } + } + + return [...groups.entries()] + .map(([key, project]) => ({ + ...project, + key, + tasks: [...project.tasks.values()], + })) + .sort( + (left, right) => + left.label.localeCompare(right.label) || + (left.path ?? "").localeCompare(right.path ?? ""), + ); +} + /** * Completing can move a task within the source list; while a completion is * held, tasks keep the order they were last shown in so the row stays put. diff --git a/src/components/bounded-list.tsx b/src/components/bounded-list.tsx index ff72442c..9e631c0e 100644 --- a/src/components/bounded-list.tsx +++ b/src/components/bounded-list.tsx @@ -6,13 +6,21 @@ import { import { useCallback, useEffect, + useImperativeHandle, useLayoutEffect, useMemo, useRef, useState, type ReactNode, + type Ref, } from "react"; +export const FOCUS_ADJACENT_TASK = "tasknotes:focus-adjacent-task"; + +export interface BoundedListHandle { + reveal(key: string, selector: string, block?: ScrollLogicalPosition): void; +} + const defaultEstimate = () => 84; // Mobile detail temporarily hides the mounted workspace. Zero is not a new row height. const measureVisibleRow: typeof measureElement = (element, entry, instance) => { @@ -36,6 +44,9 @@ export function BoundedList({ relatedIndices, taskId, className = "", + group, + navigateTasks = false, + ref, }: { items: readonly T[]; getKey(item: T): string; @@ -44,6 +55,12 @@ export function BoundedList({ relatedIndices?(index: number): number[]; className?: string; taskId?(item: T): string | undefined; + group?: { + key(item: T): string; + render(key: string, items: ReactNode[]): ReactNode; + }; + navigateTasks?: boolean; + ref?: Ref; }) { const root = useRef(null); const [scrollMargin, setScrollMargin] = useState(0); @@ -74,6 +91,8 @@ export function BoundedList({ [focusedIndex, relatedIndices], ); const virtualizer = useWindowVirtualizer({ + // Collapsing a group can change the scroll range during React layout. + useFlushSync: false, count: items.length, getItemKey: itemKey, estimateSize: itemEstimate, @@ -82,35 +101,89 @@ export function BoundedList({ scrollMargin, rangeExtractor, }); + const revealFrame = useRef(0); + const reveal = useCallback( + ( + index: number, + selector: string, + block: ScrollLogicalPosition = "nearest", + ) => { + cancelAnimationFrame(revealFrame.current); + const key = itemKey(index); + const wrapped = () => + root.current?.querySelector( + `[data-bounded-key="${CSS.escape(key)}"]`, + ); + if (!wrapped()) { + setFocusedKey(key); + virtualizer.scrollToIndex(index, { + align: block === "start" ? "start" : "auto", + }); + } + let attempts = 0; + const focus = () => { + const item = wrapped(); + const target = item?.querySelector(selector); + if (target && item) { + target.focus({ preventScroll: true }); + item.scrollIntoView({ block }); + } else if (++attempts < 10) { + revealFrame.current = requestAnimationFrame(focus); + } + }; + revealFrame.current = requestAnimationFrame(focus); + }, + [itemKey, virtualizer], + ); + useImperativeHandle( + ref, + () => ({ + reveal(key, selector, block) { + const index = indexByKey.get(key); + if (index !== undefined) reveal(index, selector, block); + }, + }), + [indexByKey, reveal], + ); + useEffect(() => () => cancelAnimationFrame(revealFrame.current), []); + useEffect(() => { + const list = root.current; const region = root.current?.closest("[data-task-selection-list]"); if (!region || !taskId) return; - let frame = 0; - const reveal = (event: Event) => { + const revealTask = (event: Event) => { const id = (event as CustomEvent).detail; const index = items.findIndex((item) => taskId(item) === id); if (index < 0) return; - // A task may belong to two project lists in this selection region. - // Only the first matching list should scroll and take keyboard focus. event.stopImmediatePropagation(); - virtualizer.scrollToIndex(index, { align: "auto" }); - // Scroll materializes the target; focus it after React measures the window. - let attempts = 0; - const focus = () => { - const title = root.current?.querySelector( - `.task-row[data-task-id="${CSS.escape(id)}"] .task-row-title`, - ); - if (title) title.focus({ preventScroll: true }); - else if (++attempts < 10) frame = requestAnimationFrame(focus); - }; - frame = requestAnimationFrame(focus); + reveal(index, ".task-row-title"); + }; + const focusAdjacent = (event: Event) => { + if (!(event.target instanceof Element)) return; + const item = event.target.closest("[data-bounded-key]"); + const key = item?.dataset.boundedKey; + const index = key === undefined ? undefined : indexByKey.get(key); + if (index === undefined) return; + event.preventDefault(); + const direction = (event as CustomEvent<1 | -1>).detail; + for ( + let next = index + direction; + next >= 0 && next < items.length; + next += direction + ) { + if (!taskId(items[next])) continue; + reveal(next, ".task-row-title"); + break; + } }; - region.addEventListener("tasknotes:reveal-task", reveal); + region.addEventListener("tasknotes:reveal-task", revealTask); + if (navigateTasks) + list?.addEventListener(FOCUS_ADJACENT_TASK, focusAdjacent); return () => { - region.removeEventListener("tasknotes:reveal-task", reveal); - cancelAnimationFrame(frame); + region.removeEventListener("tasknotes:reveal-task", revealTask); + list?.removeEventListener(FOCUS_ADJACENT_TASK, focusAdjacent); }; - }, [items, taskId, virtualizer]); + }, [indexByKey, items, navigateTasks, reveal, taskId]); useLayoutEffect(() => { const measure = () => { if (root.current?.getClientRects().length) @@ -146,29 +219,45 @@ export function BoundedList({ document.removeEventListener("pointerdown", focus); }; }, []); + const virtualItems = virtualizer.getVirtualItems(); + const renderVirtualItem = (item: (typeof virtualItems)[number]) => ( +
+ {renderItem(items[item.index], item.index)} +
+ ); + let content: ReactNode; + if (group) { + const mounted = new Map(); + for (const item of virtualItems) { + const key = group.key(items[item.index]); + const children = mounted.get(key) ?? []; + children.push(renderVirtualItem(item)); + mounted.set(key, children); + } + content = [...mounted].map(([key, children]) => + group.render(key, children), + ); + } else content = virtualItems.map(renderVirtualItem); + return (
- {virtualizer.getVirtualItems().map((item) => ( -
- {renderItem(items[item.index], item.index)} -
- ))} + {content}
); } diff --git a/src/domain/task-occurrence.ts b/src/domain/task-occurrence.ts index 005a3da2..1800b3d8 100644 --- a/src/domain/task-occurrence.ts +++ b/src/domain/task-occurrence.ts @@ -1,5 +1,6 @@ import { generateRecurringInstances } from "@tasknotes/model/recurrence"; import { normalizeTaskReference } from "@tasknotes/model/operations"; +import { shiftTaskDate } from "./task-date-actions"; import { parseRecurrenceRule, recurrenceStartStorageValue, @@ -256,6 +257,43 @@ export function projectUpcomingTasks( }; } +/** Find the first upcoming entry when the caller only needs one suggestion. */ +export function nextUpcomingTask( + tasks: readonly TaskSummary[], + today: string, + recurrenceEnd: string, + materialized: ReadonlySet, +): TaskOccurrenceEntry | undefined { + const tomorrow = shiftTaskDate(today, 1); + let next: TaskOccurrenceEntry | undefined; + let repeatThrough = recurrenceEnd; + for (const task of tasks) { + if (task.recurrence) { + for (const date of recurringDatesBetween(task, tomorrow, repeatThrough)) { + const occurrence = taskOccurrenceForDate(task, date); + if ( + occurrence.completed || + occurrence.skipped || + materialized.has(occurrence.key) + ) + continue; + next = { key: occurrence.key, task, occurrence, date }; + break; + } + } else if (!task.completed && !task.skipped && !task.archived) { + const date = taskDatePart(task.scheduled ?? task.due, task.timezone); + if (date > today && (!next || date < next.date)) + next = { key: task.id, task, date }; + } + // Same-day ties keep the first task in source order. The repeating-task + // horizon still applies when the earliest dated task is beyond it. + if (next?.date === tomorrow) break; + if (next && next.date <= repeatThrough) + repeatThrough = shiftTaskDate(next.date, -1); + } + return next; +} + export function findOccurrenceParent( tasks: readonly TaskSummary[], occurrence: Pick, diff --git a/src/domain/today-summary.test.ts b/src/domain/today-summary.test.ts index b78dbf92..5d9df942 100644 --- a/src/domain/today-summary.test.ts +++ b/src/domain/today-summary.test.ts @@ -71,6 +71,53 @@ describe("summarizeToday", () => { expect([next?.task.id, next?.date]).toEqual(["weekly", "2026-07-29"]); expect(summarizeToday([finished], today).next).toBeUndefined(); }); + it("keeps source order on ties and ignores handled repeat dates", () => { + const series = task("series", { + completed: false, + recurrence: "FREQ=DAILY", + scheduled: today, + completeInstances: ["2026-07-27"], + skippedInstances: ["2026-07-28"], + }); + const materialized = task("materialized", { + recurrenceParent: "[[tasks/series]]", + occurrenceDate: "2026-07-29", + completed: true, + scheduled: "2026-07-29", + }); + const sameDay = task("same-day", { + completed: false, + scheduled: "2026-07-30", + }); + expect( + summarizeToday([series, materialized, sameDay], today).next, + ).toMatchObject({ + task: { id: "series" }, + date: "2026-07-30", + }); + expect( + summarizeToday([sameDay, series, materialized], today).next, + ).toMatchObject({ + task: { id: "same-day" }, + date: "2026-07-30", + }); + }); + + it("still suggests a dated task beyond the repeat horizon", () => { + const series = task("future-series", { + completed: false, + recurrence: "DTSTART:20261111;FREQ=DAILY", + scheduled: "2026-11-11", + }); + const dated = task("future-task", { + completed: false, + due: "2026-11-12", + }); + expect(summarizeToday([series, dated], today).next).toMatchObject({ + task: { id: "future-task" }, + date: "2026-11-12", + }); + }); }); function task(id: string, patch: Partial = {}): TaskSummary { diff --git a/src/domain/today-summary.ts b/src/domain/today-summary.ts index 29c565f3..fe3d157d 100644 --- a/src/domain/today-summary.ts +++ b/src/domain/today-summary.ts @@ -8,7 +8,7 @@ import { } from "./task"; import { materializedOccurrenceKeys, - projectUpcomingTasks, + nextUpcomingTask, type TaskOccurrenceEntry, } from "./task-occurrence"; @@ -52,13 +52,12 @@ export function summarizeToday( ) completedToday += 1; } - const next = projectUpcomingTasks( + const next = nextUpcomingTask( active, today, shiftTaskDate(today, NEXT_HORIZON_DAYS), - 1, materialized, - ).groups[0]?.tasks[0]; + ); return { completedToday, ...(next ? { next } : {}) }; } diff --git a/src/domain/view-values.ts b/src/domain/view-values.ts index 1e417903..b55e33f6 100644 --- a/src/domain/view-values.ts +++ b/src/domain/view-values.ts @@ -66,6 +66,7 @@ export function viewPropertyDetails( labelFor?: typeof propertyLabel; } = {}, ): ViewPropertyDetail[] | undefined { + const displayed = occurrence ? occurrenceTask(occurrence) : row.task; return resolvedViewProperties(properties).flatMap((property) => { if ( property.hidden || @@ -74,11 +75,16 @@ export function viewPropertyDetails( ) return []; const field = notePropertyName(property.key) ?? property.key; - const displayed = occurrence ? occurrenceTask(occurrence) : row.task; const projectedValue = !properties.length && field in displayed ? displayed[field as keyof TaskSummary] - : viewPropertyValue(row, property.key, occurrence); + : rowPropertyValue( + row, + property.key, + field, + displayed, + Boolean(occurrence), + ); const value = isViewValueDiagnostic(projectedValue) && projectedValue.kind === "unavailable" && @@ -119,8 +125,23 @@ export function viewPropertyValue( occurrence?: TaskOccurrence, ): unknown { const displayed = occurrence ? occurrenceTask(occurrence) : row.task; - const field = notePropertyName(key) ?? key; - if (occurrence && Object.prototype.hasOwnProperty.call(displayed, field)) + return rowPropertyValue( + row, + key, + notePropertyName(key) ?? key, + displayed, + Boolean(occurrence), + ); +} + +function rowPropertyValue( + row: TaskViewRow, + key: string, + field: string, + displayed: TaskSummary, + isOccurrence: boolean, +): unknown { + if (isOccurrence && Object.prototype.hasOwnProperty.call(displayed, field)) return displayed[field as keyof TaskSummary]; if (Object.prototype.hasOwnProperty.call(row.values, key)) return row.values[key]; diff --git a/src/styles/03-task-rows.css b/src/styles/03-task-rows.css index 23da3fc0..1824ef0e 100644 --- a/src/styles/03-task-rows.css +++ b/src/styles/03-task-rows.css @@ -20,6 +20,7 @@ .task-list-view, .full-calendar-day-tasks, .search-results, + .project-window, .project-group { overflow-x: clip; } diff --git a/src/styles/10-lists-and-boards.css b/src/styles/10-lists-and-boards.css index cfe74797..4bed958b 100644 --- a/src/styles/10-lists-and-boards.css +++ b/src/styles/10-lists-and-boards.css @@ -203,13 +203,13 @@ .projects-view.is-focused { gap: 8px; } -.projects-view.is-focused .project-group > header h2 { +.projects-view.is-focused .project-group-header h2 { font-size: var(--type-section); } .projects-view.is-focused .project-toggle { cursor: default; } -.project-group > header .project-toggle { +.project-group-header .project-toggle { color: var(--ink); font: inherit; text-align: left; @@ -242,7 +242,7 @@ overflow-wrap: anywhere; } -.project-group > header { +.project-group-header { display: flex; flex-wrap: wrap; align-items: end; @@ -252,12 +252,12 @@ padding-bottom: 9px; } -.project-group > header h2 { +.project-group-header h2 { margin: 0; font-size: var(--type-control); } -.project-group > header small { +.project-group-header small { display: block; margin-top: 2px; overflow-wrap: anywhere; @@ -266,7 +266,7 @@ font-size: var(--type-label); } -.project-group > header button { +.project-group-header button { display: inline-flex; align-items: center; gap: 6px; @@ -279,6 +279,14 @@ cursor: pointer; } +.project-window-heading { + padding-top: 30px; +} + +.project-window .project-group-header[data-expanded="true"] { + border-bottom: 1px solid var(--line); +} + .saved-view-groups { padding-top: 0; } diff --git a/src/styles/11-calendar.css b/src/styles/11-calendar.css index 7d84208f..7c4c6f80 100644 --- a/src/styles/11-calendar.css +++ b/src/styles/11-calendar.css @@ -127,7 +127,7 @@ .full-calendar-navigation button:last-child { display: grid; place-items: center; - width: 44px; + min-width: 44px; padding: 0; } diff --git a/src/test/demo-entry-fixture.tsx b/src/test/demo-entry-fixture.tsx index b4d3e13e..f70c280b 100644 --- a/src/test/demo-entry-fixture.tsx +++ b/src/test/demo-entry-fixture.tsx @@ -11,6 +11,24 @@ const largeCollection: DemoSeed = { scratchpads: () => [], }; +const manyProjects: DemoSeed = { + tasks: (model) => { + const now = new Date().toISOString(); + return Array.from({ length: 10_000 }, (_, index) => { + const project = String(Math.floor(index / 80) + 1).padStart(3, "0"); + const number = String((index % 80) + 1).padStart(2, "0"); + return model.create( + { + title: `Task ${project}-${number}`, + projects: [`[[Projects/Project ${project}]]`], + }, + { id: `project-task-${index}`, now }, + ); + }); + }, + scratchpads: () => [], +}; + /** Original demo semantics, retained solely for local browser assertions. * This entry is unreachable and omitted outside the exact e2e build mode; * none of its behavior qualifies native source writes or model readiness. @@ -30,7 +48,9 @@ export function DemoEntryFixture() { ? storeDemoSeed : demo === "10000" ? largeCollection - : undefined; + : demo === "projects-scale" + ? manyProjects + : undefined; const count = seed ? 1 : Number(demo); const many = new URL(location.href).searchParams.has("many-options"); return count > 0 ? (