Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/releases/unreleased.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
153 changes: 153 additions & 0 deletions e2e/issues/issue-2712-subtask-view-sort.spec.ts
Original file line number Diff line number Diff line change
@@ -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();
});
}
71 changes: 71 additions & 0 deletions src/bases/relationshipSubtaskSort.ts
Original file line number Diff line number Diff line change
@@ -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<BasesViewConfig, "getSort">;

interface SubtaskSortQuery {
getViewConfig(name: string): SubtaskViewConfig | null;
}

interface BasesEmbed {
loadQuery(): Promise<SubtaskSortQuery>;
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<string[] | undefined> {
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);
}
4 changes: 3 additions & 1 deletion src/editor/TaskCardNoteDecorations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
5 changes: 4 additions & 1 deletion src/modals/TaskEditModal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [];

Expand Down
33 changes: 30 additions & 3 deletions src/services/ProjectSubtasksService.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -283,9 +284,35 @@ export class ProjectSubtasksService {
};
}

/**
* Sort tasks by priority and status
*/
async sortTasksByRelationshipsView(parent: TFile, tasks: TaskInfo[]): Promise<TaskInfo[]> {
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)
Expand Down
6 changes: 5 additions & 1 deletion src/templates/defaultBasesFiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, "\\\\")
Expand Down Expand Up @@ -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}
Expand Down
2 changes: 2 additions & 0 deletions src/ui/TaskCard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down
21 changes: 10 additions & 11 deletions src/ui/taskCardRelationshipExpansion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
1 change: 1 addition & 0 deletions src/ui/taskCardRelationships.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Loading