diff --git a/docs/releases/unreleased.md b/docs/releases/unreleased.md index c3602f625..f3b3958c6 100644 --- a/docs/releases/unreleased.md +++ b/docs/releases/unreleased.md @@ -16,6 +16,7 @@ Example: ``` ## Fixed +- (#2712) Made the Task Edit modal and the task card inside a note follow the sort configured in the Relationships Base’s Subtasks view. Thanks to @Glint-Eye for reporting. - (#768) Fixed calendar view appearing empty in week and day views due to invalid time configuration values - Added time validation in settings UI with proper error messages and debouncing - Prevents "Cannot read properties of null (reading 'years')" error from FullCalendar diff --git a/e2e/issues/issue-2712-subtask-view-sort.spec.ts b/e2e/issues/issue-2712-subtask-view-sort.spec.ts new file mode 100644 index 000000000..f176a3bad --- /dev/null +++ b/e2e/issues/issue-2712-subtask-view-sort.spec.ts @@ -0,0 +1,153 @@ +import { expect, test } from "@playwright/test"; +import { closeObsidian, launchObsidian, type ObsidianApp } from "../obsidian"; + +let instance: ObsidianApp; +let originalRelationshipsPath: string; +const folder = `E2E issue 2712 ${Date.now()}`; +const parentPath = `${folder}/Parent.md`; +const basePath = `${folder}/relationships.base`; +const children = [ + ["Alpha", 10], + ["Bravo", 30], + ["Charlie", 30], +] as const; + +function relationshipsBase(sort: boolean): string { + return [ + "formulas:", + " score: if(this.rank == 2, number(rank), -number(rank))", + "views:", + " - type: table", + " name: Projects", + " filters: 'false'", + " sort:", + " - property: file.name", + " direction: ASC", + " - type: table", + " name: Subtasks", + " filters: list(note.projects).contains(this.file.asLink()) && rank > 10", + " limit: 1", + ...(sort + ? [ + " sort:", + " - property: formula.score", + " direction: DESC", + " - column: file.name", + " direction: DESC", + ] + : []), + "", + ].join("\n"); +} + +const paths = (...titles: string[]) => titles.map((title) => `${folder}/${title}.md`); +const configuredOrder = paths("Charlie", "Bravo", "Alpha"); +const defaultOrder = paths("Alpha", "Bravo", "Charlie"); + +test.beforeAll(async () => { + instance = await launchObsidian(); + originalRelationshipsPath = await instance.page.evaluate(async (fixture) => { + const app = (window as any).app; + const plugin = app.plugins.getPlugin("tasknotes"); + await app.vault.createFolder(fixture.folder); + for (const [title, rank] of [["Parent", 2], ...fixture.children]) { + await app.vault.create(`${fixture.folder}/${title}.md`, [ + "---", + `title: ${title}`, + "status: open", + "priority: normal", + `rank: ${rank}`, + `tags: [${JSON.stringify(plugin.settings.taskTag)}]`, + ...(title === "Parent" ? [] : [`projects: ["[[${fixture.folder}/Parent]]"]`]), + "---", + "", + "Subtask sorting fixture.", + ].join("\n")); + } + await app.vault.create(fixture.basePath, fixture.base); + const previous = plugin.settings.commandFileMapping.relationships; + plugin.settings.commandFileMapping.relationships = fixture.basePath; + return previous; + }, { folder, basePath, children, base: relationshipsBase(true) }); + + await expect.poll(() => instance.page.evaluate(async ({ parentPath }) => { + const app = (window as any).app; + const plugin = app.plugins.getPlugin("tasknotes"); + return (await plugin.projectSubtasksService.getTasksLinkedToProject( + app.vault.getAbstractFileByPath(parentPath) + )).length; + }, { parentPath })).toBe(children.length); +}); + +test.afterAll(async () => { + if (!instance) return; + try { + await instance.page.evaluate(async ({ folder, originalRelationshipsPath }) => { + const app = (window as any).app; + const plugin = app.plugins.getPlugin("tasknotes"); + plugin.settings.commandFileMapping.relationships = originalRelationshipsPath; + for (const leaf of app.workspace.getLeavesOfType("markdown")) { + if (leaf.view.file?.path.startsWith(`${folder}/`)) leaf.detach(); + } + const fixture = app.vault.getAbstractFileByPath(folder); + if (fixture) await app.vault.delete(fixture, true); + }, { folder, originalRelationshipsPath }); + } finally { + await closeObsidian(instance); + } +}); + +test("the Task Edit modal uses the configured Subtasks view sort and falls back when it is removed", async () => { + const openModal = () => instance.page.evaluate(async (path) => { + const plugin = (window as any).app.plugins.getPlugin("tasknotes"); + await plugin.openTaskEditModal(await plugin.cacheManager.getTaskInfo(path)); + }, parentPath); + const rows = instance.page.locator(".modal .task-project-card-host .task-card"); + const rowPaths = () => rows.evaluateAll((cards) => cards.map((card) => card.getAttribute("data-task-path"))); + + await openModal(); + await expect.poll(rowPaths).toEqual(configuredOrder); + await instance.page.keyboard.press("Escape"); + await expect(rows).toHaveCount(0); + + await instance.page.evaluate(async ({ basePath, base }) => { + const app = (window as any).app; + await app.vault.modify(app.vault.getAbstractFileByPath(basePath), base); + }, { basePath, base: relationshipsBase(false) }); + try { + await openModal(); + await expect.poll(rowPaths).toEqual(defaultOrder); + } finally { + await instance.page.keyboard.press("Escape"); + await instance.page.evaluate(async ({ basePath, base }) => { + const app = (window as any).app; + await app.vault.modify(app.vault.getAbstractFileByPath(basePath), base); + }, { basePath, base: relationshipsBase(true) }); + } +}); + +for (const [mode, label, viewClass] of [ + ["preview", "Reading view", "markdown-preview-view"], + ["source", "Live Preview", "markdown-source-view"], +]) { + test(`the standalone task card in ${label} uses the configured Subtasks view sort`, async () => { + await instance.page.evaluate(async ({ path, mode }) => { + const app = (window as any).app; + const leaf = app.workspace.getLeaf("tab"); + await leaf.openFile(app.vault.getAbstractFileByPath(path), { state: { mode, source: false } }); + app.workspace.setActiveLeaf(leaf, { focus: true }); + }, { path: parentPath, mode }); + + const parent = instance.page.locator( + `.workspace-leaf.mod-active .${viewClass} .task-card-note-widget__card[data-task-path="${parentPath}"]` + ); + const expand = parent.getByRole("button", { name: "Expand subtasks", exact: true }); + await expect(expand).toBeVisible(); + await expand.click(); + const rows = parent.locator(".task-card__subtasks > .task-card"); + await expect.poll(() => rows.evaluateAll( + (cards) => cards.map((card) => card.getAttribute("data-task-path")) + )).toEqual(configuredOrder); + await parent.getByRole("button", { name: "Collapse subtasks", exact: true }).click(); + }); +} diff --git a/src/bases/relationshipSubtaskSort.ts b/src/bases/relationshipSubtaskSort.ts new file mode 100644 index 000000000..373822d54 --- /dev/null +++ b/src/bases/relationshipSubtaskSort.ts @@ -0,0 +1,71 @@ +import { + BasesEntry, + BasesQueryResult, + type App, + type BasesPropertyId, + type BasesViewConfig, + type TFile, +} from "obsidian"; +import { getSubtasksViewName } from "../templates/defaultBasesFiles"; + +type SubtaskViewConfig = Pick; + +interface SubtaskSortQuery { + getViewConfig(name: string): SubtaskViewConfig | null; +} + +interface BasesEmbed { + loadQuery(): Promise; + controller: { + query: SubtaskSortQuery; + buildBasesContext(): unknown; + }; +} + +interface BasesEmbedRegistry { + getEmbedCreator(file: TFile): (( + context: { app: App; containerEl: HTMLElement; sourcePath: string; linktext: string }, + file: TFile + ) => BasesEmbed) | null; +} + +// Obsidian exposes the result and entry types but keeps creation of a query +// context (including formulas and the parent note's `this`) inside the embed. +const QueryEntry = BasesEntry as unknown as new (context: unknown, file: TFile) => BasesEntry; +const SortedQueryResult = BasesQueryResult as unknown as new ( + app: App, + config: SubtaskViewConfig & { getLimit(): number }, + properties: BasesPropertyId[], + entries: BasesEntry[] +) => BasesQueryResult; + +export async function sortSubtaskFilesByRelationshipsView( + app: App, + base: TFile, + parent: TFile, + subtasks: TFile[] +): Promise { + const { embedRegistry } = app as unknown as { embedRegistry?: BasesEmbedRegistry }; + const createEmbed = embedRegistry?.getEmbedCreator?.(base); + if (!createEmbed) return; + + // Keep the embed unloaded. The sort applies only to the known subtasks, so + // there is no need to render a view, scan the vault or apply its filters. + const containerEl = activeWindow.createDiv(); + const embed = createEmbed({ app, containerEl, sourcePath: parent.path, linktext: base.path }, base); + const query = await embed.loadQuery(); + const view = query.getViewConfig(getSubtasksViewName()) ?? query.getViewConfig("Subtasks"); + const sort = view?.getSort(); + if (!sort?.length) return; + + embed.controller.query = query; + const context = embed.controller.buildBasesContext(); + const entries = subtasks.map((file) => new QueryEntry(context, file)); + const result = new SortedQueryResult( + app, + { getSort: () => sort, getLimit: () => 0 }, + sort.map(({ property }) => property), + entries + ); + return result.data.map((entry) => entry.file.path); +} diff --git a/src/editor/TaskCardNoteDecorations.ts b/src/editor/TaskCardNoteDecorations.ts index 93afa5f49..1ce13fb8c 100644 --- a/src/editor/TaskCardNoteDecorations.ts +++ b/src/editor/TaskCardNoteDecorations.ts @@ -122,7 +122,9 @@ function createTaskCardWidget(plugin: TaskNotesPlugin, task: TaskInfo): HTMLElem : undefined; // Create the task card - const taskCard = createTaskCard(task, plugin, visibleProperties); + const taskCard = createTaskCard(task, plugin, visibleProperties, { + useRelationshipsSubtaskSort: true, + }); // Add specific styling for the note widget taskCard.classList.add("task-card-note-widget__card"); diff --git a/src/modals/TaskEditModal.ts b/src/modals/TaskEditModal.ts index a9a0d04d1..1c5b8500b 100644 --- a/src/modals/TaskEditModal.ts +++ b/src/modals/TaskEditModal.ts @@ -633,7 +633,10 @@ export class TaskEditModal extends TaskModal { const subtasks = await this.plugin.projectSubtasksService.getTasksLinkedToProject(taskFile); - const sortedSubtasks = this.plugin.projectSubtasksService.sortTasks([...subtasks]); + const sortedSubtasks = await this.plugin.projectSubtasksService.sortTasksByRelationshipsView( + taskFile, + subtasks + ); this.selectedSubtaskFiles = []; this.initialSubtaskFiles = []; diff --git a/src/services/ProjectSubtasksService.ts b/src/services/ProjectSubtasksService.ts index fa50c7059..58237d3fc 100644 --- a/src/services/ProjectSubtasksService.ts +++ b/src/services/ProjectSubtasksService.ts @@ -1,5 +1,6 @@ /* eslint-disable @typescript-eslint/no-non-null-assertion -- Project graph construction validates parent links before dereferencing. */ import { EventRef, TFile } from "obsidian"; +import { sortSubtaskFilesByRelationshipsView } from "../bases/relationshipSubtaskSort"; import TaskNotesPlugin from "../main"; import { TaskInfo } from "../types"; import { parseLinkToPath } from "../utils/linkUtils"; @@ -283,9 +284,35 @@ export class ProjectSubtasksService { }; } - /** - * Sort tasks by priority and status - */ + async sortTasksByRelationshipsView(parent: TFile, tasks: TaskInfo[]): Promise { + const fallback = this.sortTasks([...tasks]); + if (fallback.length < 2) return fallback; + + const path = this.plugin.settings?.commandFileMapping?.relationships; + if (!path) return fallback; + const base = this.plugin.app.vault.getFileByPath(path); + if (base?.extension !== "base") return fallback; + + const tasksByPath = new Map(fallback.map((task) => [task.path, task])); + const files = fallback.map((task) => this.plugin.app.vault.getFileByPath(task.path)); + if (!files.every((file): file is TFile => file instanceof TFile)) return fallback; + + try { + const paths = await sortSubtaskFilesByRelationshipsView( + this.plugin.app, + base, + parent, + files + ); + const sorted = paths?.map((path) => tasksByPath.get(path)); + return sorted?.every((task): task is TaskInfo => task !== undefined) ? sorted : fallback; + } catch { + // The configured Base may be invalid or the host's embed API unavailable. + return fallback; + } + } + + /** Sort by completion, priority, due date and title. */ sortTasks(tasks: TaskInfo[]): TaskInfo[] { return tasks.sort((a, b) => { // First sort by completion status (incomplete first) diff --git a/src/templates/defaultBasesFiles.ts b/src/templates/defaultBasesFiles.ts index d903aed74..8e6dfdf56 100644 --- a/src/templates/defaultBasesFiles.ts +++ b/src/templates/defaultBasesFiles.ts @@ -25,6 +25,10 @@ import { isPropertyPresenceTaskIdentification, } from "../utils/taskIdentification"; +export function getSubtasksViewName(): string { + return uiText(msg({ message: "Subtasks", context: "generated Bases view name" })); +} + function escapeBasesStringLiteral(value: string): string { return value .replace(/\\/g, "\\\\") @@ -1108,7 +1112,7 @@ ${formulasSection} views: - type: tasknotesKanban - name: ${JSON.stringify(uiText(msg({ message: "Subtasks", context: "generated Bases view name" })))} + name: ${JSON.stringify(getSubtasksViewName())} filters: and: ${taskRelationshipFilterYaml} diff --git a/src/ui/TaskCard.ts b/src/ui/TaskCard.ts index 4d0fce241..bc47f8bc5 100644 --- a/src/ui/TaskCard.ts +++ b/src/ui/TaskCard.ts @@ -58,6 +58,8 @@ export interface TaskCardOptions { navigationSubpath?: string; /** How expanded subtasks/dependencies should interact with the current view filter. */ expandedRelationshipFilterMode?: "inherit" | "show-all"; + /** Use the configured Relationships Subtasks view order for standalone note cards. */ + useRelationshipsSubtaskSort?: boolean; /** Optional live resolver for the current expanded relationship filter mode. */ resolveExpandedRelationshipFilterMode?: () => "inherit" | "show-all"; /** Paths visible in the current view after Bases/search filtering. */ diff --git a/src/ui/taskCardRelationshipExpansion.ts b/src/ui/taskCardRelationshipExpansion.ts index 4ee78af68..9a3d74bf7 100644 --- a/src/ui/taskCardRelationshipExpansion.ts +++ b/src/ui/taskCardRelationshipExpansion.ts @@ -183,21 +183,20 @@ export async function toggleSubtasksExpansion( relationshipOptions ); - loadingEl.remove(); - if (subtasks.length === 0) { - container.createDiv({ - cls: "task-card__subtasks-loading", - text: plugin.i18n.translate(msg({ message: "No subtasks found", context: "contextMenus.task.subtasks.noSubtasks" })), - }); + loadingEl.textContent = plugin.i18n.translate(msg({ message: "No subtasks found", context: "contextMenus.task.subtasks.noSubtasks" })); return; } - const sortedSubtasks = sortExpandedRelationshipTasks( - subtasks, - relationshipOptions, - (tasks) => plugin.projectSubtasksService.sortTasks(tasks) - ); + const sortedSubtasks = relationshipOptions.useRelationshipsSubtaskSort + ? await plugin.projectSubtasksService.sortTasksByRelationshipsView(file, subtasks) + : sortExpandedRelationshipTasks( + subtasks, + relationshipOptions, + (tasks) => plugin.projectSubtasksService.sortTasks(tasks) + ); + if (loadingEl.parentElement !== container || container.parentElement !== card) return; + loadingEl.remove(); const parentChain = buildParentTaskChain(card); for (const subtask of sortedSubtasks) { diff --git a/src/ui/taskCardRelationships.ts b/src/ui/taskCardRelationships.ts index 26b0fc9c7..2510a567f 100644 --- a/src/ui/taskCardRelationships.ts +++ b/src/ui/taskCardRelationships.ts @@ -6,6 +6,7 @@ import { stringifyUnknown } from "../utils/stringUtils"; export type ExpandedRelationshipFilterMode = "inherit" | "show-all"; export interface TaskCardRelationshipOptions { + useRelationshipsSubtaskSort?: boolean; expandedRelationshipFilterMode?: ExpandedRelationshipFilterMode; resolveExpandedRelationshipFilterMode?: () => ExpandedRelationshipFilterMode; expandedRelationshipTaskPaths?: ReadonlySet; diff --git a/tests/unit/issues/issue-2081-reading-mode-widget-stability.test.ts b/tests/unit/issues/issue-2081-reading-mode-widget-stability.test.ts index ff2e19b85..337683037 100644 --- a/tests/unit/issues/issue-2081-reading-mode-widget-stability.test.ts +++ b/tests/unit/issues/issue-2081-reading-mode-widget-stability.test.ts @@ -247,7 +247,8 @@ describe("Issue #2081: reading mode note widgets stay mounted", () => { expect(createTaskCard).toHaveBeenCalledWith( expect.objectContaining({ title: "Updated task", status: "done" }), pluginMock.plugin, - expect.any(Array) + expect.any(Array), + { useRelationshipsSubtaskSort: true } ); } finally { cleanup();