${points}`;
+fs.writeFileSync(path.join(output,'layout.html'),html);
+console.log('Layout fixture ready:',path.join(output,'layout.html'));
diff --git a/scripts/check-habits-i18n.cjs b/scripts/check-habits-i18n.cjs
new file mode 100644
index 000000000..2e2a91010
--- /dev/null
+++ b/scripts/check-habits-i18n.cjs
@@ -0,0 +1,40 @@
+const fs = require('node:fs');
+const path = require('node:path');
+const ts = require('typescript');
+const base = 'src/integrations/habits';
+const sources = [];
+function discover(dir) {
+ for (const name of fs.readdirSync(dir)) {
+ const file = path.join(dir, name);
+ if (fs.statSync(file).isDirectory()) { if (name !== 'i18n') discover(file); }
+ else if (name.endsWith('.ts')) sources.push(file);
+ }
+}
+discover(base);
+sources.push('src/components/features/habit/habit.ts', 'src/components/features/settings/tabs/HabitSettingsTab.ts');
+const keys = new Set();
+for (const file of sources) {
+ const tree = ts.createSourceFile(file, fs.readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true);
+ const visitCall = node => {
+ if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && (path.resolve(file).startsWith(path.resolve(base)) ? ['t', 'ht'] : ['ht']).includes(node.expression.text)
+ && node.arguments[0] && ts.isStringLiteralLike(node.arguments[0])) keys.add(node.arguments[0].text);
+ ts.forEachChild(node, visitCall);
+ };
+ visitCall(tree);
+}
+const tree = ts.createSourceFile('zh.ts', fs.readFileSync(`${base}/i18n/zh.ts`, 'utf8'), ts.ScriptTarget.Latest, true);
+const dictionary = new Map();
+const visitProperty = node => {
+ if (ts.isPropertyAssignment(node) && (ts.isStringLiteralLike(node.name) || ts.isIdentifier(node.name)) && ts.isStringLiteralLike(node.initializer)) {
+ dictionary.set(node.name.text, node.initializer.text);
+ }
+ ts.forEachChild(node, visitProperty);
+};
+visitProperty(tree);
+const missing = [...keys].filter(key => !dictionary.has(key));
+const placeholders = text => [...text.matchAll(/\{\w+\}/g)].map(match => match[0]).sort().join(',');
+const invalid = [...keys].filter(key => dictionary.has(key) && placeholders(key) !== placeholders(dictionary.get(key)));
+if (missing.length || invalid.length) {
+ console.error(JSON.stringify({missing, invalid}, null, 2));
+ process.exitCode = 1;
+} else console.log(`Habits: ${keys.size} English/Chinese strings and placeholders verified.`);
diff --git a/scripts/check-release-version.cjs b/scripts/check-release-version.cjs
new file mode 100644
index 000000000..c13f55df2
--- /dev/null
+++ b/scripts/check-release-version.cjs
@@ -0,0 +1,8 @@
+const fs = require("fs");
+const pkg = JSON.parse(fs.readFileSync("package.json", "utf8"));
+const manifest = JSON.parse(fs.readFileSync("manifest.json", "utf8"));
+const versions = JSON.parse(fs.readFileSync("versions.json", "utf8"));
+const expected = process.argv[2];
+if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(manifest.version) || pkg.version !== manifest.version || versions[manifest.version] !== manifest.minAppVersion || (expected && expected !== manifest.version)) {
+ console.error("Release version mismatch: package.json, manifest.json, versions.json and the release tag must agree."); process.exitCode = 1;
+} else console.log("Release files agree on version " + manifest.version);
diff --git a/scripts/check-settings-i18n.cjs b/scripts/check-settings-i18n.cjs
new file mode 100644
index 000000000..5fa995511
--- /dev/null
+++ b/scripts/check-settings-i18n.cjs
@@ -0,0 +1,33 @@
+const fs = require("fs");
+const path = require("path");
+const ts = require("typescript");
+const vm = require("vm");
+
+function locale(name) {
+ const filename = path.join("src/translations/locale", name + ".ts");
+ const js = ts.transpileModule(fs.readFileSync(filename, "utf8"), { compilerOptions: { module: ts.ModuleKind.CommonJS } }).outputText;
+ const context = { exports: {} }; vm.runInNewContext(js, context); return context.exports.default;
+}
+function settingsKeys() {
+ const keys = new Set(JSON.parse(fs.readFileSync("scripts/settings-i18n-keys.json", "utf8")));
+ function visitFile(filename) {
+ const source = ts.createSourceFile(filename, fs.readFileSync(filename, "utf8"), ts.ScriptTarget.Latest, true);
+ function visit(node) {
+ if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && ["t", "settingsText"].includes(node.expression.text) && node.arguments[0] && ts.isStringLiteralLike(node.arguments[0])) keys.add(node.arguments[0].text);
+ ts.forEachChild(node, visit);
+ } visit(source);
+ }
+ function directory(folder) { for (const entry of fs.readdirSync(folder, { withFileTypes: true })) { const file = path.join(folder, entry.name); if (entry.isDirectory()) directory(file); else if (/\.tsx?$/.test(file)) visitFile(file); } }
+ directory("src/components/features/settings"); visitFile("src/setting.ts"); return [...keys];
+}
+const en = locale("en"), zh = locale("zh-cn"), keys = settingsKeys();
+const tokens = text => (text.match(/\{\{[^{}]+\}\}|\{[A-Za-z_][\w]*\}/g) || []).sort().join("|");
+const errors = [];
+for (const key of keys) {
+ for (const [name, dictionary] of [["en", en], ["zh-cn", zh]]) {
+ if (typeof dictionary[key] !== "string" || !dictionary[key].trim()) errors.push(name + ": missing " + key);
+ else if (tokens(key) !== tokens(dictionary[key])) errors.push(name + ": placeholder mismatch " + key);
+ }
+}
+if (errors.length) { console.error(errors.slice(0, 25).join("\n")); console.error(errors.length + " settings translation errors"); process.exitCode = 1; }
+else console.log("Settings coverage: " + keys.length + " English/Chinese keys; interpolation placeholders match.");
diff --git a/scripts/patch-calendar.cjs b/scripts/patch-calendar.cjs
new file mode 100644
index 000000000..00e05ce5d
--- /dev/null
+++ b/scripts/patch-calendar.cjs
@@ -0,0 +1,21 @@
+// Keep local fixes reproducible without requiring a commit to the upstream submodule.
+const fs = require("fs"), path = require("path"), crypto = require("crypto");
+const patches = require("../patches/calendar-layout.json");
+const check = process.argv.includes("--check");
+const hash = value => crypto.createHash("sha256").update(value).digest("hex");
+let changed = 0;
+for (const patch of patches.files) {
+ const file = path.join(__dirname, "..", "packages", "calendar", patch.file);
+ let source = fs.readFileSync(file, "utf8").replace(/\r\n/g, "\n");
+ if (hash(source) === patch.result) continue;
+ if (check) throw new Error("Calendar fixes are missing. Run pnpm build:release: " + patch.file);
+ if (hash(source) !== patch.baseline) throw new Error("Calendar source changed; review the layout patch before rebuilding: " + patch.file);
+ for (const step of patch.steps) {
+ const index = source.indexOf(step.before);
+ if (index < 0 || source.indexOf(step.before, index + 1) >= 0) throw new Error("Ambiguous calendar patch: " + patch.file);
+ source = source.slice(0, index) + step.after + source.slice(index + step.before.length);
+ }
+ if (hash(source) !== patch.result) throw new Error("Calendar patch verification failed: " + patch.file);
+ fs.writeFileSync(file, source); changed++;
+}
+console.log(`Calendar fixes verified (${changed} files patched).`);
diff --git a/scripts/scope-habits-css.mjs b/scripts/scope-habits-css.mjs
new file mode 100644
index 000000000..11eed1128
--- /dev/null
+++ b/scripts/scope-habits-css.mjs
@@ -0,0 +1,23 @@
+import fs from 'node:fs';
+import postcss from 'postcss';
+import selectorParser from 'postcss-selector-parser';
+
+const directory = 'src/integrations/habits/';
+const root = postcss.parse(fs.readFileSync(directory + 'upstream.css', 'utf8'));
+root.walkRules(rule => {
+ let parent = rule.parent;
+ while (parent) {
+ if (parent.type === 'atrule' && /keyframes$/i.test(parent.name)) return;
+ parent = parent.parent;
+ }
+ rule.selector = selectorParser(selectors => {
+ selectors.each(selector => {
+ const scope = selectorParser().astSync(':where(.tg-habits-surface, .tg-habits-surface *)').first.first.clone();
+ // Scope the subject of the selector, before pseudo-elements.
+ const pseudo = selector.nodes.find(node => node.type === 'pseudo' && node.value.startsWith('::'));
+ if (pseudo) selector.insertBefore(pseudo, scope);
+ else selector.append(scope);
+ });
+ }).processSync(rule.selector);
+});
+fs.writeFileSync(directory + 'scoped.css', '/* Generated by scripts/scope-habits-css.mjs; upstream MIT licensed. */\n' + root.toString());
diff --git a/scripts/settings-i18n-keys.json b/scripts/settings-i18n-keys.json
new file mode 100644
index 000000000..bd6f6d61e
--- /dev/null
+++ b/scripts/settings-i18n-keys.json
@@ -0,0 +1,1800 @@
+[
+ " (truncated)",
+ " for more information.",
+ "# heading",
+ "(Copy)",
+ "(Optional) Maximum value for the count",
+ "(Optional) Minimum value for the count",
+ "(Optional) Specific text representing completion, leave blank for any non-empty value to be considered completed",
+ "(Optional) Trigger a notification when this value is reached",
+ "(Optional) Unit for the count, such as 'cups', 'times', etc.",
+ "(space)",
+ "+ Add Custom Cycle",
+ "+ Add Status",
+ ", Replacement: ",
+ "- [ ] Your task here",
+ "0.0.0.0 (All interfaces - for external access)",
+ "1 → 2 → 3 → 4 → 5",
+ "1) Initialize",
+ "12-hour format (1:30 PM)",
+ "127.0.0.1 (Local only)",
+ "2) Call tool with session id",
+ "24-hour format (13:30)",
+ "A basic linear workflow with sequential stages",
+ "A descriptive name for the workflow",
+ "A descriptive name for the workspace",
+ "A descriptive name for this workflow stage",
+ "A descriptive name for your workflow",
+ "A link to the current file will be added to the parent task of the moved incomplete tasks.",
+ "A link to the current file will be added to the parent task of the moved tasks.",
+ "A unique identifier for the stage (used in tags)",
+ "A unique identifier for the workflow (used in tags)",
+ "AM (Morning)",
+ "AND",
+ "AND NOT",
+ "API Documentation",
+ "Abandoned",
+ "About",
+ "Academic or professional research workflow",
+ "Active",
+ "Active Rules",
+ "Active strategies: ",
+ "Add",
+ "Add Column",
+ "Add Custom Mapping",
+ "Add Custom View",
+ "Add Cycle",
+ "Add Detailed Cycle",
+ "Add Detection Method",
+ "Add File",
+ "Add File Rule",
+ "Add Filter Rule",
+ "Add Folder",
+ "Add Folder Rule",
+ "Add ICS Source",
+ "Add Item",
+ "Add Metadata Mapping",
+ "Add New Calendar Source",
+ "Add New Preset",
+ "Add New Workflow",
+ "Add Number Cycle",
+ "Add Path Mapping",
+ "Add Pattern",
+ "Add Pattern Rule",
+ "Add Simple Cycle",
+ "Add Sort Criterion",
+ "Add Stage",
+ "Add Sub-stage",
+ "Add Template",
+ "Add Text Replacement Rule",
+ "Add a new progress percentage range with custom text",
+ "Add custom date format patterns. Date patterns: yyyy (4-digit year), yy (2-digit year), MM (2-digit month), M (1-2 digit month), dd (2-digit day), d (1-2 digit day), MMM (short month name), MMMM (full month name). Time patterns: HH (2-digit hour), mm (2-digit minute), ss (2-digit second). Use single quotes for literals (e.g., 'T' for ISO format).",
+ "Add custom status mappings for your workflow.",
+ "Add filter",
+ "Add filter group",
+ "Add headings to focus on. Only tasks under these headings will be included in indexing. Examples: '## Project', '## Inbox', '# Tasks'",
+ "Add headings to ignore. Tasks under these headings will be excluded from indexing. Examples: '## Project', '## Inbox', '# Archive'",
+ "Add metadata fields that indicate a file should be treated as a task (e.g., dueDate, status, priority)",
+ "Add multiple events that need to be completed",
+ "Add new event",
+ "Add new habit",
+ "Add new mapping",
+ "Add new range",
+ "Add occurrence level",
+ "Add paths that contain task files (e.g., Projects/, Tasks/2024/, Work/TODO/)",
+ "Add progress bar to Heading",
+ "Add progress bar to Projects view",
+ "Add progress bar to non-task bullet",
+ "Add reward item",
+ "Add tags that indicate a file should be treated as a task (e.g., #task, #todo, #actionable)",
+ "Add {{value0}} Theme as New Cycle?",
+ "Additional stages that can follow this one (for right-click menu)",
+ "Advanced",
+ "Advanced Filter",
+ "Advanced Filtering",
+ "Advanced Settings",
+ "Advanced view management features that extend the default Task Genius views with additional functionality.",
+ "After heading",
+ "Agenda",
+ "Agenda View",
+ "All",
+ "All Fields",
+ "All Workspaces",
+ "All history",
+ "All settings have been reset to their default values",
+ "All tasks",
+ "Allow Task Genius to recognize files as tasks using metadata, tags, or templates.",
+ "Allow cross-origin requests (required for web clients)",
+ "Allow files to be recognized and treated as tasks based on their metadata, tags, or file paths. This provides advanced recognition strategies beyond simple metadata parsing.",
+ "Allow subtasks to inherit metadata from file frontmatter. When disabled, only top-level tasks inherit file metadata",
+ "Allow tasks to inherit metadata properties from their file's frontmatter",
+ "Almost there",
+ "Almost there {{PROGRESS}}%",
+ "Analysis",
+ "Any",
+ "Append",
+ "Append to file",
+ "Applied recommended configuration: ",
+ "Apply",
+ "Apply Theme",
+ "Apply {{value0}} Theme?",
+ "Are you sure you want to delete \"{{name}}\"? This action cannot be undone.",
+ "Are you sure you want to delete the '{{value0}}' workflow?",
+ "Are you sure you want to delete the habit ",
+ "Are you sure you want to delete this calendar source?",
+ "Are you sure you want to delete this filter configuration?",
+ "Are you sure you want to delete this text replacement rule?",
+ "Are you sure you want to force reindex all tasks?",
+ "Are you sure you want to reset all settings to their default values?\n\nThis action cannot be undone.",
+ "Arguments:",
+ "Ascending",
+ "Ascending respects status order (Overdue first). Descending reverses it.",
+ "Ascending: A-Z. Descending: Z-A",
+ "Ascending: Earlier -> Later -> None. Descending: None -> Later -> Earlier",
+ "Ascending: High -> Low -> None. Descending: None -> Low -> High",
+ "Authentication",
+ "Authentication (Optional)",
+ "Authentication Method",
+ "Authentication Token",
+ "Authentication Type",
+ "Auto Date Manager",
+ "Auto Update Priority",
+ "Auto Update Tags",
+ "Auto complete parent checkbox",
+ "Auto remove last stage marker",
+ "Auto-add next task",
+ "Auto-add task prefix",
+ "Auto-add timestamp",
+ "Auto-detect Status Mappings",
+ "Auto-expand project tree",
+ "Auto-open on startup",
+ "Auto-start timer",
+ "Automatically add a timestamp to the task when it is created",
+ "Automatically add cancelled dates when tasks are marked as abandoned, and remove them when changed to other statuses.",
+ "Automatically add completion dates when tasks are marked as completed, and remove them when changed to other statuses.",
+ "Automatically add start dates when tasks are marked as in progress, and remove them when changed to other statuses.",
+ "Automatically add task checkbox prefix to captured content",
+ "Automatically add/remove urgent/important tags when moved between quadrants",
+ "Automatically convert between metadata status values and task symbols",
+ "Automatically create a new task with the next stage when completing a task",
+ "Automatically detect and group holiday events",
+ "Automatically expand all project nodes when opening the project view in tree mode.",
+ "Automatically manage dates based on checkbox status changes",
+ "Automatically map ICS events to specific task statuses",
+ "Automatically move completed tasks to a default file without manual selection.",
+ "Automatically move incomplete tasks to a default file without manual selection.",
+ "Automatically open the timeline sidebar when Obsidian starts.",
+ "Automatically parse natural language time expressions and specific times (12:00, 1:30 PM, 12:00-13:00)",
+ "Automatically refresh calendar sources in the background",
+ "Automatically remove the last stage marker when a task is completed",
+ "Automatically start the timer when creating a new task via quick capture (checkbox mode only)",
+ "Automatically sync settings from the Daily Notes plugin",
+ "Automatically sync with task status configuration",
+ "Automatically update task priority when moved between quadrants",
+ "Available Tools",
+ "Available placeholders: {{COMPLETED}}, {{TOTAL}}, {{IN_PROGRESS}}, {{ABANDONED}}, {{PLANNED}}, {{NOT_STARTED}}, {{PERCENT}}, {{COMPLETED_SYMBOL}}, {{IN_PROGRESS_SYMBOL}}, {{ABANDONED_SYMBOL}}, {{PLANNED_SYMBOL}}",
+ "Back to main settings",
+ "Badge",
+ "Base View",
+ "Base View Type",
+ "Based on current date",
+ "Based on due date",
+ "Based on scheduled date",
+ "Based on: ",
+ "Bases Support",
+ "Basic",
+ "Basic Auth",
+ "Basic Task",
+ "Bearer Token",
+ "Bearer token for authenticating MCP requests (keep this secret)",
+ "Beginning of file",
+ "Beta Features",
+ "Beta Features Warning",
+ "Beta Feedback",
+ "Beta Test Features",
+ "Blacklist",
+ "Blacklist (Exclude)",
+ "Block References",
+ "Block reference prefix",
+ "Both",
+ "Both graphical and text",
+ "Bottom Section",
+ "Bracketed fraction ([3/4])",
+ "Bracketed percentage ([75%])",
+ "Built-in View Templates",
+ "Cache Size",
+ "Cache TTL",
+ "Calculate and display the time spent on the task when moving to the next stage",
+ "Calculate full spent time",
+ "Calculate spent time",
+ "Calculate spent time when move to next stage.",
+ "Calculate the full spent time from the start of the task to the last stage",
+ "Calendar Sources",
+ "Calendar Sync",
+ "Calendar View Configuration",
+ "Calendar Views",
+ "Calendar view created: ",
+ "Calendar view updated: ",
+ "Can proceed to",
+ "Cancel",
+ "Cancelled",
+ "Cannot enable views without indexer. Please enable the indexer first in Index & Sources settings.",
+ "Capture as:",
+ "Capture to:",
+ "Capture your thoughts...",
+ "Case Sensitive Matching",
+ "Categories",
+ "Category Mapping",
+ "Chance (%)",
+ "Chance must be between 0 and 100.",
+ "Changelog",
+ "Character to trigger the suggestion menu",
+ "Character used to separate project hierarchy levels (e.g., '/' in 'Project/SubProject').",
+ "Characters used to separate time ranges (comma-separated)",
+ "Chat with us",
+ "Checkbox Status",
+ "Checkbox Status Settings",
+ "Checkbox Switcher",
+ "Checkbox Tasks",
+ "Checkbox task indexing disabled. The index will prune inline tasks shortly.",
+ "Child Tasks",
+ "Choose a color for this workspace",
+ "Choose a preset or customize the time range",
+ "Choose a template to start with or create a custom workflow",
+ "Choose an icon for this view",
+ "Choose an icon for this workspace",
+ "Choose how rewards are displayed when earned.",
+ "Choose how task marks are displayed: default checkboxes, custom text marks, or Task Genius icons.",
+ "Choose how to calculate the next date for recurring tasks",
+ "Choose how to classify tasks into quadrants",
+ "Choose how to display task progress",
+ "Choose how to display the task progress",
+ "Choose the authentication method for client configurations",
+ "Choose the default display mode for all views. This affects how tasks are displayed when you first open a view or create a new view.",
+ "Choose the note that should be copied; {{CONTENT}} placeholders are replaced, otherwise the captured text is appended.",
+ "Choose what type of marker to add to moved incomplete tasks",
+ "Choose what type of marker to add to moved tasks",
+ "Choose where this view appears in the sidebar. Views in the bottom section are visually separated from top section views.",
+ "Choose whether to capture to a fixed file or daily note",
+ "Choose whether to display projects as a flat list or hierarchical tree by default.",
+ "Choose whether to include only specified files/folders (whitelist) or exclude them (blacklist)",
+ "Choose whether to include or exclude tasks that match the filters",
+ "Choose whether to show or hide tasks that match the filters",
+ "Choose your preferred interface style and configure how Task Genius displays in your workspace.",
+ "Claim Reward",
+ "Classic",
+ "Classic & Familiar",
+ "Clear Logs",
+ "Clear search",
+ "Clearing task cache and rebuilding index...",
+ "Click the button above to add your first habit",
+ "Click the button below to automatically add this MCP server to Cursor:",
+ "Click to open the timeline sidebar view.",
+ "Client Configuration",
+ "Close",
+ "Coding",
+ "Collapse/Expand",
+ "Color",
+ "Color for events from this source (optional)",
+ "Color-coded Status",
+ "Column Title",
+ "Columns that are currently hidden from view. Click the eye icon to show them again.",
+ "Combine emoji and dataview syntax as needed",
+ "Comma-separated list of folder paths where task timer should be enabled",
+ "Comma-separated list of tags that enable task timer",
+ "Common Mappings",
+ "Common Metadata Symbols",
+ "Complete all moved tasks",
+ "Completed",
+ "Completed Task Mover",
+ "Completed Tasks",
+ "Completed tasks",
+ "Completion text",
+ "Condition (e.g., #tag AND project)",
+ "Config File-based Project Detection",
+ "Config file name",
+ "Configure Custom Date Formats",
+ "Configure Date Formats",
+ "Configure Focus Headings",
+ "Configure Ignore Headings",
+ "Configure Symbols",
+ "Configure Task Fields",
+ "Configure Task Paths",
+ "Configure Task Tags",
+ "Configure additional methods to detect project files",
+ "Configure checkbox status settings",
+ "Configure custom columns for the selected grouping property",
+ "Configure custom date format patterns.",
+ "Configure external calendar sources to display events in your task views.",
+ "Configure fallback project naming when no explicit project is found",
+ "Configure file filtering to improve indexing performance and focus on relevant content",
+ "Configure habit settings, including adding new habits, editing existing habits, and managing habit completion.",
+ "Configure headings to focus on. Only tasks under these headings will be included in indexing.",
+ "Configure headings to ignore. Tasks under these headings will be excluded from indexing.",
+ "Configure hidden modules",
+ "Configure how ICS events are mapped to task statuses",
+ "Configure how Task Genius discovers and indexes tasks from various sources including inline tasks, file metadata, and projects.",
+ "Configure how dates and times are displayed in views.",
+ "Configure how files are recognized as tasks. At least one strategy must be enabled.",
+ "Configure how holiday events are detected and displayed",
+ "Configure how metadata fields are mapped and transformed",
+ "Configure how projects are displayed in tree view.",
+ "Configure how tasks are parsed from markdown content.",
+ "Configure how tasks are sorted in the document.",
+ "Configure how tasks inherit metadata from file frontmatter",
+ "Configure inline editing and metadata positioning.",
+ "Configure keywords for date parsing",
+ "Configure metadata fields that indicate a file should be treated as a task (e.g., dueDate, status, priority)",
+ "Configure multiple status cycles with different workflows. You can apply preset themes or create custom cycles.",
+ "Configure options specific to the Fluent interface.",
+ "Configure paths that contain task files (e.g., Projects/, Tasks/2024/, Work/TODO/)",
+ "Configure performance-related indexing settings",
+ "Configure project detection from file frontmatter",
+ "Configure project detection from project configuration files",
+ "Configure project display, organization and metadata mappings",
+ "Configure project names based on file paths",
+ "Configure rewards for completing tasks. Define items, their occurrence chances, and conditions.",
+ "Configure rules to modify event text using regular expressions",
+ "Configure symbols that represent abandoned tasks in square brackets",
+ "Configure symbols that represent completed tasks in square brackets",
+ "Configure symbols that represent not started tasks in square brackets. Default is space \" \"",
+ "Configure symbols that represent planned tasks in square brackets",
+ "Configure symbols that represent tasks in progress in square brackets",
+ "Configure system tray, notifications, and desktop features",
+ "Configure tags that indicate a file should be treated as a task (e.g., #task, #todo, #actionable)",
+ "Configure task workflows for project and process management",
+ "Configure the Task Genius sidebar views, visibility, order, and create custom views.",
+ "Configure the format of time expressions",
+ "Configure the task gutter.",
+ "Configure which files and folders to include or exclude from task indexing",
+ "Configure which files, folders, or patterns are included during task indexing.",
+ "Configure which modules should be hidden in this workspace. Hidden views will not appear in the sidebar.",
+ "Configure which task markers to count or exclude",
+ "Configure workflow templates for different types of processes",
+ "Connection test failed: ",
+ "Connection test successful! MCP server is working.",
+ "Contains match",
+ "Content",
+ "Context",
+ "Context tag prefix",
+ "Contexts",
+ "Control which days are displayed in the calendar",
+ "Copied!",
+ "Copy",
+ "Copy Install Link",
+ "Copy Settings From",
+ "Copy URL",
+ "Copy View",
+ "Copy of ",
+ "Copy settings from an existing workspace",
+ "Copy this cycle",
+ "Copy view: ",
+ "Core Settings",
+ "Count habit",
+ "Count other statuses as",
+ "Count sub children of current Task",
+ "Create",
+ "Create Calendar View",
+ "Create Custom View",
+ "Create New Calendar View",
+ "Create New Workflow",
+ "Create New Workspace",
+ "Create Workflow",
+ "Create a backup of active timers",
+ "Create a custom view from the templates above to get started.",
+ "Create a custom workflow from scratch",
+ "Create a new workspace with custom settings",
+ "Create and manage preset filters for quick access to commonly used task filters.",
+ "Create custom calendar views based on Month, Week, or Day views. Each custom view can have its own display settings.",
+ "Create custom view",
+ "Create new habit",
+ "Create task timer backup",
+ "Created",
+ "Created Date",
+ "Creating a copy based on: ",
+ "Current Events Status",
+ "Current Workspace",
+ "Current status management and date management may conflict with the Tasks plugin. Please check the ",
+ "Currently supports English and Chinese time expressions. More languages may be added in future updates.",
+ "Custom",
+ "Custom Calendar Views",
+ "Custom Columns",
+ "Custom Content Field",
+ "Custom Cycle",
+ "Custom Date Formats",
+ "Custom Headers",
+ "Custom Mappings",
+ "Custom Project Detection Methods",
+ "Custom Range",
+ "Custom Selection",
+ "Custom Workflow",
+ "Custom date formats",
+ "Custom days",
+ "Custom format",
+ "Custom marker",
+ "Custom marker text",
+ "Custom metadata field",
+ "Custom text marks",
+ "Customize how dates are displayed in headers",
+ "Customize progress ranges",
+ "Customize the prefix used for context tags (e.g., '@home' for @home). Changes require reindexing.",
+ "Customize the prefix used for context tags in dataview format (e.g., 'context' for [context:: home]). Changes require reindexing.",
+ "Customize the prefix used for project tags (e.g., 'project' for #project/myproject). Changes require reindexing.",
+ "Customize the prefix used for project tags in dataview format (e.g., 'project' for [project:: myproject]). Changes require reindexing.",
+ "Cycle (repeatable)",
+ "Daily Note",
+ "Daily Notes plugin is not enabled",
+ "Daily habit",
+ "Daily note",
+ "Daily note folder",
+ "Daily note format",
+ "Daily note path",
+ "Daily note template",
+ "Daily notes settings synced successfully",
+ "Daily summary",
+ "Data Collection",
+ "Data Management",
+ "Dataview metadata",
+ "Date Filter",
+ "Date Keywords Configuration",
+ "Date and Time Display",
+ "Date format for daily notes (e.g., YYYY-MM-DD)",
+ "Date formats updated. The parser will now recognize these custom formats.",
+ "Date marker",
+ "Date marker text",
+ "Date picker",
+ "Dates & Priority",
+ "Day",
+ "Day Filter",
+ "Day Header Format",
+ "Day View",
+ "Days to Show",
+ "Debug",
+ "Default",
+ "Default AM/PM Period",
+ "Default Archive File",
+ "Default Archive Section",
+ "Default Cycle",
+ "Default Event Color",
+ "Default Project Naming",
+ "Default Task Status",
+ "Default checkboxes",
+ "Default color for events without a specific color",
+ "Default field to sort tasks by within each column.",
+ "Default file for archive action",
+ "Default file name template",
+ "Default file to move completed tasks to (e.g., 'Archive.md')",
+ "Default file to move incomplete tasks to (e.g., 'Backlog.md')",
+ "Default folder for new files",
+ "Default format preference for ambiguous time expressions",
+ "Default heading name",
+ "Default heading name for incomplete tasks",
+ "Default insertion mode",
+ "Default insertion mode for incomplete tasks",
+ "Default order to sort tasks within each column.",
+ "Default period when AM/PM is ambiguous in 12-hour format",
+ "Default project view mode",
+ "Default refresh interval for all sources (minutes)",
+ "Default section for archive action",
+ "Default settings",
+ "Default sort field",
+ "Default sort order",
+ "Default status for newly created file tasks",
+ "Default target file",
+ "Default target file for incomplete tasks",
+ "Default title for the right column (tasks list)",
+ "Default view mode",
+ "Default workspace",
+ "Default workspace cannot be deleted",
+ "Define cycle sub-stages (optional)",
+ "Define different levels of reward rarity and their probability.",
+ "Define mappings from numeric values to display text",
+ "Define progress ranges and their corresponding text representations.",
+ "Define the order in which tasks should be sorted. Criteria are applied sequentially.",
+ "Define the statuses in cycling order",
+ "Delegate - Interruptions & distractions",
+ "Delete",
+ "Delete Filter Configuration",
+ "Delete Level",
+ "Delete View",
+ "Delete Workspace",
+ "Delete habit",
+ "Delete item",
+ "Delete reward item",
+ "Delete rule",
+ "Delete this calendar source",
+ "Delete this cycle",
+ "Delete this item",
+ "Delete workflow",
+ "Descending",
+ "Describe the purpose and use of this workflow...",
+ "Describe your workflow...",
+ "Description",
+ "Descriptive name for this replacement rule",
+ "Desktop Integration",
+ "Desktop integration features are only available in the desktop app",
+ "Desktop only",
+ "Detailed",
+ "Detailed ([3✓ 1⟳ 0✗ 1? / 5])",
+ "Details",
+ "Detect project from file frontmatter metadata",
+ "Detect project from project configuration files",
+ "Detected features: ",
+ "Detection Patterns",
+ "Development",
+ "Disable",
+ "Disable this source",
+ "Disabled",
+ "Discord",
+ "Display",
+ "Display & Progress",
+ "Display a full year with 12 mini-month calendars",
+ "Display days with no events",
+ "Display event count badges on date cells",
+ "Display name for this calendar source",
+ "Display name for this calendar view",
+ "Display name of the habit",
+ "Display project folders even if they don't contain any tasks.",
+ "Display tasks for a single day with detailed time slots",
+ "Display tasks in a monthly calendar grid",
+ "Display tasks in a weekly time grid with hourly slots",
+ "Display timer usage statistics",
+ "Display upcoming tasks in a list format grouped by day",
+ "Display week numbers in the month view",
+ "Do First - Crisis & emergencies",
+ "Documentation",
+ "Donate",
+ "Done",
+ "Drag to reorder",
+ "Drag views between sections or within sections to reorder them. Toggle visibility with the eye icon.",
+ "Drink a cup of good tea",
+ "Due",
+ "Due Date",
+ "Due Date Keywords",
+ "Due Dates",
+ "Due date",
+ "Duplicate",
+ "Duplicate filter group",
+ "Eat a piece of chocolate",
+ "Edit",
+ "Edit Calendar View",
+ "Edit File Filter Rules",
+ "Edit Filter",
+ "Edit Filter: ",
+ "Edit ICS Source",
+ "Edit Stage",
+ "Edit Text Replacement Rule",
+ "Edit View",
+ "Edit Workflow",
+ "Edit habit",
+ "Edit this calendar source",
+ "Edit view: ",
+ "Edit workflow",
+ "Editor Configuration",
+ "Eliminate - Time wasters",
+ "Emoji Progress Bar",
+ "Emoji metadata",
+ "Empty state text",
+ "Enable",
+ "Enable Background Refresh",
+ "Enable Base View",
+ "Enable Base View functionality. This feature provides enhanced view management capabilities but may be affected by future Obsidian API changes.",
+ "Enable Base View functionality. This feature provides enhanced view management capabilities but may be affected by future Obsidian API changes. You may need to restart Obsidian to see the changes.",
+ "Enable CORS",
+ "Enable File Filter",
+ "Enable File Task",
+ "Enable Holiday Detection",
+ "Enable Indexer",
+ "Enable MCP Server",
+ "Enable OnCompletion",
+ "Enable Status Mapping",
+ "Enable Task Filter",
+ "Enable Task Genius Views",
+ "Enable Task Genius Views above to configure view settings.",
+ "Enable Task Genius sidebar views to display and manage tasks. Requires the indexer to be enabled.",
+ "Enable Task Sorting",
+ "Enable Task Timer",
+ "Enable Time Filter",
+ "Enable Time Parsing",
+ "Enable Timeline Sidebar",
+ "Enable auto date manager",
+ "Enable auto-move for completed tasks",
+ "Enable auto-move for incomplete tasks",
+ "Enable automatic actions when tasks are completed",
+ "Enable case-sensitive matching for status values",
+ "Enable checkbox status switcher",
+ "Enable checkbox tasks",
+ "Enable completed task mover",
+ "Enable config file project detection",
+ "Enable custom date format patterns for parsing dates. When enabled, the parser will try your custom formats before falling back to default formats.",
+ "Enable custom date formats",
+ "Enable cycle complete status",
+ "Enable date picker",
+ "Enable default project naming",
+ "Enable dynamic metadata positioning",
+ "Enable file metadata inheritance",
+ "Enable file tasks",
+ "Enable focus mode by default, which highlights today's events and dims past/future events.",
+ "Enable habits",
+ "Enable incomplete task mover",
+ "Enable inline editing of task content and metadata directly in task views. When disabled, tasks can only be edited in the source file.",
+ "Enable inline editor",
+ "Enable metadata project detection",
+ "Enable minimal mode",
+ "Enable notifications",
+ "Enable path-based, metadata-based, and config file-based project detection",
+ "Enable priority keyboard shortcuts",
+ "Enable priority picker",
+ "Enable progress bar in reading mode",
+ "Enable project features",
+ "Enable quick capture",
+ "Enable rewards",
+ "Enable simplified single-line quick capture with inline suggestions",
+ "Enable task gutter",
+ "Enable task timer functionality for tracking time spent on tasks",
+ "Enable text mark in source mode",
+ "Enable this source",
+ "Enable worker processing",
+ "Enable workflow",
+ "Enable/disable the ability to automatically cycle through task states when pressing a mark.",
+ "Enable/disable the ability to cycle through task states by clicking.",
+ "Enable/disable this cycle",
+ "Enabled",
+ "Enabled:",
+ "End Hour",
+ "End of file",
+ "Enhanced",
+ "Enter a description for this filter configuration (optional)",
+ "Enter a name for this filter configuration",
+ "Enter a task using any of the formats shown above",
+ "Enter any Lucide icon name (e.g., list-checks, filter, inbox)",
+ "Enter date format (e.g., yyyy-MM-dd or yyyyMMdd_HHmmss)",
+ "Enter details for {{value0}}...",
+ "Enter file name...",
+ "Enter heading (e.g., ## Inbox)",
+ "Enter heading (e.g., ## Tasks)",
+ "Enter metadata field name",
+ "Enter metadata key (e.g., project-name)",
+ "Enter metadata value and symbol (e.g., 'done:x')",
+ "Enter new name",
+ "Enter path (e.g., Projects/, Tasks/**/*.md)",
+ "Enter tag (e.g., #task)",
+ "Enter template...",
+ "Enter text to test the replacement rule",
+ "Enter value",
+ "Enter workflow name",
+ "Enter workspace name",
+ "Error",
+ "Error loading statistics",
+ "Error rendering format",
+ "Error:",
+ "Error: View ID already exists.",
+ "Event",
+ "Event categories that indicate holidays (one per line)",
+ "Event details",
+ "Event name",
+ "Event name cannot be empty",
+ "Events",
+ "Exact match",
+ "Example",
+ "Example Request",
+ "Examples",
+ "Examples of advanced formats using expressions",
+ "Examples of time expressions",
+ "Examples:",
+ "Exclude Archive Folder",
+ "Exclude Temporary Files",
+ "Exclude specific task markers",
+ "Experimental features that are currently in testing phase. These features may be unstable and could change or be removed in future updates.",
+ "Export all timer data to JSON",
+ "Export task timer data",
+ "Export task timer data (YAML)",
+ "Export to YAML format",
+ "Expression examples",
+ "Failed to delete filter configuration",
+ "Failed to force reindex tasks",
+ "Failed to load filter configuration",
+ "Failed to load tools. Is the MCP server running?",
+ "Failed to open quick capture. Please try again later.",
+ "Failed to reindex tasks",
+ "Failed to restart server: ",
+ "Failed to save filter configuration",
+ "Failed to sync daily notes settings",
+ "Failed to sync mapping",
+ "Features to be enabled",
+ "Field name in frontmatter to check for enabling task timer (e.g., 'task-timer: true')",
+ "File",
+ "File Content",
+ "File Creation Mode",
+ "File Filter",
+ "File Filter Mode",
+ "File Filter Rules",
+ "File Metadata Inheritance",
+ "File Name",
+ "File Path",
+ "File Task is disabled",
+ "File Task is enabled and monitoring files",
+ "File Tasks",
+ "File filtering helps you focus on relevant content while improving performance, especially in large vaults.",
+ "File task recognition disabled. Existing file tasks will be pruned shortly.",
+ "File tasks are disabled. Enable them to configure recognition strategies.",
+ "FileSource status mapping synced",
+ "Filename",
+ "Files",
+ "Filter Configuration Description",
+ "Filter Configuration Name",
+ "Filter Mode",
+ "Filter Rules",
+ "Filter Summary",
+ "Filter Tasks",
+ "Filter blanks",
+ "Filter configuration deleted successfully",
+ "Filter configuration loaded successfully",
+ "Filter configuration name is required",
+ "Filter configuration saved successfully",
+ "Filter files during task indexing to improve performance",
+ "Filter name",
+ "Filter out blank tasks in this view.",
+ "Filter query",
+ "First Day of Week",
+ "First H1 heading",
+ "First day of week",
+ "First hour to display (0-23)",
+ "Fixed file",
+ "Flagged",
+ "Fluent",
+ "Fluent Interface Settings",
+ "Focus all tasks behind heading",
+ "Focus mode by default",
+ "Focus on Projects",
+ "Folder",
+ "Folder path for daily notes (leave empty for root)",
+ "Folder paths",
+ "Folder that contains Quick Capture templates for File mode.",
+ "Force a complete rebuild of the task index. Use this if you notice missing or incorrect tasks.",
+ "Forecast",
+ "Format Examples:",
+ "Format Pattern",
+ "Format for day headers (e.g., dddd, MMMM D)",
+ "Format for day view header (e.g., yyyy'年'M'月'd'日')",
+ "Format for grouped holiday display. Use {title}, {count}, {startDate}, {endDate}",
+ "Format for month view header (e.g., yyyy M)",
+ "Format for spent time:",
+ "Fraction (3/4)",
+ "Friday",
+ "Frontmatter field",
+ "Frontmatter title",
+ "Full project workflow",
+ "Full year",
+ "Future Events Status",
+ "Gamification",
+ "General",
+ "Glob pattern (e.g., Projects/**/*.md)",
+ "Global Refresh Interval",
+ "Global Settings",
+ "Good progress",
+ "Good progress {{PROGRESS}}%",
+ "Graphical progress bar",
+ "Group Display Format",
+ "Group by",
+ "Group by task property",
+ "Grouping Strategy",
+ "Habit",
+ "Habit added",
+ "Habit deleted",
+ "Habit name",
+ "Habit type",
+ "Habit updated",
+ "Habit with multiple events",
+ "Habits",
+ "Half way",
+ "Half way {{PROGRESS}}%",
+ "Heading filters updated. Rebuild the task index to apply to existing tasks.",
+ "Heading name to insert incomplete tasks after (will be created if it doesn't exist)",
+ "Heading name to insert tasks after (will be created if it doesn't exist)",
+ "Help improve these features by providing feedback on your experience.",
+ "Hidden Columns",
+ "Hidden Days",
+ "Hidden Modules Configuration",
+ "Hide",
+ "Hide Empty Quadrants",
+ "Hide Weekends",
+ "Hide by folders",
+ "Hide by metadata",
+ "Hide by tags",
+ "Hide columns that have no tasks.",
+ "Hide completed and abandoned tasks",
+ "Hide completed and abandoned tasks in this view.",
+ "Hide empty columns",
+ "Hide from sidebar",
+ "Hide matching tasks",
+ "Hide progress bars",
+ "Hide progress bars based on conditions",
+ "Hide quadrants that have no tasks",
+ "Hide weekend columns (Saturday and Sunday) in calendar views.",
+ "Hide weekend columns (Saturday and Sunday) in forecast calendar.",
+ "Hide weekends",
+ "High",
+ "High priority",
+ "Higher priority",
+ "Highest",
+ "Highest priority",
+ "Holiday Configuration",
+ "Holiday Status",
+ "Host",
+ "Host changed to 0.0.0.0. Server is now accessible from external networks.",
+ "How long to keep cached data (hours)",
+ "How often to refresh this source (minutes)",
+ "How paths should be matched",
+ "How tags should be matched against file tags",
+ "How to add captured content to the target location",
+ "How to display events from this source in calendar views",
+ "How to handle consecutive holiday events",
+ "How to handle time ranges that cross midnight (e.g., 23:00-01:00)",
+ "How to use",
+ "ICS Auth None",
+ "ICS Bearer Token",
+ "ICS Calendar Integration",
+ "ICS Disabled",
+ "ICS Enabled",
+ "ICS Password",
+ "ICS Source Name",
+ "ICS URL",
+ "ICS Username",
+ "Icon",
+ "Icon name",
+ "If enabled, #tags in the editor content are written into YAML frontmatter tags (merged and deduplicated)",
+ "If enabled, abandoned tasks will be treated as completed.",
+ "If enabled, all moved tasks will be marked as completed.",
+ "If enabled, the daily note path will be used as the date for tasks.",
+ "If you encounter any issues with beta features, please report them to help improve the plugin.",
+ "If you like this plugin, consider donating to support continued development:",
+ "Ignore all tasks behind heading",
+ "Ignore system and temporary files",
+ "Image not found:",
+ "Image url (optional)",
+ "Import task timer data",
+ "Import timer data from JSON file",
+ "Important Priority Threshold",
+ "Important Tag",
+ "In Progress",
+ "In progress",
+ "In progress tasks",
+ "Inbox",
+ "Include Abandoned Tasks",
+ "Include Child Tasks",
+ "Include Completed Tasks",
+ "Include In Progress Tasks",
+ "Include Not Started Tasks",
+ "Include Parent Tasks",
+ "Include Planned Tasks",
+ "Include Related Tasks",
+ "Include Sibling Tasks",
+ "Include all-day events from this source",
+ "Include completed tasks in the timeline view. When disabled, only incomplete tasks will be shown.",
+ "Include or exclude tasks based on their status",
+ "Include parent, child, and sibling tasks in the filter",
+ "Include task creation guide",
+ "Include time",
+ "Include timed events from this source",
+ "Incomplete Task Mover",
+ "Incomplete Tasks",
+ "Incomplete custom marker text",
+ "Incomplete date marker text",
+ "Incomplete task marker type",
+ "Incomplete tasks",
+ "Incomplete version marker text",
+ "Index & Sources",
+ "Index & Task Source Configuration",
+ "Index Maintenance",
+ "Index markdown checkbox tasks. Disable this if you only want to use file-based or external task sources.",
+ "Index only specific project folders",
+ "Info",
+ "Information",
+ "Inherit from frontmatter",
+ "Inherit from frontmatter for subtasks",
+ "Inline",
+ "Inline task parsing",
+ "Input: ",
+ "Integration",
+ "Intelligently position task metadata. When enabled, metadata appears on the same line as short tasks and below long tasks. When disabled, metadata always appears below the task content.",
+ "Interface",
+ "Interface Mode",
+ "Interface Style",
+ "Invalid inventory number.",
+ "Invalid regular expression pattern",
+ "Inventory (-1 for ∞)",
+ "Items",
+ "JSON object with custom headers",
+ "Just started",
+ "Just started {{PROGRESS}}%",
+ "Keep open after capture",
+ "Keep the familiar interface and interaction style you know",
+ "Keep the modal open after capturing content",
+ "Keywords",
+ "Keywords that indicate due dates (comma-separated)",
+ "Keywords that indicate scheduled dates (comma-separated)",
+ "Keywords that indicate start dates (comma-separated)",
+ "Keywords to detect in event text (one per line)",
+ "Last hour to display (0-23)",
+ "Last month",
+ "Last updated: {{date}}",
+ "Last week",
+ "Last year",
+ "Learn the different ways to create and format tasks in Task Genius. You can use either emoji-based or Dataview-style syntax.",
+ "Left column title",
+ "Legacy",
+ "Level Name (e.g., common)",
+ "Line Number",
+ "Linear (sequential)",
+ "Link Filter",
+ "Linked Note",
+ "List View",
+ "Literature Review",
+ "Load",
+ "Load Filter Configuration",
+ "Load Saved Filter",
+ "Loading tools...",
+ "Locale Default",
+ "Location",
+ "Log Level",
+ "Logging verbosity for debugging",
+ "Low",
+ "Low priority",
+ "Lower priority",
+ "Lowest",
+ "Lowest priority",
+ "MCP Integration",
+ "MCP Server Logs",
+ "MCP Server Status",
+ "MCP Server enabled. Keep your authentication token secure!",
+ "MCP Server not initialized",
+ "MCP integration is only available on desktop",
+ "MCP server is not running",
+ "MCP server restarted",
+ "Make the text mark in source mode follow the checkbox status cycle when clicked.",
+ "Making progress",
+ "Making progress {{PROGRESS}}%",
+ "Manage Views",
+ "Manage Workspaces...",
+ "Manage cancelled dates",
+ "Manage completion dates",
+ "Manage file name templates for quick selection in File mode",
+ "Manage start dates",
+ "Manage the specific rewards that can be obtained.",
+ "Manage workspaces to organize different contexts with their own settings and filters.",
+ "Manual Configuration",
+ "Manually refresh filter statistics to see current data",
+ "Map between human-readable metadata values (e.g., 'completed') and task symbols (e.g., 'x').",
+ "Map specific categories to statuses (format: category:status, one per line)",
+ "Mapping",
+ "Mapping habit",
+ "Mapping key must be a number",
+ "Mark",
+ "Mark parent as 'In Progress' when partially complete",
+ "Match",
+ "Matrix",
+ "Max Events Per Row",
+ "Max Events Per Source",
+ "Max other views before overflow",
+ "Max percentage (0-100)",
+ "Maximum Cache Age",
+ "Maximum Gap Days",
+ "Maximum days between events to consider them consecutive",
+ "Maximum events to show",
+ "Maximum events to show per day cell before showing '+N more'",
+ "Maximum number of events to display in the timeline. Higher numbers may affect performance.",
+ "Maximum number of events to load from each source",
+ "Maximum value",
+ "Medium",
+ "Medium priority",
+ "Meeting",
+ "Metadata",
+ "Metadata Detection",
+ "Metadata Mappings",
+ "Metadata Property",
+ "Metadata Value",
+ "Metadata field to use as project name",
+ "Metadata key",
+ "Metadata-based Project Detection",
+ "Metadata-based Recognition",
+ "Method",
+ "Method A (Custom Header):",
+ "Method A: Custom Headers",
+ "Method B (Combined Bearer):",
+ "Method B: Combined Bearer (Recommended)",
+ "Midnight Crossing Behavior",
+ "Migrated from legacy settings",
+ "Min percentage (0-100)",
+ "Minimal Mode",
+ "Minimum value",
+ "Missed",
+ "Mixed Format",
+ "Modal dialog",
+ "Modern",
+ "Modern & Sleek",
+ "Mon first",
+ "Monday",
+ "Month",
+ "Month Header Format",
+ "Month View",
+ "Move Down",
+ "Move Up",
+ "Move down",
+ "Move up",
+ "Multi-select Text",
+ "My Calendar",
+ "My Custom Task View",
+ "My Custom View",
+ "NOR",
+ "Name and ID are required.",
+ "Name of the metadata field to use as task content",
+ "Name of the project configuration file",
+ "Naming strategy",
+ "Network Timeout",
+ "New Calendar View",
+ "New Column",
+ "New Filter",
+ "New Level",
+ "New Name",
+ "New Preset",
+ "New Reward",
+ "New Sub-stage",
+ "New Workflow",
+ "New custom view",
+ "New token generated",
+ "New visual design with elegant animations and modern interactions",
+ "Next day (23:00 today - 01:00 tomorrow)",
+ "Next stage",
+ "Next: ",
+ "No additional destination stages defined.",
+ "No available port found in range",
+ "No calendar sources configured. Add a source to get started.",
+ "No changes to save",
+ "No custom calendar views yet",
+ "No custom columns defined. Add columns below.",
+ "No filter rules configured yet",
+ "No habits yet",
+ "No items configured. Click 'Add Item' to get started.",
+ "No items selected",
+ "No levels defined",
+ "No logs match your search.",
+ "No logs yet. Tool calls will appear here.",
+ "No markdown notes were found in the selected folder.",
+ "No metadata mappings configured yet.",
+ "No path mappings configured yet.",
+ "No preset filters created yet. Click 'Add New Preset' to create one.",
+ "No priority",
+ "No progress indicators",
+ "No reward items defined yet.",
+ "No saved filter configurations",
+ "No settings found",
+ "No sort criteria defined. Add criteria below.",
+ "No stages defined yet. Add a stage to get started.",
+ "No stages defined. Choose a template or add stages manually.",
+ "No sub-stages defined yet.",
+ "No text replacement rules configured",
+ "No tools available",
+ "No weekends",
+ "No workflow definitions created yet. Click 'Add New Workflow' to create one.",
+ "None",
+ "Not Started",
+ "Not Urgent & Important",
+ "Not Urgent & Not Important",
+ "Not started",
+ "Note:",
+ "Notes",
+ "Notice (Auto-accept)",
+ "Notice threshold",
+ "Notify shortly before each task's due time",
+ "Number of 'Other Views' to show before grouping the rest into an overflow menu (ellipsis)",
+ "Number of days to display in the agenda",
+ "Numeric progress tracking",
+ "OR",
+ "Occurrence levels",
+ "On Completion",
+ "Onboarding",
+ "Only count specific task markers",
+ "Only show certain hours of the day",
+ "Open Discord",
+ "Open Documentation",
+ "Open Timeline",
+ "Open Timeline Sidebar",
+ "Open in external browser",
+ "Optimize Performance",
+ "Optional description for the workflow",
+ "Optional description of the workflow purpose",
+ "Optional habit description",
+ "Optional heading to append content under (leave empty to append to file)",
+ "Optional rules based on event properties (higher priority than timing rules)",
+ "Optional: Only match links containing this text",
+ "Other Views",
+ "Output: ",
+ "Override ICS Status",
+ "Override original ICS event status with mapped status",
+ "Overrides the locale default for calendar views.",
+ "Overrides the locale default for forecast views.",
+ "PM (Afternoon/Evening)",
+ "Parent Tasks",
+ "Past Events Status",
+ "Path Matching Mode",
+ "Path pattern (e.g., Projects/Work)",
+ "Path-based Project Mappings",
+ "Path-based Recognition",
+ "Path:",
+ "Paths",
+ "Pattern",
+ "Pattern (Regular Expression)",
+ "Pattern: ",
+ "Per-task reminders",
+ "Percentage (75%)",
+ "Performance",
+ "Performance Configuration",
+ "Placeholder text",
+ "Placeholder text to display in the capture panel",
+ "Plan",
+ "Planned",
+ "Planning",
+ "Play a game",
+ "Please add at least one event",
+ "Please add at least one mapping value",
+ "Please add at least one stage to the workflow",
+ "Please enter a URL for the source",
+ "Please enter a habit name",
+ "Please enter a name",
+ "Please enter a name for the rule",
+ "Please enter a name for the source",
+ "Please enter a pattern",
+ "Please enter a property name",
+ "Please enter a task to validate",
+ "Please enter a valid URL",
+ "Please enter a workspace name",
+ "Please enter details",
+ "Please enter text for all mapping values",
+ "Please provide a workflow name and ID",
+ "Please restart Obsidian for the Indexer change to take effect.",
+ "Populate FileSource status mapping from your checkbox status configuration",
+ "Port",
+ "Port updated to ",
+ "Practice Task",
+ "Practice creating a task with the format you prefer:",
+ "Prefer Frontmatter Title",
+ "Prefer metadata format of task",
+ "Preferred Time Format",
+ "Prefix (e.g., Projects/ matches Projects/App.md)",
+ "Prefix for generated block reference IDs (e.g., 'timer' creates ^timer-123456-7890)",
+ "Prefix match",
+ "Prepend",
+ "Preset",
+ "Preset Filters",
+ "Preset filters",
+ "Preset name",
+ "Preset saved",
+ "Preview",
+ "Preview of workflow stages (edit after creation for advanced options)",
+ "Preview:",
+ "Priorities",
+ "Priority",
+ "Priority A",
+ "Priority B",
+ "Priority C",
+ "Priority Picker Settings",
+ "Progress Display",
+ "Progress Ranges",
+ "Progress Tracker",
+ "Progress bar",
+ "Progress display mode",
+ "Progress format",
+ "Project",
+ "Project Management",
+ "Project Tree View Settings",
+ "Project Workflow",
+ "Project name",
+ "Project path separator",
+ "Project tag prefix",
+ "Project tags",
+ "Project/tag",
+ "Projects",
+ "Projects List",
+ "Property Rules",
+ "Property name",
+ "Published",
+ "Quadrant Classification Method",
+ "Query",
+ "Quick Add Rules",
+ "Quick Capture",
+ "Quick Install",
+ "Quick Name Templates",
+ "Quick TODO/DONE cycle",
+ "Quick Templates",
+ "Quick Workflow Creation",
+ "Quick capture",
+ "Quick capture is now enabled in your configuration!",
+ "Quickly add common workflow patterns",
+ "Range",
+ "Range-based text",
+ "Rebuild",
+ "Rebuild index",
+ "Recognition Strategies",
+ "Recognize files as tasks based on their file path",
+ "Recognize files as tasks if they have specific frontmatter fields",
+ "Recognize files as tasks if they have specific tags",
+ "Recommended Configurations",
+ "Record Details for {{value0}}",
+ "Record numeric values, e.g., how many cups of water",
+ "Recurrence",
+ "Recurrence date calculation",
+ "Recurring task",
+ "Refresh",
+ "Refresh Interval",
+ "Refresh Statistics",
+ "Refreshing...",
+ "Regenerate",
+ "Regex Flags",
+ "Regex patterns to match in event titles (one per line)",
+ "Regular expression (advanced)",
+ "Regular expression flags (e.g., 'g' for global, 'i' for case-insensitive)",
+ "Regular expression pattern to match. Use parentheses for capture groups.",
+ "Reindex",
+ "Related Tasks",
+ "Remember last mode",
+ "Remember the last used quick capture mode",
+ "Remove",
+ "Remove Column",
+ "Remove Criterion",
+ "Remove Meeting Prefix",
+ "Remove Original Time Expressions",
+ "Remove file extension from filename when using as project name",
+ "Remove filter",
+ "Remove filter group",
+ "Remove parsed time expressions from the task text",
+ "Remove prefix",
+ "Remove stage",
+ "Remove the .md extension from filename when using as task content",
+ "Remove the timestamp from the current task when moving to the next stage",
+ "Remove this status",
+ "Remove timestamp when moving to next stage",
+ "Remove workflow",
+ "Rename",
+ "Rename Workspace",
+ "Replace",
+ "Replace room numbers",
+ "Replacement",
+ "Report Issue",
+ "Report Issues",
+ "Request timeout in seconds",
+ "Requests",
+ "Require All Fields",
+ "Require all specified fields to be present (otherwise any field is sufficient)",
+ "Research Process",
+ "Reset",
+ "Reset All Settings",
+ "Reset Columns",
+ "Reset Settings",
+ "Reset all settings to their default values",
+ "Reset progress ranges to default values",
+ "Reset to Default Presets",
+ "Reset to Defaults",
+ "Reset to defaults",
+ "Restart",
+ "Restart Onboarding",
+ "Restart Server",
+ "Restart the welcome guide and setup wizard",
+ "Result:",
+ "Review",
+ "Review Projects",
+ "Review Your Configuration",
+ "Review the settings that will be applied for your selected mode",
+ "Reward Name/Text",
+ "Reward display type",
+ "Reward items",
+ "Rewards",
+ "Right column title",
+ "Root condition",
+ "Rule Name",
+ "Rule {{value0}}",
+ "Running",
+ "Same day (treat as error)",
+ "Sat first",
+ "Saturday",
+ "Save",
+ "Save Current Filter",
+ "Save Filter Configuration",
+ "Saved. Reopen the view to apply.",
+ "Scan now",
+ "Schedule - Planning & development",
+ "Scheduled",
+ "Scheduled Date",
+ "Scheduled Date Keywords",
+ "Scheduled Dates",
+ "Scheduled date",
+ "Scheduled events",
+ "Scheduled habit",
+ "Scope:",
+ "Search logs...",
+ "Search results",
+ "Search settings",
+ "Search settings...",
+ "Security Warning",
+ "Select a predefined checkbox status collection or customize your own",
+ "Select a preset...",
+ "Select a project to review its tasks.",
+ "Select a project to see related tasks",
+ "Select a saved filter configuration",
+ "Select a saved filter preset to apply",
+ "Select a tag to see related tasks",
+ "Select a template folder above to enable the dropdown.",
+ "Select a template...",
+ "Select between the modern Fluent interface or the classic Legacy interface.",
+ "Select target field",
+ "Select the folder that contains the daily note.",
+ "Select the interface style to use.",
+ "Select the status to count other statuses as. Default is \"Not Started\".",
+ "Select the type of view to create",
+ "Select which days to hide from the calendar",
+ "Select which task property to use for creating columns",
+ "Select which task property to use for left column grouping",
+ "Selected folder was not found in the vault.",
+ "Send now",
+ "Send one notification for today's due tasks at a specific time (HH:mm)",
+ "Server Actions",
+ "Server Configuration",
+ "Server Endpoint",
+ "Server host address. Use 127.0.0.1 for local only, 0.0.0.0 for all interfaces",
+ "Server port number (default: 7777)",
+ "Set value",
+ "Show",
+ "Show Advanced Options",
+ "Show All Days",
+ "Show All Events",
+ "Show All-Day Events",
+ "Show Empty Days",
+ "Show Event Counts",
+ "Show First Day Only",
+ "Show First and Last",
+ "Show Summary",
+ "Show Timed Events",
+ "Show Type",
+ "Show Week Numbers",
+ "Show a bell with count in system tray, status bar, or both",
+ "Show a checkbox for each task in the kanban view.",
+ "Show a quick tutorial on creating your first task",
+ "Show advanced configuration options in task editors",
+ "Show changelog after plugin updates",
+ "Show checkbox",
+ "Show completed tasks",
+ "Show empty project folders",
+ "Show error",
+ "Show in Calendar",
+ "Show in Forecast",
+ "Show in sidebar",
+ "Show indicator with checkbox",
+ "Show matching tasks",
+ "Show percentage",
+ "Show progress bars based on heading",
+ "Show project progress in Projects header",
+ "Show task timer statistics",
+ "Show the status indicator directly next to the checkbox. When enabled, a indicator will be shown next to the checkbox.",
+ "Sibling Tasks",
+ "Sidebar Components",
+ "Sidebar Position",
+ "Simple",
+ "Simple Linear Workflow",
+ "Simple daily check-in habit",
+ "Skip",
+ "Skip archived content",
+ "Sort Criteria",
+ "Source key (e.g., proj)",
+ "Specific task markers to count",
+ "Specify folder paths that will hide progress bars (comma-separated). Example: \"Daily Notes,Projects/Hidden\"",
+ "Specify frontmatter metadata that will hide progress bars. Example: \"hide-progress-bar: true\"",
+ "Specify tags that will hide progress bars (comma-separated, without #). Example: \"no-progress-bar,hide-progress\"",
+ "Specify task markers to exclude from counting. Example: \"?|/\"",
+ "Specify which task markers to count. Example: \"x|X|>|/\"",
+ "Spent time format",
+ "Stage ID",
+ "Stage name",
+ "Stage type",
+ "Standard project management workflow",
+ "Standard task lifecycle with all states",
+ "Standard view",
+ "Start",
+ "Start Date",
+ "Start Date Keywords",
+ "Start Dates",
+ "Start Hour",
+ "Start date",
+ "Start the MCP server to allow external tool connections",
+ "Statistics",
+ "Status",
+ "Status Cancelled",
+ "Status Complete",
+ "Status Cycles Management",
+ "Status In Progress",
+ "Status Incomplete",
+ "Status Mapping",
+ "Status Question",
+ "Status bar",
+ "Status for events detected as holidays",
+ "Status for events happening today",
+ "Status for events in the future",
+ "Status for events that have already ended",
+ "Status mappings work with your Task Status Settings. ",
+ "Status name",
+ "Status sequence",
+ "Status with Icons",
+ "Stop and restart the MCP server",
+ "Stopped",
+ "Strategy for generating default project names",
+ "Strip File Extension",
+ "Strip file extension",
+ "Sub-stage",
+ "Sub-stage ID",
+ "Sub-stage name",
+ "Sub-stages",
+ "Submit",
+ "Suggest trigger character",
+ "Summary Patterns",
+ "Summary/Title",
+ "Sunday",
+ "Support expression in format, like using data.percentages to get the percentage of completed tasks. And using math or even repeat functions to get the result.",
+ "Support hover to show progress info",
+ "Supported Authentication Methods:",
+ "Supported Languages",
+ "Swap words",
+ "Switch",
+ "Switch Workspace",
+ "Sync",
+ "Sync completed successfully",
+ "Sync failed: ",
+ "Sync from Task Status Settings",
+ "Sync now",
+ "Sync this calendar source now",
+ "Sync with Daily Notes plugin",
+ "Syncing...",
+ "System Default",
+ "System tray",
+ "TODO → PLAN → IN PROGRESS → DONE",
+ "TODO ↔ DONE",
+ "TODO.md in any direct subfolder of Work",
+ "Table",
+ "Tag",
+ "Tag Matching Mode",
+ "Tag to identify important tasks (e.g., #important, #key)",
+ "Tag to identify urgent tasks (e.g., #urgent, #fire)",
+ "Tag-based Recognition",
+ "Tags",
+ "Target",
+ "Target Field",
+ "Target file",
+ "Target heading",
+ "Target type",
+ "Task",
+ "Task Content",
+ "Task Counting Settings",
+ "Task Fields",
+ "Task Filter",
+ "Task Format Examples",
+ "Task Genius Icons",
+ "Task Genius icons",
+ "Task Genius icons are designed by",
+ "Task Genius will use moment.js and also this format to parse the daily note path.",
+ "Task Gutter",
+ "Task Handler",
+ "Task Management",
+ "Task Paths",
+ "Task Properties",
+ "Task Properties for Files",
+ "Task Sorting",
+ "Task Status Markers",
+ "Task Symbol",
+ "Task Tags",
+ "Task Timer",
+ "Task Title Source",
+ "Task fields updated. Rebuild the task index to apply to existing files.",
+ "Task index completely rebuilt",
+ "Task mark display style",
+ "Task marker type",
+ "Task paths updated. Rebuild the task index to apply to existing files.",
+ "Task prefix format",
+ "Task tags updated. Rebuild the task index to apply to existing files.",
+ "Tasks",
+ "Tasks Plugin Detected",
+ "Tasks due within this many days are considered urgent",
+ "Tasks inherit metadata properties like priority, context, etc. from file frontmatter when not explicitly set on the task",
+ "Tasks with priority >= this value are considered important (1-5)",
+ "Tasks with priority >= this value are considered urgent (1-5)",
+ "Template file path for new daily notes (optional)",
+ "Template folder",
+ "Template folder is invalid; update the folder to continue.",
+ "Template for displaying completed task time. Use {h} for hours, {m} for minutes, {s} for seconds",
+ "Template note",
+ "Template text with",
+ "Templates",
+ "Templates/Quick Capture",
+ "Terminal (end stage)",
+ "Test",
+ "Test Connection",
+ "Test Input",
+ "Test Rule",
+ "Test the MCP server connection",
+ "Testing",
+ "Testing...",
+ "Text Progress Bar",
+ "Text Replacements",
+ "Text progress indicator",
+ "Text template (use {{PROGRESS}})",
+ "Text to append to incomplete tasks when moved (e.g., 'moved on 2023-12-31')",
+ "Text to append to incomplete tasks when moved (e.g., 'version 1.0')",
+ "Text to append to tasks when moved (e.g., 'archived on 2023-12-31')",
+ "Text to append to tasks when moved (e.g., 'version 1.0')",
+ "Text to replace matches with. Use $1, $2, etc. for capture groups.",
+ "Text to show when multiple items are selected",
+ "Text to show when no items are selected",
+ "The calendar layout this view is based on",
+ "The file where captured text will be saved. You can include a path, e.g., 'folder/Quick Capture.md'. Supports date templates like {{DATE:YYYY-MM-DD}} or {{date:YYYY-MM-DD-HHmm}}",
+ "The frontmatter key to use for project name",
+ "The prefix to add before captured content (e.g., '- [ ]' for task, '- ' for list item)",
+ "The property name in daily note front matter to store count values",
+ "The property name in daily note front matter to store mapping values",
+ "The property name of the daily note front matter",
+ "The stage to proceed to after this one",
+ "The symbols defined here should match those in your checkbox status configuration.",
+ "The type of this workflow stage",
+ "These features are experimental and may be unstable. They could change significantly or be removed in future updates due to Obsidian API changes or other factors. Please use with caution and provide feedback to help improve these features.",
+ "This action cannot be undone.",
+ "This change affects how tasks inherit metadata from files. Rebuild the index now so changes take effect immediately?",
+ "This doesn't look like a valid task. Tasks should start with '- [ ]'",
+ "This will add a new status cycle based on the {{value0}} theme.",
+ "This will override your current checkbox status settings with the {{value0}} theme. Do you want to continue?",
+ "This will replace all your current presets with the default set. Are you sure?",
+ "Thursday",
+ "Time Filter",
+ "Time Format",
+ "Time Format Configuration",
+ "Time Parsing",
+ "Time Parsing Settings",
+ "Time Range Preset",
+ "Time Range Separators",
+ "Time filter is only available for Week and Day views",
+ "Time filter is only available for Week and Day views.",
+ "Time format template",
+ "Time-to-live for cached results in milliseconds (default: 300000 = 5 minutes)",
+ "Timeline Sidebar",
+ "Timeline sidebar opened",
+ "Timer Integration",
+ "Timestamp format",
+ "Timestamp format:",
+ "Timing Rules",
+ "Title for the left column (items list)",
+ "To Do",
+ "Toggle between date-only and date+time input",
+ "Toggle this to allow adding progress bars to regular list items (non-task bullets).",
+ "Toggle this to allow this plugin to add progress bar for Task below the headings.",
+ "Toggle this to allow this plugin to auto complete parent checkbox when all child tasks are completed.",
+ "Toggle this to allow this plugin to count sub tasks when generating progress bar.",
+ "Toggle this to allow this plugin to find the pattern g::number as goal of the parent task.",
+ "Toggle this to allow this plugin to show progress bars in reading mode.",
+ "Toggle this to allow this plugin to show progress info when hovering over the progress bar.",
+ "Toggle this to customize the text for different progress ranges.",
+ "Toggle this to enable Org-mode style quick capture panel.",
+ "Toggle this to enable automatic date management when checkbox status changes. Dates will be added/removed based on your preferred metadata format (Tasks emoji format or Dataview format).",
+ "Toggle this to enable commands for moving completed tasks to another file.",
+ "Toggle this to enable commands for moving incomplete tasks to another file.",
+ "Toggle this to enable commands for sorting tasks.",
+ "Toggle this to enable date picker for tasks. This will add a calendar icon near your tasks which you can click to select a date.",
+ "Toggle this to enable file and folder filtering during task indexing. This can significantly improve performance for large vaults.",
+ "Toggle this to enable hiding progress bars based on tags, folders, or metadata.",
+ "Toggle this to enable showing progress bars based on heading.",
+ "Toggle this to enable the task filter panel",
+ "Toggle this to enable the task gutter.",
+ "Toggle this to enable the timeline sidebar view for quick access to your daily events and tasks.",
+ "Toggle this to only count specific task markers",
+ "Toggle this to show percentage instead of completed/total count.",
+ "Toggle to enable keyboard shortcuts for setting task priorities.",
+ "Toggle to enable or disable the reward system.",
+ "Toggle to enable priority picker dropdown for emoji and letter format priorities.",
+ "Toggle to enable the workflow system for tasks",
+ "Token copied to clipboard",
+ "Tools for managing and rebuilding the task index",
+ "Top Section",
+ "Total: {{value0}} | Success: {{value1}} | Errors: {{value2}}",
+ "Tray indicator",
+ "Treat abandoned tasks as completed",
+ "Tree View",
+ "Try It Yourself",
+ "Try Quick Capture",
+ "Tuesday",
+ "Two column view",
+ "Two column view settings",
+ "Type of authentication required",
+ "Type:",
+ "URL",
+ "URL to the ICS/iCal file (supports http://, https://, and webcal:// protocols)",
+ "URL: ",
+ "Unhide column",
+ "Unique identifier (auto-generated from name)",
+ "Unit",
+ "Unnamed View",
+ "Unsaved Changes",
+ "Untitled View",
+ "Update now",
+ "Updated",
+ "Uptime",
+ "Urgent & Important",
+ "Urgent & Not Important",
+ "Urgent Priority Threshold",
+ "Urgent Tag",
+ "Urgent Threshold Days",
+ "Use",
+ "Use Next Available Port",
+ "Use advanced multi-group filtering with complex conditions",
+ "Use as date type",
+ "Use background worker for file parsing to improve performance. Recommended for large vaults.",
+ "Use boolean operations: AND, OR, NOT. Example: 'text content AND #tag1 AND DATE:<2022-01-02 NOT PRIORITY:>=#B' - Supports >, <, =, >=, <=, != for PRIORITY and DATE.",
+ "Use boolean operations: AND, OR, NOT. Example: 'text content AND #tag1'",
+ "Use custom goal for progress bar",
+ "Use daily note path as date",
+ "Use default naming strategy when no project is explicitly defined",
+ "Use different values to map, e.g., emotion tracking",
+ "Use filename",
+ "Use folder name",
+ "Use left/right workspace side leaves for Sidebar and Details. When enabled, the main fluent view won't render in-view sidebar or details.",
+ "Use metadata field",
+ "Use placeholders like {{COMPLETED}}, {{TOTAL}}, {{PERCENT}}, etc.",
+ "Use quick capture panel to quickly capture tasks from anywhere in Obsidian.",
+ "Use relative time for date",
+ "Use relative time for date in task list item, e.g. 'yesterday', 'today', 'tomorrow', 'in 2 days', '3 months ago', etc.",
+ "Use system notifications when possible",
+ "Use template for new files",
+ "Use the command palette to access timer data management:",
+ "Use these templates as a starting point to create your own custom calendar views.",
+ "Use timing rules",
+ "Use workspace side leaves",
+ "Use {{DATE:format}} for date formatting (e.g., {{DATE:YYYY-MM-DD}}",
+ "Used by File mode (requires FileSource). Leave empty for vault root.",
+ "Used by File mode to prefill the file name input (supports date templates like {{DATE:YYYY-MM-DD}})",
+ "User Interface",
+ "Valid task format!",
+ "Validate Task",
+ "Value",
+ "Value cannot be empty",
+ "Value mapping",
+ "Version",
+ "Version marker",
+ "Version marker text",
+ "View Configuration",
+ "View Icon",
+ "View Logs",
+ "View Name",
+ "View Server Logs",
+ "View all MCP server tool calls and their results",
+ "View configuration saved.",
+ "View copied successfully: ",
+ "View deleted: ",
+ "View duplicated: ",
+ "View the documentation for this plugin",
+ "View type",
+ "Views",
+ "Views are disabled",
+ "WARNING: Enabling the MCP server will allow external AI tools and applications to access and modify your task data. This includes:\n\n• Reading all tasks and their details\n• Creating new tasks\n• Updating existing tasks\n• Deleting tasks\n• Accessing task metadata and properties\n\nOnly enable this if you trust the applications that will connect to the MCP server. Make sure to keep your authentication token secure.\n\nDo you want to continue?",
+ "Warning",
+ "Watch an episode of a favorite series",
+ "Wednesday",
+ "Week",
+ "Week View",
+ "Weekends Only",
+ "Weekends only",
+ "What should be used as the task title when a file becomes a task",
+ "When File mode is used, create the new note from a template and then insert the captured content.",
+ "When some but not all child tasks are completed, mark the parent checkbox as 'In Progress'. Only works when 'Auto complete parent' is enabled.",
+ "When updating task content, prefer updating frontmatter title over renaming the file. This protects the original filename.",
+ "Where to insert completed tasks in the target file",
+ "Where to insert incomplete tasks in the target file",
+ "Whether this rule is active",
+ "Whether this source is active",
+ "Whether to show holiday events in calendar view",
+ "Whether to show holiday events in forecast view",
+ "Which day should the week start on",
+ "Which field to apply the replacement to",
+ "Whitelist",
+ "Whitelist (Include only)",
+ "Whitelist: Include only specified paths | Blacklist: Exclude specified paths",
+ "Whitelist: include only specified paths. Blacklist: exclude specified paths.",
+ "Why File Filtering?",
+ "With Dataview Metadata",
+ "With Emoji Metadata",
+ "With current file link",
+ "With current file link for incomplete tasks",
+ "Workflow",
+ "Workflow & Automation",
+ "Workflow ID",
+ "Workflow Name",
+ "Workflow Stages",
+ "Workflow Template",
+ "Workflow definitions",
+ "Workflow name",
+ "Workflows",
+ "Working Hours (9:00-18:00)",
+ "Working On",
+ "Workspace \"{{name}}\" created",
+ "Workspace \"{{name}}\" deleted",
+ "Workspace Color",
+ "Workspace Icon",
+ "Workspace Management",
+ "Workspace Name",
+ "Workspace manager is not available.",
+ "Workspace updated",
+ "Workspaces",
+ "Write content tags to frontmatter",
+ "Writing",
+ "Year",
+ "Year View",
+ "Year view displays 12 mini-month calendars. Use the Date Filter tab to hide weekends if needed.",
+ "Yes, I understand the risks",
+ "You can choose dataview format or tasks format, that will influence both index and save format.",
+ "You can choose due, start, or scheduled as the date type for tasks.",
+ "You can customize any of these settings later in the plugin settings",
+ "You can customize the progress bar behind the parent task(usually at the end of the task). You can also customize the progress bar for the task below the heading.",
+ "You can modify all settings below. The original view will remain unchanged.",
+ "You have unsaved changes. Save before closing?",
+ "You need to close all bases view if you already create task view in them and remove unused view via edit them manually when disable this feature.",
+ "You need to set `yyyy` instead of `YYYY` in the format string. And `dd` instead of `DD`.",
+ "You've Earned a Reward!",
+ "Your custom calendar views. Drag to reorder, toggle visibility, or edit settings.",
+ "Your reward:",
+ "all .md files in Projects and subfolders",
+ "all .md files in Projects folder",
+ "archived on",
+ "archived on {{date}}",
+ "as a placeholder for the percentage value",
+ "common",
+ "compatibility documentation",
+ "contains",
+ "does not contain",
+ "e.g., every day, every week",
+ "ends with",
+ "equals",
+ "files ending with .task.md in Tasks folder",
+ "files starting with date in Tasks",
+ "filter",
+ "filter group",
+ "filter in this group",
+ "is",
+ "is empty",
+ "is false",
+ "is not",
+ "is not empty",
+ "is not set",
+ "is set",
+ "is true",
+ "legendary",
+ "matches all files under Projects folder",
+ "matches all files under Tasks/2024 folder",
+ "min",
+ "moved",
+ "moved on",
+ "moved on {{date}}",
+ "placeholder",
+ "projects selected",
+ "rare",
+ "selected items",
+ "starts with",
+ "tags selected",
+ "version 1.0",
+ "{title} ({count} days)",
+ "{{count}} field(s) configured",
+ "{{count}} format(s) configured",
+ "{{count}} heading(s) configured",
+ "{{count}} path(s) configured",
+ "{{count}} symbol(s) configured",
+ "{{count}} tag(s) configured",
+ "{{hidden}}/{{total}} hidden",
+ "{{status}} Task Symbols",
+ "{{value0}} theme workflow",
+ "{{value0}} · Heatmap",
+ "{{value0}}: Error",
+ "{{value0}}ms",
+ "⚠️ **WARNING**: Switching to 0.0.0.0 will make the MCP server accessible from external networks.\n\nThis could expose your Obsidian data to:\n- Other devices on your local network\n- Potentially the internet if your firewall is misconfigured\n\n**Only proceed if you:**\n- Understand the security implications\n- Have properly configured your firewall\n- Need external access for legitimate reasons\n\nAre you sure you want to continue?",
+ "📅 = Due date, 🔺 = High priority, #project/ = Docs project tag"
+]
diff --git a/scripts/task-form-layout-fixture.mjs b/scripts/task-form-layout-fixture.mjs
new file mode 100644
index 000000000..c98e29989
--- /dev/null
+++ b/scripts/task-form-layout-fixture.mjs
@@ -0,0 +1,12 @@
+// Render actual capture/edit DOM exported by the UI regression fixture.
+import fs from 'node:fs';
+import path from 'node:path';
+const output=path.resolve('output/playwright');
+const css=['src/styles/quick-capture.css','src/styles/fluent/fluent-main.css',path.join(output,'pause.css')].map(file=>fs.readFileSync(file,'utf8')).join('\n');
+const read=name=>fs.readFileSync(path.join(output,name+'.html'),'utf8');
+fs.writeFileSync(path.join(output,'task-forms.html'),`Task Genius shared task forms
Filter label
${read('filter')}
New task
${read('capture')}
Edit task
${read('edit')}`);
+console.log('Task form fixture ready.');
diff --git a/src/__mocks__/obsidian.ts b/src/__mocks__/obsidian.ts
index f5ec0e6a2..a0af6e936 100644
--- a/src/__mocks__/obsidian.ts
+++ b/src/__mocks__/obsidian.ts
@@ -144,6 +144,11 @@ export class TFile {
}
}
+export class TFolder {
+ path: string;
+ constructor(path = "") { this.path = path; }
+}
+
export class Notice {
constructor(message: string) {
// Mock implementation
diff --git a/src/__tests__/WriteAPI.board-drag.test.ts b/src/__tests__/WriteAPI.board-drag.test.ts
new file mode 100644
index 000000000..2725516cd
--- /dev/null
+++ b/src/__tests__/WriteAPI.board-drag.test.ts
@@ -0,0 +1,27 @@
+// Use the real local-time formatter; the shared mock formats midnight as UTC.
+jest.mock("obsidian", () => ({ ...jest.requireActual("obsidian"), moment: jest.requireActual("moment/min/moment-with-locales") }));
+import { App, MetadataCache, TFile } from "obsidian";
+import { WriteAPI } from "@/dataflow/api/WriteAPI";
+import { ConfigurableTaskParser } from "@/dataflow/core/ConfigurableTaskParser";
+
+test("board moves survive writing and reindexing while keeping task deadlines and unrelated text", async () => {
+ const app=new App() as any;
+ const file=Object.assign(new TFile(),{path:"Tasks.md",name:"Tasks.md"});
+ let text="- [ ] Keep this [[Reference]] #keep #urgent #important 📅 2026-11-10";
+ const parser=new ConfigurableTaskParser({} as any);let task=parser.parseLegacy(text,file.path)[0];
+ const vault:any={getAbstractFileByPath:()=>file,read:async()=>text,modify:async(_file:any,next:string)=>{text=next;}};
+ app.vault=vault;app.workspace={trigger:jest.fn()};
+ const metadata=new MetadataCache() as any;metadata.getFileCache=()=>({frontmatter:{}});
+ const plugin:any={settings:{preferMetadataFormat:"tasks",projectTagPrefix:{tasks:"project",dataview:"project"},contextTagPrefix:{tasks:"@",dataview:"context"},taskStatuses:{completed:"x"},autoDateManager:{manageCompletedDate:true}}};
+ const api=new WriteAPI(app,vault,metadata,plugin,async()=>task);
+ const originalDeadline=task.metadata.dueDate;
+ for(const quadrant of ["urgent-important","not-urgent-important","urgent-not-important","not-urgent-not-important"]){
+ const tags=["#keep",`#quadrant/${quadrant}`];
+ expect((await api.updateTask({taskId:task.id,updates:{metadata:{...task.metadata,tags}}})).success).toBe(true);
+ task=parser.parseLegacy(text,file.path)[0];
+ expect(task.metadata.tags).toContain(`#quadrant/${quadrant}`);expect(task.metadata.tags.filter(tag=>tag.includes("quadrant/"))).toHaveLength(1);
+ expect(task.metadata.dueDate).toBe(originalDeadline);expect(text).toContain("[[Reference]]");expect(task.metadata.tags).toContain("#keep");
+ }
+ expect((await api.updateTask({taskId:task.id,updates:{status:"x",completed:true,metadata:{...task.metadata,completedDate:Date.now()}}})).success).toBe(true);
+ task=parser.parseLegacy(text,file.path)[0];expect(task.completed).toBe(true);expect(task.metadata.completedDate).toBeDefined();expect(text).toMatch(/✅ \d{4}-\d{2}-\d{2}/);
+});
diff --git a/src/__tests__/WriteAPI.canvas-project-move.test.ts b/src/__tests__/WriteAPI.canvas-project-move.test.ts
new file mode 100644
index 000000000..6fe51323a
--- /dev/null
+++ b/src/__tests__/WriteAPI.canvas-project-move.test.ts
@@ -0,0 +1,53 @@
+import { App, MetadataCache, TFile, TFolder } from "obsidian";
+import { WriteAPI } from "@/dataflow/api/WriteAPI";
+import type { Task } from "@/types/task";
+
+describe("Canvas task project assignment", () => {
+ function setup(deleteSucceeds: boolean) {
+ const files = new Map }>();
+ const folder = Object.assign(new TFolder(), { path: "Projects" });
+ const app: any = new App();
+ const vault: any = {
+ getAbstractFileByPath: (path: string) => path === "Projects" ? folder : files.get(path)?.file || null,
+ getMarkdownFiles: () => [...files.values()].map(value => value.file),
+ createFolder: jest.fn(async () => folder),
+ create: jest.fn(async (path: string, text: string) => {
+ const file = Object.assign(new TFile(), { path, name: path.split("/").pop() || path });
+ files.set(path, { file, text, fm: { project: "New Project" } });
+ return file;
+ }),
+ read: jest.fn(async (file: TFile) => files.get(file.path)!.text),
+ modify: jest.fn(async (file: TFile, text: string) => { files.get(file.path)!.text = text; }),
+ };
+ const metadataCache = new MetadataCache() as any;
+ metadataCache.getFileCache = (file: TFile) => ({ frontmatter: files.get(file.path)?.fm });
+ app.vault = vault;
+ app.metadataCache = metadataCache;
+ app.workspace = { trigger: jest.fn(), on: jest.fn(() => ({ unload: jest.fn() })) };
+ const task = {
+ id: "canvas-task-1", content: "Plan whiteboard", filePath: "Board.canvas", line: 1,
+ completed: false, status: " ", originalMarkdown: "- [ ] Plan whiteboard #project/OldProject",
+ metadata: { sourceType: "canvas", canvasNodeId: "node-1", project: "OldProject", tags: ["#project/OldProject"], children: [] },
+ } as Task;
+ const plugin: any = { settings: { projectTagPrefix: { tasks: "project", dataview: "project" } } };
+ const api = new WriteAPI(app, vault, metadataCache, plugin, async () => task);
+ api.canvasTaskUpdater.deleteCanvasTask = jest.fn(async () => ({ success: deleteSucceeds }));
+ return { api, task, files };
+ }
+
+ test("converts a Canvas checkbox to a project Markdown task and removes its old project tag", async () => {
+ const { api, task, files } = setup(true);
+ const result = await api.updateTask({ taskId: task.id, updates: { metadata: { ...task.metadata, project: "New Project" } as any } });
+ expect(result.success).toBe(true);
+ expect(files.get("Projects/New-Project.md")?.text).toContain("- [ ] Plan whiteboard");
+ expect(files.get("Projects/New-Project.md")?.text).not.toContain("#project/");
+ expect(api.canvasTaskUpdater.deleteCanvasTask).toHaveBeenCalledWith(task, false);
+ });
+
+ test("rolls back the project note if removing the Canvas task fails", async () => {
+ const { api, task, files } = setup(false);
+ const result = await api.updateTask({ taskId: task.id, updates: { metadata: { ...task.metadata, project: "New Project" } as any } });
+ expect(result.success).toBe(false);
+ expect(files.get("Projects/New-Project.md")?.text).not.toContain("Plan whiteboard");
+ });
+});
diff --git a/src/__tests__/WriteAPI.optional-datetime.test.ts b/src/__tests__/WriteAPI.optional-datetime.test.ts
new file mode 100644
index 000000000..c66ea0b06
--- /dev/null
+++ b/src/__tests__/WriteAPI.optional-datetime.test.ts
@@ -0,0 +1,70 @@
+jest.mock("obsidian", () => ({ ...jest.requireActual("obsidian"), moment: jest.requireActual("moment/min/moment-with-locales") }));
+import { App, MetadataCache, TFile } from "obsidian";
+import { WriteAPI } from "@/dataflow/api/WriteAPI";
+import { ConfigurableTaskParser } from "@/dataflow/core/ConfigurableTaskParser";
+import { parseOptionalDateTime, formatOptionalDateTime, taskDatePrecisions } from "@/utils/date/optional-date-time";
+
+test.each(["2026-11-12", "2026-11-12 09:35", "2026-11-12 00:00"])("date or datetime survives saving and reindexing: %s", async (value: string) => {
+ const app=new App() as any,file=Object.assign(new TFile(),{path:"Task.md"});let text="- [ ] Test 📅 2026-12-01";
+ const parser=new ConfigurableTaskParser();let task=parser.parseLegacy(text,file.path)[0];
+ const vault:any={getAbstractFileByPath:()=>file,read:async()=>text,modify:async(_file:any,next:string)=>{text=next;}};app.vault=vault;app.workspace={trigger:jest.fn()};const cache=new MetadataCache() as any;cache.getFileCache=()=>({frontmatter:{}});
+ const plugin:any={settings:{preferMetadataFormat:"tasks",taskStatuses:{completed:"x"},projectTagPrefix:{tasks:"project"},contextTagPrefix:{tasks:"@"}}};
+ const api=new WriteAPI(app,vault,cache,plugin,async()=>task),date=parseOptionalDateTime(value)!;
+ expect((await api.updateTask({taskId:task.id,updates:{metadata:{...task.metadata,scheduledDate:date.timestamp,datePrecision:{...task.metadata.datePrecision,scheduledDate:date.precision}}}})).success).toBe(true);
+ expect(text).toContain(`⏳ ${value}`);expect(text).toContain("📅 2026-12-01");
+ task=parser.parseLegacy(text,file.path)[0];expect(formatOptionalDateTime(task.metadata.scheduledDate,task.metadata.datePrecision?.scheduledDate)).toBe(value);
+ // Editing an unrelated property must keep an explicit 00:00 as a time.
+ expect((await api.updateTask({taskId:task.id,updates:{metadata:{...task.metadata,priority:3}}})).success).toBe(true);expect(text).toContain(`⏳ ${value}`);
+});
+
+test("raw Markdown date precision wins over legacy ambiguous timestamps",()=>{
+ expect(taskDatePrecisions({originalMarkdown:"- [ ] Test 📅 2026-11-12 ⏳ 2026-11-13 00:00"})).toMatchObject({dueDate:"date",scheduledDate:"datetime"});
+ expect(parseOptionalDateTime("2026-02-31")).toBeNull();expect(parseOptionalDateTime("2026-11-12 25:00")).toBeNull();
+});
+
+
+test("clearing an existing time saves a date-only value and stays cleared after reindexing", async()=>{
+ const app=new App() as any,file=Object.assign(new TFile(),{path:"Task.md"});let text="- [ ] Test 📅 2026-11-12 09:35";
+ const parser=new ConfigurableTaskParser();let task=parser.parseLegacy(text,file.path)[0];const vault:any={getAbstractFileByPath:()=>file,read:async()=>text,modify:async(_file:any,next:string)=>{text=next;}};app.vault=vault;app.workspace={trigger:jest.fn()};const cache=new MetadataCache() as any;cache.getFileCache=()=>({frontmatter:{}});
+ const plugin:any={settings:{preferMetadataFormat:"tasks",taskStatuses:{completed:"x"},projectTagPrefix:{tasks:"project"},contextTagPrefix:{tasks:"@"}}};const api=new WriteAPI(app,vault,cache,plugin,async()=>task),date=parseOptionalDateTime("2026-11-12")!;
+ expect((await api.updateTask({taskId:task.id,updates:{metadata:{...task.metadata,dueDate:date.timestamp,datePrecision:{...task.metadata.datePrecision,dueDate:"date"}}}})).success).toBe(true);expect(text).not.toContain("09:35");task=parser.parseLegacy(text,file.path)[0];expect(formatOptionalDateTime(task.metadata.dueDate,task.metadata.datePrecision?.dueDate)).toBe("2026-11-12");
+});
+
+
+test("calendar workflow saves completion dates only at the completed step and retains deadlines", async () => {
+ const app = new App() as any;
+ const file = Object.assign(new TFile(), {path: "Calendar.md"});
+ let text = "- [ ] Review [[Reference]] #keep 📅 2026-12-01";
+ const parser = new ConfigurableTaskParser();
+ let task = parser.parseLegacy(text, file.path)[0];
+ const vault: any = {
+ getAbstractFileByPath: () => file,
+ read: async () => text,
+ modify: async (_file: unknown, next: string) => { text = next; },
+ };
+ app.vault = vault;
+ app.workspace = {trigger: jest.fn()};
+ const cache = new MetadataCache() as any;
+ cache.getFileCache = () => ({frontmatter: {}});
+ const plugin: any = {settings: {
+ preferMetadataFormat: "tasks",
+ taskStatuses: {completed: "x", notStarted: " ", planned: "?", inProgress: "/", archived: "a", abandoned: "-"},
+ projectTagPrefix: {tasks: "project"},
+ contextTagPrefix: {tasks: "@"},
+ }};
+ const api = new WriteAPI(app, vault, cache, plugin, async () => task);
+ for (const status of ["?", "/", "x", "=", "-", " "]) {
+ const completed = status === "x";
+ const result = await api.updateTask({
+ taskId: task.id,
+ updates: {status, completed, metadata: {completedDate: completed ? Date.now() : undefined} as typeof task.metadata},
+ });
+ expect(result.success).toBe(true);
+ task = parser.parseLegacy(text, file.path)[0];
+ expect(task.status).toBe(status);
+ expect(task.completed).toBe(completed);
+ expect(!!task.metadata.completedDate).toBe(completed);
+ expect(text).toContain("📅 2026-12-01");
+ expect(text).toContain("[[Reference]] #keep");
+ }
+});
diff --git a/src/__tests__/WriteAPI.project-move.test.ts b/src/__tests__/WriteAPI.project-move.test.ts
new file mode 100644
index 000000000..a06057428
--- /dev/null
+++ b/src/__tests__/WriteAPI.project-move.test.ts
@@ -0,0 +1,62 @@
+import { App, MetadataCache, TFile, TFolder } from "obsidian";
+import { WriteAPI } from "@/dataflow/api/WriteAPI";
+import type { Task } from "@/types/task";
+
+describe("WriteAPI project assignment", () => {
+ test("moves the task into a project note instead of writing a project tag", async () => {
+ const files = new Map }>();
+ const folder = Object.assign(new TFolder(), { path: "Projects" });
+ const app = new App() as any;
+ const fakeVault: any = {
+ getAbstractFileByPath: (path: string) => path === "Projects" ? folder : files.get(path)?.file || null,
+ getMarkdownFiles: () => [...files.values()].map(value => value.file),
+ createFolder: jest.fn(async () => folder),
+ create: jest.fn(async (path: string, text: string) => {
+ const file = Object.assign(new TFile(), { path, name: path.split("/").pop() || path });
+ files.set(path, { file, text, fm: { project: "New Project" } });
+ return file;
+ }),
+ read: jest.fn(async (file: TFile) => files.get(file.path)!.text),
+ modify: jest.fn(async (file: TFile, text: string) => { files.get(file.path)!.text = text; }),
+ };
+ const source = Object.assign(new TFile(), { path: "Notes.md", name: "Notes.md" });
+ files.set(source.path, { file: source, text: "- [ ] Write report #project/OldProject\n", fm: {} });
+ app.vault = fakeVault;
+ app.workspace = { trigger: jest.fn(), on: jest.fn(() => ({ unload: jest.fn() })) };
+ const metadataCache = new MetadataCache() as any;
+ metadataCache.getFileCache = (file: TFile) => ({ frontmatter: files.get(file.path)?.fm });
+ const task = {
+ id: "task-1", content: "Write report", filePath: source.path, line: 0,
+ completed: false, status: " ", originalMarkdown: "- [ ] Write report #project/OldProject",
+ metadata: { tags: ["#project/OldProject"], project: "OldProject", children: [] },
+ } as Task;
+ const plugin: any = { settings: {
+ preferMetadataFormat: "tasks", projectTagPrefix: { tasks: "project", dataview: "project" },
+ contextTagPrefix: { tasks: "@", dataview: "context" }, taskStatuses: { completed: "x" },
+ autoDateManager: { manageStartDate: false, manageCancelledDate: false },
+ } };
+ const api = new WriteAPI(app, fakeVault, metadataCache, plugin, async () => task);
+
+ const result = await api.updateTask({ taskId: task.id, updates: { metadata: { ...task.metadata, project: "New Project" } as any } });
+
+ expect(result.success).toBe(true);
+ expect(files.get("Notes.md")?.text).not.toContain("Write report");
+ expect(files.get("Projects/New-Project.md")?.text).toContain("- [ ] Write report");
+ expect(files.get("Projects/New-Project.md")?.text).not.toContain("#project/");
+ const created = await api.createTask({ content: "New capture", project: "New Project", filePath: "Notes.md", tags: ["#project/OldProject", "writing"] });
+ expect(created.success).toBe(true);
+ expect(files.get("Notes.md")?.text).not.toContain("New capture");
+ expect(files.get("Projects/New-Project.md")?.text).toContain("- [ ] New capture #writing");
+ expect(files.get("Projects/New-Project.md")?.text).not.toContain("#project/");
+ const captured = await api.addProjectTaskToQuickCapture({ content: "Project quick capture", project: "New Project" });
+ expect(captured).toEqual({ filePath: "Projects/New-Project.md", success: true });
+ expect(files.get("Projects/New-Project.md")?.text).toContain("- [ ] Project quick capture");
+ task.filePath = "Projects/New-Project.md";
+ task.line = files.get(task.filePath)!.text.split("\n").findIndex(line => line.includes("New capture"));
+ task.originalMarkdown = "- [ ] New capture #writing";
+ task.metadata = { ...task.metadata, project: "New Project", tags: ["#writing"] };
+ const edited = await api.updateTask({ taskId: task.id, updates: { metadata: { ...task.metadata, priority: 4 } } });
+ expect(edited.success).toBe(true);
+ expect(files.get("Projects/New-Project.md")?.text).not.toContain("#project/");
+ });
+});
diff --git a/src/__tests__/fluent-status-menu-regression.test.ts b/src/__tests__/fluent-status-menu-regression.test.ts
new file mode 100644
index 000000000..98815cf2f
--- /dev/null
+++ b/src/__tests__/fluent-status-menu-regression.test.ts
@@ -0,0 +1,55 @@
+jest.mock("@/components/features/quick-capture/modals/QuickCaptureModalWithSwitch", () => ({ QuickCaptureModal: class {} }));
+jest.mock("@/components/features/task/view/details", () => ({ createTaskCheckbox: jest.fn() }));
+jest.mock("@/components/ui/modals/ConfirmModal", () => ({ ConfirmModal: class {} }));
+jest.mock("@/components/ui/date-picker/DatePickerModal", () => ({ DatePickerModal: class {} }));
+jest.mock("@/components/ui/modals/TextPromptModal", () => ({ TextPromptModal: class {} }));
+const mockMenuItems: any[] = [];
+jest.mock("obsidian", () => {
+ const original = jest.requireActual("obsidian");
+ class TestMenu {
+ addItem(callback: (item: any) => void) {
+ const item: any = { label: "", callback: undefined };
+ item.titleEl = { createEl: (_tag: string, options: any) => { if (options?.text) item.label = options.text; return item.titleEl; } };
+ const proxy = new Proxy(item, { get(target, name) {
+ if (name in target) return target[name];
+ if (name === "setSubmenu") return () => new TestMenu();
+ if (name === "setTitle") return (text: string) => { target.label = text; return proxy; };
+ if (name === "onClick") return (fn: any) => { target.callback = fn; return proxy; };
+ return () => proxy;
+ } });
+ callback(proxy); mockMenuItems.push(item); return this;
+ }
+ addSeparator() { return this; }
+ showAtMouseEvent() {}
+ }
+ return { ...original, Menu: TestMenu };
+});
+import { FluentActionHandlers } from "@/components/features/fluent/managers/FluentActionHandlers";
+import type { Task } from "@/types/task";
+
+const marks = { "Not Started": " ", Planned: "?", "In Progress": "/", Completed: "x", Paused: "=", Abandoned: "-" };
+function harness() {
+ mockMenuItems.length = 0;
+ const plugin: any = { settings: { taskStatuses: { completed: "x", inProgress: "/", abandoned: "-", notStarted: " ", planned: "?" }, statusCycles: [{ id: "default", name: "Default", enabled: true, priority: 0, cycle: Object.keys(marks), marks }] } };
+ const handler: any = new FluentActionHandlers({} as any, plugin, () => "default", () => false);
+ for (const method of ["addPriorityMenuItems", "addDateMenuItems", "addTimerMenuItems"]) handler[method] = jest.fn();
+ const update = jest.spyOn(handler, "handleTaskUpdate").mockResolvedValue(undefined);
+ const task = Object.freeze({ id: "one", content: "Write report", status: " ", completed: false, metadata: Object.freeze({ tags: [], children: [] }) }) as unknown as Task;
+ handler.handleTaskContextMenu({} as MouseEvent, task);
+ return { handler, update, task };
+}
+describe("Fluent status context menu", () => {
+ for (const [name, mark] of Object.entries(marks).filter(([, mark]) => mark !== " ")) it(`writes the selected ${name} status using the original task`, async () => {
+ const { update, task } = harness();
+ const item = mockMenuItems.find(item => item.label === name);
+ expect(item?.callback).toBeDefined(); await item.callback();
+ expect(update).toHaveBeenCalledWith(task, expect.objectContaining({ status: mark, completed: mark === "x" }));
+ expect(task.status).toBe(" "); expect(task.metadata.completedDate).toBeUndefined();
+ });
+ it("writes the next cycle status instead of comparing an already changed task", async () => {
+ const { update, task } = harness();
+ const item = mockMenuItems.find(item => item.label.includes("→") && item.label.includes("Planned"));
+ expect(item?.callback).toBeDefined(); await item.callback();
+ expect(update).toHaveBeenCalledWith(task, expect.objectContaining({ status: "?" }));
+ });
+});
diff --git a/src/__tests__/legacy-settings-invalidation.test.ts b/src/__tests__/legacy-settings-invalidation.test.ts
new file mode 100644
index 000000000..5ac6c8e9d
--- /dev/null
+++ b/src/__tests__/legacy-settings-invalidation.test.ts
@@ -0,0 +1,40 @@
+import { DataflowOrchestrator } from "@/dataflow/Orchestrator";
+import { snapshotIndexSettings } from "@/dataflow/settings-signature";
+
+describe("legacy settings invalidation", () => {
+ function harness() {
+ const settings = { projectConfig: { metadataConfig: { metadataKey: "project" } }, taskStatuses: { completed: "x" }, showProgress: true };
+ const orchestrator: any = Object.create(DataflowOrchestrator.prototype);
+ Object.assign(orchestrator, {
+ indexSettingsSignature: snapshotIndexSettings(settings), settingsUpdateQueue: Promise.resolve(),
+ app: { workspace: { trigger: jest.fn() } }, plugin: { settings },
+ augmentor: { updateSettings: jest.fn() }, projectResolver: { updateOptions: jest.fn() },
+ workerOrchestrator: { setWorkerProcessingEnabled: jest.fn() }, onSettingsChange: jest.fn().mockResolvedValue(undefined),
+ });
+ return { settings, orchestrator };
+ }
+ it("detects nested edits to the same settings object and invalidates only once", async () => {
+ const { settings, orchestrator } = harness(); settings.projectConfig.metadataConfig.metadataKey = "project_name";
+ await orchestrator.updateSettings(settings); await orchestrator.updateSettings(settings);
+ expect(orchestrator.onSettingsChange).toHaveBeenCalledTimes(1);
+ expect(orchestrator.onSettingsChange).toHaveBeenCalledWith(["parser", "augment", "project"]);
+ });
+ it("does not rebuild the index for display-only changes", async () => {
+ const { settings, orchestrator } = harness(); settings.showProgress = false;
+ await orchestrator.updateSettings(settings); expect(orchestrator.onSettingsChange).not.toHaveBeenCalled();
+ });
+ it("retries failed invalidation instead of recording the change as completed", async () => {
+ const { settings, orchestrator } = harness(); settings.taskStatuses.completed = "X";
+ orchestrator.onSettingsChange.mockRejectedValueOnce(new Error("temporary failure"));
+ await expect(orchestrator.updateSettings(settings)).rejects.toThrow("temporary failure");
+ await orchestrator.updateSettings(settings); expect(orchestrator.onSettingsChange).toHaveBeenCalledTimes(2);
+ });
+ it("serializes a newer change while an earlier rebuild is pending", async () => {
+ const { settings, orchestrator } = harness(); let finish!: () => void; let entered!: () => void; const started = new Promise(resolve => { entered = resolve; });
+ orchestrator.onSettingsChange.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; entered(); }));
+ settings.taskStatuses.completed = "X"; const first = orchestrator.updateSettings(settings); await started;
+ settings.taskStatuses.completed = "*"; const second = orchestrator.updateSettings(settings); finish();
+ await Promise.all([first, second]); expect(orchestrator.onSettingsChange).toHaveBeenCalledTimes(2);
+ expect(orchestrator.indexSettingsSignature).toBe(snapshotIndexSettings(settings));
+ });
+});
diff --git a/src/__tests__/legacy-settings-language.test.ts b/src/__tests__/legacy-settings-language.test.ts
new file mode 100644
index 000000000..c453ec5da
--- /dev/null
+++ b/src/__tests__/legacy-settings-language.test.ts
@@ -0,0 +1,30 @@
+import { readFileSync } from "fs";
+import { join } from "path";
+import english from "@/translations/locale/en";
+import chinese from "@/translations/locale/zh-cn";
+import { translationManager } from "@/translations/manager";
+
+describe("legacy settings language coverage", () => {
+ const keys: string[] = JSON.parse(readFileSync(join(process.cwd(), "scripts/settings-i18n-keys.json"), "utf8"));
+ afterEach(() => translationManager.setLocale("en"));
+ it("provides both language entries for every audited settings label and preserves substitutions", () => {
+ const placeholders = (value: string) => (value.match(/\{\{[^{}]+\}\}|\{[A-Za-z_][\w]*\}/g) || []).sort();
+ for (const key of keys) {
+ for (const dictionary of [english, chinese] as Record[]) {
+ expect(dictionary[key]).toBeTruthy();
+ expect(placeholders(dictionary[key])).toEqual(placeholders(key));
+ }
+ }
+ });
+ it("renders the index and timer labels in Chinese while keeping user names in messages", () => {
+ translationManager.setLocale("zh-cn");
+ expect(translationManager.t("Index & Sources")).toBe("索引与来源");
+ expect(translationManager.t("Enable Task Timer")).toBe("启用任务计时器");
+ expect(translationManager.t("{{value0}} theme workflow", { interpolation: { value0: "My personal theme" } })).toBe("My personal theme 主题工作流");
+ });
+ it("keeps English available without fetching a language pack", () => {
+ translationManager.setLocale("en");
+ expect(translationManager.t("Enable Task Timer")).toBe("Enable Task Timer");
+ expect(translationManager.t("Index & Sources")).toBe("Index & Sources");
+ });
+});
diff --git a/src/__tests__/native-workflows-regression.test.ts b/src/__tests__/native-workflows-regression.test.ts
new file mode 100644
index 000000000..4c5c9f82c
--- /dev/null
+++ b/src/__tests__/native-workflows-regression.test.ts
@@ -0,0 +1,87 @@
+import { App } from "obsidian";
+import { stampStatusTransitions } from "@/services/markdown-status-sync";
+import { projectDateChange } from "@/managers/project-dates";
+import { dependencyWouldCycle, TaskDependencyPicker } from "@/components/features/task/edit/TaskDependencyPicker";
+import { defaultSavedFilters, savedTaskFilters } from "@/utils/task/saved-task-filters";
+import { FluentDataManager } from "@/components/features/fluent/managers/FluentDataManager";
+import { Task } from "@/types/task";
+
+const task = (id: string, status = " ", metadata: Record = {}) => ({ id, content: id, status, completed: status === "x", filePath: "Inbox.md", line: 0, metadata } as Task);
+describe("ordinary note status dates", () => {
+ const stamp = (before: string, after: string, format: "tasks" | "dataview" = "tasks") => stampStatusTransitions(before, after, "x|X", format, "2026-11-08");
+ test("stamps a checked task in Tasks syntax", () => expect(stamp("- [ ] Exercise", "- [x] Exercise")).toBe("- [x] Exercise ✅ 2026-11-08"));
+ test("handles multiple changes and numbered tasks", () => expect(stamp("1. [ ] One\n- [/] Two", "1. [X] One\n- [x] Two")).toBe("1. [X] One ✅ 2026-11-08\n- [x] Two ✅ 2026-11-08"));
+ test("supports inline properties without duplicate dates", () => {
+ expect(stamp("- [ ] Exercise", "- [x] Exercise", "dataview")).toBe("- [x] Exercise [completion:: 2026-11-08]");
+ expect(stamp("- [ ] Exercise", "- [x] Exercise ✅ 2025-01-01")).toBe("- [x] Exercise ✅ 2025-01-01");
+ });
+ test("reopening removes the completion date and preserves other dates", () => expect(stamp("- [x] Exercise 📅 2026-12-01 ✅ 2026-11-07", "- [ ] Exercise 📅 2026-12-01 ✅ 2026-11-07")).toBe("- [ ] Exercise 📅 2026-12-01"));
+ test("does not stamp old tasks, imported checked tasks, or text-only changes", () => {
+ expect(stamp("- [x] Old", "- [x] Old\n- [x] Imported")).toBe("- [x] Old\n- [x] Imported");
+ expect(stamp("- [x] Old", "- [x] Edited")).toBe("- [x] Edited");
+ });
+ test("does not alter example checkboxes in fenced code or frontmatter", () => {
+ const before = "---\nexample: - [ ] Example\n---\n```md\n- [ ] Example\n```\n- [ ] Real";
+ const after = before.replace(/\[ \]/g, "[x]");
+ expect(stamp(before, after)).toBe(after + " ✅ 2026-11-08");
+ });
+ test("does not guess which duplicate task changed", () => expect(stamp("- [ ] Same\n- [ ] Same", "- [x] Same\n- [ ] Same")).toBe("- [x] Same\n- [ ] Same"));
+});
+
+describe("project Gantt dates", () => {
+ const start = new Date(2026, 10, 8).getTime(), end = new Date(2026, 10, 10).getTime();
+ test("dragging preserves duration across a month boundary", () => expect(projectDateChange(start, end, 24, "move")).toEqual({ startDate: "2026-12-02", dueDate: "2026-12-04" }));
+ test("start and end handles change only the selected edge", () => {
+ expect(projectDateChange(start, end, -2, "start")).toEqual({ startDate: "2026-11-06", dueDate: "2026-11-10" });
+ expect(projectDateChange(start, end, 3, "end")).toEqual({ startDate: "2026-11-08", dueDate: "2026-11-13" });
+ });
+ test("resizing cannot invert the date range", () => expect(projectDateChange(start, end, 10, "start")).toEqual({ startDate: "2026-11-10", dueDate: "2026-11-10" }));
+});
+
+describe("saved filters through the real task filtering pipeline", () => {
+ const rows = [task("todo"), task("complete", "x"), task("abandoned", "-"), task("active", "/")];
+ function apply(id: string, items = rows) {
+ const app = new App() as any; app.vault.getMarkdownFiles = () => [];
+ const plugin = { app, settings: { taskStatuses: { completed: "x|X", inProgress: "/", abandoned: "-", planned: "?", notStarted: " " },
+ viewConfiguration: [{ id: "table", name: "Table", hideCompletedAndAbandonedTasks: true, filterRules: {} }], globalFilterRules: { advancedFilter: { rootCondition: "all", filterGroups: [{ id: "old-global", groupCondition: "all", filters: [{ id: "impossible", property: "content", condition: "contains", value: "never matches any task" }] }] } } } } as any;
+ const preset = defaultSavedFilters().find(preset => preset.id === id)!;
+ const manager = new FluentDataManager(plugin, () => "table", () => ({ activeTaskPreset: preset.options, liveFilterState: null, currentFilterState: null, viewStateFilters: {}, selectedProject: undefined, searchQuery: "", filterInputValue: "" }), () => false);
+ return manager.applyFilters(items).map(task => task.id);
+ }
+ test("completed and abandoned presets override the view's hide-completed flag", () => {
+ expect(apply("builtin-completed")).toEqual(["complete"]);
+ expect(apply("builtin-abandoned")).toEqual(["abandoned"]);
+ expect(apply("builtin-todo").sort()).toEqual(["active", "todo"]);
+ });
+ test("this month includes a start date even when there is a due date next month", () => {
+ const now = new Date();
+ expect(apply("builtin-month", [task("this-month", " ", { startDate: new Date(now.getFullYear(), now.getMonth(), 3).getTime(), dueDate: new Date(now.getFullYear(), now.getMonth() + 1, 3).getTime() }), task("undated")])).toEqual(["this-month"]);
+ });
+ test("editing a built-in preset replaces its saved definition", () => { const replacement = { ...defaultSavedFilters()[0], name: "My queue" }; expect(savedTaskFilters([replacement]).filter(item => item.id === replacement.id)).toEqual([replacement]); });
+});
+
+test("dependency selection rejects self-dependencies and indirect cycles", () => {
+ const a = task("a", " ", { id: "stable-a" }), b = task("b", " ", { id: "stable-b", dependsOn: ["stable-a"] }), c = task("c", " ", { dependsOn: ["stable-b"] });
+ expect(dependencyWouldCycle([a, b, c], a, a)).toBe(true);
+ expect(dependencyWouldCycle([a, b, c], a, c)).toBe(true);
+ expect(dependencyWouldCycle([a, b, c], c, a)).toBe(false);
+});
+
+test("choosing a dependency creates a persistent task ID before saving the reference", async () => {
+ const source = task("source"), target = task("target"), selected: string[] = [];
+ const plugin = { writeAPI: { updateTask: jest.fn(async () => ({ success: true })) } } as any;
+ const picker = new TaskDependencyPicker(new App(), plugin, source, [source, target], id => selected.push(id));
+ await picker.onChooseItem(target);
+ expect(selected[0]).toMatch(/^tg-/);
+ expect(plugin.writeAPI.updateTask).toHaveBeenCalledWith({ taskId: "target", updates: { metadata: { id: selected[0] } } });
+ expect(source.metadata.dependsOn).toBeUndefined();
+ await picker.onChooseItem(target);
+ expect(selected[1]).toBe(selected[0]);
+ expect(plugin.writeAPI.updateTask).toHaveBeenCalledTimes(1);
+});
+
+test("a failed dependency ID write does not save a broken reference", async () => {
+ const selected = jest.fn(), source = task("source"), target = task("target");
+ const picker = new TaskDependencyPicker(new App(), { writeAPI: { updateTask: jest.fn(async () => ({ success: false, error: "Could not write" })) } } as any, source, [source, target], selected);
+ await picker.onChooseItem(target); expect(selected).not.toHaveBeenCalled();
+});
diff --git a/src/__tests__/removeBlankTasks.test.ts b/src/__tests__/removeBlankTasks.test.ts
new file mode 100644
index 000000000..5de58ebec
--- /dev/null
+++ b/src/__tests__/removeBlankTasks.test.ts
@@ -0,0 +1,30 @@
+import { removeBlankTasks } from "@/utils/task/removeBlankTasks";
+import type { Task } from "@/types/task";
+
+const task = (id: string, content: string, parent?: string, children: string[] = []): Task => ({ id, content, status: " ", completed: false, filePath: "a.md", line: 0, originalMarkdown: "", metadata: { tags: [], children, parent } } as Task);
+
+describe("empty task placeholders", () => {
+ it("drops empty and whitespace placeholders without deleting real tasks", () => {
+ const tasks = [task("empty", ""), task("spaces", " \t\u200b"), task("real", "Prepare report")];
+ expect(removeBlankTasks(tasks).map(t => t.id)).toEqual(["real"]);
+ });
+ it("promotes children through blank containers and preserves the surrounding hierarchy", () => {
+ const tasks = [task("root", "Project", undefined, ["blank"]), task("blank", "", "root", ["child"]), task("child", "Write draft", "blank")];
+ const before = JSON.stringify(tasks);
+ const result = removeBlankTasks(tasks);
+ expect(result[0].metadata.children).toEqual(["child"]);
+ expect(result[1].metadata.parent).toBe("root");
+ expect(JSON.stringify(tasks)).toBe(before);
+ });
+ it("promotes a task below a blank root to a root task", () => {
+ expect(removeBlankTasks([task("blank", ""), task("child", "Read", "blank")])[0].metadata.parent).toBeUndefined();
+ });
+ it("terminates malformed cycles in blank parents", () => {
+ const result = removeBlankTasks([task("a", "", "b"), task("b", "", "a"), task("child", "Read", "a")]);
+ expect(result[0].metadata.parent).toBeUndefined();
+ });
+ it("retains completed and custom-status tasks that have titles", () => {
+ const tasks = [{ ...task("done", "Read"), status: "x", completed: true }, { ...task("pause", "Draft"), status: "=" }];
+ expect(removeBlankTasks(tasks)).toBe(tasks);
+ });
+});
diff --git a/src/__tests__/view-feedback-regression.test.ts b/src/__tests__/view-feedback-regression.test.ts
new file mode 100644
index 000000000..2cf31c9b4
--- /dev/null
+++ b/src/__tests__/view-feedback-regression.test.ts
@@ -0,0 +1,60 @@
+import { App } from "obsidian";
+import { buildVisibleTaskTree, flattenTaskTree } from "@/utils/ui/tree-view-utils";
+import { isProjectCalendarEntry } from "@/utils/task/project-calendar";
+import { isDependencyTask, TaskDependencyPicker } from "@/components/features/task/edit/TaskDependencyPicker";
+import { ConfigurableTaskParser } from "@/dataflow/core/ConfigurableTaskParser";
+import { Augmentor } from "@/dataflow/augment/Augmentor";
+
+const task = (id: string, metadata: any = {}) => ({ id, content: `Task ${id}`, originalMarkdown: `- [ ] Task ${id}`, filePath: "Projects/Alpha.md", line: 1, status: " ", completed: false, metadata } as any);
+
+test("search matches remain roots when their parents are filtered out or children metadata is absent", () => {
+ const child = task("child", { parent: "hidden-parent" });
+ const tree = buildVisibleTaskTree([child]);
+ expect(tree.roots.map(item => item.id)).toEqual(["child"]);
+ expect(child.metadata).toEqual({ parent: "hidden-parent" });
+ expect(tree.taskMap.get("child")?.metadata.children).toEqual([]);
+});
+
+test("cyclic and self-parented tasks cannot create an empty search result or infinite recursion", () => {
+ const items = [task("a", { parent: "b" }), task("b", { parent: "a" }), task("self", { parent: "self" })];
+ const tree = buildVisibleTaskTree(items);
+ expect(tree.roots.length).toBeGreaterThan(0);
+ expect(flattenTaskTree(tree.roots, tree.taskMap).map(item => item.id).sort()).toEqual(["a", "b", "self"]);
+});
+
+test("a matching parent does not pull nonmatching children back into the displayed tree", () => {
+ const parent = task("parent", { children: ["hidden"] });
+ const tree = buildVisibleTaskTree([parent]);
+ expect(tree.roots[0].metadata.children).toEqual([]);
+ expect(parent.metadata.children).toEqual(["hidden"]);
+});
+
+test("task dependencies offer existing tasks rather than whole-note tasks or project rows", () => {
+ const checkbox = task("checkbox"), source = task("source"), file = task("file-source:Projects/Alpha.md", { source: "file-source" });
+ expect(isDependencyTask(file)).toBe(false);
+ expect(isDependencyTask({ ...task("old-file"), isFileTask: true })).toBe(false);
+ expect(isDependencyTask(task("plan", { projectPlan: true }))).toBe(false);
+ const picker = new TaskDependencyPicker(new App(), {} as any, source, [source, checkbox, file], () => {});
+ expect(picker.getItems()).toEqual([checkbox]);
+ expect(picker.getItemText(checkbox)).toBe("Task checkbox");
+});
+
+test("project notes are excluded from calendar events while their checkbox tasks remain", () => {
+ const app = new App() as any;
+ app.vault.getFileByPath = () => ({ path: "Projects/Alpha.md" });
+ app.metadataCache.getFileCache = () => ({ frontmatter: { project: "Alpha" } });
+ expect(isProjectCalendarEntry(app, task("file-source:Projects/Alpha.md", { source: "file-source" }))).toBe(true);
+ expect(isProjectCalendarEntry(app, task("plan", { projectPlan: true }))).toBe(true);
+ expect(isProjectCalendarEntry(app, task("checkbox", { project: "Alpha", dueDate: Date.now() }))).toBe(false);
+});
+
+test("project date changes do not become task deadlines during parsing or augmentation", async () => {
+ const parser = new ConfigurableTaskParser({ fileMetadataInheritance: { enabled: true, inheritFromFrontmatter: true, inheritFromFrontmatterForSubtasks: true } } as any);
+ const parse = (dueDate: string) => parser.parse("- [ ] Undated\n- [ ] Own deadline 📅 2026-12-10", "Projects/Alpha.md", { project: "Alpha", startDate: "2026-11-01", dueDate });
+ const before = parse("2026-12-01"), after = parse("2027-01-15");
+ expect(after[0].metadata.dueDate).toBeUndefined(); expect(after[0].metadata.startDate).toBeUndefined();
+ expect(after[1].metadata.dueDate).toBe(before[1].metadata.dueDate); expect(after[1].metadata.dueDate).toBeDefined();
+ const augmented = await new Augmentor().merge({ filePath: "Projects/Alpha.md", fileMeta: { project: "Alpha", dueDate: 123, startDate: 100 }, tasks: after as any });
+ expect(augmented[0].metadata.dueDate).toBeUndefined();
+ expect(augmented[1].metadata.dueDate).toBe(after[1].metadata.dueDate);
+});
diff --git a/src/common/setting-definition.ts b/src/common/setting-definition.ts
index bfeb673bc..6fa2d4e48 100644
--- a/src/common/setting-definition.ts
+++ b/src/common/setting-definition.ts
@@ -311,6 +311,8 @@ export interface PresetTaskFilter {
name: string;
options: {
// TaskFilterOptions structure is embedded here
+ conditions?: Array<{ field: string; operator: string; value: string }>;
+ relation?: "AND" | "OR";
includeCompleted: boolean;
includeInProgress: boolean;
includeAbandoned: boolean;
@@ -486,6 +488,16 @@ export interface RewardItem {
inventory: number; // Remaining count (-1 for unlimited)
imageUrl?: string; // Optional image URL
condition?: string; // Optional condition string for triggering (e.g., "#project AND #milestone")
+ pointCost?: number;
+}
+
+export interface PointsLedgerEntry {
+ id: string;
+ delta: number;
+ label: string;
+ createdAt: number;
+ source: "task" | "manual" | "redemption";
+ taskId?: string;
}
export interface OccurrenceLevel {
@@ -498,6 +510,10 @@ export interface RewardSettings {
rewardItems: RewardItem[];
occurrenceLevels: OccurrenceLevel[];
showRewardType: "modal" | "notice"; // Type of reward display - modal (default) or notice
+ pointsPerTask?: number;
+ pointsLedger?: PointsLedgerEntry[];
+ /** Markdown file that owns the existing check-in rules and manual ledger. */
+ pointsDataFile?: string;
}
export interface HabitSettings {
@@ -802,6 +818,7 @@ export interface ChangelogSettings {
}
export interface TaskProgressBarSettings {
+ interfaceRevision?: number;
// General Settings (Example)
progressBarDisplayMode: "none" | "graphical" | "text" | "both";
supportHoverToShowProgressInfo: boolean;
@@ -920,8 +937,6 @@ export interface TaskProgressBarSettings {
defaultViewMode: "list" | "tree"; // Global default view mode for all views
viewConfiguration: ViewConfig[]; // Manages order, visibility, basic info, AND filter rules
- // Global Filter Settings
- globalFilterRules: ViewFilterRule; // Global filter rules that apply to all Views by default
// Review Settings
reviewSettings: Record;
@@ -931,6 +946,7 @@ export interface TaskProgressBarSettings {
// Habit Settings
habit: HabitSettings;
+ habitsIntegration?: Partial;
// Filter Configuration Settings
filterConfig: FilterConfigSettings;
@@ -1360,8 +1376,6 @@ export const DEFAULT_SETTINGS: TaskProgressBarSettings = {
enableDynamicMetadataPositioning: false, // Enable intelligent metadata positioning by default
defaultViewMode: "list", // Global default view mode for all views
- // Global Filter Defaults
- globalFilterRules: {}, // Empty global filter rules by default
viewConfiguration: [
{
@@ -1401,7 +1415,7 @@ export const DEFAULT_SETTINGS: TaskProgressBarSettings = {
},
{
id: "projects",
- name: t("Projects"),
+ name: t("Project Gantt"),
icon: "folders",
type: "default",
visible: true,
@@ -1597,6 +1611,8 @@ export const DEFAULT_SETTINGS: TaskProgressBarSettings = {
// Reward Settings Defaults (NEW)
rewards: {
enableRewards: false,
+ pointsPerTask: 0,
+ pointsLedger: [],
rewardItems: [
{
id: "reward-tea",
diff --git a/src/components/features/calendar/index.ts b/src/components/features/calendar/index.ts
index 2b88bd3d3..ca02231f2 100644
--- a/src/components/features/calendar/index.ts
+++ b/src/components/features/calendar/index.ts
@@ -1,3 +1,7 @@
+import { getNextTaskStatusMark, getTaskStatusGroup } from "@/utils/status-cycle-resolver";
+import { calendarWeekNumber } from "@/utils/date/calendar-week";
+import { openPeriodNote, NotePeriod } from "@/managers/period-notes";
+import { isProjectCalendarEntry } from "@/utils/task/project-calendar";
/**
* CalendarComponent - Enhanced calendar view using @taskgenius/calendar
*
@@ -89,11 +93,13 @@ export interface CalendarEvent extends Task {
export class CalendarComponent extends Component {
public containerEl: HTMLElement;
private tasks: Task[] = [];
+ private pendingStatusChanges = new Set();
private events: CalendarEvent[] = [];
private currentViewMode: CalendarViewMode = "month";
private currentDate: moment.Moment = moment();
private headerEl: HTMLElement;
+ private dateDisplayEl: HTMLElement | null = null;
private viewContainerEl: HTMLElement;
private app: App;
@@ -216,6 +222,8 @@ export class CalendarComponent extends Component {
// Public API
// ============================================
+ public onShown(): void { this.tgCalendar?.refresh(); }
+
public updateTasks(newTasks: Task[]) {
this.tasks = newTasks;
this.badgeEventsCache.clear();
@@ -256,6 +264,7 @@ export class CalendarComponent extends Component {
} else {
this.tgCalendar.next();
}
+ this.updateDateHeader();
} else {
this.render();
}
@@ -266,6 +275,7 @@ export class CalendarComponent extends Component {
if (this.tgCalendar) {
this.tgCalendar.today();
+ this.updateDateHeader();
} else {
this.render();
}
@@ -289,6 +299,7 @@ export class CalendarComponent extends Component {
const badgeEvents: CalendarEvent[] = [];
this.tasks.forEach((task) => {
+ if (isProjectCalendarEntry(this.app, task)) return;
const isIcsTask = (task as any).source?.type === "ics";
const icsTask = isIcsTask ? (task as IcsTask) : null;
const showAsBadge = icsTask?.icsEvent?.source?.showType === "badge";
@@ -322,6 +333,16 @@ export class CalendarComponent extends Component {
this.renderCurrentView();
}
+ private updateDateHeader = (date?: Date): void => {
+ if (date) this.currentDate = moment(date);
+ if (this.dateDisplayEl) {
+ const mode = this.getCustomViewConfig(this.currentViewMode)?.baseViewType || this.currentViewMode;
+ this.dateDisplayEl.textContent = this.getCurrentDateDisplay() + (mode === "week" ? ` · ${t("Week")} ${calendarWeekNumber(this.currentDate.toDate(), this.getEffectiveFirstDayOfWeek())}` : "");
+ }
+ };
+
+ public refreshConfiguration(): void { this.render(); }
+
private renderHeader() {
this.headerEl.empty();
@@ -345,7 +366,11 @@ export class CalendarComponent extends Component {
// Date display
const dateDisplay = this.headerEl.createSpan("calendar-current-date");
- dateDisplay.textContent = this.getCurrentDateDisplay();
+ this.dateDisplayEl = dateDisplay;
+ this.updateDateHeader();
+ dateDisplay.setAttribute("role", "button"); dateDisplay.tabIndex = 0;
+ const openCurrent = () => { const mode = this.getCustomViewConfig(this.currentViewMode)?.baseViewType || this.currentViewMode; void this.openNote(mode === "year" ? "yearly" : mode === "month" ? "monthly" : mode === "week" || mode === "agenda" ? "weekly" : "daily", this.currentDate.toDate()); };
+ dateDisplay.onclick = event => { event.preventDefault(); event.stopPropagation(); openCurrent(); }; dateDisplay.onkeydown = event => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); event.stopPropagation(); openCurrent(); } };
// View switcher - segmented control style
const viewGroup = this.headerEl.createDiv("calendar-view-switcher");
@@ -753,6 +778,7 @@ export class CalendarComponent extends Component {
this.handleTGEventDrop(event, newStart, newEnd),
onEventResize: (event: any, newStart: any, newEnd: any) =>
this.handleTGEventResize(event, newStart, newEnd),
+ onDateChange: this.updateDateHeader,
onDateClick: (date: Date) => this.handleDateClick(date),
onDateDoubleClick: (date: Date) => this.handleDateDoubleClick(date),
onDateContextMenu: (date: Date, x: number, y: number) =>
@@ -844,6 +870,7 @@ export class CalendarComponent extends Component {
onEventResize: (event: any, newStart: any, newEnd: any) =>
this.handleTGEventResize(event, newStart, newEnd),
// Date interactions (v0.6.0+) - match library's callback signatures
+ onDateChange: this.updateDateHeader,
onDateClick: (date: Date) => this.handleDateClick(date),
onDateDoubleClick: (date: Date) => this.handleDateDoubleClick(date),
onDateContextMenu: (date: Date, x: number, y: number) =>
@@ -935,26 +962,21 @@ export class CalendarComponent extends Component {
* Based on CalendarEventComponent implementation in event-renderer.ts
*/
private handleTGRenderEvent(ctx: EventRenderContext) {
- console.log(
- "[Calendar] handleTGRenderEvent called",
- ctx.event.id,
- ctx.viewType,
- );
-
// First render the default content
ctx.defaultRender();
const { event, el } = ctx;
- // Skip if checkbox already added
- if (el.querySelector(".task-list-item-checkbox")) {
- return;
- }
-
- // Find the corresponding task
const task = getTaskFromEvent(event as any);
if (!task) return;
+ // Bind to the rendered task, including its title, badges and checkbox. The
+ // engine's delegated hit testing does not cover every custom event surface.
+ // Assignment replaces the previous handler when the same element is reused.
+ el.oncontextmenu = ev => this.onEventContextMenu(ev, task as CalendarEvent);
+
+ if (el.querySelector(".task-list-item-checkbox")) return;
+
// Create checkbox using the shared utility function
// This ensures consistent styling with other calendar views
const checkbox = createTaskCheckbox(task.status || " ", task, el);
@@ -964,40 +986,10 @@ export class CalendarComponent extends Component {
el.insertBefore(checkbox, el.firstChild);
}
- // Handle checkbox click - same pattern as CalendarEventComponent
- this.registerDomEvent(checkbox, "click", async (ev) => {
+ this.registerDomEvent(checkbox, "click", ev => {
+ ev.preventDefault();
ev.stopPropagation();
-
- // Toggle task status
- const newStatus = task.completed ? " " : "x";
-
- if (this.plugin.writeAPI) {
- const result = await this.plugin.writeAPI.updateTaskStatus({
- taskId: task.id,
- status: newStatus,
- completed: !task.completed,
- });
-
- if (result.success) {
- // Update UI immediately
- checkbox.checked = !task.completed;
- checkbox.dataset.task = newStatus;
-
- // Trigger task-completed event if needed
- if (!task.completed) {
- this.app.workspace.trigger(
- "task-genius:task-completed",
- task,
- );
- }
-
- // Refresh calendar
- setTimeout(() => {
- this.processTasks();
- this.renderCurrentView();
- }, 100);
- }
- }
+ void this.cycleTaskStatus(task, checkbox);
});
}
@@ -1454,51 +1446,11 @@ export class CalendarComponent extends Component {
cls: "task-checkbox-overlay",
});
- const checkbox = checkboxContainer.createEl("input", {
- cls: "task-list-item-checkbox",
- type: "checkbox",
- attr: {
- "data-task": task.status || " ",
- },
- });
-
- checkbox.checked = task.status !== " " && task.status !== "?";
-
- // Handle checkbox click
- this.registerDomEvent(checkbox, "click", async (ev) => {
+ const checkbox = createTaskCheckbox(task.status || " ", task, checkboxContainer);
+ this.registerDomEvent(checkbox, "click", ev => {
+ ev.preventDefault();
ev.stopPropagation();
-
- // Toggle task status
- const newStatus = task.completed ? " " : "x";
-
- if (this.plugin.writeAPI) {
- const result =
- await this.plugin.writeAPI.updateTaskStatus({
- taskId: task.id,
- status: newStatus,
- completed: !task.completed,
- });
-
- if (result.success) {
- // Update UI
- checkbox.checked = !task.completed;
- checkbox.dataset.task = newStatus;
-
- // Trigger task-completed event if needed
- if (!task.completed) {
- this.app.workspace.trigger(
- "task-genius:task-completed",
- task,
- );
- }
-
- // Refresh calendar
- setTimeout(() => {
- this.processTasks();
- this.renderCurrentView();
- }, 100);
- }
- }
+ void this.cycleTaskStatus(task, checkbox);
});
});
}, 50); // Small delay to ensure TGCalendar has rendered events
@@ -1521,6 +1473,9 @@ export class CalendarComponent extends Component {
/**
* Handle single click on a date cell (month view)
*/
+ private async openNote(period: NotePeriod, date: Date): Promise {
+ try { await openPeriodNote(this.app, period, date); } catch (error) { new Notice(String(error)); }
+ }
private handleDateClick(date: Date) {
// Allow event bubbling for other interactions
// This maintains compatibility with existing click behavior
@@ -1641,13 +1596,52 @@ export class CalendarComponent extends Component {
private onMonthHover = (ev: MouseEvent, month: number) => {};
private onEventContextMenu = (ev: MouseEvent, event: CalendarEvent) => {
- this.params?.onEventContextMenu?.(ev, event);
+ if (!this.params?.onEventContextMenu) return;
+ ev.preventDefault();
+ ev.stopPropagation();
+ const current = this.tasks.find(task => task.id === event.id) || getTaskFromEvent(event as any) || event;
+ this.params.onEventContextMenu(ev, current as CalendarEvent);
};
private onEventComplete = (ev: MouseEvent, event: CalendarEvent) => {
- this.params?.onTaskCompleted?.(event);
+ ev.preventDefault();
+ ev.stopPropagation();
+ void this.cycleTaskStatus(event);
};
+ /** All calendar renderers write through the configured workflow. */
+ private async cycleTaskStatus(task: Task, checkbox?: HTMLInputElement): Promise {
+ if (this.pendingStatusChanges.has(task.id)) return;
+ if (!this.plugin.writeAPI) {
+ new Notice(t("Task update system not available"));
+ return;
+ }
+ this.pendingStatusChanges.add(task.id);
+ if (checkbox) checkbox.disabled = true;
+ try {
+ const current = this.tasks.find(item => item.id === task.id) || task;
+ const status = getNextTaskStatusMark(current.status || " ", this.plugin.settings);
+ const completed = getTaskStatusGroup(status, this.plugin.settings) === "completed";
+ const metadata = { completedDate: completed ? current.metadata?.completedDate || Date.now() : undefined };
+ const result = await this.plugin.writeAPI.updateTask({
+ taskId: current.id, updates: { status, completed, metadata: metadata as Task["metadata"] },
+ });
+ if (!result.success) throw new Error(result.error || t("Failed to update task"));
+ if (this.tasks.some(item => item.id === current.id)) {
+ this.tasks = this.tasks.map(item => item.id === current.id
+ ? result.task || { ...current, status, completed, metadata: { ...current.metadata, ...metadata } }
+ : item);
+ }
+ await this.processTasks();
+ this.renderCurrentView();
+ } catch (error) {
+ new Notice(String(error));
+ } finally {
+ this.pendingStatusChanges.delete(task.id);
+ if (checkbox) checkbox.disabled = false;
+ }
+ }
+
// ============================================
// Task Processing
// ============================================
@@ -1770,6 +1764,8 @@ export class CalendarComponent extends Component {
if (customConfig) {
// Use the base view type's unit
switch (customConfig.baseViewType) {
+ case "year": return "year";
+ case "agenda": return "week";
case "month":
return "month";
case "week":
@@ -1870,8 +1866,10 @@ export class CalendarComponent extends Component {
// Use the base view type's format, with custom view name prefix
const prefix = ``;
switch (customConfig.baseViewType) {
+ case "year": return this.currentDate.format("YYYY");
case "month":
return prefix + this.currentDate.format("MMMM/YYYY");
+ case "agenda":
case "week": {
// Use config-aware week start/end
const startOfWeek = this.getStartOfWeekWithConfig(
diff --git a/src/components/features/calendar/rendering/event-renderer.ts b/src/components/features/calendar/rendering/event-renderer.ts
index e185b147c..3b6865881 100644
--- a/src/components/features/calendar/rendering/event-renderer.ts
+++ b/src/components/features/calendar/rendering/event-renderer.ts
@@ -179,16 +179,12 @@ export class CalendarEventComponent extends Component {
);
this.registerDomEvent(checkbox, "click", (ev) => {
+ ev.preventDefault();
ev.stopPropagation();
if (this.params?.onEventComplete) {
this.params.onEventComplete(ev, this.event);
}
-
- if (this.event.status === " ") {
- checkbox.checked = true;
- checkbox.dataset.task = "x";
- }
});
// Create a container for the title to render markdown into
@@ -269,16 +265,12 @@ export class CalendarEventComponent extends Component {
);
this.registerDomEvent(checkbox, "click", (ev) => {
+ ev.preventDefault();
ev.stopPropagation();
if (this.params?.onEventComplete) {
this.params.onEventComplete(ev, this.event);
}
-
- if (this.event.status === " ") {
- checkbox.checked = true;
- checkbox.dataset.task = "x";
- }
});
const titleEl = this.eventEl.createDiv({ cls: "calendar-event-title" });
@@ -312,16 +304,12 @@ export class CalendarEventComponent extends Component {
);
this.registerDomEvent(checkbox, "click", (ev) => {
+ ev.preventDefault();
ev.stopPropagation();
if (this.params?.onEventComplete) {
this.params.onEventComplete(ev, this.event);
}
-
- if (this.event.status === " ") {
- checkbox.checked = true;
- checkbox.dataset.task = "x";
- }
});
// Append title
diff --git a/src/components/features/calendar/views/tg-agenda-view.ts b/src/components/features/calendar/views/tg-agenda-view.ts
index ff8324f81..82cf4307e 100644
--- a/src/components/features/calendar/views/tg-agenda-view.ts
+++ b/src/components/features/calendar/views/tg-agenda-view.ts
@@ -1,3 +1,4 @@
+import { t as settingsText } from "@/translations/helper";
/**
* TGAgendaView - Agenda view extending @taskgenius/calendar BaseView
*
@@ -57,7 +58,7 @@ export interface AgendaViewOptions {
export class TGAgendaView extends BaseView {
static meta: ViewMeta = {
type: "agenda",
- label: "Agenda",
+ label: settingsText("Agenda"),
shortLabel: "A",
order: 40,
};
diff --git a/src/components/features/calendar/views/tg-year-view.ts b/src/components/features/calendar/views/tg-year-view.ts
index 05a22f986..78c63ffad 100644
--- a/src/components/features/calendar/views/tg-year-view.ts
+++ b/src/components/features/calendar/views/tg-year-view.ts
@@ -1,3 +1,4 @@
+import { t as settingsText } from "@/translations/helper";
/**
* TGYearView - Year view extending @taskgenius/calendar BaseView
*
@@ -65,7 +66,7 @@ export interface YearViewOptions {
export class TGYearView extends BaseView {
static meta: ViewMeta = {
type: "year",
- label: "Year",
+ label: settingsText("Year"),
shortLabel: "Y",
order: 50,
};
diff --git a/src/components/features/fluent/FluentIntegration.ts b/src/components/features/fluent/FluentIntegration.ts
index 9b1437ad6..ce2ac24e1 100644
--- a/src/components/features/fluent/FluentIntegration.ts
+++ b/src/components/features/fluent/FluentIntegration.ts
@@ -5,10 +5,7 @@ import {
LeftSidebarView,
TG_LEFT_SIDEBAR_VIEW_TYPE,
} from "@/pages/LeftSidebarView";
-import {
- RightDetailView,
- TG_RIGHT_DETAIL_VIEW_TYPE,
-} from "@/pages/RightDetailView";
+
import { t } from "@/translations/helper";
import { TASK_VIEW_TYPE } from "@/pages/TaskView";
@@ -29,6 +26,11 @@ export class FluentIntegration {
return;
}
+ // Remove only panes left by the retired Task Genius detail view.
+ this.plugin.app.workspace.onLayoutReady(() => {
+ for (const leaf of this.plugin.app.workspace.getLeavesOfType("tg-right-detail")) leaf.detach();
+ });
+
// Register the Fluent view
this.plugin.registerView(
FLUENT_TASK_VIEW,
@@ -40,10 +42,7 @@ export class FluentIntegration {
TG_LEFT_SIDEBAR_VIEW_TYPE,
(leaf: WorkspaceLeaf) => new LeftSidebarView(leaf, this.plugin),
);
- this.plugin.registerView(
- TG_RIGHT_DETAIL_VIEW_TYPE,
- (leaf: WorkspaceLeaf) => new RightDetailView(leaf, this.plugin),
- );
+
}
// Register side leaf views for new architecture
@@ -58,7 +57,6 @@ export class FluentIntegration {
const watched = new Set([
FLUENT_TASK_VIEW,
TG_LEFT_SIDEBAR_VIEW_TYPE,
- TG_RIGHT_DETAIL_VIEW_TYPE,
]);
if (!watched.has(vt)) return;
const ws = this.plugin.app.workspace as Workspace & any;
@@ -70,25 +68,16 @@ export class FluentIntegration {
"left",
{ active: false },
);
- const rightLeaf = await ws.ensureSideLeaf(
- TG_RIGHT_DETAIL_VIEW_TYPE,
- "right",
- { active: false },
- );
+
// Bring them to front within their splits (without keeping focus)
if (leftLeaf) ws.revealLeaf(leftLeaf);
- if (rightLeaf) ws.revealLeaf(rightLeaf);
// Expand sidebars if they are collapsed
if (
ws.leftSplit?.collapsed &&
typeof ws.leftSplit.expand === "function"
)
ws.leftSplit.expand();
- if (
- ws.rightSplit?.collapsed &&
- typeof ws.rightSplit.expand === "function"
- )
- ws.rightSplit.expand();
+
// Restore focus to the currently active (incoming) leaf
if (ws.setActiveLeaf && leaf)
ws.setActiveLeaf(leaf, { focus: true });
@@ -142,15 +131,8 @@ export class FluentIntegration {
TG_LEFT_SIDEBAR_VIEW_TYPE,
);
}
- const rightSidebarLeaves =
- this.plugin.app.workspace.getLeavesOfType(
- TG_RIGHT_DETAIL_VIEW_TYPE,
- );
- if (rightSidebarLeaves.length > 0) {
- this.plugin.app.workspace.detachLeavesOfType(
- TG_RIGHT_DETAIL_VIEW_TYPE,
- );
- }
+
+ return;
}
const ws = this.plugin.app.workspace as Workspace;
@@ -158,9 +140,7 @@ export class FluentIntegration {
await ws.ensureSideLeaf(TG_LEFT_SIDEBAR_VIEW_TYPE, "left", {
active: false,
});
- await ws.ensureSideLeaf(TG_RIGHT_DETAIL_VIEW_TYPE, "right", {
- active: false,
- });
+
}
/**
diff --git a/src/components/features/fluent/components/FluentSidebar.ts b/src/components/features/fluent/components/FluentSidebar.ts
index 6137c6a43..c3e6f0c17 100644
--- a/src/components/features/fluent/components/FluentSidebar.ts
+++ b/src/components/features/fluent/components/FluentSidebar.ts
@@ -31,7 +31,7 @@ export class FluentSidebar extends Component {
private containerEl: HTMLElement;
private plugin: TaskProgressBarPlugin;
private workspaceSelector: WorkspaceSelector;
- public projectList: ProjectList;
+ public projectList?: ProjectList;
private collapsed = false;
private currentWorkspaceId: string;
private isTreeView = false;
@@ -44,10 +44,14 @@ export class FluentSidebar extends Component {
string,
{ icon: string; label: () => string }
> = {
+ planner: { icon: "calendar-clock", label: () => t("Task scheduling") },
inbox: { icon: "inbox", label: () => t("Inbox") },
today: { icon: "calendar-days", label: () => t("Today") },
upcoming: { icon: "calendar", label: () => t("Upcoming") },
flagged: { icon: "flag", label: () => t("Flagged") },
+ points: { icon: "sparkles", label: () => t("Points and rewards") },
+ projects: { icon: "folder-kanban", label: () => t("Projects") },
+ gantt: { icon: "gantt-chart", label: () => t("Project Gantt") },
};
private otherItems: FluentTaskNavigationItem[] = [];
@@ -86,29 +90,6 @@ export class FluentSidebar extends Component {
const systemViewIds = Object.keys(this.SYSTEM_VIEWS);
let changed = false;
- // One-time migration: reset top region to only system views for version <= 9.12.3
- const lastVersion = this.plugin.settings.changelog?.lastVersion;
- const needsMigration =
- !lastVersion || this.compareVersions(lastVersion, "9.12.3") <= 0;
-
- if (needsMigration) {
- // Move all non-system views from top to bottom
- config.forEach((v) => {
- if (!systemViewIds.includes(v.id) && v.region === "top") {
- v.region = "bottom";
- changed = true;
- }
- });
- }
-
- // Ensure existing system views have region: "top"
- config.forEach((v) => {
- if (systemViewIds.includes(v.id) && v.region !== "top") {
- v.region = "top";
- changed = true;
- }
- });
-
// Add system views at the beginning if they don't exist
const systemViewsToAdd: ViewConfig[] = [];
Object.entries(this.SYSTEM_VIEWS).forEach(([id, def]) => {
@@ -141,23 +122,11 @@ export class FluentSidebar extends Component {
}
}
- private compareVersions(v1: string, v2: string): number {
- const parts1 = v1.split(".").map((n) => parseInt(n, 10) || 0);
- const parts2 = v2.split(".").map((n) => parseInt(n, 10) || 0);
- const len = Math.max(parts1.length, parts2.length);
- for (let i = 0; i < len; i++) {
- const a = parts1[i] || 0;
- const b = parts2[i] || 0;
- if (a < b) return -1;
- if (a > b) return 1;
- }
- return 0;
- }
-
private getViewItems(region: "top" | "bottom"): FluentTaskNavigationItem[] {
const config = this.plugin.settings.viewConfiguration;
return config
.filter((v) => {
+ if (v.id === "review") return false;
const r = v.region || "top";
return (
r === region &&
@@ -180,7 +149,8 @@ export class FluentSidebar extends Component {
});
}
- private render() {
+ public render() {
+ if (this.projectList) { this.removeChild(this.projectList); this.projectList = undefined; }
this.containerEl.empty();
this.destroySortables();
this.containerEl.addClass("fluent-sidebar");
@@ -231,7 +201,7 @@ export class FluentSidebar extends Component {
// Top navigation section (system views like Inbox, Today, etc.)
const topItems = this.getViewItems("top");
- if (topItems.length > 0) {
+ {
const topSection = content.createDiv({
cls: "fluent-sidebar-section primary",
attr: { "data-region": "top" },
@@ -321,11 +291,6 @@ export class FluentSidebar extends Component {
if (!isOtherViewsHidden) {
const allBottomItems = this.getViewItems("bottom");
- const visibleCount =
- this.plugin?.settings?.fluentView?.fluentConfig
- ?.maxOtherViewsBeforeOverflow ?? 5;
- const displayedItems = allBottomItems.slice(0, visibleCount);
- const overflowItems = allBottomItems.slice(visibleCount);
const bottomSection = content.createDiv({
cls: "fluent-sidebar-section other-views",
@@ -338,18 +303,7 @@ export class FluentSidebar extends Component {
});
otherHeader.createSpan({ text: t("Other Views") });
- if (overflowItems.length > 0) {
- const moreBtn = otherHeader.createDiv({
- cls: "fluent-section-action",
- attr: { "aria-label": t("More views") },
- });
- setIcon(moreBtn, "more-horizontal");
- this.registerDomEvent(moreBtn, "click", (e) =>
- this.showOtherViewsMenu(e as MouseEvent, overflowItems),
- );
- }
-
- this.renderSortableSection(bottomSection, displayedItems, "bottom");
+ this.renderSortableSection(bottomSection, allBottomItems, "bottom");
}
}
@@ -383,26 +337,7 @@ export class FluentSidebar extends Component {
)
) {
const bottomItems = this.getViewItems("bottom");
- const visibleCount =
- this.plugin?.settings?.fluentView?.fluentConfig
- ?.maxOtherViewsBeforeOverflow ?? 5;
- const displayedBottom = bottomItems.slice(0, visibleCount);
- const overflowBottom = bottomItems.slice(visibleCount);
-
- displayedBottom.forEach((item) => {
- this.renderRailButton(item);
- });
-
- if (overflowBottom.length > 0) {
- const moreBtn = this.railEl.createDiv({
- cls: "fluent-rail-btn",
- attr: { "aria-label": t("More views") },
- });
- setIcon(moreBtn, "more-horizontal");
- this.registerDomEvent(moreBtn, "click", (e) =>
- this.showOtherViewsMenu(e as MouseEvent, overflowBottom),
- );
- }
+ bottomItems.forEach((item) => this.renderRailButton(item));
}
// Projects menu button
@@ -486,6 +421,8 @@ export class FluentSidebar extends Component {
// Initialize Sortable with cross-region drag support
const sortable = Sortable.create(listDiv, {
group: "fluent-sidebar-views",
+ draggable: ".fluent-navigation-item",
+ emptyInsertThreshold: 16,
animation: 150,
ghostClass: "sortable-ghost",
chosenClass: "sortable-chosen",
@@ -539,41 +476,11 @@ export class FluentSidebar extends Component {
})
.filter((v) => v !== undefined) as ViewConfig[];
- const systemViewIds = Object.keys(this.SYSTEM_VIEWS);
- const newBottomConfigs = bottomIds
- .map((id) => {
- const cfg = findConfig(id);
- if (cfg) {
- // System views must stay in top region
- cfg.region = systemViewIds.includes(id) ? "top" : "bottom";
- }
- return cfg;
- })
- .filter((v) => v !== undefined) as ViewConfig[];
-
- // Separate system views (always top) from bottom configs
- const systemViewsInBottom = newBottomConfigs.filter((v) =>
- systemViewIds.includes(v.id),
- );
- const nonSystemBottomConfigs = newBottomConfigs.filter(
- (v) => !systemViewIds.includes(v.id),
- );
-
- // Update settings: Top (including system views) -> Bottom -> Hidden
- this.plugin.settings.viewConfiguration = [
- ...newTopConfigs,
- ...systemViewsInBottom, // System views dragged to bottom go back to top
- ...nonSystemBottomConfigs,
- ...hiddenItems,
- ];
-
+ const newBottomConfigs = bottomIds.map(findConfig).filter((v): v is ViewConfig => !!v);
+ newBottomConfigs.forEach(v => { v.region = "bottom"; });
+ this.plugin.settings.viewConfiguration = [...newTopConfigs, ...newBottomConfigs, ...hiddenItems];
await this.plugin.saveSettings();
- // Re-render to restore system views to top section if they were dragged to bottom
- if (systemViewsInBottom.length > 0) {
- this.render();
- }
-
// Trigger event to notify other components (e.g., ViewSettingsTab)
this.plugin.app.workspace.trigger("task-genius:view-config-changed", {
reason: "sidebar-reorder",
@@ -947,6 +854,8 @@ export class FluentSidebar extends Component {
});
});
+ }
+
menu.addItem((item) => {
item.setTitle(t("Hide in sidebar"))
.setIcon("eye-off")
@@ -969,8 +878,6 @@ export class FluentSidebar extends Component {
);
});
});
- }
-
// Delete (for custom views only)
const view = this.plugin.settings.viewConfiguration.find(
(v) => v.id === viewId,
@@ -1012,10 +919,8 @@ export class FluentSidebar extends Component {
el.removeClass("is-active");
});
// Apply to any element that carries this view id (works in both modes)
- const activeEls = this.containerEl.querySelectorAll(
- `[data-view-id="${viewId}"]`,
- );
- activeEls.forEach((el) => el.addClass("is-active"));
+ const activeEls = this.containerEl.querySelectorAll("[data-view-id]");
+ activeEls.forEach(el => { if (el.dataset.viewId === viewId) el.addClass("is-active"); });
}
public updateWorkspace(workspaceOrId: string | WorkspaceData) {
diff --git a/src/components/features/fluent/components/FluentTopNavigation.ts b/src/components/features/fluent/components/FluentTopNavigation.ts
index 71b578ebe..f9b856a75 100644
--- a/src/components/features/fluent/components/FluentTopNavigation.ts
+++ b/src/components/features/fluent/components/FluentTopNavigation.ts
@@ -12,6 +12,8 @@ import TaskProgressBarPlugin from "@/index";
import { Task } from "@/types/task";
import { t } from "@/translations/helper";
import { Events, on } from "@/dataflow/events/Events";
+import { SavedTaskFilterModal } from "./SavedTaskFilterModal";
+import { savedTaskFilters } from "@/utils/task/saved-task-filters";
export type ViewMode = "list" | "kanban" | "tree" | "calendar";
@@ -45,6 +47,19 @@ export class TopNavigation extends Component {
private searchInput: HTMLInputElement;
private currentViewMode: ViewMode = "list";
private notificationCount = 0;
+ private contextViewId = "inbox";
+ private searchQuery = "";
+ private activePresetId: string | null = null;
+ public updateContext(viewId: string): void {
+ this.contextViewId = viewId;
+ const label = this.containerEl.querySelector(".tg-active-filter-label");
+ if (label) label.hidden = !label.textContent || ["points", "rewards", "habit"].includes(viewId);
+
+ this.containerEl.show();
+ const taskContext = !["points", "rewards", "habit"].includes(viewId);
+ (this.containerEl.querySelector(".tg-quick-filter-button") as HTMLElement | null)?.toggle(taskContext);
+ if (this.searchInput) this.searchInput.placeholder = t(viewId === "habit" ? "Search habits" : viewId === "rewards" ? "Search rewards" : viewId === "points" ? "Search bonuses, rewards and records" : "Search tasks, projects ...");
+ }
private availableModes: ViewMode[] = ["list", "kanban", "tree", "calendar"];
private viewTabsContainer: HTMLElement | null = null;
private customButtonsContainer: HTMLElement | null = null;
@@ -52,6 +67,7 @@ export class TopNavigation extends Component {
string,
{ buttonEl: HTMLElement; config: CustomNavButton }
> = new Map();
+ private headerControls: HTMLElement | null = null;
private cycleSelectorContainer: HTMLElement | null = null;
private selectedCycleId: string | null = null;
private onCycleChange: ((cycleId: string | null) => void) | null = null;
@@ -61,7 +77,7 @@ export class TopNavigation extends Component {
plugin: TaskProgressBarPlugin,
private onSearch: (query: string) => void,
private onViewModeChange: (mode: ViewMode) => void,
- private onFilterClick: () => void,
+ private onFilterClick: (presetId: string | null) => void,
private onSortClick: () => void,
private onSettingsClick: () => void,
availableModes?: ViewMode[],
@@ -169,18 +185,15 @@ export class TopNavigation extends Component {
}
}
+ onunload(): void { this.headerControls?.remove(); }
+
private render() {
+ this.headerControls?.remove();
+ this.headerControls = null;
this.containerEl.empty();
this.containerEl.addClass("fluent-top-navigation");
- // Hide entire navigation if no view modes are available
- if (this.availableModes.length === 0) {
- this.containerEl.hide();
- this.containerEl.toggleClass("other-view", true);
- return;
- }
-
- this.containerEl.toggleClass("other-view", false);
+ this.containerEl.toggleClass("other-view", this.availableModes.length === 0);
// Show navigation when modes are available
this.containerEl.show();
@@ -196,9 +209,41 @@ export class TopNavigation extends Component {
new SearchComponent(searchContainer)
.setPlaceholder(t("Search tasks, projects ..."))
+ .setValue(this.searchQuery)
.onChange((value) => {
+ this.searchQuery = value;
this.onSearch(value);
});
+ this.searchInput = searchContainer.querySelector("input")!;
+ const filterButton = searchContainer.createEl("button", {
+ cls: "fluent-nav-icon-button tg-quick-filter-button",
+ attr: { "aria-label": t("Quick filters") },
+ });
+ setIcon(filterButton, "list-filter");
+ searchContainer.createSpan({ cls: "tg-active-filter-label", attr: { hidden: "" } });
+ filterButton.toggleClass("is-active", !!this.activePresetId);
+ this.registerDomEvent(filterButton, "click", (event) => {
+ const menu = new Menu();
+ const presets = savedTaskFilters(this.plugin.settings.taskFilter?.presetTaskFilters);
+ const apply = (id: string | null) => { this.activePresetId = id; filterButton.toggleClass("is-active", !!id); this.onFilterClick(id); };
+ menu.addItem(item => item.setTitle(t("New saved filter")).setIcon("plus").onClick(() => new SavedTaskFilterModal(this.plugin.app, this.plugin, this.searchQuery, apply).open()));
+ if (!presets.length) {
+ menu.addItem(item => item.setTitle(t("No saved filters")).setDisabled(true));
+ } else {
+ menu.addItem(item => item.setTitle(t("Clear quick filter")).setIcon("x").onClick(() => apply(null)));
+ menu.addSeparator();
+ for (const preset of presets) {
+ menu.addItem(item => item.setTitle(preset.name).setIcon("filter").setChecked(preset.id === this.activePresetId).onClick(() => apply(preset.id)));
+ }
+ const active = presets.find(preset => preset.id === this.activePresetId);
+ if (active) {
+ menu.addSeparator();
+ menu.addItem(item => item.setTitle(t("Edit saved filter")).setIcon("pencil").onClick(() => new SavedTaskFilterModal(this.plugin.app, this.plugin, this.searchQuery, apply, active).open()));
+ menu.addItem(item => item.setTitle(t("Delete saved filter")).setIcon("trash").onClick(async () => { this.plugin.settings.taskFilter.presetTaskFilters = presets.filter(preset => preset.id !== active.id); await this.plugin.saveSettings(); apply(null); }));
+ }
+ }
+ menu.showAtMouseEvent(event);
+ });
// Center section - View mode tabs
const centerSection = this.containerEl.createDiv({
@@ -210,6 +255,7 @@ export class TopNavigation extends Component {
cls: "fluent-view-tabs",
});
this.renderViewTabs();
+ if (this.availableModes.length === 0) centerSection.hide();
// Right section - Notifications and Settings
const rightSection = this.containerEl.createDiv({
@@ -220,6 +266,7 @@ export class TopNavigation extends Component {
this.customButtonsContainer = rightSection.createDiv({
cls: "fluent-nav-custom-buttons",
});
+ for (const button of this.customButtons.values()) this.customButtonsContainer.append(button.buttonEl);
// Cycle selector container (hidden by default)
this.cycleSelectorContainer = rightSection.createDiv({
@@ -228,8 +275,9 @@ export class TopNavigation extends Component {
this.cycleSelectorContainer.hide();
// Notification button
- const notificationBtn = rightSection.createDiv({
+ const notificationBtn = rightSection.createEl("button", {
cls: "fluent-nav-icon-button",
+ attr: { "aria-label": t("Notifications") },
});
setIcon(notificationBtn, "bell");
const badge = notificationBtn.createDiv({
@@ -246,9 +294,16 @@ export class TopNavigation extends Component {
);
// Settings button
- const settingsBtn = rightSection.createDiv({
+ const settingsBtn = rightSection.createEl("button", {
cls: "fluent-nav-icon-button",
+ attr: { "aria-label": t("Settings") },
});
+ // Share the host action strip rather than creating two separated icon groups.
+ const actions = this.containerEl.closest(".view-header")?.querySelector(".view-actions");
+ if (actions) {
+ actions.prepend(rightSection);
+ this.headerControls = rightSection;
+ }
setIcon(settingsBtn, "settings");
this.registerDomEvent(settingsBtn, "click", () =>
this.onSettingsClick(),
@@ -263,7 +318,7 @@ export class TopNavigation extends Component {
) {
const tab = container.createEl("button", {
cls: ["fluent-view-tab", "clickable-icon"],
- attr: { "data-mode": mode },
+ attr: { "data-mode": mode, "aria-label": label },
});
if (mode === this.currentViewMode) {
@@ -276,12 +331,16 @@ export class TopNavigation extends Component {
this.registerDomEvent(tab, "click", () => {
// Only trigger view change if switching to a different mode
if (this.currentViewMode !== mode) {
- this.setViewMode(mode);
- this.onViewModeChange(mode);
+ this.selectViewMode(mode);
}
});
}
+ public selectViewMode(mode: ViewMode): void {
+ this.setViewMode(mode);
+ this.onViewModeChange(mode);
+ }
+
public setViewMode(mode: ViewMode) {
this.currentViewMode = mode;
@@ -354,7 +413,7 @@ export class TopNavigation extends Component {
}
private updateNotificationBadge() {
- const badge = this.containerEl.querySelector(
+ const badge = (this.headerControls || this.containerEl).querySelector(
".fluent-notification-badge",
);
if (badge instanceof HTMLElement) {
@@ -367,6 +426,12 @@ export class TopNavigation extends Component {
}
}
+ public setActivePreset(id: string | null, advanced = false): void {
+ this.activePresetId = id;
+ const label = this.containerEl.querySelector(".tg-active-filter-label");
+ if (label) { label.textContent = id ? savedTaskFilters(this.plugin.settings.taskFilter?.presetTaskFilters).find(preset => preset.id === id)?.name || "" : advanced ? t("View filter") : ""; label.hidden = !label.textContent || ["points", "rewards", "habit"].includes(this.contextViewId); label.title = label.textContent || ""; }
+ this.containerEl.querySelector(".tg-quick-filter-button")?.classList.toggle("is-active", !!id);
+ }
public refresh() {
this.updateNotificationCount();
}
@@ -401,19 +466,21 @@ export class TopNavigation extends Component {
this.viewTabsContainer,
mode,
config.icon,
- config.label,
+ t(config.label),
);
}
}
}
public updateAvailableModes(modes: ViewMode[]) {
+ if (modes.length === this.availableModes.length && modes.every((mode, i) => mode === this.availableModes[i])) return;
const wasEmpty = this.availableModes.length === 0;
this.availableModes = modes;
// Hide entire navigation if no modes available
if (modes.length === 0) {
- this.containerEl.hide();
+ this.containerEl.show();
+ (this.containerEl.querySelector(".fluent-nav-center") as HTMLElement | null)?.hide();
this.containerEl.toggleClass("other-view", true);
return;
}
@@ -432,8 +499,7 @@ export class TopNavigation extends Component {
// If current mode is no longer available, switch to first available mode
if (!modes.includes(this.currentViewMode)) {
this.currentViewMode = modes[0];
- // Notify about the mode change
- this.onViewModeChange(this.currentViewMode);
+ // The owner resolves the mode after updating the available tabs.
}
// Update center section visibility (this should always be visible now since we handle empty modes above)
@@ -556,8 +622,10 @@ export class TopNavigation extends Component {
}
this.selectedCycleId = selectedCycleId;
- this.renderCycleSelector();
- this.cycleSelectorContainer.show();
+ const choices = (this.plugin.settings.statusCycles || []).filter(cycle => cycle.enabled && !/^default\s*cycle$|^默认周期$/i.test(cycle.name.trim()));
+ if (!choices.length) { this.cycleSelectorContainer.hide(); return; }
+ if (!choices.some(cycle => cycle.id === selectedCycleId)) this.selectedCycleId = null;
+ this.renderCycleSelector(); this.cycleSelectorContainer.show();
}
/**
@@ -657,7 +725,7 @@ export class TopNavigation extends Component {
// Get enabled cycles, sorted by priority
const enabledCycles = (this.plugin.settings.statusCycles || [])
- .filter((c) => c.enabled)
+ .filter((c) => c.enabled && !/^default\s*cycle$|^默认周期$/i.test(c.name.trim()))
.sort((a, b) => a.priority - b.priority);
if (enabledCycles.length === 0) {
diff --git a/src/components/features/fluent/components/ProjectFolders.ts b/src/components/features/fluent/components/ProjectFolders.ts
new file mode 100644
index 000000000..e3b4a765e
--- /dev/null
+++ b/src/components/features/fluent/components/ProjectFolders.ts
@@ -0,0 +1,18 @@
+import { App, setIcon } from "obsidian";
+import { t } from "@/translations/helper";
+/** Folder rows are navigation groups, never synthetic project records. */
+export function projectFolderContainer(root: HTMLElement, app: App): (folder: string) => HTMLElement {
+ const containers = new Map([["", root]]);
+ const collapsed = new Set(app.loadLocalStorage("task-genius-project-folders-collapsed") || []);
+ const get = (path: string): HTMLElement => {
+ if (containers.has(path)) return containers.get(path)!;
+ const segments = path.split("/"), name = segments.pop()!, parent = get(segments.join("/"));
+ const group = parent.createDiv({ cls: "tg-project-folder", attr: { "data-folder": path } });
+ const header = group.createEl("button", { cls: "tg-project-folder-row", attr: { "aria-expanded": String(!collapsed.has(path)) } });
+ const arrow = header.createSpan(); setIcon(arrow, collapsed.has(path) ? "chevron-right" : "chevron-down"); setIcon(header.createSpan(), "folder"); header.createSpan({ text: name });
+ const body = group.createDiv({ cls: "tg-project-folder-children" }); body.hidden = collapsed.has(path);
+ header.onclick = event => { event.stopPropagation(); body.hidden = !body.hidden; if (body.hidden) collapsed.add(path); else collapsed.delete(path); header.setAttribute("aria-expanded", String(!body.hidden)); setIcon(arrow, body.hidden ? "chevron-right" : "chevron-down"); app.saveLocalStorage("task-genius-project-folders-collapsed", [...collapsed]); };
+ containers.set(path, body); return body;
+ };
+ return get;
+}
diff --git a/src/components/features/fluent/components/ProjectList.ts b/src/components/features/fluent/components/ProjectList.ts
index ba1770fe5..47058a5b0 100644
--- a/src/components/features/fluent/components/ProjectList.ts
+++ b/src/components/features/fluent/components/ProjectList.ts
@@ -1,18 +1,24 @@
-import { Component, Platform, setIcon, Menu, Modal, App } from "obsidian";
+import { projectFolderContainer } from "./ProjectFolders";
+import { Component, setIcon, Menu, Modal, App, Notice } from "obsidian";
import TaskProgressBarPlugin from "@/index";
import { Task } from "@/types/task";
import { getEffectiveProject } from "@/utils/task/task-operations";
-import {
- ProjectPopover,
- ProjectModal,
- EditProjectModal,
-} from "./ProjectPopover";
+import { EditProjectModal } from "./ProjectPopover";
import type { CustomProject } from "@/common/setting-definition";
import { t } from "@/translations/helper";
import { onWorkspaceSwitched } from "@/components/features/fluent/events/ui-event";
import { Events, on } from "@/dataflow/events/Events";
+import {
+ ProjectFileManager,
+ ProjectCreateModal,
+ ProjectDeleteModal,
+ ProjectEditModal,
+ ProjectArchiveModal,
+} from "@/managers/project-file-manager";
+import { QuickCaptureModal } from "@/components/features/quick-capture/modals/QuickCaptureModalWithSwitch";
export interface Project {
+ folder?: string;
id: string;
name: string;
filterKey: string;
@@ -34,7 +40,7 @@ interface ProjectTreeNode {
fullPath: string;
}
-type SortOption =
+type SortOption = "manual"
| "name-asc"
| "name-desc"
| "tasks-asc"
@@ -46,10 +52,12 @@ export class ProjectList extends Component {
private containerEl: HTMLElement;
private plugin: TaskProgressBarPlugin;
private projects: Project[] = [];
+ private taskSnapshot: Task[] = [];
private activeProjectId: string | null = null;
+ private projectLoad = 0;
+ private disposed = false;
private onProjectSelect: (projectId: string) => void;
- private currentPopover: ProjectPopover | null = null;
- private currentSort: SortOption = "name-asc";
+ private currentSort: SortOption = "manual";
private readonly STORAGE_KEY = "task-genius-project-sort";
private readonly EXPANDED_KEY = "task-genius-project-expanded";
private collator: Intl.Collator;
@@ -78,10 +86,13 @@ export class ProjectList extends Component {
}
async onload() {
+ this.disposed = false;
await this.loadSortPreference();
+ if (this.disposed) return;
await this.loadExpandedNodes();
+ if (this.disposed) return;
await this.loadProjects();
- this.render();
+ if (this.disposed) return;
// Listen for workspace switches to refresh the project list
this.registerEvent(
@@ -119,29 +130,27 @@ export class ProjectList extends Component {
// Schedule a refresh with a small delay to allow tasks to load
this.refreshTimeoutId = setTimeout(() => {
- this.refresh();
this.refreshTimeoutId = null;
- }, 100);
+ void this.loadProjects(true);
+ }, 250);
}
onunload() {
+ this.disposed = true;
+ this.projectLoad++;
// Clean up any pending refresh timeout
if (this.refreshTimeoutId) {
clearTimeout(this.refreshTimeoutId);
this.refreshTimeoutId = null;
}
- // Clean up any open popover
- if (this.currentPopover) {
- this.removeChild(this.currentPopover);
- this.currentPopover = null;
- }
-
// Clear container
this.containerEl.empty();
}
- private async loadProjects() {
+ private async loadProjects(onlyIfChanged = false) {
+ if (this.disposed) return;
+ const request = ++this.projectLoad;
let tasks: Task[] = [];
if (this.plugin.dataflowOrchestrator) {
const queryAPI = this.plugin.dataflowOrchestrator.getQueryAPI();
@@ -149,11 +158,17 @@ export class ProjectList extends Component {
} else {
tasks = this.plugin.preloadedTasks || [];
}
+ if (this.disposed || request !== this.projectLoad) return;
+ this.taskSnapshot = tasks;
const projectMap = new Map();
+ const projectFiles = this.createProjectFileManager();
+ const archivedNames = new Set(
+ projectFiles.list().filter((project) => project.archived).map((project) => project.name),
+ );
tasks.forEach((task: Task) => {
const projectName = getEffectiveProject(task);
- if (!projectName) {
+ if (!projectName || archivedNames.has(projectName)) {
return;
}
@@ -177,8 +192,29 @@ export class ProjectList extends Component {
}
});
+ const previous = this.projects;
this.projects = Array.from(projectMap.values());
+ // Project notes are the canonical project records. Merge them into the
+ // sidebar even when they do not currently contain any indexed tasks.
+ for (const record of projectFiles.list()) {
+ if (record.archived) continue;
+ const existing = this.projects.find((project) => project.name === record.name);
+ if (existing) existing.folder = record.folder;
+ if (!existing) {
+ this.projects.push({
+ folder: record.folder,
+ id: record.name,
+ name: record.name,
+ filterKey: record.name,
+ displayName: record.name,
+ color: this.generateColorForProject(record.name),
+ taskCount: 0,
+ createdAt: record.file.stat.ctime,
+ });
+ }
+ }
+
// Load custom projects
this.loadCustomProjects();
@@ -190,7 +226,7 @@ export class ProjectList extends Component {
this.buildTreeStructure();
}
- this.render();
+ if (!onlyIfChanged || JSON.stringify(previous) !== JSON.stringify(this.projects)) this.render();
}
private async loadSortPreference() {
@@ -209,6 +245,7 @@ export class ProjectList extends Component {
private isValidSortOption(value: string): boolean {
return [
+ "manual",
"name-asc",
"name-desc",
"tasks-asc",
@@ -240,6 +277,7 @@ export class ProjectList extends Component {
private sortProjects() {
this.projects.sort((a, b) => {
switch (this.currentSort) {
+ case "manual": return this.createProjectFileManager().compareNames(a.name, b.name);
case "name-asc":
return this.collator.compare(
a.displayName || a.name,
@@ -387,6 +425,7 @@ export class ProjectList extends Component {
nodes.sort((a, b) => {
switch (this.currentSort) {
+ case "manual": return this.createProjectFileManager().compareNames(a.project.name, b.project.name);
case "name-asc":
return this.collator.compare(
a.project.displayName || a.project.name,
@@ -447,6 +486,7 @@ export class ProjectList extends Component {
}
private generateColorForProject(projectName: string): string {
+ const saved = this.createProjectFileManager().find(projectName)?.color; if (saved) return saved;
const colors = [
"#e74c3c",
"#3498db",
@@ -479,7 +519,10 @@ export class ProjectList extends Component {
cls: "fluent-project-scroll",
});
- if (this.isTreeView) {
+ if (this.projects.some(project => project.folder)) {
+ const folder = projectFolderContainer(scrollArea, this.plugin.app);
+ for (const project of this.projects) this.renderProjectItem(folder(project.folder || ""), project, 0, false);
+ } else if (this.isTreeView) {
// Build tree structure first
this.buildTreeStructure();
// Render tree view
@@ -509,6 +552,10 @@ export class ProjectList extends Component {
this.registerDomEvent(addProjectBtn, "click", () => {
this.handleAddProject(addProjectBtn);
});
+ const archiveButton = this.containerEl.createDiv({ cls: "fluent-project-item" });
+ setIcon(archiveButton.createSpan(), "archive");
+ archiveButton.createSpan({ cls: "fluent-project-name", text: t("Archived projects") });
+ this.registerDomEvent(archiveButton, "click", () => new ProjectArchiveModal(this.plugin.app, this.createProjectFileManager(), () => this.loadProjects()).open());
}
private renderTreeNodes(
@@ -547,6 +594,9 @@ export class ProjectList extends Component {
},
});
+ this.createProjectFileManager().bindReorder(projectItem, project.name, () => this.projects.map(project => project.name), () => {
+ this.currentSort = "manual"; void this.saveSortPreference(); void this.loadProjects(); void this.plugin.triggerViewUpdate();
+ });
// Add virtual class for styling
if (project.isVirtual) {
projectItem.addClass("is-virtual");
@@ -684,9 +734,8 @@ export class ProjectList extends Component {
});
if (projectId) {
- const activeEl = this.containerEl.querySelector(
- `[data-project-id="${projectId}"]`,
- );
+ const activeEl = Array.from(this.containerEl.querySelectorAll("[data-project-id]"))
+ .find(el => el.dataset.projectId === projectId);
if (activeEl) {
activeEl.addClass("is-active");
}
@@ -714,43 +763,11 @@ export class ProjectList extends Component {
}
private handleAddProject(buttonEl: HTMLElement) {
- // Clean up any existing popover
- if (this.currentPopover) {
- this.removeChild(this.currentPopover);
- this.currentPopover = null;
- }
-
- if (Platform.isPhone) {
- // Mobile: Use Obsidian Modal
- const modal = new ProjectModal(
- this.plugin.app,
- this.plugin,
- async (project) => {
- await this.saveProject(project);
- },
- );
- modal.open();
- } else {
- // Desktop: Use popover
- this.currentPopover = new ProjectPopover(
- this.plugin,
- buttonEl,
- async (project) => {
- await this.saveProject(project);
- if (this.currentPopover) {
- this.removeChild(this.currentPopover);
- this.currentPopover = null;
- }
- },
- () => {
- if (this.currentPopover) {
- this.removeChild(this.currentPopover);
- this.currentPopover = null;
- }
- },
- );
- this.addChild(this.currentPopover);
- }
+ new ProjectCreateModal(
+ this.plugin.app,
+ this.createProjectFileManager(),
+ () => this.loadProjects(),
+ ).open();
}
private async saveProject(project: CustomProject) {
@@ -804,23 +821,11 @@ export class ProjectList extends Component {
);
if (existingIndex === -1) {
- // Add new custom project
- this.projects.push({
- id: customProject.id,
- name: customProject.name,
- filterKey: customProject.name,
- displayName:
- customProject.displayName || customProject.name,
- color: customProject.color,
- taskCount: 0, // Will be updated by task counting
- createdAt: customProject.createdAt,
- updatedAt: customProject.updatedAt,
- });
+ // A saved display preference is not a project record.
+ return;
} else {
// Update existing project with custom color
- this.projects[existingIndex].id = customProject.id;
- this.projects[existingIndex].filterKey = customProject.name;
- this.projects[existingIndex].color = customProject.color;
+ this.projects[existingIndex].color = this.createProjectFileManager().find(customProject.name)?.color || customProject.color;
this.projects[existingIndex].displayName =
customProject.displayName || customProject.name;
this.projects[existingIndex].createdAt =
@@ -831,6 +836,34 @@ export class ProjectList extends Component {
});
}
+ private createProjectFileManager(): ProjectFileManager {
+ const prefixes = Object.values(this.plugin.settings.projectTagPrefix || {}).map(String);
+ return new ProjectFileManager(this.plugin.app, prefixes.length ? prefixes : ["project"]);
+ }
+
+ private async consolidateProject(name: string): Promise {
+ try {
+ const manager = this.createProjectFileManager(), project = await manager.create(name);
+ if (!project) return;
+ const matching = this.taskSnapshot.filter(task => getEffectiveProject(task) === name);
+ const canvas = matching.filter(task => task.metadata?.sourceType === "canvas");
+ let moved = await manager.moveTasks(matching.filter(task => !canvas.includes(task)), name);
+ for (const task of canvas) {
+ const result = await this.plugin.writeAPI?.updateTask({ taskId: task.id, updates: { metadata: { ...task.metadata, project: name } } });
+ if (result?.success) moved++;
+ }
+ await this.plugin.app.vault.process(project.file, text => {
+ let fenced = false;
+ return text.split("\n").map(line => {
+ if (/^\s*(```|~~~)/.test(line)) fenced = !fenced;
+ return !fenced && /^\s*[-*+]\s+\[[^\]]*\]/.test(line) ? manager.stripProjectMarkers(line, name) : line;
+ }).join("\n");
+ });
+ new Notice(`${t("Project note created; tasks moved")}: ${moved}`);
+ await this.loadProjects(); await this.plugin.triggerViewUpdate();
+ } catch (error) { console.error("Project consolidation failed", error); new Notice(t("Failed to move project tasks")); }
+ }
+
public showSortMenu(buttonEl: HTMLElement) {
const menu = new Menu();
@@ -839,6 +872,7 @@ export class ProjectList extends Component {
value: SortOption;
icon: string;
}[] = [
+ { label: t("Manual order"), value: "manual", icon: "grip-vertical" },
{ label: t("Name (A-Z)"), value: "name-asc", icon: "arrow-up-a-z" },
{
label: t("Name (Z-A)"),
@@ -896,38 +930,65 @@ export class ProjectList extends Component {
private showProjectContextMenu(event: MouseEvent, project: Project) {
const menu = new Menu();
+ const projectFiles = this.createProjectFileManager();
+ const projectFile = projectFiles.find(project.name);
+ if (projectFile) {
+ menu.addItem(item => item.setTitle(t("Move project tasks into note")).setIcon("folder-input").onClick(() => void this.consolidateProject(project.name)));
+ menu.addItem((item) => item
+ .setTitle(t("Open project note"))
+ .setIcon("file-text")
+ .onClick(() => void this.plugin.app.workspace.getLeaf(false).openFile(projectFile.file)));
+ menu.addItem((item) => item
+ .setTitle(t("Edit project details"))
+ .setIcon("pencil")
+ .onClick(() => new ProjectEditModal(
+ this.plugin.app,
+ projectFiles,
+ projectFile,
+ () => this.loadProjects(),
+ ).open()));
+ menu.addItem((item) => item
+ .setTitle(projectFile.archived ? t("Restore project") : t("Archive project"))
+ .setIcon(projectFile.archived ? "archive-restore" : "archive")
+ .onClick(async () => {
+ await projectFiles.setArchived(project.name, !projectFile.archived);
+ await this.loadProjects();
+ }));
+ menu.addItem((item) => item
+ .setTitle(t("Add task to project"))
+ .setIcon("plus")
+ .onClick(() => new QuickCaptureModal(this.plugin.app, this.plugin, { project: project.name }, true).open()));
+ menu.addItem(item => item.setTitle(t("Delete project")).setIcon("trash").onClick(() =>
+ new ProjectDeleteModal(this.plugin.app, projectFiles, projectFile, () => this.loadProjects()).open()));
+ menu.showAtMouseEvent(event);
+ return;
+ }
- // Check if this is a custom project
- const isCustomProject =
- this.plugin.settings.projectConfig?.customProjects?.some(
- (cp) => cp.id === project.id || cp.name === project.name,
- );
-
- // Edit Project option
- menu.addItem((item) => {
- item.setTitle(t("Edit Project")).setIcon("edit");
-
- if (isCustomProject) {
- item.onClick(() => {
- this.editProject(project);
- });
- } else {
- item.setDisabled(true);
- }
- });
-
- // Delete Project option
- menu.addItem((item) => {
- item.setTitle(t("Delete Project")).setIcon("trash");
-
- if (isCustomProject) {
- item.onClick(() => {
- this.deleteProject(project);
- });
- } else {
- item.setDisabled(true);
- }
- });
+ menu.addItem((item) => item
+ .setTitle(t("Create project note and move tasks"))
+ .setIcon("folder-plus")
+ .onClick(async () => {
+ try {
+ const projectNote = await projectFiles.create(project.name);
+ if (!projectNote) return;
+ const matchingTasks = this.taskSnapshot.filter(task => getEffectiveProject(task) === project.name);
+ const canvasTasks = matchingTasks.filter(task => task.metadata?.sourceType === "canvas" || task.filePath.toLowerCase().endsWith(".canvas"));
+ const markdownTasks = matchingTasks.filter(task => !canvasTasks.includes(task));
+ let movedCount = await projectFiles.moveTasks(markdownTasks, project.name);
+ for (const task of canvasTasks) {
+ const result = await this.plugin.writeAPI?.updateTask({
+ taskId: task.id,
+ updates: { metadata: { ...task.metadata, project: project.name } as any },
+ });
+ if (result?.success) movedCount++;
+ }
+ new Notice(`${t("Project note created; tasks moved")}: ${movedCount}`);
+ await this.loadProjects();
+ } catch (error) {
+ console.error("Failed to migrate legacy project tasks", error);
+ new Notice(t("Failed to move project tasks"));
+ }
+ }));
menu.showAtMouseEvent(event);
}
diff --git a/src/components/features/fluent/components/SavedTaskFilterModal.ts b/src/components/features/fluent/components/SavedTaskFilterModal.ts
new file mode 100644
index 000000000..4db36512f
--- /dev/null
+++ b/src/components/features/fluent/components/SavedTaskFilterModal.ts
@@ -0,0 +1,76 @@
+import { App, Modal, Notice, Setting } from "obsidian";
+import type TaskProgressBarPlugin from "@/index";
+import type { PresetTaskFilter } from "@/common/setting-definition";
+import { t } from "@/translations/helper";
+import { parseAdvancedFilterQuery } from "@/utils/task/filter-compatibility";
+import { conditionsQuery, FilterCondition } from "@/utils/task/saved-task-filters";
+
+export class SavedTaskFilterModal extends Modal {
+ constructor(app: App, private plugin: TaskProgressBarPlugin, private query: string,
+ private onSave: (id: string) => void, private existing?: PresetTaskFilter) { super(app); }
+ onOpen(): void {
+ this.modalEl.addClass("tg-saved-filter-modal");
+ this.setTitle(t(this.existing ? "Edit saved filter" : "New saved filter"));
+ let name = this.existing?.name || "", relation = this.existing?.options.relation || "AND";
+ let advanced = this.existing?.options.advancedFilterQuery || this.query;
+ let useAdvanced = !!advanced && !this.existing?.options.conditions;
+ const conditions: FilterCondition[] = this.existing?.options.conditions?.map(row => ({ ...row })) || [{ field: "status", operator: "=", value: "not-started" }];
+ new Setting(this.contentEl).setName(t("Name")).addText(text => text.setValue(name).onChange(value => name = value));
+ new Setting(this.contentEl).setName(t("Combine conditions")).addDropdown(dropdown => dropdown.addOption("AND", t("Match all conditions")).addOption("OR", t("Match any condition")).setValue(relation).onChange(value => relation = value as "AND" | "OR"));
+ const rows = this.contentEl.createDiv();
+ const render = () => {
+ rows.empty();
+ for (const [index, condition] of conditions.entries()) {
+ const row = new Setting(rows);
+ row.addDropdown(dropdown => {
+ for (const [field, label] of [["status", "Status"], ["date", "Any task date"], ["due", "Due date"], ["start", "Start date"], ["scheduled", "Scheduled date"], ["priority", "Priority"], ["project", "Project"], ["tag", "Tag"], ["text", "Text"], ["path", "File path"]]) dropdown.addOption(field, t(label));
+ dropdown.setValue(condition.field).onChange(value => { condition.field = value; condition.value = ""; condition.operator = "="; render(); });
+ });
+ const isDate = ["date", "due", "start", "scheduled"].includes(condition.field);
+ row.addDropdown(dropdown => {
+ for (const [operator, label] of [["=", "Equals"], ["!=", "Does not equal"], ...(["text", "path", "tag", "project"].includes(condition.field) ? [["contains", "Contains"]] : []), ...(isDate || condition.field === "priority" ? [[">=", "At least / on or after"], ["<=", "At most / on or before"]] : [])]) dropdown.addOption(operator, t(label));
+ dropdown.setValue(condition.operator).onChange(value => condition.operator = value);
+ });
+ const choices = condition.field === "status" ? [["not-started", "Not started"], ["planned", "Planned"], ["in-progress", "In progress"], ["completed", "Completed"], ["abandoned", "Abandoned"], ["paused", "Paused"]]
+ : condition.field === "priority" ? [["0", "None"], ["1", "Lowest"], ["2", "Low"], ["3", "Medium"], ["4", "High"], ["5", "Highest"]]
+ : isDate ? [["today", "Today"], ["tomorrow", "Tomorrow"], ["this-week", "This week"], ["this-month", "This month"], ["next-7-days", "Next 7 days"], ["none", "No date"], ["custom", "Choose date"]]
+ : condition.field === "project" ? [...new Set(this.app.vault.getMarkdownFiles().map(file => this.app.metadataCache.getFileCache(file)?.frontmatter?.project).filter(value => typeof value === "string"))].map(value => [value, value])
+ : condition.field === "tag" ? [...new Set([...(this.plugin.preloadedTasks || []).flatMap(task => task.metadata.tags || []), ...this.app.vault.getMarkdownFiles().flatMap(file => (this.app.metadataCache.getFileCache(file)?.tags || []).map(tag => tag.tag))])].map(value => [value, value]) : null;
+ if (choices) row.addDropdown(dropdown => {
+ dropdown.addOption("", t("Select a value"));
+ for (const [value, label] of choices) dropdown.addOption(value, ["project", "tag"].includes(condition.field) ? label : t(label));
+ const customDate = isDate && /^\d{4}-\d{2}-\d{2}$/.test(condition.value);
+ if (condition.value && !customDate && !choices.some(([value]) => value === condition.value)) dropdown.addOption(condition.value, condition.value);
+ dropdown.setValue(customDate ? "custom" : condition.value).onChange(value => { condition.value = value; render(); });
+ });
+ if (!choices || (isDate && (condition.value === "custom" || /^\d{4}-\d{2}-\d{2}$/.test(condition.value)))) row.addText(text => {
+ if (isDate) text.inputEl.type = "date";
+ text.setPlaceholder(t("Value")).setValue(condition.value === "custom" ? "" : condition.value).onChange(value => condition.value = value);
+ });
+ row.addExtraButton(button => button.setIcon("trash").setTooltip(t("Remove condition")).onClick(() => { conditions.splice(index, 1); render(); }));
+ }
+ }; render();
+ new Setting(this.contentEl).addButton(button => button.setButtonText(t("Add condition")).onClick(() => { conditions.push({ field: "status", operator: "=", value: "" }); render(); }));
+ const details = this.contentEl.createEl("details"); details.createEl("summary", { text: t("Advanced query (optional)") });
+ new Setting(details).setName(t("Use advanced query")).addToggle(toggle => toggle.setValue(useAdvanced).onChange(value => useAdvanced = value));
+ new Setting(details).addTextArea(text => text.setValue(advanced).onChange(value => advanced = value));
+ new Setting(this.contentEl).addButton(button => button.setButtonText(t("Save")).setCta().onClick(async () => {
+ if (!name.trim()) { new Notice(t("Enter a filter name.")); return; }
+ if (!useAdvanced && conditions.some(row => !row.value || row.value === "custom")) { new Notice(t("Choose a value for every condition.")); return; }
+ button.setDisabled(true);
+ try {
+ const query = useAdvanced ? advanced : conditionsQuery(conditions, relation); parseAdvancedFilterQuery(query);
+ const id = this.existing?.id || `filter-${Date.now()}`;
+ const preset: PresetTaskFilter = { id, name: name.trim(), options: {
+ includeCompleted: true, includeInProgress: true, includeAbandoned: true, includeNotStarted: true, includePlanned: true,
+ includeParentTasks: false, includeChildTasks: false, includeSiblingTasks: false,
+ conditions: useAdvanced ? undefined : conditions, relation, advancedFilterQuery: query.trim(), filterMode: "INCLUDE",
+ } };
+ const filters = this.plugin.settings.taskFilter.presetTaskFilters;
+ const index = filters.findIndex(item => item.id === id);
+ if (index < 0) filters.push(preset); else filters[index] = preset;
+ await this.plugin.saveSettings(); this.onSave(id); this.close();
+ } catch (error) { new Notice(String(error)); button.setDisabled(false); }
+ }));
+ }
+}
diff --git a/src/components/features/fluent/managers/FluentActionHandlers.ts b/src/components/features/fluent/managers/FluentActionHandlers.ts
index ec18ab90c..fa6b64690 100644
--- a/src/components/features/fluent/managers/FluentActionHandlers.ts
+++ b/src/components/features/fluent/managers/FluentActionHandlers.ts
@@ -1,3 +1,4 @@
+import { t as settingsText } from "@/translations/helper";
import { App, Component, Menu, Notice, TFile } from "obsidian";
import TaskProgressBarPlugin from "@/index";
import { StandardTaskMetadata, Task } from "@/types/task";
@@ -49,9 +50,6 @@ export class FluentActionHandlers extends Component {
private onSearchQueryChanged?: (query: string) => void;
private onProjectSelected?: (projectId: string) => void;
private onViewModeChanged?: (mode: ViewMode) => void;
- private showDetailsPanel?: (task: Task) => void;
- private toggleDetailsVisibility?: (visible: boolean) => void;
- private getIsDetailsVisible?: () => boolean;
constructor(
private app: App,
@@ -73,9 +71,6 @@ export class FluentActionHandlers extends Component {
onSearchQueryChanged?: (query: string) => void;
onProjectSelected?: (projectId: string) => void;
onViewModeChanged?: (mode: ViewMode) => void;
- showDetailsPanel?: (task: Task) => void;
- toggleDetailsVisibility?: (visible: boolean) => void;
- getIsDetailsVisible?: () => boolean;
}): void {
this.onTaskSelectionChanged = callbacks.onTaskSelectionChanged;
this.onTaskUpdated = callbacks.onTaskUpdated;
@@ -84,50 +79,14 @@ export class FluentActionHandlers extends Component {
this.onSearchQueryChanged = callbacks.onSearchQueryChanged;
this.onProjectSelected = callbacks.onProjectSelected;
this.onViewModeChanged = callbacks.onViewModeChanged;
- this.showDetailsPanel = callbacks.showDetailsPanel;
- this.toggleDetailsVisibility = callbacks.toggleDetailsVisibility;
- this.getIsDetailsVisible = callbacks.getIsDetailsVisible;
}
/**
* Handle task selection
*/
handleTaskSelection(task: Task | null): void {
- // Emit cross-view selection when using side leaves
- if (this.useSideLeaves()) {
- emitTaskSelected(this.app, {
- taskId: task?.id ?? null,
- origin: "main",
- workspaceId: this.getWorkspaceId(),
- });
- }
-
- if (task) {
- const now = Date.now();
- const timeSinceLastToggle = now - this.lastToggleTimestamp;
-
- if (this.currentSelectedTaskId !== task.id) {
- this.currentSelectedTaskId = task.id;
- this.showDetailsPanel?.(task);
- const isDetailsVisible = this.getIsDetailsVisible?.() ?? false;
- if (!isDetailsVisible) {
- this.toggleDetailsVisibility?.(true);
- }
- this.lastToggleTimestamp = now;
- this.onTaskSelectionChanged?.(task);
- return;
- }
-
- if (timeSinceLastToggle > 150) {
- const isDetailsVisible = this.getIsDetailsVisible?.() ?? false;
- this.toggleDetailsVisibility?.(!isDetailsVisible);
- this.lastToggleTimestamp = now;
- }
- } else {
- this.toggleDetailsVisibility?.(false);
- this.currentSelectedTaskId = null;
- this.onTaskSelectionChanged?.(null);
- }
+ this.currentSelectedTaskId = task?.id || null;
+ this.onTaskSelectionChanged?.(task);
}
/**
@@ -196,7 +155,6 @@ export class FluentActionHandlers extends Component {
}
const updated = writeResult.task || updatedTask;
-
// Notify about task update
this.onTaskUpdated?.(originalTask.id, updated);
@@ -310,30 +268,7 @@ export class FluentActionHandlers extends Component {
text: `${priorityIndicator}${cycle.name}: → ${nextStatusResult.statusName}`,
});
subItem.onClick(async () => {
- const willComplete = this.isCompletedMark(
- nextStatusResult.mark
- );
- const updatedTask = {
- ...task,
- status: nextStatusResult.mark,
- completed: willComplete,
- };
-
- if (!task.completed && willComplete) {
- updatedTask.metadata.completedDate =
- Date.now();
- } else if (
- task.completed &&
- !willComplete
- ) {
- updatedTask.metadata.completedDate =
- undefined;
- }
-
- await this.handleKanbanTaskStatusUpdate(
- updatedTask,
- nextStatusResult.mark
- );
+ await this.handleKanbanTaskStatusUpdate(task, nextStatusResult.mark);
});
});
}
@@ -375,23 +310,7 @@ export class FluentActionHandlers extends Component {
text: statusName,
});
subItem.onClick(async () => {
- const willComplete = this.isCompletedMark(mark);
- const updatedTask = {
- ...task,
- status: mark,
- completed: willComplete,
- };
-
- if (!task.completed && willComplete) {
- updatedTask.metadata.completedDate = Date.now();
- } else if (task.completed && !willComplete) {
- updatedTask.metadata.completedDate = undefined;
- }
-
- await this.handleKanbanTaskStatusUpdate(
- updatedTask,
- mark
- );
+ await this.handleKanbanTaskStatusUpdate(task, mark);
});
});
}
@@ -416,20 +335,7 @@ export class FluentActionHandlers extends Component {
text: status,
});
subItem.onClick(async () => {
- const willComplete = this.isCompletedMark(mark);
- const updatedTask = {
- ...task,
- status: mark,
- completed: willComplete,
- };
-
- if (!task.completed && willComplete) {
- updatedTask.metadata.completedDate = Date.now();
- } else if (task.completed && !willComplete) {
- updatedTask.metadata.completedDate = undefined;
- }
-
- await this.handleTaskUpdate(task, updatedTask);
+ await this.handleKanbanTaskStatusUpdate(task, mark);
});
});
}
@@ -505,11 +411,11 @@ export class FluentActionHandlers extends Component {
.setSubmenu();
const priorityLevels = [
- { level: 5, label: "Highest", icon: "alert-triangle" },
- { level: 4, label: "High", icon: "arrow-up" },
- { level: 3, label: "Medium", icon: "minus" },
- { level: 2, label: "Low", icon: "arrow-down" },
- { level: 1, label: "Lowest", icon: "chevron-down" },
+ { level: 5, label: settingsText("Highest"), icon: "alert-triangle" },
+ { level: 4, label: settingsText("High"), icon: "arrow-up" },
+ { level: 3, label: settingsText("Medium"), icon: "minus" },
+ { level: 2, label: settingsText("Low"), icon: "arrow-down" },
+ { level: 1, label: settingsText("Lowest"), icon: "chevron-down" },
] as const;
priorityLevels.forEach(({ level, label, icon }) => {
@@ -1100,9 +1006,11 @@ export class FluentActionHandlers extends Component {
/**
* Handle navigation to a view or create new task
*/
- handleNavigate(viewId: string): void {
+ handleNavigate(viewId: string, project?: string | null): void {
+ if (viewId === "review") viewId = "projects";
+ if (viewId === "rewards") viewId = "points";
if (viewId === "new-task") {
- new QuickCaptureModal(this.app, this.plugin).open();
+ new QuickCaptureModal(this.app, this.plugin, project ? { project } : undefined).open();
} else {
console.log(`[FluentAction] handleNavigate to ${viewId}`);
this.onNavigateToView?.(viewId);
diff --git a/src/components/features/fluent/managers/FluentComponentManager.ts b/src/components/features/fluent/managers/FluentComponentManager.ts
index 3cc02d77c..199aa9752 100644
--- a/src/components/features/fluent/managers/FluentComponentManager.ts
+++ b/src/components/features/fluent/managers/FluentComponentManager.ts
@@ -5,7 +5,6 @@ import { ContentComponent } from "@/components/features/task/view/content";
import { ForecastComponent } from "@/components/features/task/view/forecast";
import { TagsComponent } from "@/components/features/task/view/tags";
import { ProjectsComponent } from "@/components/features/task/view/projects";
-import { ReviewComponent } from "@/components/features/task/view/review";
import { Habit } from "@/components/features/habit/habit";
import { CalendarComponent } from "@/components/features/calendar";
import { KanbanComponent } from "@/components/features/kanban/kanban";
@@ -23,6 +22,7 @@ import { t } from "@/translations/helper";
import { ViewMode, TopNavigation } from "../components/FluentTopNavigation";
import { TaskSelectionManager } from "@/components/features/task/selection/TaskSelectionManager";
import { ErrorContext } from "@/types/fluent-types";
+import { PointsDashboard } from "@/components/features/rewards/PointsDashboard";
type ManagedViewComponent = {
containerEl: HTMLElement;
@@ -76,13 +76,15 @@ const ERROR_CSS_CLASSES = {
* - Render loading, error, and empty states
*/
export class FluentComponentManager extends Component {
+ private searchQuery = "";
+ setSearchQuery(query: string): void { this.searchQuery = query; }
// View components
private contentComponent: ContentComponent;
private forecastComponent: ForecastComponent;
private tagsComponent: TagsComponent;
private projectsComponent: ProjectsComponent;
- private reviewComponent: ReviewComponent;
private habitComponent: Habit;
+ private pointsComponent: PointsDashboard;
private calendarComponent: CalendarComponent;
private kanbanComponent: KanbanComponent;
private ganttComponent: GanttComponent;
@@ -288,39 +290,16 @@ export class FluentComponentManager extends Component {
this.parentView.addChild(this.projectsComponent);
this.projectsComponent.load();
- // Initialize ReviewComponent
- this.reviewComponent = new ReviewComponent(
- this.contentArea,
- this.app,
- this.plugin,
- {
- onTaskSelected: (task) => {
- if (task) this.viewHandlers.onTaskSelected(task);
- },
- onTaskCompleted: (task) => {
- if (task) this.viewHandlers.onTaskCompleted(task);
- },
- onTaskUpdate: async (originalTask, updatedTask) => {
- if (originalTask && updatedTask) {
- await this.viewHandlers.onTaskUpdate(
- originalTask,
- updatedTask
- );
- }
- },
- onTaskContextMenu: (event, task) => {
- if (task) this.viewHandlers.onTaskContextMenu(event, task);
- },
- }
- );
- this.parentView.addChild(this.reviewComponent);
- this.reviewComponent.load();
// Initialize HabitComponent
- this.habitComponent = new Habit(this.plugin, this.contentArea);
+ this.habitComponent = new Habit(this.plugin, this.contentArea, true);
this.parentView.addChild(this.habitComponent);
this.habitComponent.load();
+ this.pointsComponent = new PointsDashboard(this.app, this.plugin, this.contentArea);
+ this.parentView.addChild(this.pointsComponent);
+ this.pointsComponent.load();
+
// Initialize CalendarComponent
this.calendarComponent = new CalendarComponent(
this.app,
@@ -404,51 +383,26 @@ export class FluentComponentManager extends Component {
* Hide all components
*/
hideAllComponents(forceHideAll = false): void {
- const isInitialHide = forceHideAll;
-
- // Smart hiding - only hide currently visible component (unless initial hide)
- if (!isInitialHide && this.currentVisibleComponent) {
- console.log(
- "[FluentComponent] Smart hide - only hiding current visible component"
- );
- this.currentVisibleComponent.containerEl?.hide();
- this.currentVisibleComponent = null;
- } else {
- // Hide all components
- console.log(
- "[FluentComponent] Hiding all components",
- isInitialHide ? "(initial hide)" : ""
- );
- this.contentComponent?.containerEl.hide();
- this.forecastComponent?.containerEl.hide();
- this.tagsComponent?.containerEl.hide();
- this.projectsComponent?.containerEl.hide();
- this.reviewComponent?.containerEl.hide();
- this.habitComponent?.containerEl.hide();
- this.calendarComponent?.containerEl.hide();
- this.kanbanComponent?.containerEl.hide();
- this.ganttComponent?.containerEl.hide();
- this.viewComponentManager?.hideAllComponents();
-
- // Hide two column views
- this.twoColumnViewComponents.forEach((component) => {
- component.containerEl.hide();
- });
-
- // Hide legacy containers
- this.listContainer?.hide();
- this.treeContainer?.hide();
- }
-
- // Hide cycle selector when hiding all components
- if (this.topNavigation) {
- this.topNavigation.hideCycleSelector();
- }
+ for (const component of [this.contentComponent, this.forecastComponent, this.tagsComponent, this.projectsComponent, this.habitComponent, this.pointsComponent, this.calendarComponent, this.kanbanComponent, this.ganttComponent]) component?.containerEl?.hide();
+ this.viewComponentManager?.hideAllComponents();
+ for (const component of this.twoColumnViewComponents.values()) component.containerEl.hide();
+ this.listContainer?.hide(); this.treeContainer?.hide();
+ this.currentVisibleComponent = null;
+ this.topNavigation?.hideCycleSelector();
}
/**
* Switch to a specific view
*/
+ refreshConfiguration(): void {
+ this.calendarComponent?.refreshConfiguration();
+ for (const component of this.twoColumnViewComponents.values()) {
+ this.parentView.removeChild(component);
+ component.containerEl.remove();
+ }
+ this.twoColumnViewComponents.clear();
+ }
+
switchView(
viewId: string,
tasks: Task[],
@@ -562,6 +516,10 @@ export class FluentComponentManager extends Component {
} else {
// Standard view types
switch (viewId) {
+ case "rewards":
+ case "points":
+ targetComponent = this.pointsComponent;
+ break;
case "habit":
targetComponent = this.habitComponent;
break;
@@ -587,7 +545,8 @@ export class FluentComponentManager extends Component {
}
break;
case "review":
- targetComponent = this.reviewComponent;
+ targetComponent = this.projectsComponent;
+ modeForComponent = "projects";
break;
case "calendar":
targetComponent = this.calendarComponent;
@@ -641,10 +600,16 @@ export class FluentComponentManager extends Component {
`[FluentComponent] Setting view mode for ${viewId} to ${modeForComponent}`
);
targetComponent.setViewMode(modeForComponent as any, project);
+ if (targetComponent === this.contentComponent) {
+ this.contentComponent.setIsTreeView(viewMode === "tree");
+ }
}
// Set tasks on the component
- if (typeof targetComponent.setTasks === "function") {
+ (targetComponent as ManagedViewComponent & { setSearchQuery?: (query: string) => void }).setSearchQuery?.(this.searchQuery);
+ if (targetComponent === this.contentComponent) {
+ this.contentComponent.setTasks(filteredTasks, tasks, false, true);
+ } else if (typeof targetComponent.setTasks === "function") {
// Special handling for components that need filtered + all tasks
// Tags view: uses filtered tasks for tag index (left sidebar), all tasks for tree view lookup
if (viewId === "tags") {
@@ -687,7 +652,7 @@ export class FluentComponentManager extends Component {
}
// Handle updateTasks method for table view adapter
- if (typeof targetComponent.updateTasks === "function") {
+ if (typeof targetComponent.setTasks !== "function" && typeof targetComponent.updateTasks === "function") {
const filterOptions: any = {};
if (
currentFilterState &&
@@ -697,16 +662,11 @@ export class FluentComponentManager extends Component {
filterOptions.advancedFilter = currentFilterState;
}
- targetComponent.updateTasks(
- filterTasks(
- tasks,
- viewId as any,
- this.plugin,
- filterOptions
- )
- );
+ targetComponent.updateTasks(filteredTasks);
}
+ (targetComponent as ManagedViewComponent & { onShown?: () => void }).onShown?.();
+
// Refresh review settings if needed
if (
viewId === "review" &&
@@ -766,7 +726,7 @@ export class FluentComponentManager extends Component {
"[FluentComponent] Setting tasks to ContentComponent, filtered:",
filteredTasks.length
);
- this.contentComponent.setTasks(filteredTasks, tasks);
+ this.contentComponent.setTasks(filteredTasks, tasks, false, true);
this.currentVisibleComponent = this.contentComponent;
break;
@@ -861,7 +821,7 @@ export class FluentComponentManager extends Component {
this.contentComponent?.setTasks?.(
filteredTasks,
tasks,
- true
+ true, true
);
break;
}
@@ -886,7 +846,7 @@ export class FluentComponentManager extends Component {
forecast: this.forecastComponent,
tags: this.tagsComponent,
projects: this.contentComponent,
- review: this.reviewComponent,
+ review: this.projectsComponent,
habit: this.habitComponent,
gantt: this.ganttComponent,
kanban: this.kanbanComponent,
@@ -1116,7 +1076,7 @@ export class FluentComponentManager extends Component {
projects: t("Projects"),
tags: t("Tags"),
forecast: t("Forecast"),
- review: t("Review"),
+ review: t("Projects"),
habit: t("Habit"),
calendar: t("Calendar"),
kanban: t("Kanban"),
@@ -1178,9 +1138,10 @@ export class FluentComponentManager extends Component {
/**
* Check if view is content-based (supports multiple view modes)
*/
- private isContentBasedView(viewId: string): boolean {
+ public isContentBasedView(viewId: string): boolean {
const contentBasedViews = [
"inbox",
+ "working-on",
"today",
"upcoming",
"flagged",
diff --git a/src/components/features/fluent/managers/FluentDataManager.ts b/src/components/features/fluent/managers/FluentDataManager.ts
index e49f2a075..db65196af 100644
--- a/src/components/features/fluent/managers/FluentDataManager.ts
+++ b/src/components/features/fluent/managers/FluentDataManager.ts
@@ -1,3 +1,4 @@
+import { isProjectCalendarEntry } from "@/utils/task/project-calendar";
import { Component, debounce } from "obsidian";
import TaskProgressBarPlugin from "@/index";
import { Task } from "@/types/task";
@@ -7,9 +8,13 @@ import { isDataflowEnabled } from "@/dataflow/createDataflow";
import { Events, on } from "@/dataflow/events/Events";
import { sortTasks } from "@/commands/sortTaskCommands";
import { TaskTimerManager } from "@/managers/timer-manager";
+import { PresetTaskFilter } from "@/common/setting-definition";
+import { evaluateFilterNode, parseAdvancedFilterQuery } from "@/utils/task/filter-compatibility";
+import { buildProjectPlan } from "@/managers/project-plan";
+import { ProjectFileManager } from "@/managers/project-file-manager";
/**
- * FluentDataManager - Stateless data loading, filtering, and sorting executor
+ * FluentDataManager - Data loading, filtering, and sorting executor
*
* Responsibilities:
* - Load tasks from dataflow or preloaded cache (returns via callback)
@@ -18,8 +23,8 @@ import { TaskTimerManager } from "@/managers/timer-manager";
* - Register dataflow event listeners for real-time updates
* - Schedule and batch updates to prevent rapid re-renders
*
- * NOTE: This manager is STATELESS - it does not hold tasks or filtered tasks.
- * All state is managed by TaskViewV2, this manager only executes operations.
+ * The view owns its task arrays. The manager remembers the last delivered
+ * snapshot so repeated sync events do not repaint an unchanged view.
*/
export class FluentDataManager extends Component {
// Callbacks
@@ -29,6 +34,20 @@ export class FluentDataManager extends Component {
// Batch operation state flag
private isBatchOperating = false;
+ private loadRequest = 0;
+ private disposed = false;
+ private listenersRegistered = false;
+ private pendingDataRefresh = false;
+ private lastSnapshot: string | undefined;
+ private showingLoading = false;
+
+ async finishInitialization(): Promise {
+ if (this.disposed || !this.pendingDataRefresh) return;
+ this.pendingDataRefresh = false;
+ await this.loadTasks(false);
+ }
+
+ onunload(): void { this.disposed = true; this.loadRequest++; }
constructor(
private plugin: TaskProgressBarPlugin,
@@ -40,6 +59,7 @@ export class FluentDataManager extends Component {
selectedProject: string | undefined;
searchQuery: string;
filterInputValue: string;
+ activeTaskPreset: PresetTaskFilter["options"] | null;
},
private isInitializing: () => boolean,
) {
@@ -63,7 +83,9 @@ export class FluentDataManager extends Component {
* Load tasks from dataflow or preloaded cache
* Returns loaded tasks via callback
*/
- async loadTasks(showLoading = true): Promise {
+ async loadTasks(showLoading = true, onlyIfChanged = false): Promise {
+ if (this.disposed) return;
+ const request = ++this.loadRequest;
try {
console.log(
"[FluentData] loadTasks started, showLoading:",
@@ -72,6 +94,7 @@ export class FluentDataManager extends Component {
// Notify loading state
if (showLoading && !this.isInitializing()) {
+ this.showingLoading = true;
console.log("[FluentData] Notifying loading state");
this.onLoadingStateChanged?.(true);
}
@@ -84,7 +107,7 @@ export class FluentDataManager extends Component {
);
const queryAPI = this.plugin.dataflowOrchestrator.getQueryAPI();
console.log("[FluentData] Getting all tasks from queryAPI...");
- loadedTasks = await queryAPI.getAllTasks();
+ loadedTasks = await queryAPI.getAllTasks(true);
console.log(
`[FluentData] Loaded ${loadedTasks.length} tasks from dataflow`,
);
@@ -98,18 +121,30 @@ export class FluentDataManager extends Component {
);
}
- // Return loaded tasks via callback
+ if (this.disposed || request !== this.loadRequest) return;
+ const viewId = this.getCurrentViewId();
+ const projects = viewId === "projects" || viewId === "gantt"
+ ? new ProjectFileManager(this.plugin.app).list().map(({ file, ...project }) => ({ ...project, path: file.path }))
+ : undefined;
+ const snapshot = JSON.stringify([loadedTasks, projects]);
+ if (onlyIfChanged && !this.showingLoading && snapshot === this.lastSnapshot) return;
+ this.lastSnapshot = snapshot;
this.onTasksLoaded?.(loadedTasks, null);
} catch (error) {
console.error("[FluentData] Failed to load tasks:", error);
const errorMessage =
(error as Error).message || "Failed to load tasks";
- // Return error via callback
- this.onTasksLoaded?.([], errorMessage);
+ if (!this.disposed && request === this.loadRequest) {
+ this.lastSnapshot = undefined;
+ this.onTasksLoaded?.([], errorMessage);
+ }
} finally {
// Always notify loading complete
console.log("[FluentData] loadTasks complete");
- this.onLoadingStateChanged?.(false);
+ if (!this.disposed && request === this.loadRequest) {
+ this.showingLoading = false;
+ this.onLoadingStateChanged?.(false);
+ }
}
}
@@ -121,13 +156,17 @@ export class FluentDataManager extends Component {
applyFilters(tasks: Task[]): Task[] {
const viewId = this.getCurrentViewId();
const filterState = this.getCurrentFilterState();
+ if (viewId === "gantt") tasks = buildProjectPlan(this.plugin.app, tasks);
+ if (viewId === "calendar" || this.plugin.settings.viewConfiguration.find(view => view.id === viewId)?.specificConfig?.viewType === "calendar") tasks = tasks.filter(task => !isProjectCalendarEntry(this.plugin.app, task));
+ const query = filterState.filterInputValue || filterState.searchQuery || "";
+ const structuredQuery = /\b(?:AND|OR|NOT)\b|\b[\w-]+\s*:/i.test(query);
console.log(`[FluentData] applyFilters called for viewId: ${viewId}, total tasks: ${tasks.length}`);
// Build filter options
const filterOptions: any = {
- textQuery:
- filterState.filterInputValue || filterState.searchQuery || "",
+ textQuery: structuredQuery ? "" : query,
+ includeClosedTasks: !!filterState.activeTaskPreset,
};
// Always enable v2Filters for Working-on so the special filter runs
@@ -185,6 +224,76 @@ export class FluentDataManager extends Component {
);
}
+ if (structuredQuery) {
+ try {
+ const tree = parseAdvancedFilterQuery(query);
+ filteredTasks = filteredTasks.filter(task => evaluateFilterNode(tree, task));
+ } catch { filteredTasks = []; }
+ }
+ const preset = filterState.activeTaskPreset;
+ if (preset) {
+ let presetTree: ReturnType | null = null;
+ try { if (preset.advancedFilterQuery?.trim()) presetTree = parseAdvancedFilterQuery(preset.advancedFilterQuery); }
+ catch { return []; }
+ const marks = this.plugin.settings.taskStatuses;
+ const split = (value?: string) => String(value || "").split("|").map(mark => mark.toLowerCase());
+ const inProgress = split(marks?.inProgress);
+ const completed = split(marks?.completed);
+ const abandoned = split(marks?.abandoned);
+ const planned = split(marks?.planned);
+ const notStarted = split(marks?.notStarted || " ");
+ const statusMatch = (task: Task) => {
+ const mark = String(task.status ?? " ").toLowerCase();
+ if (task.completed || completed.includes(mark)) return preset.includeCompleted;
+ if (abandoned.includes(mark)) return preset.includeAbandoned;
+ if (inProgress.includes(mark)) return preset.includeInProgress;
+ if (planned.includes(mark)) return preset.includePlanned;
+ if (notStarted.includes(mark)) return preset.includeNotStarted;
+ return preset.includeNotStarted;
+ };
+ const queryMatch = (task: Task) => {
+ const query = preset.advancedFilterQuery?.trim();
+ if (!query) return true;
+ const mark = String(task.status ?? " ").toLowerCase();
+ const statusName = task.completed || completed.includes(mark) ? "completed"
+ : abandoned.includes(mark) ? "abandoned"
+ : inProgress.includes(mark) ? "in-progress"
+ : planned.includes(mark) ? "planned"
+ : ["~", "="].includes(mark) || (this.plugin.settings.statusCycles || []).some(cycle => Object.entries(cycle.marks).some(([name, symbol]) => symbol === task.status && /pause|暂停/i.test(name))) ? "paused"
+ : "not-started";
+ return evaluateFilterNode(presetTree, { ...task, statusName });
+ };
+ const directMatches = new Set();
+ for (const task of filteredTasks) {
+ const matchesQuery = queryMatch(task);
+ const matchesPreset = preset.filterMode === "EXCLUDE" ? !matchesQuery : matchesQuery;
+ if (statusMatch(task) && matchesPreset) directMatches.add(task.id);
+ }
+ const included = new Set(directMatches);
+ const allById = new Map(tasks.map(task => [task.id, task]));
+ for (const id of directMatches) {
+ const task = allById.get(id);
+ if (!task) continue;
+ const parentId = task.metadata?.parent;
+ if (preset.includeParentTasks && parentId) included.add(parentId);
+ if (preset.includeSiblingTasks && parentId) {
+ for (const sibling of tasks) if (sibling.metadata?.parent === parentId) included.add(sibling.id);
+ }
+ if (preset.includeChildTasks) {
+ const addChildren = (parent: Task) => {
+ for (const childId of parent.metadata?.children || []) {
+ if (included.has(childId)) continue;
+ included.add(childId);
+ const child = allById.get(childId);
+ if (child) addChildren(child);
+ }
+ };
+ addChildren(task);
+ }
+ }
+ filteredTasks = tasks.filter(task => included.has(task.id));
+ }
+
console.log(
`[FluentData] Final filtered result: ${filteredTasks.length} tasks from ${tasks.length} total for viewId: ${viewId}`,
);
@@ -400,8 +509,11 @@ export class FluentDataManager extends Component {
* Notifies parent via onUpdateNeeded callback
*/
async registerDataflowListeners(): Promise {
+ if (this.listenersRegistered || this.disposed) return;
+ this.listenersRegistered = true;
// Add debounced view update to prevent rapid successive refreshes
const debouncedViewUpdate = debounce(async () => {
+ if (this.disposed) return;
console.log("[FluentData] debouncedViewUpdate triggered");
// Skip update during batch operation to prevent list flashing
@@ -413,20 +525,21 @@ export class FluentDataManager extends Component {
}
if (!this.isInitializing()) {
- // Load tasks and notify parent
- await this.loadTasks(false);
- // Notify parent that data changed
- this.onUpdateNeeded?.("dataflow");
+ this.pendingDataRefresh = false;
+ await this.loadTasks(false, true);
}
- }, 500);
+ }, 500, true);
// Add debounced filter application
const debouncedApplyFilter = debounce(() => {
- if (!this.isInitializing()) {
+ if (!this.disposed && !this.isInitializing()) {
this.onUpdateNeeded?.("filter-changed");
}
}, 400);
+ this.register(() => { (debouncedViewUpdate as any).cancel?.(); (debouncedApplyFilter as any).cancel?.(); });
+ const requestDataRefresh = () => { this.pendingDataRefresh = true; debouncedViewUpdate(); };
+
const scheduleFilterRefresh = () => {
if (this.isInitializing()) {
return;
@@ -436,6 +549,11 @@ export class FluentDataManager extends Component {
debouncedApplyFilter();
};
+ // Listen for cache ready event
+ this.registerEvent(
+ on(this.plugin.app, Events.CACHE_READY, () => this.loadTasks(false, true)),
+ );
+
// Register dataflow event listeners
if (isDataflowEnabled(this.plugin)) {
// Listen for batch operation start
@@ -459,29 +577,19 @@ export class FluentDataManager extends Component {
);
this.isBatchOperating = false;
- // Immediately refresh view after batch operation (skip debounce)
- if (!this.isInitializing()) {
- await this.loadTasks(false);
- this.onUpdateNeeded?.("batch-operation-complete");
- }
+ // Use the same scheduled refresh as the cache events from the batch.
+ requestDataRefresh();
},
),
);
- // Listen for cache ready event
- this.registerEvent(
- on(this.plugin.app, Events.CACHE_READY, async () => {
- await this.loadTasks();
- this.onUpdateNeeded?.("cache-ready");
- }),
- );
// Listen for task cache updates
this.registerEvent(
on(
this.plugin.app,
Events.TASK_CACHE_UPDATED,
- debouncedViewUpdate,
+ requestDataRefresh,
),
);
} else {
@@ -489,7 +597,7 @@ export class FluentDataManager extends Component {
this.registerEvent(
this.plugin.app.workspace.on(
"task-genius:task-cache-updated",
- debouncedViewUpdate,
+ requestDataRefresh,
),
);
}
diff --git a/src/components/features/fluent/managers/FluentLayoutManager.ts b/src/components/features/fluent/managers/FluentLayoutManager.ts
index 52cbcc5df..241958e87 100644
--- a/src/components/features/fluent/managers/FluentLayoutManager.ts
+++ b/src/components/features/fluent/managers/FluentLayoutManager.ts
@@ -8,7 +8,7 @@ import {
} from "obsidian";
import TaskProgressBarPlugin from "@/index";
import { FluentSidebar } from "../components/FluentSidebar";
-import { TaskDetailsComponent } from "@/components/features/task/view/details";
+import { TaskDetailsModal } from "@/components/features/task/edit/TaskDetailsModal";
import { Task } from "@/types/task";
import { t } from "@/translations/helper";
import { TG_LEFT_SIDEBAR_VIEW_TYPE } from "../../../../pages/LeftSidebarView";
@@ -37,28 +37,20 @@ import { RootFilterState } from "@/components/features/task/filter/ViewTaskFilte
export class FluentLayoutManager extends Component {
// Layout state
public isSidebarCollapsed = false;
- public isDetailsVisible = false;
public isMobileDrawerOpen = false;
// UI elements
private sidebarToggleBtn: HTMLElement | null = null;
private drawerOverlay: HTMLElement | null = null;
- private detailsToggleBtn: HTMLElement | null = null;
- private mobileDetailsOverlayHandler?: (e: MouseEvent) => void;
+ private editorModal: TaskDetailsModal | null = null;
// Components (non-leaves mode only)
public sidebar: FluentSidebar | null = null;
- public detailsComponent: TaskDetailsComponent | null = null;
+
// Callbacks
private onSidebarNavigate?: (viewId: string) => void;
private onProjectSelect?: (projectId: string) => void;
- private onTaskToggleComplete?: (task: Task) => void;
- private onTaskEdit?: (task: Task) => void;
- private onTaskUpdate?: (
- originalTask: Task,
- updatedTask: Task,
- ) => Promise;
private onFilterReset?: () => void;
private getLiveFilterState?: () => RootFilterState | null;
private leaf: WorkspaceLeaf;
@@ -91,19 +83,6 @@ export class FluentLayoutManager extends Component {
this.onProjectSelect = callback;
}
- /**
- * Set task callbacks for details component
- */
- setTaskCallbacks(callbacks: {
- onTaskToggleComplete: (task: Task) => void;
- onTaskEdit: (task: Task) => void;
- onTaskUpdate: (originalTask: Task, updatedTask: Task) => Promise;
- }): void {
- this.onTaskToggleComplete = callbacks.onTaskToggleComplete;
- this.onTaskEdit = callbacks.onTaskEdit;
- this.onTaskUpdate = callbacks.onTaskUpdate;
- }
-
/**
* Set filter callbacks
*/
@@ -163,54 +142,13 @@ export class FluentLayoutManager extends Component {
this.addChild(this.sidebar);
}
- /**
- * Initialize details component (non-leaves mode only)
- */
- initializeDetailsComponent(): void {
- if (this.useSideLeaves()) {
- console.log(
- "[FluentLayout] Using workspace side leaves: skip in-view details panel",
- );
- return;
- }
-
- // Initialize details component (hidden by default)
- this.detailsComponent = new TaskDetailsComponent(
- this.rootContainerEl,
- this.app,
- this.plugin,
- );
- this.addChild(this.detailsComponent);
- this.detailsComponent.load();
-
- // Set up callbacks
- this.detailsComponent.onTaskToggleComplete = (task: Task) =>
- this.onTaskToggleComplete?.(task);
- this.detailsComponent.onTaskEdit = (task: Task) =>
- this.onTaskEdit?.(task);
- this.detailsComponent.onTaskUpdate = async (
- originalTask: Task,
- updatedTask: Task,
- ) => {
- await this.onTaskUpdate?.(originalTask, updatedTask);
- };
- this.detailsComponent.toggleDetailsVisibility = (visible: boolean) => {
- this.toggleDetailsVisibility(visible);
- };
- this.detailsComponent.setVisible(this.isDetailsVisible);
- }
-
/**
* Create sidebar toggle button in header
*/
createSidebarToggle(): void {
- const headerBtns = !Platform.isPhone
- ? (this.headerEl?.querySelector(
- ".view-header-nav-buttons",
- ) as HTMLElement | null)
- : (this.headerEl?.querySelector(
- ".view-header-left",
- ) as HTMLElement);
+ const headerBtns = Platform.isPhone
+ ? this.rootContainerEl.querySelector(".tg-fluent-phone-toolbar")
+ : this.headerEl?.querySelector(".view-header-nav-buttons");
if (!headerBtns) {
console.warn("[FluentLayout] header buttons container not found");
@@ -231,6 +169,9 @@ export class FluentLayoutManager extends Component {
.setClass("clickable-icon")
.onClick(() => this.toggleSidebar());
+ btn.buttonEl.setAttribute("aria-label", t("Toggle Sidebar"));
+ if (Platform.isPhone) return;
+
this.registerEvent(
this.plugin.app.workspace.on(
"task-genius:leaf-width-updated",
@@ -352,16 +293,9 @@ export class FluentLayoutManager extends Component {
cls: "drawer-overlay",
});
this.drawerOverlay.hide();
- this.registerDomEvent(
- this.drawerOverlay,
- "click",
- () => {
- this.closeMobileDrawer();
- },
- {
- once: true,
- },
- );
+ this.registerDomEvent(this.drawerOverlay, "click", () => {
+ this.closeMobileDrawer();
+ });
}
/**
@@ -371,87 +305,7 @@ export class FluentLayoutManager extends Component {
* - Non-leaves mode: Toggle internal details component
* - Mobile: Overlay with backdrop
*/
- toggleDetailsVisibility(visible: boolean): void {
- this.isDetailsVisible = visible;
-
- if (this.useSideLeaves()) {
- // In side-leaf mode, reveal/collapse the right details pane
- const ws = this.app.workspace;
- if (visible) {
- // Try to expand right split if it's collapsed
- if (ws.rightSplit?.collapsed) {
- ws.rightSplit.expand();
- }
- } else {
- ws.rightSplit.collapse();
- }
-
- // Update header toggle visual state
- if (this.detailsToggleBtn) {
- this.detailsToggleBtn.toggleClass("is-active", visible);
- this.detailsToggleBtn.setAttribute(
- "aria-label",
- visible ? t("Hide Details") : t("Show Details"),
- );
- }
- return;
- }
-
- // Legacy/in-view mode
- this.rootContainerEl?.toggleClass("details-visible", visible);
- this.rootContainerEl?.toggleClass("details-hidden", !visible);
-
- if (this.detailsComponent) {
- this.detailsComponent.setVisible(visible);
- }
-
- if (this.detailsToggleBtn) {
- this.detailsToggleBtn.toggleClass("is-active", visible);
- this.detailsToggleBtn.setAttribute(
- "aria-label",
- visible ? t("Hide Details") : t("Show Details"),
- );
- }
-
- // On mobile, add click handler to overlay to close details
- if (Platform.isPhone && visible) {
- // Use setTimeout to avoid immediate close on open
- setTimeout(() => {
- const overlayClickHandler = (e: MouseEvent) => {
- // Check if click is on the overlay (pseudo-element area)
- const detailsEl =
- this.rootContainerEl?.querySelector(".task-details");
- if (detailsEl && !detailsEl.contains(e.target as Node)) {
- this.toggleDetailsVisibility(false);
- document.removeEventListener(
- "click",
- overlayClickHandler,
- );
- }
- };
- document.addEventListener("click", overlayClickHandler);
- this.mobileDetailsOverlayHandler = overlayClickHandler;
- }, 100);
- } else if (
- Platform.isPhone &&
- !visible &&
- this.mobileDetailsOverlayHandler
- ) {
- document.removeEventListener(
- "click",
- this.mobileDetailsOverlayHandler,
- );
- delete this.mobileDetailsOverlayHandler;
- }
- }
-
- /**
- * Store details toggle button reference
- */
- setDetailsToggleBtn(btn: HTMLElement): void {
- this.detailsToggleBtn = btn;
- this.detailsToggleBtn.toggleClass("is-active", this.isDetailsVisible);
- }
+ closeTaskEditor(): void { this.editorModal?.close(); this.editorModal = null; }
/**
* Check and auto-collapse sidebar on narrow screens (desktop only)
@@ -489,13 +343,10 @@ export class FluentLayoutManager extends Component {
* Show task details in details panel
*/
showTaskDetails(task: Task): void {
- if (this.useSideLeaves()) {
- // In leaves mode, emit event to side leaf details view
- // This will be handled by the main view's event emission
- return;
- }
-
- this.detailsComponent?.showTaskDetails(task);
+ if (!task?.id) return;
+ this.editorModal?.close();
+ this.editorModal = new TaskDetailsModal(this.app, this.plugin, task);
+ this.editorModal.open();
}
/**
@@ -527,79 +378,9 @@ export class FluentLayoutManager extends Component {
* - Reset filter button (conditional)
*/
createActionButtons(): void {
- // Details toggle button
- this.detailsToggleBtn = this.view.addAction(
- "panel-right-dashed",
- t("Details"),
- () => {
- this.toggleDetailsVisibility(!this.isDetailsVisible);
- },
- );
-
- if (this.detailsToggleBtn) {
- this.detailsToggleBtn.toggleClass("panel-toggle-btn", true);
- this.detailsToggleBtn.toggleClass(
- "is-active",
- this.isDetailsVisible,
- );
- }
-
// Capture button
this.view.addAction("notebook-pen", t("Capture"), () => {
- const modal = new QuickCaptureModal(
- this.app,
- this.plugin,
- {},
- true,
- );
- modal.open();
- });
-
- // Filter button
- this.view.addAction("filter", t("Filter"), (e: MouseEvent) => {
- if (Platform.isDesktop) {
- const popover = new ViewTaskFilterPopover(
- this.app,
- undefined,
- this.plugin,
- );
-
- // Set onClose callback for consistency (realtime event listeners handle the actual updates)
- popover.onClose = (filterState) => {
- // Realtime event listeners already handle filter changes
- // This callback is kept for potential future extensions
- };
-
- // Load current filter state after popover is shown
- setTimeout(() => {
- const liveFilterState = this.getLiveFilterState?.();
- if (liveFilterState && popover.taskFilterComponent) {
- popover.taskFilterComponent.loadFilterState(
- liveFilterState,
- );
- }
- }, 100);
-
- popover.showAtPosition({ x: e.clientX, y: e.clientY });
- } else {
- const modal = new ViewTaskFilterModal(
- this.app,
- this.leaf.id,
- this.plugin,
- );
-
- modal.open();
-
- // Load current filter state after modal is opened
- setTimeout(() => {
- const liveFilterState = this.getLiveFilterState?.();
- if (liveFilterState && modal.taskFilterComponent) {
- modal.taskFilterComponent.loadFilterState(
- liveFilterState,
- );
- }
- }, 100);
- }
+ this.onSidebarNavigate?.("new-task");
});
// Update action buttons visibility
@@ -636,14 +417,5 @@ export class FluentLayoutManager extends Component {
/**
* Clean up mobile event listeners
*/
- onunload(): void {
- if (Platform.isPhone && (this as any).mobileDetailsOverlayHandler) {
- document.removeEventListener(
- "click",
- (this as any).mobileDetailsOverlayHandler,
- );
- delete (this as any).mobileDetailsOverlayHandler;
- }
- super.onunload();
- }
+ onunload(): void { this.closeTaskEditor(); }
}
diff --git a/src/components/features/gantt/drag-pan.ts b/src/components/features/gantt/drag-pan.ts
new file mode 100644
index 000000000..e03c345e5
--- /dev/null
+++ b/src/components/features/gantt/drag-pan.ts
@@ -0,0 +1,18 @@
+import type { Component } from "obsidian";
+
+/** Drag empty chart space to pan; project bars keep their date-edit gesture. */
+export function registerGanttPan(owner: Component, container: HTMLElement): void {
+ let cancel: (() => void) | undefined;
+ owner.registerDomEvent(container, "pointerdown", event => {
+ if (event.button !== 0 || (event.target as Element).closest(".gantt-task-item,button,input")) return;
+ cancel?.(); event.preventDefault();
+ const x = event.clientX, y = event.clientY, left = container.scrollLeft, top = container.scrollTop;
+ const doc = container.ownerDocument;
+ container.addClass("is-panning");
+ const move = (next: PointerEvent) => { container.scrollLeft = left - (next.clientX - x); container.scrollTop = top - (next.clientY - y); };
+ const end = () => { doc.removeEventListener("pointermove", move); doc.removeEventListener("pointerup", end); doc.removeEventListener("pointercancel", end); doc.defaultView?.removeEventListener("blur", end); container.removeClass("is-panning"); cancel = undefined; };
+ cancel = end;
+ doc.addEventListener("pointermove", move); doc.addEventListener("pointerup", end); doc.addEventListener("pointercancel", end); doc.defaultView?.addEventListener("blur", end);
+ });
+ owner.register(() => cancel?.());
+}
diff --git a/src/components/features/gantt/gantt.ts b/src/components/features/gantt/gantt.ts
index 3a1114194..440a4c7f8 100644
--- a/src/components/features/gantt/gantt.ts
+++ b/src/components/features/gantt/gantt.ts
@@ -4,6 +4,9 @@ import {
debounce,
MarkdownRenderer as ObsidianMarkdownRenderer,
TFile,
+ Menu,
+ ButtonComponent,
+ Notice,
} from "obsidian";
import { type Task } from "@/types/task";
import "@/styles/gantt/gantt.css";
@@ -23,6 +26,11 @@ import { ScrollToDateButton } from '@/components/features/task/filter/in-view/cu
import { PRIORITY_MAP } from "@/common/default-symbol";
import { GanttSpecificConfig } from "@/common/setting-definition";
+import { buildProjectPlan } from "@/managers/project-plan";
+import { ProjectFileManager, ProjectEditModal } from "@/managers/project-file-manager";
+import { t } from "@/translations/helper";
+import { projectDateChange, ProjectDateEdge } from "@/managers/project-dates";
+import { registerGanttPan } from "./drag-pan";
// Define the PRIORITY_MAP here as well, or import it if moved to a shared location
// This is needed to convert filter value (icon/text) back to number for comparison
@@ -105,6 +113,8 @@ export class GanttComponent extends Component {
private app: App;
private timescale: Timescale = "Day";
+ private projectScale: "Week" | "Month" | "Year" = "Month";
+ private periodAnchor = new Date();
private dayWidth: number = DAY_WIDTH_DEFAULT;
private startDate: Date | null = null;
private endDate: Date | null = null;
@@ -215,27 +225,6 @@ export class GanttComponent extends Component {
this.createBaseSVG(); // Creates SVG and groups
// Instantiate Child Components
- this.filterComponent = this.addChild(
- new FilterComponent(
- {
- container: this.filterContainerEl,
- options: buildFilterOptionsFromTasks(this.tasks), // Initialize with empty array to satisfy type, will be updated dynamically
- onChange: (activeFilters: ActiveFilter[]) => {
- this.applyFiltersAndRender(activeFilters);
- },
- components: [
- new ScrollToDateButton(
- this.filterContainerEl,
- (date: Date) => this.scrollToDate(date)
- ),
- ],
- },
- this.plugin
-
-
-
- )
- );
if (this.headerContainerEl) {
this.timelineHeaderComponent = this.addChild(
@@ -263,6 +252,10 @@ export class GanttComponent extends Component {
this.registerDomEvent(this.containerEl, "wheel", this.handleWheel, {
passive: false,
});
+ registerGanttPan(this, this.scrollContainerEl);
+ const controls = this.filterContainerEl.createDiv({ cls: "gantt-project-controls" });
+ new ButtonComponent(controls).setButtonText(t("Today")).onClick(() => { this.periodAnchor = new Date(); this.setProjectScale(this.projectScale); });
+ for (const scale of ["Week", "Month", "Year"] as const) new ButtonComponent(controls).setButtonText(t(scale)).onClick(() => this.setProjectScale(scale));
this.applyEffectiveConfig();
// Initial render is triggered by updateTasks or refresh
@@ -320,6 +313,7 @@ export class GanttComponent extends Component {
setTasks(newTasks: Task[]) {
+ if (this.viewId === "gantt" && newTasks.length > 0 && !newTasks.some(task => task.metadata.projectPlan)) newTasks = buildProjectPlan(this.app, newTasks);
this.preparedTasks = []; // Clear prepared tasks
this.tasks = this.sortTasks(newTasks);
@@ -374,10 +368,27 @@ export class GanttComponent extends Component {
// --- Date Range and Timescale Calculations ---
+ public onShown(): void { if (this.viewId === "gantt") this.setProjectScale(this.projectScale); }
+
+ public setProjectScale(scale: "Week" | "Month" | "Year"): void {
+ this.projectScale = scale; this.startDate = null; this.endDate = null;
+ this.calculateDateRange(true); this.prepareTasksForRender(); this.renderInternal();
+ this.scrollToDate(this.periodAnchor);
+ }
+
private calculateDateRange(forceRecalculate: boolean = false): {
startDate: Date;
endDate: Date;
} {
+ if (this.viewId === "gantt") {
+ const anchor = new Date(this.periodAnchor); anchor.setHours(0,0,0,0);
+ if (this.projectScale === "Week") { anchor.setDate(anchor.getDate()-(anchor.getDay()+6)%7-7); this.startDate = anchor; this.endDate = this.dateHelper.addDays(anchor,21); }
+ else if (this.projectScale === "Month") { this.startDate = new Date(anchor.getFullYear(),anchor.getMonth()-1,1); this.endDate = new Date(anchor.getFullYear(),anchor.getMonth()+2,1); }
+ else { this.startDate = new Date(anchor.getFullYear()-1,0,1); this.endDate = new Date(anchor.getFullYear()+2,0,1); }
+ this.dayWidth = Math.max(.2, (this.scrollContainerEl?.clientWidth || 1000)/Math.max(1,this.dateHelper.daysBetween(this.startDate,this.endDate)));
+ this.visibleStartDate = new Date(this.startDate); this.visibleEndDate = new Date(this.endDate);
+ return { startDate: this.startDate, endDate: this.endDate };
+ }
if (!forceRecalculate && this.startDate && this.endDate) {
return { startDate: this.startDate, endDate: this.endDate };
}
@@ -492,6 +503,7 @@ export class GanttComponent extends Component {
}
private calculateTimescaleParams() {
+ if (this.viewId === "gantt") { this.timescale = this.projectScale; return; }
if (!this.startDate || !this.endDate) return;
// Determine appropriate timescale based on dayWidth
@@ -546,7 +558,7 @@ export class GanttComponent extends Component {
// Optional: end bar at completion date if no due date
}
- if (
+ if (!task.metadata.projectPlan && (
(taskDue && !taskStart) ||
(taskStart &&
taskDue &&
@@ -554,7 +566,7 @@ export class GanttComponent extends Component {
new Date(taskStart),
new Date(taskDue)
) === 0)
- ) {
+ )) {
const milestoneDate = taskDue
? new Date(taskDue)
: taskStart
@@ -822,6 +834,8 @@ export class GanttComponent extends Component {
// 3. Update Tasks - Pass only visible tasks
this.taskRendererComponent.updateParams({
+ dayWidth: this.dayWidth,
+ onDateChange: (task, days, edge) => void this.changeProjectDates(task, days, edge),
app: this.app,
taskGroupEl: this.taskGroupEl!, // Assert non-null as checked above
preparedTasks: visibleTasks, // Pass filtered list
@@ -1057,10 +1071,37 @@ export class GanttComponent extends Component {
};
private handleTaskClick(task: Task) {
+ if (task.metadata.projectPlan) { void this.app.workspace.openLinkText(task.filePath, "", false); return; }
this.params.onTaskSelected?.(task);
}
+ private zoomBy(factor: number): void {
+ const center = this.startDate ? this.dateHelper.xToDate(this.scrollContainerEl.scrollLeft + this.scrollContainerEl.clientWidth / 2, this.startDate, this.dayWidth) : new Date();
+ this.dayWidth = Math.max(MIN_DAY_WIDTH, Math.min(MAX_DAY_WIDTH, this.dayWidth * factor));
+ this.prepareTasksForRender(); this.renderInternal(); this.scrollToDate(center || new Date());
+ }
+
+ private async changeProjectDates(task: Task, days: number, edge: ProjectDateEdge): Promise {
+ if (!task.metadata.projectPlan || !task.metadata.startDate || !task.metadata.dueDate) return;
+ try {
+ const dates = projectDateChange(task.metadata.startDate, task.metadata.dueDate, days, edge);
+ if (!await new ProjectFileManager(this.app).update(task.metadata.project || task.content, dates)) throw new Error(t("Project not found"));
+ const local = (value: string) => { const [year, month, day] = value.split("-").map(Number); return new Date(year, month - 1, day).getTime(); };
+ for (const item of this.tasks) if (item.id === task.id) item.metadata = { ...item.metadata, startDate: local(dates.startDate), dueDate: local(dates.dueDate) };
+ this.calculateDateRange(true); this.prepareTasksForRender(); this.renderInternal();
+ } catch (error) { new Notice(String(error)); this.renderInternal(); }
+ }
+
private handleTaskContextMenu(event: MouseEvent, task: Task) {
+ if (task.metadata.projectPlan) {
+ const manager = new ProjectFileManager(this.app);
+ const project = manager.find(task.metadata.project || task.content);
+ if (!project) return;
+ const menu = new Menu();
+ menu.addItem(item => item.setTitle(t("Edit project details")).setIcon("pencil").onClick(() => new ProjectEditModal(this.app, manager, project, () => void this.plugin.triggerViewUpdate()).open()));
+ menu.addItem(item => item.setTitle(t("Archive project")).setIcon("archive").onClick(async () => { await manager.setArchived(project.name, true); await this.plugin.triggerViewUpdate(); }));
+ menu.showAtMouseEvent(event); return;
+ }
this.params.onTaskContextMenu?.(event, task);
}
diff --git a/src/components/features/gantt/task-renderer.ts b/src/components/features/gantt/task-renderer.ts
index 1d75ddcaa..bc3125048 100644
--- a/src/components/features/gantt/task-renderer.ts
+++ b/src/components/features/gantt/task-renderer.ts
@@ -8,6 +8,7 @@ import { GanttTaskItem, PlacedGanttTaskItem, Timescale } from './gantt'; // 添
import { Task } from "@/types/task";
import { MarkdownRendererComponent } from "@/components/ui/renderers/MarkdownRenderer";
import { sanitizePriorityForClass } from "@/utils/task/priority-utils";
+import type { ProjectDateEdge } from "@/managers/project-dates";
// Constants from GanttComponent (consider moving to a shared config/constants file)
const ROW_HEIGHT = 24;
@@ -17,6 +18,8 @@ const TASK_LABEL_PADDING = 5;
// Interface for parameters needed by the task renderer
interface TaskRendererParams {
+ dayWidth?: number;
+ onDateChange?: (task: Task, days: number, edge: ProjectDateEdge) => void;
app: App;
taskGroupEl: SVGGElement; // The element to draw tasks into
preparedTasks: PlacedGanttTaskItem[]; // 使用PlacedGanttTaskItem替代GanttTaskItem
@@ -37,6 +40,8 @@ export class TaskRendererComponent extends Component {
private taskGroupEl: SVGGElement;
private params: TaskRendererParams | null = null;
private eventListeners: Array<{ element: Element; type: string; handler: EventListener }> = [];
+ private cancelDrag?: () => void;
+ private ignoreClickUntil = 0;
constructor(app: App, taskGroupEl: SVGGElement) {
super();
@@ -62,6 +67,7 @@ export class TaskRendererComponent extends Component {
}
private cleanupEventListeners() {
+ this.cancelDrag?.();
for (const { element, type, handler } of this.eventListeners) {
element.removeEventListener(type, handler);
}
@@ -133,7 +139,7 @@ export class TaskRendererComponent extends Component {
});
group.setAttribute("data-task-id", task.id);
// Add listener for clicking task (using our tracked addEventListener)
- const clickHandler = () => handleTaskClick(task);
+ const clickHandler = () => { if (Date.now() > this.ignoreClickUntil) handleTaskClick(task); };
const contextMenuHandler = (event: Event) => handleTaskContextMenu(event as MouseEvent, task);
this.addEventListener(group, "click", clickHandler);
this.addEventListener(group, "contextmenu", contextMenuHandler);
@@ -158,6 +164,7 @@ export class TaskRendererComponent extends Component {
class: "gantt-task-milestone", // Base class
},
});
+ if (task.metadata.projectPlan && /^#[0-9a-f]{6}$/i.test(String(task.metadata.projectColor))) taskElement.style.setProperty("fill", String(task.metadata.projectColor));
// Add status and priority classes safely
if (task.status && task.status.trim()) {
taskElement.classList.add(`status-${task.status.trim()}`);
@@ -239,6 +246,7 @@ export class TaskRendererComponent extends Component {
class: "gantt-task-bar", // Base class
},
});
+ if (task.metadata.projectPlan && /^#[0-9a-f]{6}$/i.test(String(task.metadata.projectColor))) taskElement.style.setProperty("fill", String(task.metadata.projectColor));
// Add status and priority classes safely
if (task.status && task.status.trim()) {
taskElement.classList.add(`status-${task.status.trim()}`);
@@ -335,6 +343,52 @@ export class TaskRendererComponent extends Component {
}
// Apply status class to the group for potential styling overrides
+ if (task.metadata.projectPlan && this.params.onDateChange) {
+ for (const edge of ["start", "end"] as const) group.createSvg("rect", { attr: {
+ x: preparedTask.startX + (edge === "end" ? (preparedTask.width || 0) - 5 : -1),
+ y: barY - 3, width: 6, height: barHeight + 6, class: "gantt-resize-handle", "data-edge": edge,
+ } });
+ this.addEventListener(group, "pointerdown", ((event: PointerEvent) => {
+ if (event.button !== 0) return;
+ event.preventDefault(); event.stopPropagation();
+ const edge = ((event.target as Element).getAttribute("data-edge") || "move") as ProjectDateEdge;
+ const start = event.clientX, dayWidth = this.params?.dayWidth || 50;
+ const doc = group.ownerDocument;
+ this.cancelDrag?.();
+ const hint = doc.createElement("div"); hint.className = "gantt-drag-date-hint"; hint.setAttribute("role", "status"); doc.body.appendChild(hint);
+ const startDate = new Date(task.metadata.startDate!), endDate = new Date(task.metadata.dueDate!);
+ const format = (date: Date) => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
+ let days = 0;
+ const updateHint = (x: number, y: number) => {
+ const first = new Date(startDate), last = new Date(endDate);
+ if (edge !== "end") first.setDate(first.getDate() + days);
+ if (edge !== "start") last.setDate(last.getDate() + days);
+ hint.textContent = `${format(first)} → ${format(last)}`;
+ hint.style.left = `${Math.min(x + 12, Math.max(8, (doc.defaultView?.innerWidth || 1000) - 270))}px`; hint.style.top = `${Math.max(8, y - 38)}px`;
+ };
+ updateHint(event.clientX, event.clientY);
+ const move = (next: PointerEvent) => {
+ days = Math.round((next.clientX - start) / dayWidth);
+ const duration = Math.max(0, Math.round((endDate.getTime() - startDate.getTime()) / 86400000));
+ if (edge === "start") days = Math.min(days, duration);
+ if (edge === "end") days = Math.max(days, -duration);
+ updateHint(next.clientX, next.clientY);
+ if (edge === "move") group.setAttribute("transform", `translate(${days * dayWidth},0)`);
+ else {
+ const rect = group.querySelector(".gantt-task-bar");
+ const width = preparedTask.width || dayWidth;
+ const delta = edge === "start" ? Math.min(days * dayWidth, width - dayWidth) : Math.max(days * dayWidth, dayWidth - width);
+ rect?.setAttribute("x", String(preparedTask.startX + (edge === "start" ? delta : 0)));
+ rect?.setAttribute("width", String(width + (edge === "start" ? -delta : delta)));
+ }
+ };
+ const cleanup = () => { hint.remove(); doc.removeEventListener("pointermove", move); doc.removeEventListener("pointerup", up); doc.removeEventListener("pointercancel", cancel); this.cancelDrag = undefined; };
+ const cancel = () => { cleanup(); group.removeAttribute("transform"); this.render(); };
+ const up = () => { cleanup(); group.removeAttribute("transform"); if (days) { this.ignoreClickUntil = Date.now() + 400; this.params?.onDateChange?.(task, days, edge); } };
+ this.cancelDrag = cleanup;
+ doc.addEventListener("pointermove", move); doc.addEventListener("pointerup", up); doc.addEventListener("pointercancel", cancel);
+ }) as EventListener);
+ }
if (taskElement) {
// group.classList.add(`status-${task.status}`); // Removed this redundant/potentially problematic class add
// Status is already applied to the taskElement (bar or milestone) directly
diff --git a/src/components/features/habit/habit.ts b/src/components/features/habit/habit.ts
index 9485e5ef3..e83960c0d 100644
--- a/src/components/features/habit/habit.ts
+++ b/src/components/features/habit/habit.ts
@@ -1,3 +1,10 @@
+import { importLegacyHabits, planLegacyHabits } from "@/integrations/habits/legacy-import";
+import { ConfirmModal } from "@/integrations/habits/ui/confirm-modal";
+import { HabitsBlock } from "@/integrations/habits/ui/habits-block";
+import { NativeHabitCards } from "@/integrations/habits/ui/native-cards";
+import { HabitModal } from "@/integrations/habits/ui/habit-modal";
+import { t as ht } from "@/integrations/habits/i18n";
+import { t as settingsText } from "@/translations/helper";
import {
Component,
App,
@@ -6,6 +13,7 @@ import {
Notice,
ButtonComponent,
ExtraButtonComponent,
+ SearchComponent,
} from "obsidian";
import {
HabitProps,
@@ -26,6 +34,51 @@ import "@/styles/habit.css";
import { HabitEditDialog } from "@/components/features/habit/components/HabitEditDialog";
export class Habit extends Component {
+ containerEl: HTMLElement;
+ private block?: HabitsBlock | NativeHabitCards;
+ private query = "";
+ setSearchQuery(query: string): void { this.query = query; this.block?.setSearchQuery(query); }
+ private disposed = false;
+ constructor(readonly plugin: TaskProgressBarPlugin, parentEl: HTMLElement, private externalSearch = false) {
+ super();
+ this.containerEl = parentEl.createDiv({cls: "tg-habit-component-container tg-habits-surface"});
+ }
+ async onload(): Promise {
+ try {
+ const integration = await this.plugin.ensureHabitsIntegration();
+ if (this.disposed) return;
+ const toolbar = this.containerEl.createDiv({cls: "tg-habits-toolbar"});
+ toolbar.createEl("h2", {text: ht("Habits")});
+ if (!this.externalSearch) new SearchComponent(toolbar).setPlaceholder(settingsText("Search habits")).setValue(this.query).onChange(value => this.setSearchQuery(value));
+ const root = this.containerEl.createDiv();
+ this.block = this.addChild(new HabitsBlock(this.plugin.app, integration.store, () => integration.settings, integration.events, "", root));
+ this.block.setSearchQuery(this.query);
+ if (this.plugin.settings.habit.habits?.length) {
+ const legacy = this.containerEl.createEl("details", {cls: "tg-habits-legacy"});
+ legacy.createEl("summary", {text: ht("Existing Task Genius habits")});
+ legacy.createEl("p", {text: ht("Original daily-note records remain available below. Import creates habit notes with a complete source snapshot and never changes the original records.")});
+ new ButtonComponent(legacy).setButtonText(ht("Import existing records")).onClick(async () => {
+ const plans = planLegacyHabits(this.plugin.habitManager?.habits ?? []);
+ if (!plans.length) { new Notice(ht("No records available to import.")); return; }
+ const confirmed = await ConfirmModal.ask(this.plugin.app, ht("Import existing records"), ht("Create {n} habit notes in {folder}? Existing notes and daily records will be preserved.", {n: plans.length, folder: integration.settings.habitsFolder}));
+ if (!confirmed) return;
+ try {
+ const result = await importLegacyHabits(this.plugin.app, integration.settings, plans);
+ new Notice(ht("Imported {created} habits; skipped {skipped} existing imports.", result));
+ integration.events.trigger("settings-changed");
+ } catch (error) { console.error(error); new Notice(ht("Habit import failed. Existing files have been preserved.")); }
+ });
+ this.addChild(new LegacyHabit(this.plugin, legacy));
+ }
+ } catch (error) {
+ if (!this.disposed) this.containerEl.createEl("p", {text: ht("Unable to load habits. Check the console for details.")});
+ console.error("Task Genius habits", error);
+ }
+ }
+ onunload(): void { this.disposed = true; this.containerEl.empty(); }
+}
+
+class LegacyHabit extends Component {
plugin: TaskProgressBarPlugin;
containerEl: HTMLElement; // The element where the view will be rendered
@@ -214,12 +267,12 @@ export class EventDetailModal extends Modal {
const {contentEl} = this;
contentEl.addClass("habit-event-modal");
contentEl.createEl("h2", {
- text: `Record Details for ${this.eventName}`,
+ text: settingsText("Record Details for {{value0}}", { interpolation: { value0: String(this.eventName) } }),
});
- new Setting(contentEl).setName("Details").addText((text) =>
+ new Setting(contentEl).setName(settingsText("Details")).addText((text) =>
text
- .setPlaceholder(`Enter details for ${this.eventName}...`)
+ .setPlaceholder(settingsText("Enter details for {{value0}}...", { interpolation: { value0: String(this.eventName) } }))
.onChange((value) => {
this.details = value;
})
@@ -228,7 +281,7 @@ export class EventDetailModal extends Modal {
new Setting(contentEl)
.addButton((btn) =>
btn
- .setButtonText("Cancel")
+ .setButtonText(settingsText("Cancel"))
.setWarning()
.onClick(() => {
this.close();
@@ -236,7 +289,7 @@ export class EventDetailModal extends Modal {
)
.addButton((btn) =>
btn
- .setButtonText("Submit")
+ .setButtonText(settingsText("Submit"))
.setCta()
.onClick(() => {
this.close();
diff --git a/src/components/features/habit/modals/HabitChartModal.ts b/src/components/features/habit/modals/HabitChartModal.ts
index fa968ae95..158fcb463 100644
--- a/src/components/features/habit/modals/HabitChartModal.ts
+++ b/src/components/features/habit/modals/HabitChartModal.ts
@@ -1,3 +1,4 @@
+import { t as settingsText } from "@/translations/helper";
import { App, Modal, Setting } from "obsidian";
import { DailyHabitProps } from "@/types/habit-card";
import {
@@ -35,7 +36,7 @@ export class HabitChartModal extends Modal {
contentEl.empty();
this.modalEl.toggleClass("habit-chart-modal", true);
- this.setTitle(`${this.habit.name} · Heatmap`);
+ this.setTitle(settingsText("{{value0}} · Heatmap", { interpolation: { value0: String(this.habit.name) } }));
// Controls (use Obsidian Setting + dropdowns)
const controls = contentEl.createDiv({ cls: "habit-chart-controls" });
diff --git a/src/components/features/kanban/kanban.ts b/src/components/features/kanban/kanban.ts
index e7b5beb70..57c11eede 100644
--- a/src/components/features/kanban/kanban.ts
+++ b/src/components/features/kanban/kanban.ts
@@ -1,5 +1,6 @@
import {
App,
+ Notice,
Component,
Menu,
Platform,
@@ -285,6 +286,8 @@ export class KanbanComponent extends Component {
}
private renderCycleSelector(container: HTMLElement): void {
+ const choices = (this.plugin.settings.statusCycles || []).filter(cycle => cycle.enabled && !/^default\s*cycle$|^默认周期$/i.test(cycle.name.trim()));
+ if (!choices.length) return;
// Only show cycle selector in status grouping mode
const kanbanConfig = this.getEffectiveKanbanConfig();
if (kanbanConfig?.groupBy !== "status") {
@@ -325,9 +328,7 @@ export class KanbanComponent extends Component {
menu.addSeparator();
// Get enabled cycles, sorted by priority
- const enabledCycles = (this.plugin.settings.statusCycles || [])
- .filter((c) => c.enabled)
- .sort((a, b) => a.priority - b.priority);
+ const enabledCycles = choices.slice().sort((a, b) => a.priority - b.priority);
if (enabledCycles.length === 0) {
menu.addItem((item) => {
@@ -849,6 +850,7 @@ export class KanbanComponent extends Component {
},
);
this.addChild(column);
+ column.getElement().dataset.columnValue = JSON.stringify(config.value);
this.columns.push(column);
});
}
@@ -1079,10 +1081,7 @@ export class KanbanComponent extends Component {
this.sortableInstances = [];
// Detect if we're on a mobile device
- const isMobile =
- !Platform.isDesktop ||
- "ontouchstart" in window ||
- navigator.maxTouchPoints > 0;
+ const isMobile = Platform.isMobile;
this.columns.forEach((col) => {
const columnContent = col.getContentElement();
@@ -1097,6 +1096,11 @@ export class KanbanComponent extends Component {
const instance = Sortable.create(columnContent, {
group: groupConfig,
+ draggable: ".tg-kanban-card",
+ filter: "button, input, select, textarea, a",
+ preventOnFilter: false,
+ emptyInsertThreshold: 20,
+ delayOnTouchOnly: true,
animation: 150,
ghostClass: "tg-kanban-card-ghost",
dragClass: "tg-kanban-card-dragging",
@@ -1177,12 +1181,12 @@ export class KanbanComponent extends Component {
kanbanConfig?.customColumns;
// Handle property-based grouping
- const targetValue = this.getColumnValueFromTitle(
+ const targetValue = (targetColumnEl as HTMLElement)?.dataset.columnValue !== undefined ? JSON.parse((targetColumnEl as HTMLElement).dataset.columnValue!) : this.getColumnValueFromTitle(
targetColumnTitle,
groupBy,
effectiveCustomColumns,
);
- const sourceValue = this.getColumnValueFromTitle(
+ const sourceValue = (sourceColumnEl as HTMLElement)?.dataset.columnValue !== undefined ? JSON.parse((sourceColumnEl as HTMLElement).dataset.columnValue!) : this.getColumnValueFromTitle(
sourceColumnTitle,
groupBy,
effectiveCustomColumns,
@@ -1337,31 +1341,19 @@ export class KanbanComponent extends Component {
taskId: string,
newStatusMark: string,
): Promise {
- console.log(
- `[Kanban] handleStatusUpdate called: taskId=${taskId}, mark=${newStatusMark}`,
- );
- console.log(
- "[Kanban] onTaskStatusUpdate callback exists:",
- !!this.params.onTaskStatusUpdate,
- );
-
- if (this.params.onTaskStatusUpdate) {
- try {
- console.log("[Kanban] Calling onTaskStatusUpdate callback...");
- await this.params.onTaskStatusUpdate(taskId, newStatusMark);
- console.log(
- "[Kanban] onTaskStatusUpdate callback completed successfully",
- );
- } catch (error) {
- console.error("[Kanban] Failed to update task status:", error);
- console.error("[Kanban] Error details:", error.stack);
- }
- } else {
- console.error(
- "[Kanban] CRITICAL: onTaskStatusUpdate callback is not defined!",
- );
- console.error("[Kanban] this.params:", this.params);
- }
+ const task = this.allTasks.find(task => task.id === taskId);
+ if (!task) return;
+ try {
+ if (!this.plugin.writeAPI) throw new Error("Task writer is unavailable");
+ const completed = (this.plugin.settings.taskStatuses?.completed || "x").split("|").includes(newStatusMark);
+ const updatedTask = { ...task, status: newStatusMark, completed, metadata: { ...task.metadata, completedDate: completed ? task.metadata.completedDate || Date.now() : undefined } };
+ const result = await this.plugin.writeAPI.updateTask({ taskId, updates: updatedTask });
+ if (!result.success) throw new Error(result.error || "Task update failed");
+ this.allTasks = this.allTasks.map(task => task.id === taskId ? result.task || updatedTask : task);
+ } catch (error) {
+ console.error("Failed to update task status:", error);
+ new Notice(t("Failed to update task"));
+ } finally { this.applyFiltersAndRender(); }
}
private async handlePropertyUpdate(
@@ -1385,10 +1377,7 @@ export class KanbanComponent extends Component {
return;
}
- taskToUpdate.metadata = taskToUpdate.metadata || {};
-
- // Create updated task object
- const updatedTask = { ...taskToUpdate };
+ const updatedTask = { ...taskToUpdate, metadata: { ...taskToUpdate.metadata } };
// Update the specific property based on groupBy type
switch (groupBy) {
@@ -1506,21 +1495,19 @@ export class KanbanComponent extends Component {
taskId,
updates: updatedTask,
});
- if (!result.success) {
- console.error(
- `Failed to update task ${taskId} property ${groupBy}:`,
- result.error,
- );
- }
+ if (!result.success) throw new Error(result.error || "Task update failed");
+ this.allTasks = this.allTasks.map(task => task.id === taskId ? updatedTask : task);
+ this.tasks = this.tasks.map(task => task.id === taskId ? updatedTask : task);
} else {
- console.error("WriteAPI not available");
+ throw new Error("Task writer is unavailable");
}
} catch (error) {
console.error(
`Failed to update task ${taskId} property ${groupBy}:`,
error,
);
- }
+ new Notice(t("Failed to update task"));
+ } finally { this.applyFiltersAndRender(); }
}
private getTasksForProperty(groupBy: string, value: any): Task[] {
diff --git a/src/components/features/planner/TaskPlanner.ts b/src/components/features/planner/TaskPlanner.ts
new file mode 100644
index 000000000..de16fe07f
--- /dev/null
+++ b/src/components/features/planner/TaskPlanner.ts
@@ -0,0 +1,64 @@
+import { Component, Notice } from "obsidian";
+import type TaskProgressBarPlugin from "@/index";
+import type { Task } from "@/types/task";
+import { TaskDetailsModal } from "../task/edit/TaskDetailsModal";
+import { formatOptionalDateTime, parseOptionalDateTime } from "@/utils/date/optional-date-time";
+import { t } from "@/translations/helper";
+import "@/styles/task-planner.css";
+
+/** Drag tasks from the unscheduled list or between calendar days. */
+export class TaskPlanner extends Component {
+ readonly containerEl: HTMLElement;
+ private tasks: Task[] = [];
+ private query = "";
+ private month = new Date(new Date().getFullYear(), new Date().getMonth(), 1);
+ private events?: Component;
+ private pending = new Set();
+ constructor(private plugin: TaskProgressBarPlugin, root: HTMLElement) { super(); this.containerEl = root.createDiv({ cls: "tg-task-planner" }); }
+ onload(): void { this.render(); }
+ setTasks(tasks: Task[]): void { this.tasks = tasks.filter(task => !task.completed && !task.metadata?.projectPlan && task.metadata?.source !== "file-source" && !(task as any).isFileTask && task.filePath.toLowerCase().endsWith(".md")); this.render(); }
+ setSearchQuery(value: string): void { this.query = value.toLocaleLowerCase().trim(); this.render(); }
+ private render(): void {
+ if (this.events) this.removeChild(this.events); this.events = this.addChild(new Component()); this.containerEl.empty();
+ const nav = this.containerEl.createDiv({ cls: "tg-planner-nav" });
+ for (const [label, action] of [["Previous month",()=>{this.month=new Date(this.month.getFullYear(),this.month.getMonth()-1,1);this.render();}], ["Today",()=>{this.month=new Date(new Date().getFullYear(),new Date().getMonth(),1);this.render();}], ["Next month",()=>{this.month=new Date(this.month.getFullYear(),this.month.getMonth()+1,1);this.render();}]] as const) {
+ const button = nav.createEl("button", { text: t(label) }); this.events.registerDomEvent(button,"click",action);
+ }
+ nav.createEl("strong",{text:this.month.toLocaleDateString(undefined,{year:"numeric",month:"long"})});
+ const layout = this.containerEl.createDiv({ cls:"tg-planner-layout" });
+ const unscheduled = layout.createDiv({cls:"tg-planner-unscheduled"}); unscheduled.createEl("h3",{text:t("Unscheduled tasks")}); this.dropTarget(unscheduled, null);
+ const tasks = this.tasks.filter(task=>!this.query || `${task.content} ${task.filePath}`.toLocaleLowerCase().includes(this.query));
+ for (const task of tasks.filter(task=>!task.metadata.scheduledDate)) this.card(unscheduled,task);
+ const grid=layout.createDiv({cls:"tg-planner-calendar"});
+ for(let weekday=0;weekday<7;weekday++) grid.createDiv({cls:"tg-planner-weekday",text:new Date(2024,0,1+weekday).toLocaleDateString(undefined,{weekday:"short"})});
+ const first=new Date(this.month);first.setDate(first.getDate()-(first.getDay()+6)%7);
+ for(let i=0;i<42;i++){
+ const date=new Date(first);date.setDate(first.getDate()+i);const key=formatOptionalDateTime(date,"date");
+ const day=grid.createDiv({cls:"tg-planner-day",attr:{"data-date":key}});day.toggleClass("is-other-month",date.getMonth()!==this.month.getMonth());day.toggleClass("is-today",key===formatOptionalDateTime(new Date(),"date"));day.createDiv({text:String(date.getDate()),cls:"tg-planner-day-label"});this.dropTarget(day,key);
+ for(const task of tasks.filter(task=>task.metadata.scheduledDate && formatOptionalDateTime(task.metadata.scheduledDate,"date")===key))this.card(day,task);
+ }
+ }
+ private card(root: HTMLElement,task:Task):void{
+ const card=root.createDiv({cls:"tg-planner-card",text:task.content||t("Task"),attr:{draggable: String(!this.pending.has(task.id)),"data-task-id":task.id}});
+ this.events!.registerDomEvent(card,"dragstart",event=>{event.dataTransfer?.setData("application/x-task-genius",task.id);event.dataTransfer?.setData("text/plain",task.id);if(event.dataTransfer)event.dataTransfer.effectAllowed="move";});
+ this.events!.registerDomEvent(card,"click",()=>new TaskDetailsModal(this.plugin.app,this.plugin,task).open());
+ }
+ private dropTarget(root:HTMLElement,date:string|null):void{
+ this.events!.registerDomEvent(root,"dragover",event=>{if(event.dataTransfer?.types.includes("application/x-task-genius")){event.preventDefault();event.dataTransfer.dropEffect="move";}});
+ this.events!.registerDomEvent(root,"drop",event=>{event.preventDefault();event.stopPropagation();const id=event.dataTransfer?.getData("application/x-task-genius");if(id)void this.schedule(id,date);});
+ }
+ async schedule(id:string,day:string|null):Promise{
+ const task=this.tasks.find(task=>task.id===id);if(!task||this.pending.has(id))return;this.pending.add(id);
+ try{
+ const parsed=day ? parseOptionalDateTime(day) : null;if(day&&!parsed)throw new Error(t("Enter a valid date, optionally followed by HH:mm."));
+ let scheduledDate=parsed?.timestamp;
+ if(scheduledDate!=null && task.metadata.scheduledDate && task.metadata.datePrecision?.scheduledDate!=="date"){
+ const old=new Date(task.metadata.scheduledDate),next=new Date(scheduledDate);next.setHours(old.getHours(),old.getMinutes(),0,0);scheduledDate=next.getTime();
+ }
+ if(!this.plugin.writeAPI)throw new Error(t("Task writer is unavailable"));
+ const updated={...task,metadata:{...task.metadata,scheduledDate,datePrecision:{...task.metadata.datePrecision,scheduledDate: day ? task.metadata.scheduledDate ? task.metadata.datePrecision?.scheduledDate || (new Date(task.metadata.scheduledDate).getHours() || new Date(task.metadata.scheduledDate).getMinutes() ? "datetime" as const : "date" as const) : "date" as const : undefined}}};
+ const result=await this.plugin.writeAPI.updateTask({taskId:id,updates:{metadata:updated.metadata}});if(!result.success)throw new Error(result.error||t("Failed to update task"));
+ this.tasks=this.tasks.map(task=>task.id===id?result.task||updated:task);
+ }catch(error){new Notice(String(error));}finally{this.pending.delete(id);this.render();}
+ }
+}
diff --git a/src/components/features/quadrant/quadrant-card.ts b/src/components/features/quadrant/quadrant-card.ts
index 91de41fc3..23f5dcfd8 100644
--- a/src/components/features/quadrant/quadrant-card.ts
+++ b/src/components/features/quadrant/quadrant-card.ts
@@ -101,7 +101,7 @@ export class QuadrantCardComponent extends Component {
// Add change event listener for checkbox
this.registerDomEvent(checkbox, "change", () => {
- const newStatus = checkbox.checked ? "x" : " ";
+ const newStatus = (checkbox.checked ? this.plugin.settings.taskStatuses.completed : this.plugin.settings.taskStatuses.notStarted).split("|")[0];
if (this.params.onTaskStatusUpdate) {
this.params.onTaskStatusUpdate(this.task.id, newStatus);
}
@@ -122,7 +122,9 @@ export class QuadrantCardComponent extends Component {
}
private createContent() {
- this.contentEl = this.containerEl.createDiv("tg-quadrant-card-content");
+ const header = this.containerEl.querySelector(".tg-quadrant-card-header")!;
+ this.contentEl = header.createDiv("tg-quadrant-card-content");
+ header.insertBefore(this.contentEl, header.querySelector(".tg-quadrant-card-actions"));
// Task title/content - use markdown renderer
const titleEl = this.contentEl.createDiv("tg-quadrant-card-title");
diff --git a/src/components/features/quadrant/quadrant-column.ts b/src/components/features/quadrant/quadrant-column.ts
index 44b649cb2..767977b61 100644
--- a/src/components/features/quadrant/quadrant-column.ts
+++ b/src/components/features/quadrant/quadrant-column.ts
@@ -28,6 +28,8 @@ export class QuadrantColumnComponent extends Component {
private currentPage: number = 0;
private pageSize: number = 20;
private isLoadingMore: boolean = false;
+ private renderRevision = 0;
+ private disposed = false;
private hasMoreTasks: boolean = true;
private renderedTasks: Task[] = [];
@@ -106,6 +108,7 @@ export class QuadrantColumnComponent extends Component {
}
override onunload() {
+ this.disposed = true; this.renderRevision++;
this.cleanup();
if (this.intersectionObserver) {
this.intersectionObserver.disconnect();
@@ -128,7 +131,7 @@ export class QuadrantColumnComponent extends Component {
private cleanup() {
// Clean up card components
this.cardComponents.forEach((card) => {
- card.onunload();
+ this.removeChild(card);
});
this.cardComponents = [];
}
@@ -321,7 +324,7 @@ export class QuadrantColumnComponent extends Component {
}
private async loadContent() {
- if (this.isContentLoaded) return;
+ if (this.disposed || this.isContentLoaded) return;
this.isContentLoaded = true;
@@ -343,7 +346,7 @@ export class QuadrantColumnComponent extends Component {
}
private async loadMoreTasks() {
- if (this.isLoadingMore) {
+ if (this.disposed || this.isLoadingMore) {
return;
}
@@ -356,6 +359,7 @@ export class QuadrantColumnComponent extends Component {
return;
}
+ const revision = this.renderRevision;
this.isLoadingMore = true;
this.showLoadMoreIndicator();
@@ -375,7 +379,8 @@ export class QuadrantColumnComponent extends Component {
this.renderedTasks.push(...tasksToLoad);
// Render the new batch of tasks
- await this.renderTaskBatch(tasksToLoad);
+ await this.renderTaskBatch(tasksToLoad, revision);
+ if (this.disposed || revision !== this.renderRevision) return;
// Update pagination
this.currentPage++;
@@ -391,7 +396,7 @@ export class QuadrantColumnComponent extends Component {
} catch (error) {
console.error("Error loading more tasks:", error);
} finally {
- this.isLoadingMore = false;
+ if (revision === this.renderRevision) this.isLoadingMore = false;
}
}
@@ -409,61 +414,12 @@ export class QuadrantColumnComponent extends Component {
- public setTasks(tasks: Task[]) {
- console.log(
- `setTasks called for ${this.quadrant.id} with ${tasks.length} tasks`
- );
-
- // Check if tasks have actually changed to avoid unnecessary re-renders
- if (this.areTasksEqual(this.tasks, tasks)) {
- console.log(
- `Tasks unchanged for ${this.quadrant.id}, skipping setTasks`
- );
- return;
- }
-
- this.tasks = tasks;
- this.updateCount();
-
- // Reset pagination state
- this.currentPage = 0;
- this.renderedTasks = [];
- this.hasMoreTasks = tasks.length > this.pageSize;
-
- // Always try to load content immediately if we have tasks
- if (tasks.length > 0) {
- if (this.isContentLoaded) {
- // Re-render immediately if already loaded
- this.renderTasks();
- } else {
- // For small task counts, load immediately without lazy loading
- if (tasks.length <= this.pageSize) {
- console.log(
- `Small task count (${tasks.length}), loading immediately for ${this.quadrant.id}`
- );
- // Force immediate loading for small task counts
- setTimeout(() => {
- this.loadContent();
- }, 50);
- } else {
- // More aggressive loading strategy - load content for all columns
- // since the quadrant view is typically small enough to show all columns
- setTimeout(() => {
- if (!this.isContentLoaded) {
- console.log(
- `Force loading content for ${this.quadrant.id} after setTasks (aggressive)`
- );
- this.loadContent();
- }
- }, 100);
- }
- }
- } else {
- // Handle empty state
- if (this.isContentLoaded) {
- this.showEmptyState();
- }
- }
+ public setTasks(tasks: Task[], force = false) {
+ if (this.disposed || (!force && this.areTasksEqual(this.tasks, tasks))) return;
+ this.tasks = tasks.map(task => ({ ...task, metadata: { ...task.metadata, tags: [...(task.metadata.tags || [])], children: [...(task.metadata.children || [])] } }));
+ this.updateCount(); this.isContentLoaded = true;
+ this.loadingEl?.remove(); this.loadingEl = null;
+ void this.renderTasks();
}
/**
@@ -540,26 +496,7 @@ export class QuadrantColumnComponent extends Component {
/**
* Force update tasks even if they appear to be the same
*/
- public forceSetTasks(tasks: Task[]) {
- console.log(
- `forceSetTasks called for ${this.quadrant.id} with ${tasks.length} tasks`
- );
-
- this.tasks = tasks;
- this.updateCount();
-
- // Reset pagination state
- this.currentPage = 0;
- this.renderedTasks = [];
- this.hasMoreTasks = tasks.length > this.pageSize;
-
- // Always re-render
- if (this.isContentLoaded) {
- this.renderTasks();
- } else {
- this.loadContent();
- }
- }
+ public forceSetTasks(tasks: Task[]) { this.setTasks(tasks, true); }
/**
* Update a single task in the column
@@ -668,7 +605,7 @@ export class QuadrantColumnComponent extends Component {
if (cardIndex !== -1) {
const card = this.cardComponents[cardIndex];
- card.onunload();
+ this.removeChild(card);
card.containerEl.remove();
this.cardComponents.splice(cardIndex, 1);
}
@@ -719,7 +656,9 @@ export class QuadrantColumnComponent extends Component {
}
private async renderTasks() {
- if (!this.contentEl) return;
+ if (this.disposed || !this.contentEl) return;
+ const revision = ++this.renderRevision;
+ this.isLoadingMore = false;
// Clean up existing components
this.cleanup();
@@ -731,8 +670,10 @@ export class QuadrantColumnComponent extends Component {
this.currentPage = 0;
this.renderedTasks = [];
this.hasMoreTasks = this.tasks.length > this.pageSize;
+ this.hideLoadMoreIndicator();
await this.loadMoreTasks();
+ if (this.disposed || revision !== this.renderRevision) return;
// Show empty state if no tasks
if (this.tasks.length === 0) {
@@ -740,14 +681,15 @@ export class QuadrantColumnComponent extends Component {
}
}
- private async renderTaskBatch(tasks: Task[]) {
- if (!tasks.length) return;
+ private async renderTaskBatch(tasks: Task[], revision = this.renderRevision) {
+ if (!tasks.length || this.disposed || revision !== this.renderRevision) return;
const fragment = document.createDocumentFragment();
// Render tasks in smaller sub-batches to prevent UI blocking
const subBatchSize = 5;
for (let i = 0; i < tasks.length; i += subBatchSize) {
+ if (this.disposed || revision !== this.renderRevision) return;
const subBatch = tasks.slice(i, i + subBatchSize);
subBatch.forEach((task) => {
@@ -789,6 +731,7 @@ export class QuadrantColumnComponent extends Component {
}
}
+ if (this.disposed || revision !== this.renderRevision) return;
this.contentEl.appendChild(fragment);
// Force a scroll check after rendering
@@ -830,6 +773,7 @@ export class QuadrantColumnComponent extends Component {
}
private showEmptyState() {
+ this.cleanup(); this.contentEl.empty();
const emptyEl = this.contentEl.createDiv("tg-quadrant-empty-state");
const iconEl = emptyEl.createDiv("tg-quadrant-empty-icon");
diff --git a/src/components/features/quadrant/quadrant.ts b/src/components/features/quadrant/quadrant.ts
index 438a9e742..f2712d387 100644
--- a/src/components/features/quadrant/quadrant.ts
+++ b/src/components/features/quadrant/quadrant.ts
@@ -350,13 +350,15 @@ export class QuadrantComponent extends Component {
if (!contentEl) return;
// Detect if we're on a mobile device for optimized settings
- const isMobile =
- !Platform.isDesktop ||
- "ontouchstart" in window ||
- navigator.maxTouchPoints > 0;
+ const isMobile = Platform.isMobile;
const sortable = new Sortable(contentEl, {
group: "quadrant-tasks",
+ draggable: ".tg-quadrant-card",
+ filter: "button, input, select, textarea, a",
+ preventOnFilter: false,
+ emptyInsertThreshold: 20,
+ delayOnTouchOnly: true,
animation: 150,
ghostClass: "tg-quadrant-card--ghost",
dragClass: "tg-quadrant-card--dragging",
@@ -451,109 +453,28 @@ export class QuadrantComponent extends Component {
if (!task) return;
try {
- // Create a copy of the task for modification
- const updatedTask = { ...task };
-
- // Ensure metadata exists
- if (!updatedTask.metadata) {
- updatedTask.metadata = {
- tags: [],
- children: [],
- };
- }
-
- // Update tags in metadata
- const updatedTags = [...(updatedTask.metadata.tags || [])];
-
- // Get tag names to remove (from source quadrant if provided, otherwise from config)
- const tagsToRemove: string[] = [];
-
- if (sourceQuadrant) {
- // Remove tags from source quadrant (keep # prefix since metadata.tags includes #)
- if (sourceQuadrant.urgentTag) {
- tagsToRemove.push(sourceQuadrant.urgentTag);
- }
- if (sourceQuadrant.importantTag) {
- tagsToRemove.push(sourceQuadrant.importantTag);
- }
- } else {
- // Fallback: remove all urgent/important tags from config
- const urgentTag = this.quadrantConfig.urgentTag || "#urgent";
- const importantTag =
- this.quadrantConfig.importantTag || "#important";
- tagsToRemove.push(urgentTag);
- tagsToRemove.push(importantTag);
- }
-
- // Remove existing urgent/important tags
- const filteredTags = updatedTags.filter(
- (tag) => !tagsToRemove.includes(tag)
- );
-
- // Add new tags based on target quadrant (keep # prefix since metadata.tags includes #)
- if (quadrant.urgentTag) {
- if (!filteredTags.includes(quadrant.urgentTag)) {
- filteredTags.push(quadrant.urgentTag);
- }
- }
- if (quadrant.importantTag) {
- if (!filteredTags.includes(quadrant.importantTag)) {
- filteredTags.push(quadrant.importantTag);
- }
- }
-
- // Update tags in metadata
- updatedTask.metadata.tags = filteredTags;
-
- // Only update priority if using priority-based classification
+ const urgent = this.quadrantConfig.urgentTag || "#urgent";
+ const important = this.quadrantConfig.importantTag || "#important";
+ const normalize = (tag: string) => tag.replace(/^#/, "").toLowerCase();
+ const tags = (task.metadata?.tags || []).filter(tag => ![normalize(urgent), normalize(important)].includes(normalize(tag)) && !normalize(tag).startsWith("quadrant/"));
+ if (quadrant.id.startsWith("urgent-")) tags.push(urgent);
+ if (quadrant.id.endsWith("-important") && !quadrant.id.endsWith("-not-important")) tags.push(important);
+ // An explicit matrix placement must survive a near due date or keyword inference.
+ tags.push(`#quadrant/${quadrant.id}`);
+ const updatedTask: Task = { ...task, metadata: { ...task.metadata, tags } };
if (this.quadrantConfig.usePriorityForClassification) {
- // Update priority based on quadrant
- switch (quadrant.id) {
- case "urgent-important":
- updatedTask.metadata.priority = 5; // Highest
- break;
- case "not-urgent-important":
- updatedTask.metadata.priority = 4; // High
- break;
- case "urgent-not-important":
- updatedTask.metadata.priority = 3; // Medium
- break;
- case "not-urgent-not-important":
- updatedTask.metadata.priority = 2; // Low
- break;
- }
+ updatedTask.metadata.priority = { "urgent-important": 5, "not-urgent-important": 3, "urgent-not-important": 4, "not-urgent-not-important": 2 }[quadrant.id];
}
-
- // Store quadrant information in metadata using custom fields
- if (!(updatedTask.metadata as any).customFields) {
- (updatedTask.metadata as any).customFields = {};
- }
- (updatedTask.metadata as any).customFields.quadrant = quadrant.id;
- (updatedTask.metadata as any).customFields.lastQuadrantUpdate =
- Date.now();
-
- // Call the onTaskUpdated callback if provided
- if (this.params.onTaskUpdated) {
- await this.params.onTaskUpdated(updatedTask);
- }
-
- // Update the task in our local array
- const taskIndex = this.tasks.findIndex((t) => t.id === taskId);
- if (taskIndex !== -1) {
- this.tasks[taskIndex] = updatedTask;
- }
-
- // Show success feedback
- this.showUpdateFeedback(task, quadrant);
-
- // Refresh the view after a short delay to show the feedback
- setTimeout(() => {
- this.refresh();
- }, 500);
+ if (!this.plugin.writeAPI) throw new Error("Task writer is unavailable");
+ const result = await this.plugin.writeAPI.updateTask({ taskId, updates: { metadata: updatedTask.metadata } });
+ if (!result.success) throw new Error(result.error || "Task update failed");
+ this.allTasks = this.allTasks.map(item => item.id === taskId ? updatedTask : item);
+ this.tasks = this.tasks.map(item => item.id === taskId ? updatedTask : item);
+ this.showUpdateFeedback(updatedTask, quadrant);
} catch (error) {
console.error("Failed to update task quadrant:", error);
this.showErrorFeedback(task, error);
- }
+ } finally { this.refresh(); }
}
private showUpdateFeedback(_task: Task, quadrant: QuadrantDefinition) {
@@ -589,6 +510,8 @@ export class QuadrantComponent extends Component {
}
private determineTaskQuadrant(task: Task): string {
+ const explicit = (task.metadata?.tags || []).map(tag => tag.replace(/^#/, "")).find(tag => tag.startsWith("quadrant/"))?.slice(9);
+ if (explicit && QUADRANT_DEFINITIONS.some(quadrant => quadrant.id === explicit)) return explicit;
let isUrgent = false;
let isImportant = false;
@@ -679,7 +602,7 @@ export class QuadrantComponent extends Component {
}
public setTasks(tasks: Task[]) {
- this.allTasks = [...tasks];
+ this.allTasks = tasks.map(task => ({ ...task, metadata: { ...task.metadata, tags: [...(task.metadata.tags || [])] } }));
this.applyFilters();
}
diff --git a/src/components/features/quick-capture/components/FileNameInput.ts b/src/components/features/quick-capture/components/FileNameInput.ts
index af93eb1fb..6e64b0976 100644
--- a/src/components/features/quick-capture/components/FileNameInput.ts
+++ b/src/components/features/quick-capture/components/FileNameInput.ts
@@ -1,3 +1,4 @@
+import { t as settingsText } from "@/translations/helper";
import {
App,
TFile,
@@ -178,11 +179,11 @@ export class FileNameInput {
// Get templates from settings and normalize legacy data if needed
const defaultTemplates: QuickCaptureTemplateDefinition[] = [
- { name: "Daily Note", template: "{{DATE:YYYY-MM-DD}}" },
- { name: "Meeting", template: "{{DATE:YYYY-MM-DD}} - Meeting" },
- { name: "Task", template: "{{DATE:YYYY-MM-DD}} - Task" },
- { name: "Project", template: "Project - {{DATE:YYYY-MM}}" },
- { name: "Notes", template: "Notes - {{DATE:YYYY-MM-DD-HHmm}}" },
+ { name: settingsText("Daily Note"), template: "{{DATE:YYYY-MM-DD}}" },
+ { name: settingsText("Meeting"), template: "{{DATE:YYYY-MM-DD}} - Meeting" },
+ { name: settingsText("Task"), template: "{{DATE:YYYY-MM-DD}} - Task" },
+ { name: settingsText("Project"), template: "Project - {{DATE:YYYY-MM}}" },
+ { name: settingsText("Notes"), template: "Notes - {{DATE:YYYY-MM-DD-HHmm}}" },
];
const rawTemplates = this.plugin.settings.quickCapture
diff --git a/src/components/features/quick-capture/modals/BaseQuickCaptureModal.ts b/src/components/features/quick-capture/modals/BaseQuickCaptureModal.ts
index 11f28b313..a04c4e34a 100644
--- a/src/components/features/quick-capture/modals/BaseQuickCaptureModal.ts
+++ b/src/components/features/quick-capture/modals/BaseQuickCaptureModal.ts
@@ -1,3 +1,4 @@
+import { ProjectFileManager } from "@/managers/project-file-manager";
import {
App,
Modal,
@@ -32,6 +33,10 @@ export type QuickCaptureMode = "checkbox" | "file";
* Task metadata interface
*/
export interface TaskMetadata {
+ points?: number;
+ dependsOn?: string[];
+ dailyNoteDate?: string;
+ datePrecision?: Record;
startDate?: Date;
dueDate?: Date;
scheduledDate?: Date;
@@ -143,6 +148,7 @@ export abstract class BaseQuickCaptureModal extends Modal {
}
// If FileSource is disabled, force mode to checkbox
+ if (this.taskMetadata.project) { this.inlineModeAvailable = true; this.fileModeAvailable = false; this.currentMode = "checkbox"; }
if (this.currentMode === "file" && !this.fileModeAvailable) {
this.currentMode = "checkbox";
} else if (
@@ -205,7 +211,7 @@ export abstract class BaseQuickCaptureModal extends Modal {
) {
this.tempTargetFilePath = this.taskMetadata.customFileName;
} else if (settings.targetType === "daily-note") {
- const dateStr = moment().format(settings.dailyNoteSettings.format);
+ const dateStr = moment(this.taskMetadata.dailyNoteDate || undefined).format(settings.dailyNoteSettings.format);
const pathWithDate = settings.dailyNoteSettings.folder
? `${settings.dailyNoteSettings.folder}/${dateStr}.md`
: `${dateStr}.md`;
@@ -518,6 +524,7 @@ export abstract class BaseQuickCaptureModal extends Modal {
* Handle submit action
*/
protected async handleSubmit(): Promise {
+ if (this.contentEl.querySelector('[aria-invalid="true"]')) { new Notice(t("Enter a valid date, optionally followed by HH:mm.")); return; }
const content =
this.capturedContent.trim() ||
this.markdownEditor?.value.trim() ||
@@ -616,6 +623,9 @@ export abstract class BaseQuickCaptureModal extends Modal {
const captureOptions = {
...this.plugin.settings.quickCapture,
+ dailyNoteDate: this.taskMetadata.dailyNoteDate,
+ project: this.currentMode === "checkbox" ? this.taskMetadata.project : undefined,
+ projectTagPrefixes: Object.values(this.plugin.settings.projectTagPrefix || {}).map(String),
targetFile,
targetType,
// For file mode, always replace
@@ -658,8 +668,9 @@ export abstract class BaseQuickCaptureModal extends Modal {
// Resolve the actual file path
let resolvedPath = targetFile;
- if (this.plugin.settings.quickCapture.targetType === "daily-note") {
- const dateStr = moment().format(
+ if (this.taskMetadata.project) { resolvedPath = new ProjectFileManager(this.app).find(this.taskMetadata.project)?.file.path || targetFile; }
+ else if (this.plugin.settings.quickCapture.targetType === "daily-note") {
+ const dateStr = moment(this.taskMetadata.dailyNoteDate || undefined).format(
this.plugin.settings.quickCapture.dailyNoteSettings.format,
);
const folder =
@@ -884,6 +895,8 @@ export abstract class BaseQuickCaptureModal extends Modal {
yamlLines.push(`scheduledDate: ${JSON.stringify(scheduledDate)}`);
if (priorityVal)
yamlLines.push(`priority: ${JSON.stringify(priorityVal)}`);
+ if (this.taskMetadata.points != null && Number.isFinite(this.taskMetadata.points)) yamlLines.push(`points: ${this.taskMetadata.points}`);
+ if (this.taskMetadata.dependsOn?.length) yamlLines.push(`dependsOn: ${JSON.stringify(this.taskMetadata.dependsOn)}`);
if (projectVal)
yamlLines.push(`project: ${JSON.stringify(projectVal)}`);
if (contextVal)
diff --git a/src/components/features/quick-capture/modals/MinimalQuickCaptureModal.ts b/src/components/features/quick-capture/modals/MinimalQuickCaptureModal.ts
index 9596a91d7..f03c91de1 100644
--- a/src/components/features/quick-capture/modals/MinimalQuickCaptureModal.ts
+++ b/src/components/features/quick-capture/modals/MinimalQuickCaptureModal.ts
@@ -693,6 +693,8 @@ export class MinimalQuickCaptureModal extends Modal {
const captureOptions = {
...this.plugin.settings.quickCapture,
+ project: this.taskMetadata.project,
+ projectTagPrefixes: Object.values(this.plugin.settings.projectTagPrefix || {}).map(String),
targetFile:
this.taskMetadata.targetFile || this.getTargetFile(),
targetType: (this.taskMetadata.location || "fixed") as
diff --git a/src/components/features/quick-capture/modals/QuickCaptureModal.ts b/src/components/features/quick-capture/modals/QuickCaptureModal.ts
index 6daf4d72d..15f44ce53 100644
--- a/src/components/features/quick-capture/modals/QuickCaptureModal.ts
+++ b/src/components/features/quick-capture/modals/QuickCaptureModal.ts
@@ -153,7 +153,7 @@ export class QuickCaptureModal extends Modal {
// Initialize time parsing service
this.timeParsingService = new TimeParsingService(
- this.plugin.settings.timeParsing || DEFAULT_TIME_PARSING_CONFIG,
+ DEFAULT_TIME_PARSING_CONFIG,
);
if (metadata) {
@@ -464,16 +464,6 @@ export class QuickCaptureModal extends Modal {
});
});
- // Recurrence
- new Setting(configPanel).setName(t("Recurrence")).addText((text) => {
- text.setPlaceholder(t("e.g., every day, every week"))
- .setValue(this.taskMetadata.recurrence || "")
- .onChange((value) => {
- this.taskMetadata.recurrence = value || undefined;
- this.updatePreview();
- });
- });
-
// Create editor container in the right panel
const editorContainer = editorPanel.createDiv({
cls: "quick-capture-modal-editor",
@@ -629,6 +619,8 @@ export class QuickCaptureModal extends Modal {
// Create options with current settings
const captureOptions = {
...this.plugin.settings.quickCapture,
+ project: this.taskMetadata.project,
+ projectTagPrefixes: Object.values(this.plugin.settings.projectTagPrefix || {}).map(String),
targetFile: this.tempTargetFilePath,
};
diff --git a/src/components/features/quick-capture/modals/QuickCaptureModalWithSwitch.ts b/src/components/features/quick-capture/modals/QuickCaptureModalWithSwitch.ts
index 81ed7366f..1477d9174 100644
--- a/src/components/features/quick-capture/modals/QuickCaptureModalWithSwitch.ts
+++ b/src/components/features/quick-capture/modals/QuickCaptureModalWithSwitch.ts
@@ -1,3 +1,8 @@
+import "@/styles/quick-capture.css";
+import { renderTaskDependencies } from "@/components/features/task/edit/TaskDependencyPicker";
+import { ProjectFileManager } from "@/managers/project-file-manager";
+import { attachDateTimePicker } from "@/utils/date/date-time-picker";
+import { parseOptionalDateTime, formatOptionalDateTime } from "@/utils/date/optional-date-time";
import {
App,
Setting,
@@ -54,7 +59,6 @@ export class QuickCaptureModal extends BaseQuickCaptureModal {
private startDateInput?: HTMLInputElement;
private dueDateInput?: HTMLInputElement;
private scheduledDateInput?: HTMLInputElement;
- private includeTime: boolean = true;
// File name input for file creation mode
private fileNameInput: FileNameInput | null = null;
@@ -66,6 +70,10 @@ export class QuickCaptureModal extends BaseQuickCaptureModal {
// Debounce timer for real-time parsing
private parseDebounceTimer?: number;
+ private editorSetupTimer?: number;
+ private suggestSetupTimer?: number;
+ protected rememberCaptureMode = true;
+ protected sourceTask?: Task;
constructor(
app: App,
@@ -84,10 +92,11 @@ export class QuickCaptureModal extends BaseQuickCaptureModal {
} catch {}
super(app, plugin, initialMode, metadata);
+ this.modalEl.addClass("full");
// Initialize time parsing service
this.timeParsingService = new TimeParsingService(
- this.plugin.settings.timeParsing || DEFAULT_TIME_PARSING_CONFIG,
+ DEFAULT_TIME_PARSING_CONFIG,
);
}
@@ -105,7 +114,7 @@ export class QuickCaptureModal extends BaseQuickCaptureModal {
}
// Enable universal suggest after editor is created
- setTimeout(() => {
+ this.suggestSetupTimer = window.setTimeout(() => {
if (this.markdownEditor?.editor?.editor) {
this.universalSuggest =
this.suggestManager.enableForQuickCaptureModal(
@@ -239,7 +248,7 @@ export class QuickCaptureModal extends BaseQuickCaptureModal {
// Update editor title
const editorTitle = this.contentContainer?.querySelector(
- ".quick-capture-section-title",
+ ".quick-capture-editor-panel .quick-capture-section-title",
);
if (editorTitle) {
editorTitle.setText(
@@ -315,7 +324,16 @@ export class QuickCaptureModal extends BaseQuickCaptureModal {
/**
* Create target file selector
*/
- private createTargetFileSelector(container: HTMLElement): void {
+ protected createTargetFileSelector(container: HTMLElement): void {
+ const project = this.taskMetadata.project?.trim();
+ if (project && this.currentMode !== "file") {
+ const manager = new ProjectFileManager(this.app), file = manager.find(project)?.file;
+ const slug = project.replace(/[\\/:*?"<>|]/g, "-").replace(/\s+/g, "-");
+ this.tempTargetFilePath = file?.path || `${manager.folder}/${slug}.md`;
+ container.createDiv({ cls: "quick-capture-section-title", text: t("Capture to:") });
+ container.createDiv({ cls: "quick-capture-target", text: this.tempTargetFilePath });
+ return;
+ }
const targetFileContainer = container.createDiv({
cls: "quick-capture-target-container",
});
@@ -337,6 +355,18 @@ export class QuickCaptureModal extends BaseQuickCaptureModal {
text: this.tempTargetFilePath,
});
+ if (this.plugin.settings.quickCapture.targetType === "daily-note") {
+ const day = targetFileContainer.createEl("input", { type: "date", attr: { "aria-label": t("Daily note date") } });
+ day.value = this.taskMetadata.dailyNoteDate || moment().format("YYYY-MM-DD");
+ day.addEventListener("change", () => {
+ if (!moment(day.value, "YYYY-MM-DD", true).isValid()) return;
+ this.taskMetadata.dailyNoteDate = day.value;
+ const settings = this.plugin.settings.quickCapture.dailyNoteSettings;
+ this.tempTargetFilePath = this.sanitizeFilePath(`${settings.folder ? settings.folder + "/" : ""}${moment(day.value).format(settings.format)}.md`);
+ targetFileEl.textContent = this.tempTargetFilePath;
+ });
+ }
+
// Only add file suggest for fixed file type
if (this.plugin.settings.quickCapture.targetType === "fixed") {
new FileSuggest(
@@ -390,29 +420,23 @@ export class QuickCaptureModal extends BaseQuickCaptureModal {
// Context input
this.createContextInput(container);
- // Recurrence input
- this.createRecurrenceInput(container);
+ const additional = container.createEl("details", { cls: "quick-capture-additional" });
+ additional.createEl("summary", { text: t("More properties") });
+ new Setting(additional).setName(t("Task points")).addText(text => {
+ text.inputEl.type = "number"; text.inputEl.min = "0";
+ text.setValue(this.taskMetadata.points == null ? "" : String(this.taskMetadata.points)).onChange(value => { this.taskMetadata.points = value.trim() ? Math.max(0, Number(value)) : undefined; this.updatePreview(); });
+ });
+ new Setting(additional).setName(t("Tags")).addText(text => text.setValue((this.taskMetadata.tags || []).join(" ")).onChange(value => { this.taskMetadata.tags = value.split(/[\s,]+/).map(tag => tag.replace(/^#/, "")).filter(Boolean); this.updatePreview(); }));
+ const dependencies = new Setting(additional).setName(t("Depends On"));
+ renderTaskDependencies(this.app, this.plugin, dependencies.controlEl, this.sourceTask || { id: "capture-draft", content: "", filePath: "", metadata: { dependsOn: this.taskMetadata.dependsOn || [] } } as Task, ids => this.taskMetadata.dependsOn = ids);
}
/**
* Create date inputs
*/
private createDateInputs(container: HTMLElement): void {
- const getInputType = () =>
- this.includeTime ? "datetime-local" : "date";
- const getPlaceholder = () =>
- this.includeTime ? "YYYY-MM-DD HH:mm" : "YYYY-MM-DD";
-
- // Toggle for including time in date inputs
- new Setting(container)
- .setName(t("Include time"))
- .setDesc(t("Toggle between date-only and date+time input"))
- .addToggle((toggle) => {
- toggle.setValue(this.includeTime).onChange((value) => {
- this.includeTime = value;
- this.updateDateInputsMode();
- });
- });
+ const getInputType = () => "text";
+ const getPlaceholder = () => "YYYY-MM-DD / YYYY-MM-DD HH:mm";
// Start Date
new Setting(container).setName(t("Start Date")).addText((text) => {
@@ -423,19 +447,23 @@ export class QuickCaptureModal extends BaseQuickCaptureModal {
: "",
)
.onChange((value) => {
+ this.startDateInput?.setAttribute("aria-invalid", String(!!value.trim() && !parseOptionalDateTime(value)));
if (value) {
- this.taskMetadata.startDate = this.parseDate(value);
+ const parsed = parseOptionalDateTime(value);
+ if (!parsed) return;
+ this.taskMetadata.startDate = new Date(parsed.timestamp);
+ this.taskMetadata.datePrecision = { ...this.taskMetadata.datePrecision, startDate: parsed.precision };
this.markAsManuallySet("startDate");
} else {
this.taskMetadata.startDate = undefined;
- if (this.taskMetadata.manuallySet) {
- this.taskMetadata.manuallySet.startDate = false;
- }
+ if (this.taskMetadata.datePrecision) delete this.taskMetadata.datePrecision.startDate;
+ this.markAsManuallySet("startDate");
}
this.updatePreview();
});
text.inputEl.type = getInputType();
this.startDateInput = text.inputEl;
+ attachDateTimePicker(text.inputEl, t("Start Date"));
});
// Due Date
@@ -447,19 +475,23 @@ export class QuickCaptureModal extends BaseQuickCaptureModal {
: "",
)
.onChange((value) => {
+ this.dueDateInput?.setAttribute("aria-invalid", String(!!value.trim() && !parseOptionalDateTime(value)));
if (value) {
- this.taskMetadata.dueDate = this.parseDate(value);
+ const parsed = parseOptionalDateTime(value);
+ if (!parsed) return;
+ this.taskMetadata.dueDate = new Date(parsed.timestamp);
+ this.taskMetadata.datePrecision = { ...this.taskMetadata.datePrecision, dueDate: parsed.precision };
this.markAsManuallySet("dueDate");
} else {
this.taskMetadata.dueDate = undefined;
- if (this.taskMetadata.manuallySet) {
- this.taskMetadata.manuallySet.dueDate = false;
- }
+ if (this.taskMetadata.datePrecision) delete this.taskMetadata.datePrecision.dueDate;
+ this.markAsManuallySet("dueDate");
}
this.updatePreview();
});
text.inputEl.type = getInputType();
this.dueDateInput = text.inputEl;
+ attachDateTimePicker(text.inputEl, t("Due Date"));
});
// Scheduled Date
@@ -473,19 +505,23 @@ export class QuickCaptureModal extends BaseQuickCaptureModal {
: "",
)
.onChange((value) => {
+ this.scheduledDateInput?.setAttribute("aria-invalid", String(!!value.trim() && !parseOptionalDateTime(value)));
if (value) {
- this.taskMetadata.scheduledDate = this.parseDate(value);
+ const parsed = parseOptionalDateTime(value);
+ if (!parsed) return;
+ this.taskMetadata.scheduledDate = new Date(parsed.timestamp);
+ this.taskMetadata.datePrecision = { ...this.taskMetadata.datePrecision, scheduledDate: parsed.precision };
this.markAsManuallySet("scheduledDate");
} else {
this.taskMetadata.scheduledDate = undefined;
- if (this.taskMetadata.manuallySet) {
- this.taskMetadata.manuallySet.scheduledDate = false;
- }
+ if (this.taskMetadata.datePrecision) delete this.taskMetadata.datePrecision.scheduledDate;
+ this.markAsManuallySet("scheduledDate");
}
this.updatePreview();
});
text.inputEl.type = getInputType();
this.scheduledDateInput = text.inputEl;
+ attachDateTimePicker(text.inputEl, t("Scheduled Date"));
});
}
@@ -522,7 +558,10 @@ export class QuickCaptureModal extends BaseQuickCaptureModal {
text.setPlaceholder(t("Project name"))
.setValue(this.taskMetadata.project || "")
.onChange((value) => {
- this.taskMetadata.project = value || undefined;
+ this.taskMetadata.project = value.trim() || undefined;
+ if (this.taskMetadata.project && this.currentMode === "file") { this.inlineModeAvailable = true; void this.switchMode("checkbox"); return; }
+ if (!this.taskMetadata.project) this.initializeTargetFile();
+ this.updateTargetDisplay();
this.updatePreview();
});
});
@@ -561,7 +600,7 @@ export class QuickCaptureModal extends BaseQuickCaptureModal {
* Setup markdown editor
*/
private setupMarkdownEditor(container: HTMLElement): void {
- setTimeout(() => {
+ this.editorSetupTimer = window.setTimeout(() => {
this.markdownEditor = createEmbeddableMarkdownEditor(
this.app,
container,
@@ -735,6 +774,10 @@ export class QuickCaptureModal extends BaseQuickCaptureModal {
}
}
+ if (this.taskMetadata.project) {
+ const manager = new ProjectFileManager(this.app, ["project", ...Object.values(this.plugin.settings.projectTagPrefix || {})]);
+ return processedLines.map(line => manager.stripProjectMarkers(line, this.taskMetadata.project!)).join("\n");
+ }
return processedLines.join("\n");
}
@@ -745,7 +788,7 @@ export class QuickCaptureModal extends BaseQuickCaptureModal {
taskLine: string,
lineParseResult: LineParseResult,
): string {
- const metadata = this.generateLineMetadata(lineParseResult);
+ const metadata = this.generateLineMetadata(lineParseResult, taskLine);
if (!metadata) return taskLine;
return `${taskLine} ${metadata}`.trim();
}
@@ -753,16 +796,14 @@ export class QuickCaptureModal extends BaseQuickCaptureModal {
/**
* Generate line metadata
*/
- private generateLineMetadata(lineParseResult: LineParseResult): string {
+ private generateLineMetadata(lineParseResult: LineParseResult, taskLine = ""): string {
const metadata: string[] = [];
const useDataviewFormat = this.preferMetadataFormat === "dataview";
// Use line-specific dates first, fall back to global metadata
- const startDate =
- lineParseResult.startDate || this.taskMetadata.startDate;
- const dueDate = lineParseResult.dueDate || this.taskMetadata.dueDate;
- const scheduledDate =
- lineParseResult.scheduledDate || this.taskMetadata.scheduledDate;
+ const startDate = this.isManuallySet("startDate") ? this.taskMetadata.startDate : lineParseResult.startDate || this.taskMetadata.startDate;
+ const dueDate = this.isManuallySet("dueDate") ? this.taskMetadata.dueDate : lineParseResult.dueDate || this.taskMetadata.dueDate;
+ const scheduledDate = this.isManuallySet("scheduledDate") ? this.taskMetadata.scheduledDate : lineParseResult.scheduledDate || this.taskMetadata.scheduledDate;
// Add dates
if (startDate) {
@@ -809,19 +850,15 @@ export class QuickCaptureModal extends BaseQuickCaptureModal {
}
}
- // Add project
- if (this.taskMetadata.project) {
- const projectPrefix =
- this.plugin.settings.projectTagPrefix?.[
- this.plugin.settings.preferMetadataFormat
- ] || "project";
- metadata.push(
- useDataviewFormat
- ? `[${projectPrefix}:: ${this.taskMetadata.project}]`
- : `#${projectPrefix}/${this.taskMetadata.project}`,
- );
- }
+ // Project membership is represented by the destination note, never inline text.
+ if (this.taskMetadata.points != null && Number.isFinite(this.taskMetadata.points)) metadata.push(`[points:: ${this.taskMetadata.points}]`);
+ if (this.taskMetadata.dependsOn?.length) metadata.push(useDataviewFormat ? `[dependsOn:: ${this.taskMetadata.dependsOn.join(", ")}]` : `⛔ ${this.taskMetadata.dependsOn.join(", ")}`);
+ for (const raw of this.taskMetadata.tags || []) {
+ const tag = raw.replace(/^#/, "");
+ if (this.taskMetadata.project && ["project", ...Object.values(this.plugin.settings.projectTagPrefix || {})].some(prefix => tag.startsWith(prefix + "/"))) continue;
+ if (tag && !taskLine.split(/\s+/).includes("#" + tag)) metadata.push("#" + tag);
+ }
// Add context
if (this.taskMetadata.context) {
const contextPrefix =
@@ -930,62 +967,32 @@ export class QuickCaptureModal extends BaseQuickCaptureModal {
this.taskMetadata.manuallySet[field] = true;
}
- /**
- * Update all date input elements when the includeTime mode changes
- */
- private updateDateInputsMode(): void {
- const inputType = this.includeTime ? "datetime-local" : "date";
- const placeholder = this.includeTime
- ? "YYYY-MM-DD HH:mm"
- : "YYYY-MM-DD";
-
- const updateInput = (input?: HTMLInputElement, value?: Date) => {
- if (!input) return;
- input.type = inputType;
- input.placeholder = placeholder;
- input.value = this.formatDateInputValue(value);
- };
-
- updateInput(this.startDateInput, this.taskMetadata.startDate);
- updateInput(this.dueDateInput, this.taskMetadata.dueDate);
- updateInput(this.scheduledDateInput, this.taskMetadata.scheduledDate);
-
- this.updatePreview();
- }
-
private setDateInputValue(
input: HTMLInputElement | undefined,
value?: Date,
): void {
if (!input) return;
- input.value = this.formatDateInputValue(value);
+ input.value = this.formatDateInputValue(value); input.dispatchEvent(new Event("tg-date-updated"));
}
private formatDateInputValue(value?: Date): string {
- if (!value) return "";
- return moment(value).format(
- this.includeTime ? "YYYY-MM-DD[T]HH:mm" : "YYYY-MM-DD",
- );
+ const field = (["startDate", "dueDate", "scheduledDate"] as const).find(field => this.taskMetadata[field] === value);
+ return formatOptionalDateTime(value, field ? this.taskMetadata.datePrecision?.[field] : undefined);
}
/**
- * Override formatDate to respect includeTime setting for task metadata output
+ * Format each field according to whether the user supplied a time
*/
- protected formatDate(date: Date): string {
- return formatDateSmart(date, {
- forceFormat: this.includeTime ? undefined : "date-only",
- includeSeconds: false,
- });
- }
+ protected formatDate(date: Date): string { return this.formatDateInputValue(date); }
/**
* Reset UI elements
*/
protected resetUIElements(): void {
// Reset date inputs
- if (this.startDateInput) this.startDateInput.value = "";
- if (this.dueDateInput) this.dueDateInput.value = "";
- if (this.scheduledDateInput) this.scheduledDateInput.value = "";
+ if (this.startDateInput) { this.startDateInput.value = ""; this.startDateInput.dispatchEvent(new Event("tg-date-updated")); }
+ if (this.dueDateInput) { this.dueDateInput.value = ""; this.dueDateInput.dispatchEvent(new Event("tg-date-updated")); }
+ if (this.scheduledDateInput) { this.scheduledDateInput.value = ""; this.scheduledDateInput.dispatchEvent(new Event("tg-date-updated")); }
// Clear file name input
if (this.fileNameInput) {
@@ -1003,12 +1010,13 @@ export class QuickCaptureModal extends BaseQuickCaptureModal {
*/
onClose() {
// Save last used mode if enabled
- if (this.plugin.settings.quickCapture.rememberLastMode) {
+ if (this.rememberCaptureMode && this.plugin.settings.quickCapture.rememberLastMode) {
this.plugin.settings.quickCapture.lastUsedMode = this.currentMode;
this.plugin.saveSettings();
}
// Clean up
+ window.clearTimeout(this.editorSetupTimer); window.clearTimeout(this.suggestSetupTimer);
if (this.universalSuggest) {
this.universalSuggest.disable();
this.universalSuggest = null;
diff --git a/src/components/features/rewards/PointsDashboard.ts b/src/components/features/rewards/PointsDashboard.ts
new file mode 100644
index 000000000..a31d46dea
--- /dev/null
+++ b/src/components/features/rewards/PointsDashboard.ts
@@ -0,0 +1,285 @@
+import { pointLedgerDate } from "@/managers/points-utils";
+import { App, Component, Modal, Notice, SearchComponent, Setting } from "obsidian";
+import type TaskProgressBarPlugin from "@/index";
+import { rewardCatalogRows } from "@/managers/reward-catalog";
+import { HabitsBlock } from "@/integrations/habits/ui/habits-block";
+import { localPointDate, roundPoints } from "@/managers/daily-points";
+import { pointsService, PointsSnapshot } from "@/managers/points-service";
+import { t } from "@/translations/helper";
+
+type PointsTab = "daily" | "actions" | "history" | "rules";
+const numberText = (value: number) => String(roundPoints(value));
+
+/** One native page backed by the original Markdown ledger and habit notes. */
+export class PointsDashboard extends Component {
+ readonly containerEl: HTMLElement;
+ private summaryEl!: HTMLElement;
+ private bodyEl!: HTMLElement;
+ private tabsEl!: HTMLElement;
+ private activeTab: PointsTab;
+ private query = "";
+ setSearchQuery(query: string): void { this.query = query.trim().toLocaleLowerCase(); this.renderBody(); }
+ private historyFilter = "all";
+ private snapshot?: PointsSnapshot;
+ private scope?: Component;
+ private habits?: HabitsBlock;
+ private request = 0;
+ private disposed = false;
+ private refreshTimer?: number;
+
+ constructor(private app: App, private plugin: TaskProgressBarPlugin, parent: HTMLElement, private settingsMode = false, private page: "points" | "rewards" = "points") {
+ super();
+ this.activeTab = "actions";
+ this.containerEl = parent.createDiv({ cls: "tg-points-page" });
+ }
+ onload(): void {
+ this.disposed = false;
+ const header = this.containerEl.createDiv({ cls: "tg-points-header" });
+ const heading = header.createDiv();
+ heading.createEl("h2", { text: t("Points and rewards") });
+ heading.createDiv({ cls: "tg-points-subtitle", text: t("Earn points and redeem rewards in one place.") });
+ this.button(header, t("Add points"), () => this.editRecord(), true);
+ this.summaryEl = this.containerEl.createDiv({ cls: "tg-points-summary" });
+ this.tabsEl = this.containerEl.createDiv({ cls: "tg-points-tabs", attr: { role: "tablist" } });
+ const tools = this.containerEl.createDiv({ cls: "tg-points-tools" });
+ if (this.settingsMode) new SearchComponent(tools).setPlaceholder(t("Search bonuses, rewards and records"))
+ .onChange(value => { this.query = value.toLocaleLowerCase().trim(); this.renderBody(); });
+ const filter = tools.createEl("select", { attr: { "aria-label": t("Filter") } });
+ for (const [value, label] of [["all", "All"], ["today", "Today"], ["week", "Last 7 days"], ["month", "Last 30 days"], ["positive", "Points earned"], ["negative", "Points spent"]]) filter.createEl("option", { value, text: t(label) });
+ this.registerDomEvent(filter, "change", () => { this.historyFilter = filter.value; this.renderBody(); });
+ this.bodyEl = this.containerEl.createDiv({ cls: "tg-points-body" });
+ this.renderTabs();
+ for (const event of ["task-genius:points-updated", "task-genius:cache-ready", "task-genius:task-cache-updated"]) {
+ this.registerEvent(this.app.workspace.on(event as "task-genius:points-updated", () => this.scheduleRefresh()));
+ }
+ for (const event of ["modify", "create", "delete", "rename"] as const) this.registerEvent(this.app.vault.on(event as "modify", file => {
+ const folder = this.plugin.habitsIntegration?.settings.habitsFolder || this.plugin.settings.habitsIntegration?.habitsFolder || "Habits";
+ if (file.path === pointsService(this.plugin).dataPath || file.path.startsWith(`${folder}/`)) this.scheduleRefresh();
+ }));
+ void this.refresh();
+ }
+ onunload(): void {
+ this.disposed = true;
+ this.request++;
+ window.clearTimeout(this.refreshTimer);
+ this.containerEl.empty();
+ }
+ private scheduleRefresh() {
+ window.clearTimeout(this.refreshTimer);
+ this.refreshTimer = window.setTimeout(() => void this.refresh(), 150);
+ }
+ private async refresh() {
+ const request = ++this.request;
+ try {
+ const snapshot = await pointsService(this.plugin).snapshot();
+ if (this.disposed || request !== this.request) return;
+ this.snapshot = snapshot;
+ this.summaryEl.empty();
+ for (const [label, value, primary] of [
+ [t("Available points"), numberText(snapshot.balance), true],
+ [t("Today's points"), numberText(snapshot.todayPoints), false],
+ ] as const) {
+
+ const card = this.summaryEl.createDiv({ cls: `tg-points-card${primary ? " is-primary" : ""}` });
+ card.createDiv({ cls: "tg-points-label", text: label });
+ card.createDiv({ cls: "tg-points-balance", text: value });
+ }
+ if (this.activeTab !== "daily" || !this.habits) this.renderBody();
+ } catch (error) { if (!this.disposed) this.bodyEl.setText(String(error)); }
+ }
+ private renderTabs() {
+ (this.containerEl.querySelector(".tg-points-tools select") as HTMLElement | null)?.toggle(this.activeTab === "history");
+ this.tabsEl.empty();
+ const tabs: Array<[PointsTab, string]> = [["actions", "Bonuses and rewards"], ["history", "Points history"], ["rules", "Points rules"]];
+ for (const [id, label] of tabs) {
+ const button = this.tabsEl.createEl("button", { text: t(label), attr: { role: "tab", "aria-selected": String(id === this.activeTab) } });
+ button.toggleClass("is-active", id === this.activeTab);
+ button.addEventListener("click", () => { this.activeTab = id; this.renderTabs(); this.clearBody(); this.renderBody(); });
+ }
+ }
+ private clearBody() {
+ if (this.scope) this.removeChild(this.scope);
+ this.scope = this.addChild(new Component());
+ this.habits = undefined;
+ this.bodyEl.empty();
+ }
+ private matches(text: string) { return !this.query || text.toLocaleLowerCase().includes(this.query); }
+ private renderBody() {
+ if (!this.snapshot || this.disposed) return;
+ this.bodyEl.toggleClass("is-actions", this.activeTab === "actions");
+ this.bodyEl.toggleClass("is-history", this.activeTab === "history");
+ if (this.activeTab === "daily" && this.habits) { this.habits.setSearchQuery(this.query); return; }
+ this.clearBody();
+ if (this.activeTab === "daily") void this.renderHabits();
+ else if (this.activeTab === "actions") this.renderActions();
+ else if (this.activeTab === "history") this.renderHistory();
+ else this.renderRules();
+ }
+ private async renderHabits() {
+ const scope = this.scope;
+ try {
+ const integration = await this.plugin.ensureHabitsIntegration();
+ if (this.disposed || scope !== this.scope) return;
+ const root = this.bodyEl.createDiv({ cls: "tg-habits-surface" });
+ this.habits = scope!.addChild(new HabitsBlock(this.app, integration.store, () => integration.settings, integration.events, "", root));
+ this.habits.setSearchQuery(this.query);
+ } catch (error) { if (scope === this.scope) this.bodyEl.setText(String(error)); }
+ }
+ private panel(label: string) {
+ const panel = this.bodyEl.createDiv({ cls: "tg-points-panel" });
+ panel.createEl("h3", { text: label });
+ return panel;
+ }
+ private renderActions() {
+ const snapshot = this.snapshot!;
+ const bonuses = this.panel(t("Bonus actions"));
+ this.button(bonuses, t("Edit bonus actions"), () => this.editList("examplePropertyLeft"));
+ for (const item of snapshot.bonuses.filter(item => this.matches(item.text))) {
+ const row = bonuses.createDiv({ cls: "tg-reward-card" });
+ row.createDiv({ text: item.text });
+ this.button(row, t("Record points"), () => this.editRecord(item.text, item.amount ?? 1));
+ }
+ const shop = this.panel(t("Reward shop"));
+ this.button(shop, t("Edit reward shop"), () => this.editRewardShop());
+ for (const item of snapshot.wishes.filter(item => this.matches(item.text))) {
+ const row = shop.createDiv({ cls: "tg-reward-card" }); row.createDiv({ text: item.text });
+ const cost = Math.abs(item.amount ?? 0);
+ const button = this.button(row, cost ? `${t("Redeem")} · ${numberText(cost)}` : t("Set a point cost to enable redemption"), () => this.confirmRedemption(item.text, cost));
+ button.disabled = cost <= 0 || snapshot.balance < cost;
+ }
+ for (const reward of this.plugin.settings.rewards.rewardItems.filter(item => item.pointCost !== undefined && this.matches(item.name))) {
+ const row = shop.createDiv({ cls: "tg-reward-card" }); row.createDiv({ text: reward.name });
+ const actions = row.createDiv({ cls: "tg-reward-actions" });
+ const cost = reward.pointCost || 0;
+ const redeem = this.button(actions, `${t("Redeem")} · ${numberText(cost)}`, () => this.confirmRedemption(reward.name, cost, reward.id));
+ redeem.disabled = cost <= 0 || snapshot.balance < cost || reward.inventory === 0;
+ }
+ }
+ private historyDateMatches(date: string): boolean {
+ const today = localPointDate();
+ if (this.historyFilter === "today") return date === today;
+ if (!["week", "month"].includes(this.historyFilter)) return true;
+ const cutoff = new Date(); cutoff.setDate(cutoff.getDate() - (this.historyFilter === "week" ? 6 : 29));
+ return date >= localPointDate(cutoff) && date <= today;
+ }
+ private historyAmountMatches(amount: number): boolean { return (this.historyFilter !== "positive" || amount > 0) && (this.historyFilter !== "negative" || amount < 0); }
+ private renderHistory() {
+ const snapshot = this.snapshot!;
+ const panel = this.panel(t("Points history"));
+ const records = [
+
+ ...snapshot.manual.map(item => ({ id: item.id, date: item.date, label: item.text, amount: item.points, manual: true })),
+ ...snapshot.ledger.filter(item => item.source !== "task").map(item => ({ id: item.id, date: pointLedgerDate(item), label: item.label, amount: item.delta, manual: false })),
+ ].filter(item => this.matches(`${item.date} ${item.label}`) && this.historyDateMatches(item.date) && this.historyAmountMatches(item.amount)).sort((a, b) => b.date.localeCompare(a.date));
+ for (const record of records) {
+ const row = panel.createDiv({ cls: "tg-points-entry" });
+ const detail = row.createDiv(); detail.createDiv({ text: record.label }); detail.createDiv({ cls: "tg-points-date", text: record.date });
+ row.createDiv({ cls: record.amount < 0 ? "tg-points-delta is-negative" : "tg-points-delta", text: `${record.amount > 0 ? "+" : ""}${numberText(record.amount)}` });
+ if (record.manual) this.button(detail, t("Delete"), () => this.confirm(t("Delete this points record?"), () => pointsService(this.plugin).deleteRecord(record.id)));
+ }
+ if (!records.length) panel.createDiv({ cls: "tg-points-empty", text: t("No matching records") });
+ const habits = this.panel(t("Habit points"));
+ const completionPoints = snapshot.automaticTasks.days.filter(day => this.historyDateMatches(day.date)).reduce((sum, day) => sum + day.supplement, 0) + snapshot.ledger.filter(item => item.source === "task" && this.historyDateMatches(pointLedgerDate(item))).reduce((sum, item) => sum + item.delta, 0);
+ if (!snapshot.automaticTasks.habitPaths.length && completionPoints && this.historyAmountMatches(completionPoints) && this.matches(t("Completed tasks"))) {
+ const row = habits.createDiv({ cls: "tg-points-entry" }); row.createDiv({ text: t("Completed tasks") }); row.createDiv({ text: numberText(completionPoints) });
+ }
+ for (const item of snapshot.summaries.filter(item => this.matches(item.name))) {
+ const base = ["week", "month"].includes(this.historyFilter) ? Object.entries(item.dailyPoints || {}).filter(([date]) => this.historyDateMatches(date)).reduce((sum, [, points]) => sum + points, 0) : this.historyFilter === "today" ? item.todayPoints : item.points;
+ const amount = roundPoints(base + (snapshot.automaticTasks.habitPaths[0] === item.path ? completionPoints : 0));
+ if (!amount || !this.historyAmountMatches(amount)) continue;
+ const row = habits.createDiv({ cls: "tg-points-entry" });
+ const entries = ["today", "week", "month"].includes(this.historyFilter) ? Object.entries(item.dailyEntries || Object.fromEntries(Object.keys(item.dailyPoints || {}).map(day => [day, 1]))).filter(([day]) => this.historyDateMatches(day)).reduce((sum, [, count]) => sum + count, 0) : item.entries;
+ row.createDiv({ text: `${item.name} · ${entries} ${t("check-ins")}` });
+ row.createDiv({ text: numberText(amount) });
+ }
+ }
+ private renderRules() {
+ const snapshot = this.snapshot!;
+ const panel = this.panel(t("Points rules"));
+ new Setting(panel).setName(t("Points data file")).setDesc(snapshot.path)
+ .addButton(button => button.setButtonText(t("Open")).onClick(() => void this.app.workspace.openLinkText(snapshot.path, "", false)))
+ .addButton(button => button.setButtonText(t("Change")).onClick(() => new PointTextModal(this.app, t("Points data file"), snapshot.path, async value => {
+ if (!value.trim().endsWith(".md") || /^(?:[a-zA-Z]:|[\\/])/.test(value) || value.split(/[\\/]/).includes("..")) throw new Error(t("Choose a Markdown file inside the vault."));
+ this.plugin.settings.rewards.pointsDataFile = value.trim(); await this.plugin.saveSettings(); await this.refresh();
+ }).open()));
+ new Setting(panel).setName(t("Default habit points")).setDesc(t("Habit-specific points override the default. Negative values deduct points above the habit allowance."))
+ .addToggle(toggle => toggle.setValue(snapshot.data.defaultPointRule?.enabled !== false).onChange(value => void pointsService(this.plugin).saveDefaultRate(Number(snapshot.data.defaultPointRule?.baseRate ?? 0.1), value)))
+ .addButton(button => button.setButtonText(numberText(Number(snapshot.data.defaultPointRule?.baseRate ?? 0.1))).onClick(() => new PointAmountModal(this.app, t("Default habit points"), t("Default rule"), Number(snapshot.data.defaultPointRule?.baseRate ?? 0.1), async (_label, amount) => pointsService(this.plugin).saveDefaultRate(amount, true), true).open()));
+ new Setting(panel).setName(t("Default task points")).setDesc(t("Completed checkbox tasks earn points by completion date. Existing daily task check-ins are deducted to prevent double counting."))
+ .addButton(button => button.setButtonText(String(snapshot.automaticTasks.rate)).onClick(() => new PointAmountModal(this.app, t("Default task points"), t("Task"), snapshot.automaticTasks.rate, async (_label, amount) => {
+ if (amount < 0) throw new Error(t("Enter a positive point cost."));
+ this.plugin.settings.rewards.pointsPerTask = amount; await this.plugin.saveSettings(); await this.refresh();
+ }, true).open()));
+ for (const item of snapshot.summaries.filter(item => this.matches(item.name))) {
+ new Setting(panel).setName(item.name).setDesc(`${t("Points per unit")}: ${numberText(item.rate)} · ${t("Total")}: ${numberText(item.points)}`)
+ .addButton(button => button.setButtonText(t("Edit")).onClick(() => new PointAmountModal(this.app, t("Habit points"), item.name, item.rate, async (_label, rate) => pointsService(this.plugin).saveHabitRate(item.path, rate), true).open()))
+ .addButton(button => button.setButtonText(t("Use default rule")).onClick(() => void pointsService(this.plugin).saveHabitRate(item.path, null)));
+ }
+ }
+ private editRecord(label = "", amount = 1) { new PointAmountModal(this.app, t("Record points"), label, amount, (text, points, date) => pointsService(this.plugin).addRecord(text, points, date)).open(); }
+ private editList(key: "examplePropertyLeft" | "examplePropertyRight") {
+ new PointTextModal(this.app, key === "examplePropertyLeft" ? t("Bonus actions") : t("Reward wishes"), (this.snapshot!.data[key] || []).join("\n"), value => pointsService(this.plugin).saveList(key, value.split(/\r?\n/)), true, t("One bonus per line: name +10. Remove a line to delete the item.")).open();
+ }
+ private confirmRedemption(label: string, cost: number, id?: string) { this.confirm(`${t("Redeem")}: ${label} · ${numberText(cost)}`, () => pointsService(this.plugin).redeem(label, cost, id)); }
+ private confirm(label: string, save: () => Promise) { new PointConfirmModal(this.app, label, async () => { await save(); await this.refresh(); }).open(); }
+ private editRewardShop() {
+ const rows = rewardCatalogRows(this.snapshot!.wishes.map(item => item.text), this.plugin.settings.rewards.rewardItems);
+ new PointTextModal(this.app, t("Reward shop"), rows.map(row => row.text).join("\n"),
+ async value => { await pointsService(this.plugin).saveRewardCatalog(value, rows); await this.refresh(); }, true,
+ t("One reward per line: name -100. Optional stock: name -100 | 3. Use -1 for unlimited stock. Remove a line to delete the item.")).open();
+ }
+
+ private button(parent: HTMLElement, text: string, action: () => void, primary = false) {
+ const button = parent.createEl("button", { text, cls: primary ? "mod-cta" : "" }); button.addEventListener("click", action); return button;
+ }
+}
+
+class PointAmountModal extends Modal {
+ constructor(app: App, private title: string, private label: string, private amount: number,
+ private save: (label: string, amount: number, date: string) => Promise, private allowZero = false) { super(app); }
+ onOpen() {
+ this.setTitle(this.title);
+ let label = this.label, amount = this.amount, date = localPointDate();
+ new Setting(this.contentEl).setName(t("Description")).addText(text => text.setValue(label).onChange(value => label = value));
+ new Setting(this.contentEl).setName(t("Points")).addText(text => text.setValue(String(amount)).onChange(value => amount = Number(value)));
+ if (this.title === t("Record points")) new Setting(this.contentEl).setName(t("Date")).addText(text => { text.inputEl.type = "date"; text.setValue(date).onChange(value => date = value); });
+ new Setting(this.contentEl).addButton(button => button.setButtonText(t("Save")).setCta().onClick(async () => {
+ if (!label.trim() || !Number.isFinite(amount) || !this.allowZero && amount === 0) { new Notice(t("Enter a description and a valid point amount.")); return; }
+ button.setDisabled(true);
+ try { await this.save(label, amount, date); this.close(); } catch (error) { new Notice(String(error)); button.setDisabled(false); }
+ }));
+ }
+}
+class PointTextModal extends Modal {
+ constructor(app: App, private title: string, private value: string, private save: (value: string) => Promise, private multiline = false, private description = "") { super(app); }
+ onOpen() {
+ this.setTitle(this.title); let value = this.value;
+ const setting = new Setting(this.contentEl).setName(this.multiline ? t("One item per line") : t("File path"));
+ if (this.multiline) {
+ this.modalEl.addClass("tg-points-list-modal");
+ setting.settingEl.addClass("tg-points-list-field");
+ if (this.description) setting.setDesc(this.description);
+ setting.addTextArea(text => {
+ text.setValue(value).onChange(next => value = next);
+ text.inputEl.rows = 14;
+ text.inputEl.wrap = "off";
+ text.inputEl.setAttribute("aria-label", this.title);
+ text.inputEl.spellcheck = false;
+ });
+ }
+ else setting.addText(text => text.setValue(value).onChange(next => value = next));
+ new Setting(this.contentEl).addButton(button => button.setButtonText(t("Save")).setCta().onClick(async () => {
+ button.setDisabled(true); try { await this.save(value); this.close(); } catch (error) { new Notice(String(error)); button.setDisabled(false); }
+ }));
+ }
+}
+class PointConfirmModal extends Modal {
+ constructor(app: App, private title: string, private save: () => Promise) { super(app); }
+ onOpen() {
+ this.setTitle(this.title);
+ new Setting(this.contentEl).addButton(button => button.setButtonText(t("Cancel")).onClick(() => this.close()))
+ .addButton(button => button.setButtonText(t("Confirm")).setCta().onClick(async () => {
+ button.setDisabled(true); try { await this.save(); this.close(); } catch (error) { new Notice(String(error)); button.setDisabled(false); }
+ }));
+ }
+}
diff --git a/src/components/features/settings/components/FileSourceSettingsSection.ts b/src/components/features/settings/components/FileSourceSettingsSection.ts
index 9b9a6aa56..e00547191 100644
--- a/src/components/features/settings/components/FileSourceSettingsSection.ts
+++ b/src/components/features/settings/components/FileSourceSettingsSection.ts
@@ -1,3 +1,4 @@
+import { t as settingsText } from "@/translations/helper";
/**
* FileTaskSettings - UI component for File Task configuration
*
@@ -913,7 +914,7 @@ function createStatusMappingSection(
row.createEl("td", { text: example.metadata });
row.createEl("td", { text: "→" });
row.createEl("td", {
- text: example.symbol === " " ? "(space)" : example.symbol,
+ text: example.symbol === " " ? settingsText("(space)") : example.symbol,
});
});
diff --git a/src/components/features/settings/components/SettingsSearchComponent.ts b/src/components/features/settings/components/SettingsSearchComponent.ts
index e21e55f59..8a9312f7a 100644
--- a/src/components/features/settings/components/SettingsSearchComponent.ts
+++ b/src/components/features/settings/components/SettingsSearchComponent.ts
@@ -451,10 +451,10 @@ export class SettingsSearchComponent extends Component {
private getCategoryDisplayName(category: string): string {
const categoryNames: Record = {
core: t("Core Settings"),
- display: t("Display & Progress"),
+ display: t("Views & Display"),
management: t("Task Management"),
workflow: t("Workflow & Automation"),
- gamification: t("Gamification"),
+ gamification: t("Habits and points"),
integration: t("Integration"),
advanced: t("Advanced"),
info: t("Information"),
diff --git a/src/components/features/settings/tabs/AboutSettingsTab.ts b/src/components/features/settings/tabs/AboutSettingsTab.ts
index 244858fb5..94b338da4 100644
--- a/src/components/features/settings/tabs/AboutSettingsTab.ts
+++ b/src/components/features/settings/tabs/AboutSettingsTab.ts
@@ -3,7 +3,6 @@ import { TaskProgressBarSettingTab } from "@/setting";
import { t } from "@/translations/helper";
import { ConfirmModal } from "@/components/ui/modals/ConfirmModal";
import { DEFAULT_SETTINGS } from "@/common/setting-definition";
-import { ONBOARDING_VIEW_TYPE } from "@/components/features/onboarding/OnboardingView";
export function renderAboutSettingsTab(
settingTab: TaskProgressBarSettingTab,
@@ -47,28 +46,6 @@ export function renderAboutSettingsTab(
});
});
- // Onboarding/Help Section
- new Setting(containerEl)
- .setName(t("Onboarding"))
- .setDesc(t("Restart the welcome guide and setup wizard"))
- .addButton((button) => {
- button
- .setButtonText(t("Restart Onboarding"))
- .setIcon("graduation-cap")
- .onClick(async () => {
- // Reset onboarding status
- await settingTab.plugin.onboardingConfigManager.resetOnboarding();
-
- if (typeof (settingTab as any).setting.close === "function") {
- (settingTab as any).setting.close();
-
- settingTab.plugin.app.workspace.getLeaf().setViewState({
- type: ONBOARDING_VIEW_TYPE,
- });
- }
- });
- });
-
new Setting(containerEl)
.setName(t("Reset All Settings"))
.setDesc(t("Reset all settings to their default values"))
diff --git a/src/components/features/settings/tabs/DesktopIntegrationSettingsTab.ts b/src/components/features/settings/tabs/DesktopIntegrationSettingsTab.ts
index 08e9c2e06..48875ff36 100644
--- a/src/components/features/settings/tabs/DesktopIntegrationSettingsTab.ts
+++ b/src/components/features/settings/tabs/DesktopIntegrationSettingsTab.ts
@@ -1,3 +1,4 @@
+import { t as settingsText } from "@/translations/helper";
import { Setting, Platform } from "obsidian";
import { t } from "@/translations/helper";
import { TaskProgressBarSettingTab } from "@/setting";
@@ -182,9 +183,9 @@ export function renderDesktopIntegrationSettingsTab(
};
const mode = s.desktopIntegration.trayMode || "status";
dd.addOptions({
- system: "System tray",
- status: "Status bar",
- both: "Both",
+ system: settingsText("System tray"),
+ status: settingsText("Status bar"),
+ both: settingsText("Both"),
})
.setValue(mode)
.onChange((v) => {
diff --git a/src/components/features/settings/tabs/HabitSettingsTab.ts b/src/components/features/settings/tabs/HabitSettingsTab.ts
index 107997983..061b2d01e 100644
--- a/src/components/features/settings/tabs/HabitSettingsTab.ts
+++ b/src/components/features/settings/tabs/HabitSettingsTab.ts
@@ -1,3 +1,4 @@
+import { t as ht } from "@/integrations/habits/i18n";
import { Setting } from "obsidian";
import { TaskProgressBarSettingTab } from "@/setting";
import { t } from "@/translations/helper";
@@ -22,6 +23,10 @@ export function renderHabitSettingsTab(
.onChange(async (value) => {
settingTab.plugin.settings.habit.enableHabits = value;
settingTab.applySettingsUpdate();
+ if (value) {
+ const integration = await settingTab.plugin.ensureHabitsIntegration();
+ integration.events.trigger("settings-changed");
+ }
});
});
@@ -29,8 +34,19 @@ export function renderHabitSettingsTab(
cls: "habit-settings-container",
});
- // Habit List
- displayHabitList(settingTab, habitContainer);
+ // Keep the settings navigation and layout owned by Task Genius.
+ void settingTab.plugin.ensureHabitsIntegration().then(integration => {
+ if (!habitContainer.isConnected) return;
+ integration.renderSettings(habitContainer.createDiv());
+ if (settingTab.plugin.settings.habit.habits?.length) {
+ const legacy = habitContainer.createEl("details", {cls: "tg-habits-legacy"});
+ legacy.createEl("summary", {text: ht("Existing Task Genius habits")});
+ displayHabitList(settingTab, legacy);
+ }
+ }).catch(error => {
+ habitContainer.createEl("p", {text: ht("Unable to load habits. Check the console for details.")});
+ console.error("Task Genius habit settings", error);
+ });
}
function displayHabitList(
diff --git a/src/components/features/settings/tabs/IcsSettingsTab.ts b/src/components/features/settings/tabs/IcsSettingsTab.ts
index 4036abecc..de9d44a53 100644
--- a/src/components/features/settings/tabs/IcsSettingsTab.ts
+++ b/src/components/features/settings/tabs/IcsSettingsTab.ts
@@ -1,3 +1,4 @@
+import { t as settingsText } from "@/translations/helper";
/**
* ICS Settings Component
* Provides UI for managing ICS calendar sources
@@ -682,7 +683,7 @@ class IcsSourceModal extends Modal {
"text-replacement-header"
);
const titleEl = ruleHeader.createEl("strong", {
- text: rule.name || `Rule ${index + 1}`,
+ text: rule.name || settingsText("Rule {{value0}}", { interpolation: { value0: String(index + 1) } }),
});
const statusEl = ruleHeader.createEl("span", {
@@ -1069,7 +1070,7 @@ class IcsSourceModal extends Modal {
)
.setClass("holiday-setting")
.addText((text) => {
- text.setPlaceholder("{title} ({count} days)")
+ text.setPlaceholder(settingsText("{title} ({count} days)"))
.setValue(
this.source.holidayConfig!.groupDisplayFormat || ""
)
@@ -1482,25 +1483,25 @@ class TextReplacementModal extends Modal {
// Remove prefix example
const example1 = examplesList.createEl("li");
example1.createEl("strong", { text: t("Remove prefix") + ": " });
- example1.createSpan({ text: "Pattern: " });
+ example1.createSpan({ text: settingsText("Pattern: ") });
example1.createEl("code", { text: "^Meeting: " });
- example1.createSpan({ text: ", Replacement: " });
+ example1.createSpan({ text: settingsText(", Replacement: ") });
example1.createEl("code", { text: "" });
// Replace room numbers example
const example2 = examplesList.createEl("li");
example2.createEl("strong", { text: t("Replace room numbers") + ": " });
- example2.createSpan({ text: "Pattern: " });
+ example2.createSpan({ text: settingsText("Pattern: ") });
example2.createEl("code", { text: "Room (\\d+)" });
- example2.createSpan({ text: ", Replacement: " });
+ example2.createSpan({ text: settingsText(", Replacement: ") });
example2.createEl("code", { text: "Conference Room $1" });
// Swap words example
const example3 = examplesList.createEl("li");
example3.createEl("strong", { text: t("Swap words") + ": " });
- example3.createSpan({ text: "Pattern: " });
+ example3.createSpan({ text: settingsText("Pattern: ") });
example3.createEl("code", { text: "(\\w+) with (\\w+)" });
- example3.createSpan({ text: ", Replacement: " });
+ example3.createSpan({ text: settingsText(", Replacement: ") });
example3.createEl("code", { text: "$2 and $1" });
// Test section
diff --git a/src/components/features/settings/tabs/IndexSettingsTab.ts b/src/components/features/settings/tabs/IndexSettingsTab.ts
index e4c9ce038..98b285e8e 100644
--- a/src/components/features/settings/tabs/IndexSettingsTab.ts
+++ b/src/components/features/settings/tabs/IndexSettingsTab.ts
@@ -1,3 +1,4 @@
+import { t as settingsText } from "@/translations/helper";
import { Setting, Notice, setIcon } from "obsidian";
import { TaskProgressBarSettingTab } from "@/setting";
import { t } from "@/translations/helper";
@@ -13,7 +14,7 @@ import { FileSourceConfiguration } from "@/types/file-source";
/**
* Renders the Index Settings tab that consolidates all indexing-related settings
- * including Inline Tasks, File Tasks, and Project detection
+ * including Inline Tasks, Whole-note tasks, and Project detection
*/
export function renderIndexSettingsTab(
settingTab: TaskProgressBarSettingTab,
@@ -21,10 +22,10 @@ export function renderIndexSettingsTab(
) {
// Main heading
new Setting(containerEl)
- .setName(t("Index & Task Source Configuration"))
+ .setName(t("Where tasks come from"))
.setDesc(
t(
- "Configure how Task Genius discovers and indexes tasks from various sources including inline tasks, file metadata, and projects.",
+ "Task Genius reads checkboxes in your notes. You can also use an entire note as a task.",
),
)
.setHeading();
@@ -32,24 +33,6 @@ export function renderIndexSettingsTab(
// ========================================
// SECTION 0: Core Architecture Configuration
// ========================================
- new Setting(containerEl)
- .setName(t("Enable Indexer"))
- .addToggle((toggle) => {
- toggle.setValue(settingTab.plugin.settings.enableIndexer ?? true);
- toggle.onChange(async (value) => {
- settingTab.plugin.settings.enableIndexer = value;
- settingTab.applySettingsUpdate();
- settingTab.display(); // Refresh settings display
-
- // Show restart notice
- new Notice(
- t(
- "Please restart Obsidian for the Indexer change to take effect.",
- ),
- 8000,
- );
- });
- });
// ========================================
// SECTION 1: Task Source Configuration
@@ -71,7 +54,7 @@ export function renderIndexSettingsTab(
setIcon(inlineTabIcon, "check-square");
inlineSwitcherButton
.createSpan({ cls: "fluent-view-tab-label" })
- .setText(t("Checkbox Tasks"));
+ .setText(t("Tasks in notes"));
const fileSwitcherButton = switcherRow.createEl("button", {
cls: "fluent-view-tab clickable-icon",
@@ -82,7 +65,7 @@ export function renderIndexSettingsTab(
setIcon(fileTabIcon, "file-text");
fileSwitcherButton
.createSpan({ cls: "fluent-view-tab-label" })
- .setText(t("File Tasks"));
+ .setText(t("Whole-note tasks"));
const sourcePanels = taskSourceWrapper.createDiv({
cls: "tg-index-task-source-panels",
@@ -97,60 +80,25 @@ export function renderIndexSettingsTab(
// Inline task configuration content is rendered into inlineContainer
(() => {
let containerEl: HTMLElement = inlineContainer;
- const inlineContentEnabled = scopeControls.inlineTasksEnabled !== false;
-
- new Setting(containerEl)
- .setName(t("Enable checkbox tasks"))
- .setDesc(
- t(
- "Index markdown checkbox tasks. Disable this if you only want to use file-based or external task sources.",
- ),
- )
- .addToggle((toggle) => {
- toggle.setValue(inlineContentEnabled);
- toggle.onChange((value) => {
- const controls = ensureScopeControls(
- settingTab.plugin.settings,
- );
- controls.inlineTasksEnabled = value;
- settingTab.applySettingsUpdate();
- if (!value) {
- new Notice(
- t(
- "Checkbox task indexing disabled. The index will prune inline tasks shortly.",
- ),
- 6000,
- );
- }
- updateInlineBodyState(value);
- });
- });
-
- const inlineBodyEl = containerEl.createDiv({
- cls: "tg-source-settings-body",
- });
- const updateInlineBodyState = (enabled: boolean) => {
- inlineBodyEl.classList.toggle("tg-source-disabled", !enabled);
- };
- updateInlineBodyState(inlineContentEnabled);
+ const inlineBodyEl = containerEl.createDiv({ cls: "tg-source-settings-body" });
containerEl = inlineBodyEl;
new Setting(containerEl)
- .setName(t("Inline task parsing"))
- .setDesc(t("Configure how tasks are parsed from markdown content."))
+ .setName(t("Task writing format"))
+ .setDesc(t("Existing task dates and priorities are read automatically."))
.setHeading();
new Setting(containerEl)
- .setName(t("Prefer metadata format of task"))
+ .setName(t("Save dates and priorities as"))
.setDesc(
t(
- "You can choose dataview format or tasks format, that will influence both index and save format.",
+ "Choose how new dates and priorities appear in your notes. Existing tasks do not need conversion.",
),
)
.addDropdown((dropdown) => {
dropdown
- .addOption("dataview", "Dataview")
- .addOption("tasks", "Tasks")
+ .addOption("dataview", t("Inline properties"))
+ .addOption("tasks", t("Task icons (recommended)"))
.setValue(settingTab.plugin.settings.preferMetadataFormat)
.onChange(async (value) => {
settingTab.plugin.settings.preferMetadataFormat =
@@ -163,183 +111,11 @@ export function renderIndexSettingsTab(
});
});
- // Date Format Configuration
- new Setting(containerEl)
- .setName(t("Enable custom date formats"))
- .setDesc(
- t(
- "Enable custom date format patterns for parsing dates. When enabled, the parser will try your custom formats before falling back to default formats.",
- ),
- )
- .addToggle((toggle) => {
- toggle
- .setValue(
- settingTab.plugin.settings.enableCustomDateFormats ??
- false,
- )
- .onChange((value) => {
- settingTab.plugin.settings.enableCustomDateFormats =
- value;
- settingTab.applySettingsUpdate();
- settingTab.display(); // Refresh to show/hide custom formats settings
- });
- });
-
- if (settingTab.plugin.settings.enableCustomDateFormats) {
- new Setting(containerEl)
- .setName(t("Custom date formats"))
- .setDesc(t("Configure custom date format patterns."))
- .addButton((button) => {
- const getCustomFormats = () => {
- return (
- settingTab.plugin.settings.customDateFormats ?? []
- );
- };
-
- const updateButtonText = () => {
- const formats = getCustomFormats();
- if (formats.length === 0) {
- button.setButtonText(t("Configure Date Formats"));
- } else {
- button.setButtonText(
- t("{{count}} format(s) configured", {
- interpolation: {
- count: formats.length.toString(),
- },
- }),
- );
- }
- };
-
- updateButtonText();
- button.onClick(() => {
- new ListConfigModal(settingTab.plugin, {
- title: t("Configure Custom Date Formats"),
- description: t(
- "Add custom date format patterns. Date patterns: yyyy (4-digit year), yy (2-digit year), MM (2-digit month), M (1-2 digit month), dd (2-digit day), d (1-2 digit day), MMM (short month name), MMMM (full month name). Time patterns: HH (2-digit hour), mm (2-digit minute), ss (2-digit second). Use single quotes for literals (e.g., 'T' for ISO format).",
- ),
- placeholder: t(
- "Enter date format (e.g., yyyy-MM-dd or yyyyMMdd_HHmmss)",
- ),
- values: getCustomFormats(),
- onSave: (values) => {
- settingTab.plugin.settings.customDateFormats =
- values;
- settingTab.applySettingsUpdate();
- updateButtonText();
- new Notice(
- t(
- "Date formats updated. The parser will now recognize these custom formats.",
- ),
- 6000,
- );
- },
- }).open();
- });
- });
-
- // Add example dates section
- const examplesContainer = containerEl.createDiv({
- cls: "task-genius-date-examples",
- });
-
- examplesContainer.createEl("h4", {
- text: t("Format Examples:"),
- cls: "task-genius-examples-header",
- });
-
- const exampleFormats = [
- { format: "yyyy-MM-dd", example: "2025-08-16" },
- { format: "dd/MM/yyyy", example: "16/08/2025" },
- { format: "MM-dd-yyyy", example: "08-16-2025" },
- { format: "yyyy.MM.dd", example: "2025.08.16" },
- { format: "yyyyMMdd", example: "20250816" },
- { format: "yyyyMMdd_HHmmss", example: "20250816_144403" },
- { format: "yyyyMMddHHmmss", example: "20250816144403" },
- { format: "yyyy-MM-dd'T'HH:mm", example: "2025-08-16T14:44" },
- { format: "dd MMM yyyy", example: "16 Aug 2025" },
- { format: "MMM dd, yyyy", example: "Aug 16, 2025" },
- { format: "yyyy年MM月dd日", example: "2025年08月16日" },
- ];
-
- const table = examplesContainer.createEl("table", {
- cls: "task-genius-date-examples-table",
- });
-
- const headerRow = table.createEl("tr");
- headerRow.createEl("th", { text: t("Format Pattern") });
- headerRow.createEl("th", { text: t("Example") });
-
- exampleFormats.forEach(({ format, example }) => {
- const row = table.createEl("tr");
- row.createEl("td", { text: format });
- row.createEl("td", { text: example });
- });
- }
-
- // Get current metadata format to show appropriate settings
- const isDataviewFormat =
- settingTab.plugin.settings.preferMetadataFormat === "dataview";
-
- // Project tag prefix
new Setting(containerEl)
- .setName(t("Project tag prefix"))
- .setDesc(
- isDataviewFormat
- ? t(
- "Customize the prefix used for project tags in dataview format (e.g., 'project' for [project:: myproject]). Changes require reindexing.",
- )
- : t(
- "Customize the prefix used for project tags (e.g., 'project' for #project/myproject). Changes require reindexing.",
- ),
- )
- .addText((text) => {
- text.setPlaceholder("project")
- .setValue(
- settingTab.plugin.settings.projectTagPrefix[
- settingTab.plugin.settings.preferMetadataFormat
- ],
- )
- .onChange(async (value) => {
- settingTab.plugin.settings.projectTagPrefix[
- settingTab.plugin.settings.preferMetadataFormat
- ] = value || "project";
- settingTab.applySettingsUpdate();
- });
- });
-
- // Context tag prefix with special handling
- new Setting(containerEl)
- .setName(t("Context tag prefix"))
- .setDesc(
- isDataviewFormat
- ? t(
- "Customize the prefix used for context tags in dataview format (e.g., 'context' for [context:: home]). Changes require reindexing.",
- )
- : t(
- "Customize the prefix used for context tags (e.g., '@home' for @home). Changes require reindexing.",
- ),
- )
- .addText((text) => {
- text.setPlaceholder("context")
- .setValue(
- settingTab.plugin.settings.contextTagPrefix[
- settingTab.plugin.settings.preferMetadataFormat
- ],
- )
- .onChange(async (value) => {
- settingTab.plugin.settings.contextTagPrefix[
- settingTab.plugin.settings.preferMetadataFormat
- ] = value || (isDataviewFormat ? "context" : "@");
- settingTab.applySettingsUpdate();
- });
- });
-
- new Setting(containerEl)
- .setName(t("Ignore all tasks behind heading"))
+ .setName(t("Exclude tasks in these sections"))
.setDesc(
t(
- "Configure headings to ignore. Tasks under these headings will be excluded from indexing.",
+ "For example, exclude tasks below an Archive heading. Leave blank to include all sections.",
),
)
.addButton((button) => {
@@ -393,10 +169,10 @@ export function renderIndexSettingsTab(
});
new Setting(containerEl)
- .setName(t("Focus all tasks behind heading"))
+ .setName(t("Only include tasks in these sections"))
.setDesc(
t(
- "Configure headings to focus on. Only tasks under these headings will be included in indexing.",
+ "Optional: only read tasks below the selected headings. Leave blank to include all sections.",
),
)
.addButton((button) => {
@@ -449,10 +225,10 @@ export function renderIndexSettingsTab(
});
new Setting(containerEl)
- .setName(t("Use daily note path as date"))
+ .setName(t("Use the journal date for tasks"))
.setDesc(
t(
- "If enabled, the daily note path will be used as the date for tasks.",
+ "Use the date in the journal filename when arranging its tasks.",
),
)
.addToggle((toggle) => {
@@ -809,61 +585,6 @@ export function renderIndexSettingsTab(
setActiveTaskSourcePanel("file"),
);
- // ========================================
- // SECTION 3: Performance Settings
- // ========================================
- new Setting(containerEl)
- .setName(t("Performance Configuration"))
- .setDesc(t("Configure performance-related indexing settings"))
- .setHeading();
-
- new Setting(containerEl)
- .setName(t("Enable worker processing"))
- .setDesc(
- t(
- "Use background worker for file parsing to improve performance. Recommended for large vaults.",
- ),
- )
- .addToggle((toggle) => {
- // Use the new fileSource.performance.enableWorkerProcessing setting
- toggle.setValue(
- settingTab.plugin.settings.fileSource?.performance
- ?.enableWorkerProcessing ?? true,
- );
- toggle.onChange((value) => {
- // Ensure fileSource and performance objects exist
- if (!settingTab.plugin.settings.fileSource) {
- // Initialize with minimal required properties
- settingTab.plugin.settings.fileSource = {
- enabled: false,
- performance: {
- enableWorkerProcessing: true,
- enableCaching: true,
- cacheTTL: 300000,
- },
- } as any;
- }
- if (!settingTab.plugin.settings.fileSource.performance) {
- settingTab.plugin.settings.fileSource.performance = {
- enableWorkerProcessing: true,
- enableCaching: true,
- cacheTTL: 300000,
- };
- }
- // Update the setting
- settingTab.plugin.settings.fileSource.performance.enableWorkerProcessing =
- value;
-
- // Also update the legacy fileParsingConfig for backward compatibility
- if (settingTab.plugin.settings.fileParsingConfig) {
- settingTab.plugin.settings.fileParsingConfig.enableWorkerProcessing =
- value;
- }
-
- settingTab.applySettingsUpdate();
- });
- });
-
// ========================================
// SECTION 5: Index Maintenance
// ========================================
diff --git a/src/components/features/settings/tabs/InterfaceSettingsTab.ts b/src/components/features/settings/tabs/InterfaceSettingsTab.ts
index 6449fd5e8..35e658343 100644
--- a/src/components/features/settings/tabs/InterfaceSettingsTab.ts
+++ b/src/components/features/settings/tabs/InterfaceSettingsTab.ts
@@ -177,44 +177,7 @@ export function renderInterfaceSettingsTab(
});
});
- // Max Other Views before overflow threshold
- new Setting(fluentSettingsContainer)
- .setName(t("Max other views before overflow"))
- .setDesc(
- t(
- "Number of 'Other Views' to show before grouping the rest into an overflow menu (ellipsis)"
- )
- )
- .addText((text) => {
- const current =
- settingTab.plugin.settings.fluentView?.fluentConfig
- ?.maxOtherViewsBeforeOverflow ?? 5;
- text.setPlaceholder("5")
- .setValue(String(current))
- .onChange(async (value) => {
- const n = parseInt(value, 10);
- if (!isNaN(n) && n >= 1 && n <= 50) {
- if (!settingTab.plugin.settings.fluentView) {
- settingTab.plugin.settings.fluentView = {
- enableFluent: false,
- };
- }
- if (
- !settingTab.plugin.settings.fluentView
- .fluentConfig
- ) {
- settingTab.plugin.settings.fluentView.fluentConfig =
- {
- enableWorkspaces: true,
- defaultWorkspace: "default",
- };
- }
- settingTab.plugin.settings.fluentView.fluentConfig.maxOtherViewsBeforeOverflow =
- n;
- await settingTab.plugin.saveSettings();
- }
- });
- });
+
};
// Initial render of Fluent-specific settings
diff --git a/src/components/features/settings/tabs/McpIntegrationSettingsTab.ts b/src/components/features/settings/tabs/McpIntegrationSettingsTab.ts
index 75a48094c..c080b9a54 100644
--- a/src/components/features/settings/tabs/McpIntegrationSettingsTab.ts
+++ b/src/components/features/settings/tabs/McpIntegrationSettingsTab.ts
@@ -1,3 +1,4 @@
+import { t as settingsText } from "@/translations/helper";
/**
* MCP Integration Settings Tab Component
*/
@@ -172,10 +173,10 @@ export function renderMcpIntegrationSettingsTab(
)
.addDropdown((dropdown) => {
dropdown
- .addOption("127.0.0.1", "127.0.0.1 (Local only)")
+ .addOption("127.0.0.1", settingsText("127.0.0.1 (Local only)"))
.addOption(
"0.0.0.0",
- "0.0.0.0 (All interfaces - for external access)"
+ settingsText("0.0.0.0 (All interfaces - for external access)")
)
.setValue(plugin.settings.mcpIntegration?.host || "127.0.0.1")
.onChange(async (value) => {
@@ -605,7 +606,7 @@ export function renderMcpIntegrationSettingsTab(
// Method A
const methodAItem = authList.createEl("li");
- methodAItem.createEl("strong", { text: "Method A (Custom Header):" });
+ methodAItem.createEl("strong", { text: settingsText("Method A (Custom Header):") });
methodAItem.appendText(" ");
methodAItem.createEl("code", { text: `mcp-app-id: ${appId}` });
methodAItem.appendText(" + ");
@@ -615,7 +616,7 @@ export function renderMcpIntegrationSettingsTab(
// Method B
const methodBItem = authList.createEl("li");
- methodBItem.createEl("strong", { text: "Method B (Combined Bearer):" });
+ methodBItem.createEl("strong", { text: settingsText("Method B (Combined Bearer):") });
methodBItem.appendText(" ");
methodBItem.createEl("code", {
text: `Authorization: Bearer ${authToken}+${appId}`,
@@ -1010,7 +1011,7 @@ export function renderMcpIntegrationSettingsTab(
const endpointContent = endpointBox.createDiv("mcp-endpoint-content");
const endpointLabel = endpointContent.createSpan("mcp-endpoint-label");
- endpointLabel.setText("URL: ");
+ endpointLabel.setText(settingsText("URL: "));
const endpointUrl = serverUrl;
endpointContent.createEl("code", {
@@ -1165,7 +1166,7 @@ export function renderMcpIntegrationSettingsTab(
"mcp-example-block active"
);
curlExample.createEl("div", {
- text: "1) Initialize",
+ text: settingsText("1) Initialize"),
cls: "mcp-example-subtitle",
});
const curlPreInit = curlExample.createEl("pre", {
@@ -1190,7 +1191,7 @@ export function renderMcpIntegrationSettingsTab(
}
curlExample.createEl("div", {
- text: "2) Call tool with session id",
+ text: settingsText("2) Call tool with session id"),
cls: "mcp-example-subtitle",
});
const curlPreCall = curlExample.createEl("pre", {
@@ -1219,7 +1220,7 @@ export function renderMcpIntegrationSettingsTab(
// JavaScript example (Init + Call)
const jsExample = exampleCodeContainer.createDiv("mcp-example-block");
jsExample.createEl("div", {
- text: "1) Initialize",
+ text: settingsText("1) Initialize"),
cls: "mcp-example-subtitle",
});
const jsPreInit = jsExample.createEl("pre", {
@@ -1237,7 +1238,7 @@ export function renderMcpIntegrationSettingsTab(
}
jsExample.createEl("div", {
- text: "2) Call tool with session id",
+ text: settingsText("2) Call tool with session id"),
cls: "mcp-example-subtitle",
});
const jsPreCall = jsExample.createEl("pre", {
@@ -1258,7 +1259,7 @@ export function renderMcpIntegrationSettingsTab(
const pythonExample =
exampleCodeContainer.createDiv("mcp-example-block");
pythonExample.createEl("div", {
- text: "1) Initialize",
+ text: settingsText("1) Initialize"),
cls: "mcp-example-subtitle",
});
const pythonPreInit = pythonExample.createEl("pre", {
@@ -1301,7 +1302,7 @@ print(f"Session ID: {session_id}")`,
}
pythonExample.createEl("div", {
- text: "2) Call tool with session id",
+ text: settingsText("2) Call tool with session id"),
cls: "mcp-example-subtitle",
});
const pythonPreCall = pythonExample.createEl("pre", {
diff --git a/src/components/features/settings/tabs/ProgressSettingsTab.ts b/src/components/features/settings/tabs/ProgressSettingsTab.ts
index b4837d17a..a37cf5001 100644
--- a/src/components/features/settings/tabs/ProgressSettingsTab.ts
+++ b/src/components/features/settings/tabs/ProgressSettingsTab.ts
@@ -1,3 +1,4 @@
+import { t as settingsText } from "@/translations/helper";
import { Setting, TextAreaComponent } from "obsidian";
import { DEFAULT_SETTINGS } from "@/common/setting-definition";
import { t } from "@/translations/helper";
@@ -471,7 +472,7 @@ function displayNumberToProgressbar(
);
previewEl.setText(`${t("Preview")}: ${renderedText}`);
} catch (error) {
- previewEl.setText(`${t("Preview")}: Error`);
+ previewEl.setText(settingsText("{{value0}}: Error", { interpolation: { value0: String(t("Preview")) } }));
previewEl.addClass("expression-preview-error");
}
@@ -586,7 +587,7 @@ function addProgressRangesSettings(
})
)
.addButton((button) => {
- button.setButtonText("Delete").onClick(async () => {
+ button.setButtonText(settingsText("Delete")).onClick(async () => {
settingTab.plugin.settings.progressRanges.splice(index, 1);
settingTab.applySettingsUpdate();
settingTab.display();
@@ -628,7 +629,7 @@ function addProgressRangesSettings(
})
)
.addButton((button) => {
- button.setButtonText("Add").onClick(async () => {
+ button.setButtonText(settingsText("Add")).onClick(async () => {
const settingsContainer = button.buttonEl.parentElement;
if (!settingsContainer) return;
@@ -730,7 +731,7 @@ function updateFormatPreview(
previewContainer.setText(renderedText);
previewContainer.removeClass("custom-format-preview-error");
} catch (error) {
- previewContainer.setText("Error rendering format");
+ previewContainer.setText(settingsText("Error rendering format"));
previewContainer.addClass("custom-format-preview-error");
}
}
diff --git a/src/components/features/settings/tabs/ProjectSettingsTab.ts b/src/components/features/settings/tabs/ProjectSettingsTab.ts
index c9660837a..ba972f637 100644
--- a/src/components/features/settings/tabs/ProjectSettingsTab.ts
+++ b/src/components/features/settings/tabs/ProjectSettingsTab.ts
@@ -1,820 +1,14 @@
import { Setting } from "obsidian";
-import { TaskProgressBarSettingTab } from "@/setting";
+import type { TaskProgressBarSettingTab } from "@/setting";
+import { ProjectFileManager, ProjectCreateModal, ProjectArchiveModal } from "@/managers/project-file-manager";
import { t } from "@/translations/helper";
-export function renderProjectSettingsTab(
- settingTab: TaskProgressBarSettingTab,
- containerEl: HTMLElement,
-) {
- new Setting(containerEl)
- .setName(t("Project Management"))
- .setDesc(
- t("Configure project display, organization and metadata mappings"),
- )
- .setHeading();
-
- // Initialize projectConfig if it doesn't exist
- if (!settingTab.plugin.settings.projectConfig) {
- settingTab.plugin.settings.projectConfig = {
- enableEnhancedProject: false,
- pathMappings: [],
- metadataConfig: {
- metadataKey: "project",
- enabled: false,
- },
- configFile: {
- fileName: "project.md",
- searchRecursively: true,
- enabled: false,
- },
- metadataMappings: [],
- defaultProjectNaming: {
- strategy: "filename",
- stripExtension: true,
- enabled: false,
- },
- };
- }
-
- // Main enhanced project features toggle
- new Setting(containerEl)
- .setName(t("Enable project features"))
- .setDesc(
- t(
- "Enable path-based, metadata-based, and config file-based project detection",
- ),
- )
- .addToggle((toggle) => {
- toggle
- .setValue(
- settingTab.plugin.settings.projectConfig
- ?.enableEnhancedProject || false,
- )
- .onChange(async (value) => {
- if (!settingTab.plugin.settings.projectConfig) {
- settingTab.plugin.settings.projectConfig = {
- enableEnhancedProject: false,
- pathMappings: [],
- metadataConfig: {
- metadataKey: "project",
- enabled: false,
- },
- configFile: {
- fileName: "project.md",
- searchRecursively: true,
- enabled: false,
- },
- metadataMappings: [],
- defaultProjectNaming: {
- strategy: "filename",
- stripExtension: true,
- enabled: false,
- },
- };
- }
- settingTab.plugin.settings.projectConfig.enableEnhancedProject =
- value;
- await settingTab.plugin.saveSettings();
- setTimeout(() => {
- settingTab.display();
- }, 200);
- });
- });
-
- if (settingTab.plugin.settings.projectConfig?.enableEnhancedProject) {
- // Always show project management settings
- new Setting(containerEl)
- .setName(t("Path-based Project Mappings"))
- .setDesc(t("Configure project names based on file paths"))
- .setHeading();
-
- const pathMappingsContainer = containerEl.createDiv({
- cls: "project-path-mappings-container",
- });
-
- const refreshPathMappings = () => {
- pathMappingsContainer.empty();
-
- // Ensure pathMappings is always an array
- if (!settingTab.plugin.settings.projectConfig) {
- settingTab.plugin.settings.projectConfig = {
- enableEnhancedProject: false,
- pathMappings: [],
- metadataConfig: {
- metadataKey: "project",
-
- enabled: false,
- },
- configFile: {
- fileName: "project.md",
- searchRecursively: true,
- enabled: false,
- },
- metadataMappings: [],
- defaultProjectNaming: {
- strategy: "filename",
- stripExtension: true,
- enabled: false,
- },
- };
- }
-
- if (
- !settingTab.plugin.settings.projectConfig.pathMappings ||
- !Array.isArray(
- settingTab.plugin.settings.projectConfig.pathMappings,
- )
- ) {
- settingTab.plugin.settings.projectConfig.pathMappings = [];
- }
-
- const pathMappings =
- settingTab.plugin.settings.projectConfig?.pathMappings || [];
-
- if (pathMappings.length === 0) {
- pathMappingsContainer.createDiv({
- cls: "no-mappings-message",
- text: t("No path mappings configured yet."),
- });
- }
-
- pathMappings.forEach((mapping, index) => {
- const mappingRow = pathMappingsContainer.createDiv({
- cls: "project-path-mapping-row",
- });
-
- new Setting(mappingRow)
- .setName(`${t("Mapping")} ${index + 1}`)
- .addText((text) => {
- text.setPlaceholder(
- t("Path pattern (e.g., Projects/Work)"),
- )
- .setValue(mapping.pathPattern)
- .onChange(async (value) => {
- if (settingTab.plugin.settings.projectConfig) {
- settingTab.plugin.settings.projectConfig.pathMappings[
- index
- ].pathPattern = value;
- await settingTab.plugin.saveSettings();
- }
- });
- })
- .addText((text) => {
- text.setPlaceholder(t("Project name"))
- .setValue(mapping.projectName)
- .onChange(async (value) => {
- if (settingTab.plugin.settings.projectConfig) {
- settingTab.plugin.settings.projectConfig.pathMappings[
- index
- ].projectName = value;
- await settingTab.plugin.saveSettings();
- }
- });
- })
- .addToggle((toggle) => {
- toggle
- .setTooltip(t("Enabled"))
- .setValue(mapping.enabled)
- .onChange(async (value) => {
- if (settingTab.plugin.settings.projectConfig) {
- settingTab.plugin.settings.projectConfig.pathMappings[
- index
- ].enabled = value;
- await settingTab.plugin.saveSettings();
- }
- });
- })
- .addButton((button) => {
- button
- .setIcon("trash")
- .setTooltip(t("Remove"))
- .onClick(async () => {
- if (settingTab.plugin.settings.projectConfig) {
- settingTab.plugin.settings.projectConfig.pathMappings.splice(
- index,
- 1,
- );
- await settingTab.plugin.saveSettings();
- refreshPathMappings();
- }
- });
- });
- });
-
- // Add new mapping button
- new Setting(pathMappingsContainer).addButton((button) => {
- button
- .setButtonText(t("Add Path Mapping"))
- .setCta()
- .onClick(async () => {
- // Ensure projectConfig exists
- if (!settingTab.plugin.settings.projectConfig) {
- settingTab.plugin.settings.projectConfig = {
- enableEnhancedProject: true,
- pathMappings: [],
- metadataConfig: {
- metadataKey: "project",
-
- enabled: false,
- },
- configFile: {
- fileName: "project.md",
- searchRecursively: true,
- enabled: false,
- },
- metadataMappings: [],
- defaultProjectNaming: {
- strategy: "filename",
- stripExtension: true,
- enabled: false,
- },
- };
- }
-
- // Ensure pathMappings is an array
- if (
- !Array.isArray(
- settingTab.plugin.settings.projectConfig
- .pathMappings,
- )
- ) {
- settingTab.plugin.settings.projectConfig.pathMappings =
- [];
- }
-
- // Add new mapping
- settingTab.plugin.settings.projectConfig.pathMappings.push(
- {
- pathPattern: "",
- projectName: "",
- enabled: true,
- },
- );
-
- await settingTab.plugin.saveSettings();
- setTimeout(() => {
- refreshPathMappings();
- }, 100);
- });
- });
- };
-
- refreshPathMappings();
-
- // Metadata-based project detection settings
- new Setting(containerEl)
- .setName(t("Metadata-based Project Detection"))
- .setDesc(t("Configure project detection from file frontmatter"))
- .setHeading();
-
- new Setting(containerEl)
- .setName(t("Enable metadata project detection"))
- .setDesc(t("Detect project from file frontmatter metadata"))
- .addToggle((toggle) => {
- toggle
- .setValue(
- settingTab.plugin.settings.projectConfig?.metadataConfig
- ?.enabled || false,
- )
- .onChange(async (value) => {
- if (
- settingTab.plugin.settings.projectConfig
- ?.metadataConfig
- ) {
- settingTab.plugin.settings.projectConfig.metadataConfig.enabled =
- value;
- await settingTab.plugin.saveSettings();
- }
- });
- });
-
- new Setting(containerEl)
- .setName(t("Metadata key"))
- .setDesc(t("The frontmatter key to use for project name"))
- .addText((text) => {
- text.setPlaceholder("project")
- .setValue(
- settingTab.plugin.settings.projectConfig?.metadataConfig
- ?.metadataKey || "project",
- )
- .onChange(async (value) => {
- if (
- settingTab.plugin.settings.projectConfig
- ?.metadataConfig
- ) {
- settingTab.plugin.settings.projectConfig.metadataConfig.metadataKey =
- value || "project";
- await settingTab.plugin.saveSettings();
- }
- });
- });
-
- // Config file-based project detection settings
- new Setting(containerEl)
- .setName(t("Config File-based Project Detection"))
- .setDesc(
- t(
- "Configure project detection from project configuration files",
- ),
- )
- .setHeading();
-
- new Setting(containerEl)
- .setName(t("Enable config file project detection"))
- .setDesc(t("Detect project from project configuration files"))
- .addToggle((toggle) => {
- toggle
- .setValue(
- settingTab.plugin.settings.projectConfig?.configFile
- ?.enabled || false,
- )
- .onChange(async (value) => {
- if (
- settingTab.plugin.settings.projectConfig?.configFile
- ) {
- settingTab.plugin.settings.projectConfig.configFile.enabled =
- value;
- await settingTab.plugin.saveSettings();
- }
- });
- });
-
- new Setting(containerEl)
- .setName(t("Config file name"))
- .setDesc(t("Name of the project configuration file"))
- .addText((text) => {
- text.setPlaceholder("project.md")
- .setValue(
- settingTab.plugin.settings.projectConfig?.configFile
- ?.fileName || "project.md",
- )
- .onChange(async (value) => {
- if (
- settingTab.plugin.settings.projectConfig?.configFile
- ) {
- settingTab.plugin.settings.projectConfig.configFile.fileName =
- value || "project.md";
- await settingTab.plugin.saveSettings();
- }
- });
- });
-
- // Custom Project Detection Methods
- new Setting(containerEl)
- .setName(t("Custom Project Detection Methods"))
- .setDesc(t("Configure additional methods to detect project files"))
- .setHeading();
-
- const detectionMethodsContainer = containerEl.createDiv({
- cls: "project-detection-methods-container",
- });
-
- const refreshDetectionMethods = () => {
- detectionMethodsContainer.empty();
-
- // Ensure detectionMethods exists
- if (
- !settingTab.plugin.settings.projectConfig?.metadataConfig
- ?.detectionMethods
- ) {
- if (settingTab.plugin.settings.projectConfig?.metadataConfig) {
- settingTab.plugin.settings.projectConfig.metadataConfig.detectionMethods =
- [];
- }
- }
-
- const methods =
- settingTab.plugin.settings.projectConfig?.metadataConfig
- ?.detectionMethods || [];
-
- methods.forEach((method, index) => {
- const methodDiv = detectionMethodsContainer.createDiv({
- cls: "project-detection-method",
- });
-
- new Setting(methodDiv)
- .setName(`${t("Method")} ${index + 1}`)
- .addDropdown((dropdown) => {
- dropdown
- .addOption("metadata", t("Metadata Property"))
- .addOption("tag", t("Tag"))
- .addOption("link", t("Linked Note"))
- .setValue(method.type)
- .onChange(async (value) => {
- method.type = value as
- | "metadata"
- | "tag"
- | "link";
- await settingTab.plugin.saveSettings();
- refreshDetectionMethods();
- });
- })
- .addText((text) => {
- const placeholder =
- method.type === "metadata"
- ? "project"
- : method.type === "tag"
- ? "project"
- : "category";
- text.setPlaceholder(placeholder)
- .setValue(method.propertyKey)
- .onChange(async (value) => {
- method.propertyKey = value;
- await settingTab.plugin.saveSettings();
- });
- })
- .addToggle((toggle) => {
- toggle
- .setValue(method.enabled)
- .onChange(async (value) => {
- method.enabled = value;
- await settingTab.plugin.saveSettings();
- });
- })
- .addButton((button) => {
- button
- .setIcon("trash")
- .setTooltip(t("Remove"))
- .onClick(async () => {
- methods.splice(index, 1);
- await settingTab.plugin.saveSettings();
- refreshDetectionMethods();
- });
- });
-
- // Add link filter field for link type
- if (method.type === "link") {
- new Setting(methodDiv)
- .setName(t("Link Filter"))
- .setDesc(
- t(
- "Optional: Only match links containing this text",
- ),
- )
- .addText((text) => {
- text.setPlaceholder("Projects/")
- .setValue(method.linkFilter || "")
- .onChange(async (value) => {
- method.linkFilter = value;
- await settingTab.plugin.saveSettings();
- });
- });
- }
- });
-
- // Add new method button
- new Setting(detectionMethodsContainer).addButton((button) => {
- button
- .setButtonText(t("Add Detection Method"))
- .setCta()
- .onClick(async () => {
- if (
- !settingTab.plugin.settings.projectConfig
- ?.metadataConfig?.detectionMethods
- ) {
- if (
- settingTab.plugin.settings.projectConfig
- ?.metadataConfig
- ) {
- settingTab.plugin.settings.projectConfig.metadataConfig.detectionMethods =
- [];
- }
- }
- settingTab.plugin.settings.projectConfig?.metadataConfig?.detectionMethods?.push(
- {
- type: "metadata",
- propertyKey: "",
- enabled: false,
- },
- );
- await settingTab.plugin.saveSettings();
- refreshDetectionMethods();
- });
- });
- };
-
- refreshDetectionMethods();
-
- // Metadata mappings section
- new Setting(containerEl)
- .setName(t("Metadata Mappings"))
- .setDesc(
- t("Configure how metadata fields are mapped and transformed"),
- )
- .setHeading();
-
- const metadataMappingsContainer = containerEl.createDiv({
- cls: "project-metadata-mappings-container",
- });
-
- const refreshMetadataMappings = () => {
- metadataMappingsContainer.empty();
-
- // Ensure metadataMappings is always an array
- if (
- !settingTab.plugin.settings.projectConfig?.metadataMappings ||
- !Array.isArray(
- settingTab.plugin.settings.projectConfig.metadataMappings,
- )
- ) {
- if (settingTab.plugin.settings.projectConfig) {
- settingTab.plugin.settings.projectConfig.metadataMappings =
- [];
- }
- }
-
- const metadataMappings =
- settingTab.plugin.settings.projectConfig?.metadataMappings ||
- [];
-
- if (metadataMappings.length === 0) {
- metadataMappingsContainer.createDiv({
- cls: "no-mappings-message",
- text: t("No metadata mappings configured yet."),
- });
- }
-
- metadataMappings.forEach((mapping, index) => {
- const mappingRow = metadataMappingsContainer.createDiv({
- cls: "project-metadata-mapping-row",
- });
-
- // Get already used target keys to avoid duplicates
- const usedTargetKeys = new Set(
- metadataMappings
- .filter((_, i) => i !== index)
- .map((m) => m.targetKey)
- .filter((key) => key && key.trim() !== ""),
- );
-
- // Available target keys from StandardTaskMetadata
- const availableTargetKeys = [
- "project",
- "context",
- "priority",
- "tags",
- "startDate",
- "scheduledDate",
- "dueDate",
- "completedDate",
- "createdDate",
- "recurrence",
- ].filter(
- (key) =>
- !usedTargetKeys.has(key) || key === mapping.targetKey,
- );
-
- new Setting(mappingRow)
- .setName(`${t("Mapping")} ${index + 1}`)
- .addText((text) => {
- text.setPlaceholder(t("Source key (e.g., proj)"))
- .setValue(mapping.sourceKey)
- .onChange(async (value) => {
- if (settingTab.plugin.settings.projectConfig) {
- settingTab.plugin.settings.projectConfig.metadataMappings[
- index
- ].sourceKey = value;
- await settingTab.plugin.saveSettings();
- }
- });
- })
- .addDropdown((dropdown) => {
- // Add empty option
- dropdown.addOption("", t("Select target field"));
-
- // Add available options
- availableTargetKeys.forEach((key) => {
- dropdown.addOption(key, key);
- });
-
- dropdown
- .setValue(mapping.targetKey)
- .onChange(async (value) => {
- if (settingTab.plugin.settings.projectConfig) {
- settingTab.plugin.settings.projectConfig.metadataMappings[
- index
- ].targetKey = value;
- await settingTab.plugin.saveSettings();
- // Refresh to update available options for other dropdowns
- refreshMetadataMappings();
- }
- });
- })
- .addToggle((toggle) => {
- toggle
- .setTooltip(t("Enabled"))
- .setValue(mapping.enabled)
- .onChange(async (value) => {
- if (settingTab.plugin.settings.projectConfig) {
- settingTab.plugin.settings.projectConfig.metadataMappings[
- index
- ].enabled = value;
- await settingTab.plugin.saveSettings();
- }
- });
- })
- .addButton((button) => {
- button
- .setIcon("trash")
- .setTooltip(t("Remove"))
- .onClick(async () => {
- if (settingTab.plugin.settings.projectConfig) {
- settingTab.plugin.settings.projectConfig.metadataMappings.splice(
- index,
- 1,
- );
- await settingTab.plugin.saveSettings();
- refreshMetadataMappings();
- }
- });
- });
- });
-
- // Add new mapping button
- new Setting(metadataMappingsContainer).addButton((button) => {
- button
- .setButtonText(t("Add Metadata Mapping"))
- .setCta()
- .onClick(async () => {
- if (settingTab.plugin.settings.projectConfig) {
- if (
- !Array.isArray(
- settingTab.plugin.settings.projectConfig
- .metadataMappings,
- )
- ) {
- settingTab.plugin.settings.projectConfig.metadataMappings =
- [];
- }
-
- settingTab.plugin.settings.projectConfig.metadataMappings.push(
- {
- sourceKey: "",
- targetKey: "",
- enabled: true,
- },
- );
-
- await settingTab.plugin.saveSettings();
- setTimeout(() => {
- refreshMetadataMappings();
- }, 100);
- }
- });
- });
- };
-
- refreshMetadataMappings();
-
- // Default project naming section
- new Setting(containerEl)
- .setName(t("Default Project Naming"))
- .setDesc(
- t(
- "Configure fallback project naming when no explicit project is found",
- ),
- )
- .setHeading();
-
- new Setting(containerEl)
- .setName(t("Enable default project naming"))
- .setDesc(
- t(
- "Use default naming strategy when no project is explicitly defined",
- ),
- )
- .addToggle((toggle) => {
- toggle
- .setValue(
- settingTab.plugin.settings.projectConfig
- ?.defaultProjectNaming?.enabled || false,
- )
- .onChange(async (value) => {
- if (
- settingTab.plugin.settings.projectConfig
- ?.defaultProjectNaming
- ) {
- settingTab.plugin.settings.projectConfig.defaultProjectNaming.enabled =
- value;
- await settingTab.plugin.saveSettings();
-
- setTimeout(() => {
- settingTab.display();
- }, 200);
- }
- });
- });
-
- if (!settingTab.plugin.settings.projectConfig?.defaultProjectNaming) {
- settingTab.plugin.settings.projectConfig.defaultProjectNaming = {
- strategy: "filename",
- stripExtension: true,
- enabled: false,
- };
- }
-
- new Setting(containerEl)
- .setName(t("Naming strategy"))
- .setDesc(t("Strategy for generating default project names"))
- .addDropdown((dropdown) => {
- dropdown
- .addOption("filename", t("Use filename"))
- .addOption("foldername", t("Use folder name"))
- .addOption("metadata", t("Use metadata field"))
- .setValue(
- settingTab.plugin.settings.projectConfig
- ?.defaultProjectNaming?.strategy || "filename",
- )
- .onChange(async (value) => {
- if (
- !settingTab.plugin.settings.projectConfig
- ?.defaultProjectNaming
- ) {
- settingTab.plugin.settings.projectConfig.defaultProjectNaming =
- {
- strategy: "filename",
- stripExtension: true,
- enabled: false,
- };
- }
- if (
- settingTab.plugin.settings.projectConfig
- ?.defaultProjectNaming
- ) {
- settingTab.plugin.settings.projectConfig.defaultProjectNaming.strategy =
- value as "filename" | "foldername" | "metadata";
- await settingTab.plugin.saveSettings();
- // Refresh to show/hide metadata key field
- setTimeout(() => {
- settingTab.display();
- }, 200);
- }
- });
- });
-
- console.log(
- settingTab.plugin.settings.projectConfig?.defaultProjectNaming
- ?.strategy,
- );
-
- // Show metadata key field only for metadata strategy
- if (
- settingTab.plugin.settings.projectConfig?.defaultProjectNaming
- ?.strategy === "metadata"
- ) {
- new Setting(containerEl)
- .setName(t("Metadata key"))
- .setDesc(t("Metadata field to use as project name"))
- .addText((text) => {
- text.setPlaceholder(
- t("Enter metadata key (e.g., project-name)"),
- )
- .setValue(
- settingTab.plugin.settings.projectConfig
- ?.defaultProjectNaming?.metadataKey || "",
- )
- .onChange(async (value) => {
- if (
- settingTab.plugin.settings.projectConfig
- ?.defaultProjectNaming
- ) {
- settingTab.plugin.settings.projectConfig.defaultProjectNaming.metadataKey =
- value;
- await settingTab.plugin.saveSettings();
- }
- });
- });
- }
-
- // Show strip extension option only for filename strategy
- if (
- settingTab.plugin.settings.projectConfig?.defaultProjectNaming
- ?.strategy === "filename"
- ) {
- new Setting(containerEl)
- .setName(t("Strip file extension"))
- .setDesc(
- t(
- "Remove file extension from filename when using as project name",
- ),
- )
- .addToggle((toggle) => {
- toggle
- .setValue(
- settingTab.plugin.settings.projectConfig
- ?.defaultProjectNaming?.stripExtension || true,
- )
- .onChange(async (value) => {
- if (
- settingTab.plugin.settings.projectConfig
- ?.defaultProjectNaming
- ) {
- settingTab.plugin.settings.projectConfig.defaultProjectNaming.stripExtension =
- value;
- await settingTab.plugin.saveSettings();
- }
- });
- });
- }
- }
+export function renderProjectSettingsTab(tab: TaskProgressBarSettingTab, container: HTMLElement) {
+ const manager = new ProjectFileManager(tab.app);
+ new Setting(container).setName(t("Project notes")).setHeading()
+ .setDesc(t("Each project is a Markdown note. Its project property owns task membership, and assigned tasks are moved into that note."));
+ new Setting(container).setName(t("New project folder")).setDesc(manager.folder)
+ .addButton(button => button.setButtonText(t("New project")).onClick(() => new ProjectCreateModal(tab.app, manager, () => void tab.plugin.triggerViewUpdate()).open()));
+ new Setting(container).setName(t("Archived projects")).setDesc(t("Archive finished projects and restore them when needed. Notes and task history stay available."))
+ .addButton(button => button.setButtonText(t("Manage archives")).onClick(() => new ProjectArchiveModal(tab.app, manager, () => void tab.plugin.triggerViewUpdate()).open()));
}
diff --git a/src/components/features/settings/tabs/QuickCaptureSettingsTab.ts b/src/components/features/settings/tabs/QuickCaptureSettingsTab.ts
index b2d2c4897..37a3e4a72 100644
--- a/src/components/features/settings/tabs/QuickCaptureSettingsTab.ts
+++ b/src/components/features/settings/tabs/QuickCaptureSettingsTab.ts
@@ -1,3 +1,4 @@
+import { t as settingsText } from "@/translations/helper";
import { Setting, Notice, TFile, TFolder } from "obsidian";
import { TaskProgressBarSettingTab } from "@/setting";
import { t } from "@/translations/helper";
@@ -531,11 +532,11 @@ export function renderQuickCaptureSettingsTab(
);
const defaultTemplates: QuickCaptureTemplateDefinition[] = [
- { name: "Daily Note", template: "{{DATE:YYYY-MM-DD}}" },
- { name: "Meeting", template: "{{DATE:YYYY-MM-DD}} - Meeting" },
- { name: "Task", template: "{{DATE:YYYY-MM-DD}} - Task" },
- { name: "Project", template: "Project - {{DATE:YYYY-MM}}" },
- { name: "Notes", template: "Notes - {{DATE:YYYY-MM-DD-HHmm}}" },
+ { name: settingsText("Daily Note"), template: "{{DATE:YYYY-MM-DD}}" },
+ { name: settingsText("Meeting"), template: "{{DATE:YYYY-MM-DD}} - Meeting" },
+ { name: settingsText("Task"), template: "{{DATE:YYYY-MM-DD}} - Task" },
+ { name: settingsText("Project"), template: "Project - {{DATE:YYYY-MM}}" },
+ { name: settingsText("Notes"), template: "Notes - {{DATE:YYYY-MM-DD-HHmm}}" },
];
const rawTemplates = settingTab.plugin.settings.quickCapture
diff --git a/src/components/features/settings/tabs/RewardSettingsTab.ts b/src/components/features/settings/tabs/RewardSettingsTab.ts
index c13a5f4d6..f576e33b4 100644
--- a/src/components/features/settings/tabs/RewardSettingsTab.ts
+++ b/src/components/features/settings/tabs/RewardSettingsTab.ts
@@ -1,294 +1,9 @@
-import { Setting, debounce, TextComponent, Notice } from "obsidian";
-import { OccurrenceLevel, RewardItem } from "src/common/setting-definition";
-import { TaskProgressBarSettingTab } from "src/setting";
-import { t } from "src/translations/manager";
-import { ImageSuggest } from "@/components/ui/inputs/AutoComplete";
-
-export function renderRewardSettingsTab(
- settingTab: TaskProgressBarSettingTab,
- containerEl: HTMLElement
-) {
- new Setting(containerEl)
- .setName(t("Rewards"))
- .setDesc(
- t(
- "Configure rewards for completing tasks. Define items, their occurrence chances, and conditions."
- )
- )
- .setHeading();
-
- // --- Enable Rewards ---
- new Setting(containerEl)
- .setName(t("Enable rewards"))
- .setDesc(t("Toggle to enable or disable the reward system."))
- .addToggle((toggle) =>
- toggle
- .setValue(settingTab.plugin.settings.rewards.enableRewards)
- .onChange(async (value) => {
- settingTab.plugin.settings.rewards.enableRewards = value;
- settingTab.applySettingsUpdate();
- setTimeout(() => {
- settingTab.display();
- }, 200);
- })
- );
-
- if (!settingTab.plugin.settings.rewards.enableRewards) {
- return; // Don't render the rest if rewards are disabled
- }
-
- // --- Reward Display Type ---
- new Setting(containerEl)
- .setName(t("Reward display type"))
- .setDesc(t("Choose how rewards are displayed when earned."))
- .addDropdown((dropdown) => {
- dropdown
- .addOption("modal", t("Modal dialog"))
- .addOption("notice", t("Notice (Auto-accept)"))
- .setValue(
- settingTab.plugin.settings.rewards.showRewardType || "modal"
- )
- .onChange(async (value: "modal" | "notice") => {
- settingTab.plugin.settings.rewards.showRewardType = value;
- settingTab.applySettingsUpdate();
- });
- });
-
- // --- Occurrence Levels ---
- new Setting(containerEl)
- .setName(t("Occurrence levels"))
- .setDesc(
- t("Define different levels of reward rarity and their probability.")
- )
- .setHeading();
-
- const occurrenceLevelsContainer = containerEl.createDiv({
- cls: "rewards-levels-container",
- });
-
- const debounceChanceUpdate = debounce(
- (
- text: TextComponent,
- level: OccurrenceLevel,
- value: string,
- index: number
- ) => {
- const chance = parseInt(value, 10);
- if (!isNaN(chance) && chance >= 0 && chance <= 100) {
- settingTab.plugin.settings.rewards.occurrenceLevels[
- index
- ].chance = chance;
- settingTab.applySettingsUpdate();
- } else {
- // Optional: Provide feedback for invalid input
- new Notice(t("Chance must be between 0 and 100."));
- text.setValue(level.chance.toString()); // Revert
- }
- },
- 1000
- );
-
- const debounceNameUpdate = debounce((value: string, index: number) => {
- settingTab.plugin.settings.rewards.occurrenceLevels[index].name =
- value.trim();
- settingTab.applySettingsUpdate();
- }, 1000);
-
- settingTab.plugin.settings.rewards.occurrenceLevels.forEach(
- (level, index) => {
- const levelSetting = new Setting(occurrenceLevelsContainer)
- .setClass("rewards-level-row")
- .addText((text) =>
- text
- .setPlaceholder(t("Level Name (e.g., common)"))
- .setValue(level.name)
- .onChange((value) => {
- debounceNameUpdate(value, index);
- })
- )
- .addText((text) =>
- text
- .setPlaceholder(t("Chance (%)"))
- .setValue(level.chance.toString())
- .onChange((value) => {
- debounceChanceUpdate(text, level, value, index);
- })
- )
- .addButton((button) =>
- button
- .setIcon("trash")
- .setTooltip(t("Delete Level"))
- .setClass("mod-warning")
- .onClick(() => {
- settingTab.plugin.settings.rewards.occurrenceLevels.splice(
- index,
- 1
- );
- settingTab.applySettingsUpdate();
-
- setTimeout(() => {
- settingTab.display();
- }, 200);
- })
- );
- }
- );
-
- new Setting(occurrenceLevelsContainer).addButton((button) =>
- button
- .setButtonText(t("Add occurrence level"))
- .setCta()
- .onClick(() => {
- const newLevel: OccurrenceLevel = {
- name: t("New Level"),
- chance: 0,
- };
- settingTab.plugin.settings.rewards.occurrenceLevels.push(
- newLevel
- );
- settingTab.applySettingsUpdate();
- setTimeout(() => {
- settingTab.display();
- }, 200);
- })
- );
-
- // --- Reward Items ---
- new Setting(containerEl)
- .setName(t("Reward items"))
- .setDesc(t("Manage the specific rewards that can be obtained."))
- .setHeading();
-
- const rewardItemsContainer = containerEl.createDiv({
- cls: "rewards-items-container",
- });
-
- // Get available occurrence level names for dropdown
- const levelNames = settingTab.plugin.settings.rewards.occurrenceLevels.map(
- (l) => l.name
- );
- if (levelNames.length === 0) levelNames.push(t("No levels defined"));
-
- settingTab.plugin.settings.rewards.rewardItems.forEach((item, index) => {
- const itemSetting = new Setting(rewardItemsContainer)
- .setClass("rewards-item-row")
- .addTextArea((text) =>
- text // Use TextArea for potentially longer names
- .setPlaceholder(t("Reward Name/Text"))
- .setValue(item.name)
- .onChange((value) => {
- settingTab.plugin.settings.rewards.rewardItems[
- index
- ].name = value;
- settingTab.applySettingsUpdate();
- })
- )
- .addDropdown((dropdown) => {
- levelNames.forEach((levelName) => {
- dropdown.addOption(levelName, levelName);
- });
- dropdown
- .setValue(item.occurrence || levelNames[0]) // Handle missing/default
- .onChange((value) => {
- settingTab.plugin.settings.rewards.rewardItems[
- index
- ].occurrence = value;
- settingTab.applySettingsUpdate();
- });
- })
- .addText((text) => {
- text.inputEl.ariaLabel = t("Inventory (-1 for ∞)");
- text.setPlaceholder(t("Inventory (-1 for ∞)")) // For Inventory
- .setValue(item.inventory.toString())
- .onChange((value) => {
- const inventory = parseInt(value, 10);
- if (!isNaN(inventory)) {
- settingTab.plugin.settings.rewards.rewardItems[
- index
- ].inventory = inventory;
- settingTab.applySettingsUpdate();
- } else {
- new Notice(t("Invalid inventory number."));
- text.setValue(item.inventory.toString()); // Revert
- }
- });
- })
- .addText((text) =>
- text // For Condition
- .setPlaceholder(t("Condition (e.g., #tag AND project)"))
- .setValue(item.condition || "")
- .onChange((value) => {
- settingTab.plugin.settings.rewards.rewardItems[
- index
- ].condition = value.trim() || undefined; // Store as undefined if empty
- settingTab.applySettingsUpdate();
- })
- )
- .addText((text) => {
- text.setPlaceholder(t("Image url (optional)")) // For Image URL
- .setValue(item.imageUrl || "")
- .onChange((value) => {
- settingTab.plugin.settings.rewards.rewardItems[
- index
- ].imageUrl = value.trim() || undefined; // Store as undefined if empty
- settingTab.applySettingsUpdate();
- });
-
- new ImageSuggest(
- settingTab.app,
- text.inputEl,
- settingTab.plugin
- );
- })
- .addButton((button) =>
- button
- .setIcon("trash")
- .setTooltip(t("Delete reward item"))
- .setClass("mod-warning")
- .onClick(() => {
- settingTab.plugin.settings.rewards.rewardItems.splice(
- index,
- 1
- );
- settingTab.applySettingsUpdate();
- setTimeout(() => {
- settingTab.display();
- }, 200);
- })
- );
- // Add some spacing or dividers if needed visually
- rewardItemsContainer.createEl("hr", {
- cls: "rewards-item-divider",
- });
- });
-
- if (settingTab.plugin.settings.rewards.rewardItems.length === 0) {
- rewardItemsContainer.createEl("p", {
- text: t("No reward items defined yet."),
- cls: "setting-item-description",
- });
- }
-
- new Setting(rewardItemsContainer).addButton((button) =>
- button
- .setButtonText(t("Add reward item"))
- .setCta()
- .onClick(() => {
- const newItem: RewardItem = {
- id: `reward-${Date.now()}-${Math.random()
- .toString(36)
- .substring(2, 7)}`, // Simple unique ID
- name: t("New Reward"),
- occurrence:
- settingTab.plugin.settings.rewards.occurrenceLevels[0]
- ?.name || "default", // Use first level or default
- inventory: -1, // Default to infinite
- };
- settingTab.plugin.settings.rewards.rewardItems.push(newItem);
- settingTab.applySettingsUpdate();
- setTimeout(() => {
- settingTab.display();
- }, 200);
- })
- );
+import type { TaskProgressBarSettingTab } from "@/setting";
+import { PointsDashboard } from "@/components/features/rewards/PointsDashboard";
+
+/** Settings and the main page share the same data and reward actions. */
+export function renderRewardSettingsTab(settingTab: TaskProgressBarSettingTab, containerEl: HTMLElement): PointsDashboard {
+ const dashboard = new PointsDashboard(settingTab.app, settingTab.plugin, containerEl, true);
+ dashboard.load();
+ return dashboard;
}
diff --git a/src/components/features/settings/tabs/TaskFilterSettingsTab.ts b/src/components/features/settings/tabs/TaskFilterSettingsTab.ts
index ac38e1ddf..86c389107 100644
--- a/src/components/features/settings/tabs/TaskFilterSettingsTab.ts
+++ b/src/components/features/settings/tabs/TaskFilterSettingsTab.ts
@@ -1,396 +1,24 @@
-import { App, Modal, Setting } from "obsidian";
+import { Setting } from "obsidian";
+import type { TaskProgressBarSettingTab } from "@/setting";
+import { SavedTaskFilterModal } from "@/components/features/fluent/components/SavedTaskFilterModal";
+import { savedTaskFilters } from "@/utils/task/saved-task-filters";
import { t } from "@/translations/helper";
-import { TaskProgressBarSettingTab } from "@/setting";
-import { migrateOldFilterOptions } from "@/editor-extensions/core/task-filter-panel";
-import { generateUniqueId } from "@/utils/id-generator";
-class PresetFilterModal extends Modal {
- constructor(app: App, private preset: any, private onSave: () => void) {
- super(app);
- // Migrate old preset options if needed
- if (this.preset && this.preset.options) {
- this.preset.options = migrateOldFilterOptions(this.preset.options);
+export function renderTaskFilterSettingsTab(tab: TaskProgressBarSettingTab, root: HTMLElement): void {
+ new Setting(root).setName(t("Saved filters")).setDesc(t("Choose a saved filter beside search. Edit its rules here using dropdowns.")).setHeading();
+ const list = root.createDiv({ cls: "preset-filters-container" });
+ const render = () => {
+ list.empty();
+ for (const preset of savedTaskFilters(tab.plugin.settings.taskFilter.presetTaskFilters)) {
+ const row = new Setting(list).setName(preset.name);
+ row.addExtraButton(button => button.setIcon("pencil").setTooltip(t("Edit saved filter")).onClick(() =>
+ new SavedTaskFilterModal(tab.app, tab.plugin, "", () => { render(); tab.plugin.triggerViewUpdate(); }, preset).open()));
+ const isBuiltin = preset.id.startsWith("builtin-");
+ if (!isBuiltin || tab.plugin.settings.taskFilter.presetTaskFilters.some(item => item.id === preset.id)) row.addExtraButton(button => button.setIcon(isBuiltin ? "rotate-ccw" : "trash").setTooltip(t(isBuiltin ? "Reset filter preset" : "Delete saved filter")).onClick(async () => {
+ tab.plugin.settings.taskFilter.presetTaskFilters = tab.plugin.settings.taskFilter.presetTaskFilters.filter(item => item.id !== preset.id);
+ await tab.plugin.saveSettings(); render(); await tab.plugin.triggerViewUpdate();
+ }));
}
- }
-
- onOpen() {
- const { contentEl } = this;
- contentEl.empty();
-
- // Set modal title
- this.titleEl.setText(t("Edit Filter: ") + this.preset.name);
-
- // Create form for filter options
- new Setting(contentEl).setName(t("Filter name")).addText((text) => {
- text.setValue(this.preset.name).onChange((value) => {
- this.preset.name = value;
- });
- });
-
- // Task status section
- new Setting(contentEl)
- .setName(t("Checkbox Status"))
- .setDesc(t("Include or exclude tasks based on their status"));
-
- const statusOptions = [
- { id: "includeCompleted", name: t("Include Completed Tasks") },
- { id: "includeInProgress", name: t("Include In Progress Tasks") },
- { id: "includeAbandoned", name: t("Include Abandoned Tasks") },
- { id: "includeNotStarted", name: t("Include Not Started Tasks") },
- { id: "includePlanned", name: t("Include Planned Tasks") },
- ];
-
- for (const option of statusOptions) {
- new Setting(contentEl).setName(option.name).addToggle((toggle) => {
- toggle
- .setValue(this.preset.options[option.id])
- .onChange((value) => {
- this.preset.options[option.id] = value;
- });
- });
- }
-
- // Related tasks section
- new Setting(contentEl)
- .setName(t("Related Tasks"))
- .setDesc(
- t("Include parent, child, and sibling tasks in the filter")
- );
-
- const relatedOptions = [
- { id: "includeParentTasks", name: t("Include Parent Tasks") },
- { id: "includeChildTasks", name: t("Include Child Tasks") },
- { id: "includeSiblingTasks", name: t("Include Sibling Tasks") },
- ];
-
- for (const option of relatedOptions) {
- new Setting(contentEl).setName(option.name).addToggle((toggle) => {
- toggle
- .setValue(this.preset.options[option.id])
- .onChange((value) => {
- this.preset.options[option.id] = value;
- });
- });
- }
-
- // Advanced filter section
- new Setting(contentEl)
- .setName(t("Advanced Filter"))
- .setDesc(
- t(
- "Use boolean operations: AND, OR, NOT. Example: 'text content AND #tag1'"
- )
- );
-
- new Setting(contentEl)
- .setName(t("Filter query"))
- .setDesc(
- t(
- "Use boolean operations: AND, OR, NOT. Example: 'text content AND #tag1'"
- )
- )
- .addText((text) => {
- text.setValue(this.preset.options.advancedFilterQuery).onChange(
- (value) => {
- this.preset.options.advancedFilterQuery = value;
- }
- );
- });
-
- new Setting(contentEl)
- .setName(t("Filter Mode"))
- .setDesc(
- t("Choose whether to show or hide tasks that match the filters")
- )
- .addDropdown((dropdown) => {
- dropdown
- .addOption("INCLUDE", t("Show matching tasks"))
- .addOption("EXCLUDE", t("Hide matching tasks"))
- .setValue(this.preset.options.filterMode || "INCLUDE")
- .onChange((value: "INCLUDE" | "EXCLUDE") => {
- this.preset.options.filterMode = value;
- });
- });
-
- // Save and cancel buttons
- new Setting(contentEl)
- .addButton((button) => {
- button
- .setButtonText(t("Save"))
- .setCta()
- .onClick(() => {
- this.onSave();
- this.close();
- });
- })
- .addButton((button) => {
- button.setButtonText(t("Cancel")).onClick(() => {
- this.close();
- });
- });
- }
-
- onClose() {
- const { contentEl } = this;
- contentEl.empty();
- }
-}
-
-export function renderTaskFilterSettingsTab(
- settingTab: TaskProgressBarSettingTab,
- containerEl: HTMLElement
-) {
- new Setting(containerEl).setName(t("Task Filter")).setHeading();
-
- new Setting(containerEl)
- .setName(t("Enable Task Filter"))
- .setDesc(t("Toggle this to enable the task filter panel"))
- .addToggle((toggle) => {
- toggle
- .setValue(
- settingTab.plugin.settings.taskFilter.enableTaskFilter
- )
- .onChange(async (value) => {
- settingTab.plugin.settings.taskFilter.enableTaskFilter =
- value;
- settingTab.applySettingsUpdate();
- });
- });
-
- // Preset filters section
- new Setting(containerEl)
- .setName(t("Preset Filters"))
- .setDesc(
- t(
- "Create and manage preset filters for quick access to commonly used task filters."
- )
- );
-
- // Add a container for the preset filters
- const presetFiltersContainer = containerEl.createDiv({
- cls: "preset-filters-container",
- });
-
- // Function to refresh the preset filters list
- const refreshPresetFiltersList = () => {
- // Clear the container
- presetFiltersContainer.empty();
-
- // Get current preset filters
- const presetFilters =
- settingTab.plugin.settings.taskFilter.presetTaskFilters;
-
- if (presetFilters.length === 0) {
- presetFiltersContainer.createEl("div", {
- cls: "no-presets-message",
- text: t(
- "No preset filters created yet. Click 'Add New Preset' to create one."
- ),
- });
- }
-
- // Add each preset filter in the list
- presetFilters.forEach((preset, index) => {
- const presetRow = presetFiltersContainer.createDiv({
- cls: "preset-filter-row",
- });
-
- // Create the setting
- const presetSetting = new Setting(presetRow)
- .setName(`${t("Preset")} #${index + 1}`)
- .addText((text) => {
- text.setValue(preset.name)
- .setPlaceholder(t("Preset name"))
- .onChange((value) => {
- preset.name = value;
- settingTab.applySettingsUpdate();
- });
- });
-
- // Add buttons for editing, removing
- presetSetting.addExtraButton((button) => {
- button
- .setIcon("pencil")
- .setTooltip(t("Edit Filter"))
- .onClick(() => {
- // Show modal to edit filter options
- new PresetFilterModal(settingTab.app, preset, () => {
- settingTab.applySettingsUpdate();
- refreshPresetFiltersList();
- }).open();
- });
- });
-
- presetSetting.addExtraButton((button) => {
- button
- .setIcon("trash")
- .setTooltip(t("Remove"))
- .onClick(() => {
- // Remove the preset
- presetFilters.splice(index, 1);
- settingTab.applySettingsUpdate();
- refreshPresetFiltersList();
- });
- });
- });
-
- // Add button to add new preset
- const addButtonContainer = presetFiltersContainer.createDiv();
- new Setting(addButtonContainer)
- .addButton((button) => {
- button
- .setButtonText(t("Add New Preset"))
- .setCta()
- .onClick(() => {
- // Add a new preset with default options
- const newPreset = {
- id: generateUniqueId(),
- name: t("New Filter"),
- options: {
- includeCompleted: true,
- includeInProgress: true,
- includeAbandoned: true,
- includeNotStarted: true,
- includePlanned: true,
- includeParentTasks: true,
- includeChildTasks: true,
- includeSiblingTasks: false,
- advancedFilterQuery: "",
- filterMode: "INCLUDE" as "INCLUDE" | "EXCLUDE",
- },
- };
-
- settingTab.plugin.settings.taskFilter.presetTaskFilters.push(
- newPreset
- );
- settingTab.applySettingsUpdate();
-
- // Open the edit modal for the new preset
- new PresetFilterModal(settingTab.app, newPreset, () => {
- settingTab.applySettingsUpdate();
- refreshPresetFiltersList();
- }).open();
-
- refreshPresetFiltersList();
- });
- })
- .addButton((button) => {
- button
- .setButtonText(t("Reset to Default Presets"))
- .onClick(() => {
- // Show confirmation modal
- const modal = new Modal(settingTab.app);
- modal.titleEl.setText(t("Reset to Default Presets"));
-
- const content = modal.contentEl.createDiv();
- content.setText(
- t(
- "This will replace all your current presets with the default set. Are you sure?"
- )
- );
-
- const buttonContainer = modal.contentEl.createDiv({
- cls: "tg-modal-button-container modal-button-container",
- });
-
- const cancelButton = buttonContainer.createEl("button");
- cancelButton.setText(t("Cancel"));
- cancelButton.addEventListener("click", () => {
- modal.close();
- });
-
- const confirmButton =
- buttonContainer.createEl("button");
- confirmButton.setText(t("Reset"));
- confirmButton.addClass("mod-warning");
- confirmButton.addEventListener("click", () => {
- createDefaultPresetFilters(settingTab);
- refreshPresetFiltersList();
- modal.close();
- });
-
- modal.open();
- });
- });
- };
-
- // Initial render of the preset filters list
- refreshPresetFiltersList();
-}
-
-function createDefaultPresetFilters(settingTab: TaskProgressBarSettingTab) {
- // Clear existing presets if any
- settingTab.plugin.settings.taskFilter.presetTaskFilters = [];
-
- // Add default presets
- const defaultPresets = [
- {
- id: generateUniqueId(),
- name: t("Incomplete tasks"),
- options: {
- includeCompleted: false,
- includeInProgress: true,
- includeAbandoned: false,
- includeNotStarted: true,
- includePlanned: true,
- includeParentTasks: true,
- includeChildTasks: true,
- includeSiblingTasks: false,
- advancedFilterQuery: "",
- filterMode: "INCLUDE" as "INCLUDE" | "EXCLUDE",
- },
- },
- {
- id: generateUniqueId(),
- name: t("In progress tasks"),
- options: {
- includeCompleted: false,
- includeInProgress: true,
- includeAbandoned: false,
- includeNotStarted: false,
- includePlanned: false,
- includeParentTasks: true,
- includeChildTasks: true,
- includeSiblingTasks: false,
- advancedFilterQuery: "",
- filterMode: "INCLUDE" as "INCLUDE" | "EXCLUDE",
- },
- },
- {
- id: generateUniqueId(),
- name: t("Completed tasks"),
- options: {
- includeCompleted: true,
- includeInProgress: false,
- includeAbandoned: false,
- includeNotStarted: false,
- includePlanned: false,
- includeParentTasks: false,
- includeChildTasks: true,
- includeSiblingTasks: false,
- advancedFilterQuery: "",
- filterMode: "INCLUDE" as "INCLUDE" | "EXCLUDE",
- },
- },
- {
- id: generateUniqueId(),
- name: t("All tasks"),
- options: {
- includeCompleted: true,
- includeInProgress: true,
- includeAbandoned: true,
- includeNotStarted: true,
- includePlanned: true,
- includeParentTasks: true,
- includeChildTasks: true,
- includeSiblingTasks: true,
- advancedFilterQuery: "",
- filterMode: "INCLUDE" as "INCLUDE" | "EXCLUDE",
- },
- },
- ];
-
- // Add default presets to settings
- settingTab.plugin.settings.taskFilter.presetTaskFilters = defaultPresets;
- settingTab.applySettingsUpdate();
+ }; render();
+ new Setting(root).addButton(button => button.setButtonText(t("New saved filter")).setCta().onClick(() => new SavedTaskFilterModal(tab.app, tab.plugin, "", () => render()).open()));
}
diff --git a/src/components/features/settings/tabs/TaskHandlerSettingsTab.ts b/src/components/features/settings/tabs/TaskHandlerSettingsTab.ts
index 78819b48f..7d4b1ad25 100644
--- a/src/components/features/settings/tabs/TaskHandlerSettingsTab.ts
+++ b/src/components/features/settings/tabs/TaskHandlerSettingsTab.ts
@@ -1,3 +1,4 @@
+import { t as settingsText } from "@/translations/helper";
import { Setting } from "obsidian";
import {
SortCriterion,
@@ -63,9 +64,9 @@ export function renderTaskHandlerSettingsTab(
.setDesc(t("Choose what type of marker to add to moved tasks"))
.addDropdown((dropdown) => {
dropdown
- .addOption("version", "Version marker")
- .addOption("date", "Date marker")
- .addOption("custom", "Custom marker")
+ .addOption("version", settingsText("Version marker"))
+ .addOption("date", settingsText("Date marker"))
+ .addOption("custom", settingsText("Custom marker"))
.setValue(
settingTab.plugin.settings.completedTaskMover
.taskMarkerType
@@ -91,7 +92,7 @@ export function renderTaskHandlerSettingsTab(
)
.addText((text) =>
text
- .setPlaceholder("version 1.0")
+ .setPlaceholder(settingsText("version 1.0"))
.setValue(
settingTab.plugin.settings.completedTaskMover
.versionMarker
@@ -112,7 +113,7 @@ export function renderTaskHandlerSettingsTab(
)
.addText((text) =>
text
- .setPlaceholder("archived on {{date}}")
+ .setPlaceholder(settingsText("archived on {{date}}"))
.setValue(
settingTab.plugin.settings.completedTaskMover
.dateMarker
@@ -280,7 +281,7 @@ export function renderTaskHandlerSettingsTab(
)
.addText((text) =>
text
- .setPlaceholder("Completed Tasks")
+ .setPlaceholder(settingsText("Completed Tasks"))
.setValue(
settingTab.plugin.settings.completedTaskMover
.defaultHeadingName
@@ -328,9 +329,9 @@ export function renderTaskHandlerSettingsTab(
)
.addDropdown((dropdown) => {
dropdown
- .addOption("version", "Version marker")
- .addOption("date", "Date marker")
- .addOption("custom", "Custom marker")
+ .addOption("version", settingsText("Version marker"))
+ .addOption("date", settingsText("Date marker"))
+ .addOption("custom", settingsText("Custom marker"))
.setValue(
settingTab.plugin.settings.completedTaskMover
.incompletedTaskMarkerType
@@ -357,7 +358,7 @@ export function renderTaskHandlerSettingsTab(
)
.addText((text) =>
text
- .setPlaceholder("version 1.0")
+ .setPlaceholder(settingsText("version 1.0"))
.setValue(
settingTab.plugin.settings.completedTaskMover
.incompletedVersionMarker
@@ -378,7 +379,7 @@ export function renderTaskHandlerSettingsTab(
)
.addText((text) =>
text
- .setPlaceholder("moved on {{date}}")
+ .setPlaceholder(settingsText("moved on {{date}}"))
.setValue(
settingTab.plugin.settings.completedTaskMover
.incompletedDateMarker
@@ -516,7 +517,7 @@ export function renderTaskHandlerSettingsTab(
)
.addText((text) =>
text
- .setPlaceholder("Incomplete Tasks")
+ .setPlaceholder(settingsText("Incomplete Tasks"))
.setValue(
settingTab.plugin.settings.completedTaskMover
.incompletedDefaultHeadingName
@@ -771,7 +772,7 @@ export function renderTaskHandlerSettingsTab(
.setDesc(t("Default section for archive action"))
.addText((text) =>
text
- .setPlaceholder("Completed Tasks")
+ .setPlaceholder(settingsText("Completed Tasks"))
.setValue(
settingTab.plugin.settings.onCompletion.defaultArchiveSection
)
diff --git a/src/components/features/settings/tabs/TaskStatusSettingsTab.ts b/src/components/features/settings/tabs/TaskStatusSettingsTab.ts
index bf3ee1d4f..d40fdbd96 100644
--- a/src/components/features/settings/tabs/TaskStatusSettingsTab.ts
+++ b/src/components/features/settings/tabs/TaskStatusSettingsTab.ts
@@ -1,3 +1,4 @@
+import { t as settingsText } from "@/translations/helper";
import { Modal, setIcon, Setting } from "obsidian";
import { t } from "@/translations/helper";
import { allStatusCollections } from "@/common/task-status";
@@ -110,7 +111,7 @@ export function renderTaskStatusSettingsTab(
)
.setHeading()
.addDropdown((dropdown) => {
- dropdown.addOption("custom", "Custom");
+ dropdown.addOption("custom", settingsText("Custom"));
for (const statusCollection of allStatusCollections) {
dropdown.addOption(statusCollection, statusCollection);
}
@@ -125,11 +126,11 @@ export function renderTaskStatusSettingsTab(
// Confirm before applying the theme
const modal = new Modal(settingTab.app);
- modal.titleEl.setText(`Apply ${value} Theme?`);
+ modal.titleEl.setText(settingsText("Apply {{value0}} Theme?", { interpolation: { value0: String(value) } }));
const content = modal.contentEl.createDiv();
content.setText(
- `This will override your current checkbox status settings with the ${value} theme. Do you want to continue?`,
+ settingsText("This will override your current checkbox status settings with the {{value0}} theme. Do you want to continue?", { interpolation: { value0: String(value) } }),
);
const buttonContainer = modal.contentEl.createDiv({
@@ -342,45 +343,45 @@ export function renderTaskStatusSettingsTab(
// Configure Completed status
createStatusConfigButton("completed", {
- title: "Completed",
+ title: settingsText("Completed"),
description:
- "Configure symbols that represent completed tasks in square brackets",
+ settingsText("Configure symbols that represent completed tasks in square brackets"),
placeholder: "x",
icon: "completed",
});
// Configure Planned status
createStatusConfigButton("planned", {
- title: "Planned",
+ title: settingsText("Planned"),
description:
- "Configure symbols that represent planned tasks in square brackets",
+ settingsText("Configure symbols that represent planned tasks in square brackets"),
placeholder: "?",
icon: "planned",
});
// Configure In Progress status
createStatusConfigButton("inProgress", {
- title: "In Progress",
+ title: settingsText("In Progress"),
description:
- "Configure symbols that represent tasks in progress in square brackets",
+ settingsText("Configure symbols that represent tasks in progress in square brackets"),
placeholder: "/",
icon: "inProgress",
});
// Configure Abandoned status
createStatusConfigButton("abandoned", {
- title: "Abandoned",
+ title: settingsText("Abandoned"),
description:
- "Configure symbols that represent abandoned tasks in square brackets",
+ settingsText("Configure symbols that represent abandoned tasks in square brackets"),
placeholder: "-",
icon: "abandoned",
});
// Configure Not Started status (preserves empty spaces)
createStatusConfigButton("notStarted", {
- title: "Not Started",
+ title: settingsText("Not Started"),
description:
- 'Configure symbols that represent not started tasks in square brackets. Default is space " "',
+ settingsText('Configure symbols that represent not started tasks in square brackets. Default is space " "'),
placeholder: " ",
icon: "notStarted",
preserveEmpty: true,
@@ -394,11 +395,11 @@ export function renderTaskStatusSettingsTab(
),
)
.addDropdown((dropdown) => {
- dropdown.addOption("notStarted", "Not Started");
- dropdown.addOption("abandoned", "Abandoned");
- dropdown.addOption("planned", "Planned");
- dropdown.addOption("completed", "Completed");
- dropdown.addOption("inProgress", "In Progress");
+ dropdown.addOption("notStarted", settingsText("Not Started"));
+ dropdown.addOption("abandoned", settingsText("Abandoned"));
+ dropdown.addOption("planned", settingsText("Planned"));
+ dropdown.addOption("completed", settingsText("Completed"));
+ dropdown.addOption("inProgress", settingsText("In Progress"));
dropdown.setValue(
settingTab.plugin.settings.countOtherStatusesAs || "notStarted",
);
@@ -634,7 +635,7 @@ export function renderTaskStatusSettingsTab(
),
)
.addDropdown((dropdown) => {
- dropdown.addOption("custom", "Custom");
+ dropdown.addOption("custom", settingsText("Custom"));
for (const statusCollection of allStatusCollections) {
dropdown.addOption(statusCollection, statusCollection);
}
@@ -649,13 +650,11 @@ export function renderTaskStatusSettingsTab(
// Confirm before applying the theme
const modal = new Modal(settingTab.app);
- modal.titleEl.setText(`Add ${value} Theme as New Cycle?`);
+ modal.titleEl.setText(settingsText("Add {{value0}} Theme as New Cycle?", { interpolation: { value0: String(value) } }));
const content = modal.contentEl.createDiv();
content.setText(
- t(
- `This will add a new status cycle based on the ${value} theme.`,
- ),
+ settingsText("This will add a new status cycle based on the {{value0}} theme.", { interpolation: { value0: String(value) } }),
);
const buttonContainer = modal.contentEl.createDiv({
@@ -711,7 +710,7 @@ export function renderTaskStatusSettingsTab(
const newStatusCycle: StatusCycle = {
id: `cycle-${Date.now()}`,
name: value,
- description: t(`${value} theme workflow`),
+ description: settingsText("{{value0}} theme workflow", { interpolation: { value0: String(value) } }),
priority:
settingTab.plugin.settings.statusCycles!
.length,
diff --git a/src/components/features/settings/tabs/TaskTimerSettingsTab.ts b/src/components/features/settings/tabs/TaskTimerSettingsTab.ts
index 4db76edbf..176ec5754 100644
--- a/src/components/features/settings/tabs/TaskTimerSettingsTab.ts
+++ b/src/components/features/settings/tabs/TaskTimerSettingsTab.ts
@@ -1,3 +1,4 @@
+import { t as settingsText } from "@/translations/helper";
import { Setting } from "obsidian";
import { TaskProgressBarSettingTab } from "@/setting";
@@ -11,9 +12,9 @@ export function renderTaskTimerSettingTab(
// Main enable/disable setting
new Setting(timerSection)
- .setName("Enable Task Timer")
+ .setName(settingsText("Enable Task Timer"))
.setDesc(
- "Enable task timer functionality for tracking time spent on tasks",
+ settingsText("Enable task timer functionality for tracking time spent on tasks"),
)
.addToggle((toggle) => {
toggle
@@ -46,14 +47,14 @@ export function renderTaskTimerSettingTab(
metadataSection.addClass("task-timer-metadata-section");
const metadataHeading = metadataSection.createEl("h3");
- metadataHeading.setText("Metadata Detection");
+ metadataHeading.setText(settingsText("Metadata Detection"));
metadataHeading.addClass("task-timer-section-heading");
// Frontmatter field setting
new Setting(metadataSection)
- .setName("Frontmatter field")
+ .setName(settingsText("Frontmatter field"))
.setDesc(
- "Field name in frontmatter to check for enabling task timer (e.g., 'task-timer: true')",
+ settingsText("Field name in frontmatter to check for enabling task timer (e.g., 'task-timer: true')"),
)
.addText((text) => {
text.setValue(
@@ -70,9 +71,9 @@ export function renderTaskTimerSettingTab(
// Folder paths setting
new Setting(metadataSection)
- .setName("Folder paths")
+ .setName(settingsText("Folder paths"))
.setDesc(
- "Comma-separated list of folder paths where task timer should be enabled",
+ settingsText("Comma-separated list of folder paths where task timer should be enabled"),
)
.addTextArea((textArea) => {
textArea
@@ -99,8 +100,8 @@ export function renderTaskTimerSettingTab(
// Tags setting
new Setting(metadataSection)
- .setName("Tags")
- .setDesc("Comma-separated list of tags that enable task timer")
+ .setName(settingsText("Tags"))
+ .setDesc(settingsText("Comma-separated list of tags that enable task timer"))
.addTextArea((textArea) => {
textArea
.setValue(
@@ -129,14 +130,14 @@ export function renderTaskTimerSettingTab(
formatSection.addClass("task-timer-format-section");
const formatHeading = formatSection.createEl("h3");
- formatHeading.setText("Time Format");
+ formatHeading.setText(settingsText("Time Format"));
formatHeading.addClass("task-timer-section-heading");
// Time format template setting
new Setting(formatSection)
- .setName("Time format template")
+ .setName(settingsText("Time format template"))
.setDesc(
- "Template for displaying completed task time. Use {h} for hours, {m} for minutes, {s} for seconds",
+ settingsText("Template for displaying completed task time. Use {h} for hours, {m} for minutes, {s} for seconds"),
)
.addText((text) => {
text.setValue(
@@ -156,7 +157,7 @@ export function renderTaskTimerSettingTab(
const examplesTitle = examplesDiv.createDiv();
examplesTitle.addClass("task-timer-examples-title");
- examplesTitle.setText("Format Examples:");
+ examplesTitle.setText(settingsText("Format Examples:"));
const examplesList = examplesDiv.createEl("ul");
@@ -179,14 +180,14 @@ export function renderTaskTimerSettingTab(
blockRefSection.addClass("task-timer-blockref-section");
const blockRefHeading = blockRefSection.createEl("h3");
- blockRefHeading.setText("Block References");
+ blockRefHeading.setText(settingsText("Block References"));
blockRefHeading.addClass("task-timer-section-heading");
// Block reference prefix setting
new Setting(blockRefSection)
- .setName("Block reference prefix")
+ .setName(settingsText("Block reference prefix"))
.setDesc(
- "Prefix for generated block reference IDs (e.g., 'timer' creates ^timer-123456-7890)",
+ settingsText("Prefix for generated block reference IDs (e.g., 'timer' creates ^timer-123456-7890)"),
)
.addText((text) => {
text.setValue(
@@ -206,7 +207,7 @@ export function renderTaskTimerSettingTab(
commandsSection.addClass("task-timer-commands-section");
const commandsHeading = commandsSection.createEl("h3");
- commandsHeading.setText("Data Management");
+ commandsHeading.setText(settingsText("Data Management"));
commandsHeading.addClass("task-timer-section-heading");
const commandsDesc = commandsSection.createDiv();
@@ -214,31 +215,31 @@ export function renderTaskTimerSettingTab(
const descParagraph = commandsDesc.createEl("p");
descParagraph.setText(
- "Use the command palette to access timer data management:",
+ settingsText("Use the command palette to access timer data management:"),
);
const commandsList = commandsDesc.createEl("ul");
const commands = [
{
- name: "Export task timer data",
- desc: "Export all timer data to JSON",
+ name: settingsText("Export task timer data"),
+ desc: settingsText("Export all timer data to JSON"),
},
{
- name: "Import task timer data",
- desc: "Import timer data from JSON file",
+ name: settingsText("Import task timer data"),
+ desc: settingsText("Import timer data from JSON file"),
},
{
- name: "Export task timer data (YAML)",
- desc: "Export to YAML format",
+ name: settingsText("Export task timer data (YAML)"),
+ desc: settingsText("Export to YAML format"),
},
{
- name: "Create task timer backup",
- desc: "Create a backup of active timers",
+ name: settingsText("Create task timer backup"),
+ desc: settingsText("Create a backup of active timers"),
},
{
- name: "Show task timer statistics",
- desc: "Display timer usage statistics",
+ name: settingsText("Show task timer statistics"),
+ desc: settingsText("Display timer usage statistics"),
},
];
diff --git a/src/components/features/settings/tabs/TimeParsingSettingsTab.ts b/src/components/features/settings/tabs/TimeParsingSettingsTab.ts
deleted file mode 100644
index ad1625e94..000000000
--- a/src/components/features/settings/tabs/TimeParsingSettingsTab.ts
+++ /dev/null
@@ -1,359 +0,0 @@
-import { PluginSettingTab, Setting } from "obsidian";
-import { t } from "@/translations/helper";
-import { TaskProgressBarSettingTab } from "@/setting";
-import type { EnhancedTimeParsingConfig } from "@/types/time-parsing";
-
-export function renderTimeParsingSettingsTab(
- pluginSettingTab: TaskProgressBarSettingTab,
- containerEl: HTMLElement,
-) {
- containerEl.createEl("h2", { text: t("Time Parsing Settings") });
-
- // Ensure timeParsing settings exist with enhanced configuration
- if (!pluginSettingTab.plugin.settings.timeParsing) {
- pluginSettingTab.plugin.settings.timeParsing = {
- enabled: true,
- supportedLanguages: ["en", "zh"],
- dateKeywords: {
- start: ["start", "begin", "from", "开始", "从"],
- due: ["due", "deadline", "by", "until", "截止", "到期", "之前"],
- scheduled: ["scheduled", "on", "at", "安排", "计划", "在"],
- },
- removeOriginalText: true,
- perLineProcessing: true,
- realTimeReplacement: true,
- timePatterns: {
- singleTime: [
- /\b([01]?\d|2[0-3]):([0-5]\d)(?::([0-5]\d))?\b/g,
- /\b(1[0-2]|0?[1-9]):([0-5]\d)(?::([0-5]\d))?\s*(AM|PM|am|pm)\b/g,
- ],
- timeRange: [
- /\b([01]?\d|2[0-3]):([0-5]\d)(?::([0-5]\d))?\s*[-~~]\s*([01]?\d|2[0-3]):([0-5]\d)(?::([0-5]\d))?\b/g,
- /\b(1[0-2]|0?[1-9]):([0-5]\d)(?::([0-5]\d))?\s*(AM|PM|am|pm)?\s*[-~~]\s*(1[0-2]|0?[1-9]):([0-5]\d)(?::([0-5]\d))?\s*(AM|PM|am|pm)\b/g,
- ],
- rangeSeparators: ["-", "~", "~", " - ", " ~ ", " ~ "],
- },
- timeDefaults: {
- preferredFormat: "24h" as const,
- defaultPeriod: "AM" as const,
- midnightCrossing: "next-day" as const,
- },
- } as EnhancedTimeParsingConfig;
- }
-
- // Enable Time Parsing
- new Setting(containerEl)
- .setName(t("Enable Time Parsing"))
- .setDesc(
- t(
- "Automatically parse natural language time expressions and specific times (12:00, 1:30 PM, 12:00-13:00)",
- ),
- )
- .addToggle((toggle) =>
- toggle
- .setValue(pluginSettingTab.plugin.settings.timeParsing.enabled)
- .onChange(async (value) => {
- pluginSettingTab.plugin.settings.timeParsing.enabled =
- value;
- pluginSettingTab.applySettingsUpdate();
- }),
- );
-
- // Remove Original Text
- new Setting(containerEl)
- .setName(t("Remove Original Time Expressions"))
- .setDesc(t("Remove parsed time expressions from the task text"))
- .addToggle((toggle) =>
- toggle
- .setValue(
- pluginSettingTab.plugin.settings.timeParsing
- ?.removeOriginalText ?? true,
- )
- .onChange(async (value) => {
- if (!pluginSettingTab.plugin.settings.timeParsing) return;
- pluginSettingTab.plugin.settings.timeParsing.removeOriginalText =
- value;
- pluginSettingTab.applySettingsUpdate();
- }),
- );
-
- // Supported Languages
- new Setting(containerEl)
- .setName(t("Supported Languages"))
- .setDesc(
- t(
- "Currently supports English and Chinese time expressions. More languages may be added in future updates.",
- ),
- )
- .setHeading();
-
- new Setting(containerEl)
- .setName(t("Date Keywords Configuration"))
- .setDesc(t("Configure keywords for date parsing"))
- .setHeading();
-
- // Start Date Keywords
- new Setting(containerEl)
- .setName(t("Start Date Keywords"))
- .setDesc(t("Keywords that indicate start dates (comma-separated)"))
- .addTextArea((text) => {
- const keywords =
- pluginSettingTab.plugin.settings.timeParsing?.dateKeywords
- ?.start || [];
- text.setValue(keywords.join(", "))
- .setPlaceholder("start, begin, from, 开始, 从")
- .onChange(async (value) => {
- if (!pluginSettingTab.plugin.settings.timeParsing) return;
- pluginSettingTab.plugin.settings.timeParsing.dateKeywords.start =
- value
- .split(",")
- .map((k) => k.trim())
- .filter((k) => k.length > 0);
- pluginSettingTab.applySettingsUpdate();
- });
- text.inputEl.rows = 2;
- });
-
- // Due Date Keywords
- new Setting(containerEl)
- .setName(t("Due Date Keywords"))
- .setDesc(t("Keywords that indicate due dates (comma-separated)"))
- .addTextArea((text) => {
- const keywords =
- pluginSettingTab.plugin.settings.timeParsing?.dateKeywords
- ?.due || [];
- text.setValue(keywords.join(", "))
- .setPlaceholder("due, deadline, by, until, 截止, 到期, 之前")
- .onChange(async (value) => {
- if (!pluginSettingTab.plugin.settings.timeParsing) return;
- pluginSettingTab.plugin.settings.timeParsing.dateKeywords.due =
- value
- .split(",")
- .map((k) => k.trim())
- .filter((k) => k.length > 0);
- pluginSettingTab.applySettingsUpdate();
- });
- text.inputEl.rows = 2;
- });
-
- // Scheduled Date Keywords
- new Setting(containerEl)
- .setName(t("Scheduled Date Keywords"))
- .setDesc(t("Keywords that indicate scheduled dates (comma-separated)"))
- .addTextArea((text) => {
- const keywords =
- pluginSettingTab.plugin.settings.timeParsing?.dateKeywords
- ?.scheduled || [];
- text.setValue(keywords.join(", "))
- .setPlaceholder("scheduled, on, at, 安排, 计划, 在")
- .onChange(async (value) => {
- if (!pluginSettingTab.plugin.settings.timeParsing) return;
- pluginSettingTab.plugin.settings.timeParsing.dateKeywords.scheduled =
- value
- .split(",")
- .map((k) => k.trim())
- .filter((k) => k.length > 0);
- pluginSettingTab.applySettingsUpdate();
- });
- text.inputEl.rows = 2;
- });
-
- new Setting(containerEl)
- .setName(t("Time Format Configuration"))
- .setDesc(t("Configure the format of time expressions"))
- .setHeading();
-
- // Preferred Time Format
- new Setting(containerEl)
- .setName(t("Preferred Time Format"))
- .setDesc(t("Default format preference for ambiguous time expressions"))
- .addDropdown((dropdown) => {
- dropdown
- .addOption("12h", t("12-hour format (1:30 PM)"))
- .addOption("24h", t("24-hour format (13:30)"))
- .setValue(
- pluginSettingTab.plugin.settings.timeParsing.timeDefaults
- ?.preferredFormat || "24h",
- )
- .onChange(async (value: "12h" | "24h") => {
- if (
- !pluginSettingTab.plugin.settings.timeParsing
- .timeDefaults
- ) {
- pluginSettingTab.plugin.settings.timeParsing.timeDefaults =
- {
- preferredFormat: value,
- defaultPeriod: "AM",
- midnightCrossing: "next-day",
- };
- } else {
- pluginSettingTab.plugin.settings.timeParsing.timeDefaults.preferredFormat =
- value;
- }
- pluginSettingTab.applySettingsUpdate();
- });
- });
-
- // Default AM/PM Period
- new Setting(containerEl)
- .setName(t("Default AM/PM Period"))
- .setDesc(t("Default period when AM/PM is ambiguous in 12-hour format"))
- .addDropdown((dropdown) => {
- dropdown
- .addOption("AM", t("AM (Morning)"))
- .addOption("PM", t("PM (Afternoon/Evening)"))
- .setValue(
- pluginSettingTab.plugin.settings.timeParsing.timeDefaults
- ?.defaultPeriod || "AM",
- )
- .onChange(async (value: "AM" | "PM") => {
- if (
- !pluginSettingTab.plugin.settings.timeParsing
- .timeDefaults
- ) {
- pluginSettingTab.plugin.settings.timeParsing.timeDefaults =
- {
- preferredFormat: "24h",
- defaultPeriod: value,
- midnightCrossing: "next-day",
- };
- } else {
- pluginSettingTab.plugin.settings.timeParsing.timeDefaults.defaultPeriod =
- value;
- }
- pluginSettingTab.applySettingsUpdate();
- });
- });
-
- // Midnight Crossing Behavior
- new Setting(containerEl)
- .setName(t("Midnight Crossing Behavior"))
- .setDesc(
- t(
- "How to handle time ranges that cross midnight (e.g., 23:00-01:00)",
- ),
- )
- .addDropdown((dropdown) => {
- dropdown
- .addOption(
- "next-day",
- t("Next day (23:00 today - 01:00 tomorrow)"),
- )
- .addOption("same-day", t("Same day (treat as error)"))
- .addOption("error", t("Show error"))
- .setValue(
- pluginSettingTab.plugin.settings.timeParsing.timeDefaults
- ?.midnightCrossing || "next-day",
- )
- .onChange(async (value: "next-day" | "same-day" | "error") => {
- if (
- !pluginSettingTab.plugin.settings.timeParsing
- .timeDefaults
- ) {
- pluginSettingTab.plugin.settings.timeParsing.timeDefaults =
- {
- preferredFormat: "24h",
- defaultPeriod: "AM",
- midnightCrossing: value,
- };
- } else {
- pluginSettingTab.plugin.settings.timeParsing.timeDefaults.midnightCrossing =
- value;
- }
- pluginSettingTab.applySettingsUpdate();
- });
- });
-
- // Time Range Separators
- new Setting(containerEl)
- .setName(t("Time Range Separators"))
- .setDesc(t("Characters used to separate time ranges (comma-separated)"))
- .addTextArea((text) => {
- const separators = pluginSettingTab.plugin.settings.timeParsing
- .timePatterns?.rangeSeparators || ["-", "~", "~"];
- text.setValue(separators.join(", "))
- .setPlaceholder("-, ~, ~, ' - ', ' ~ '")
- .onChange(async (value) => {
- if (
- !pluginSettingTab.plugin.settings.timeParsing
- .timePatterns
- ) {
- pluginSettingTab.plugin.settings.timeParsing.timePatterns =
- {
- singleTime: [],
- timeRange: [],
- rangeSeparators: value
- .split(",")
- .map((s) => s.trim())
- .filter((s) => s.length > 0),
- };
- } else {
- pluginSettingTab.plugin.settings.timeParsing.timePatterns.rangeSeparators =
- value
- .split(",")
- .map((s) => s.trim())
- .filter((s) => s.length > 0);
- }
- pluginSettingTab.applySettingsUpdate();
- });
- text.inputEl.rows = 2;
- });
-
- // Examples
- new Setting(containerEl)
- .setName(t("Examples"))
- .setDesc(t("Examples of time expressions"))
- .setHeading();
- const examplesEl = containerEl.createEl("div", {
- cls: "time-parsing-examples",
- });
-
- const examples = [
- // Date examples
- { input: "go to bed tomorrow", output: "go to bed 📅 2025-01-05" },
- { input: "meeting next week", output: "meeting 📅 2025-01-11" },
- { input: "project due by Friday", output: "project 📅 2025-01-04" },
- { input: "明天开会", output: "开会 📅 2025-01-05" },
- { input: "3天后完成", output: "完成 📅 2025-01-07" },
- // Time examples
- {
- input: "meeting at 2:30 PM",
- output: "meeting 📅 2025-01-04 ⏰ 14:30",
- },
- {
- input: "workshop 9:00-17:00",
- output: "workshop 📅 2025-01-04 ⏰ 09:00-17:00",
- },
- {
- input: "call scheduled 12:00",
- output: "call 📅 2025-01-04 ⏰ 12:00",
- },
- {
- input: "lunch 12:00~13:00",
- output: "lunch 📅 2025-01-04 ⏰ 12:00-13:00",
- },
- ];
-
- examples.forEach((example) => {
- const exampleEl = examplesEl.createEl("div", {
- cls: "time-parsing-example",
- });
- exampleEl.createEl("span", {
- text: "Input: ",
- cls: "example-label",
- });
- exampleEl.createEl("code", {
- text: example.input,
- cls: "example-input",
- });
- exampleEl.createEl("br");
- exampleEl.createEl("span", {
- text: "Output: ",
- cls: "example-label",
- });
- exampleEl.createEl("code", {
- text: example.output,
- cls: "example-output",
- });
- });
-}
diff --git a/src/components/features/settings/tabs/ViewSettingsTab.ts b/src/components/features/settings/tabs/ViewSettingsTab.ts
index 7957d133f..f70213588 100644
--- a/src/components/features/settings/tabs/ViewSettingsTab.ts
+++ b/src/components/features/settings/tabs/ViewSettingsTab.ts
@@ -3,7 +3,6 @@ import { ViewConfig, ViewFilterRule } from "@/common/setting-definition";
import { t } from "@/translations/helper";
import { TaskProgressBarSettingTab } from "@/setting";
import { ViewConfigModal } from "@/components/features/task/view/modals/ViewConfigModal";
-import { TaskFilterComponent } from "@/components/features/task/filter/ViewTaskFilter";
import Sortable from "sortablejs";
import "@/styles/view-setting-tab.css";
@@ -211,100 +210,9 @@ export function renderViewSettingsTab(
});
});
- // --- Global Filter Section ---
- new Setting(containerEl)
- .setName(t("Global Filter Configuration"))
- .setDesc(
- t(
- "Configure global filter rules that apply to all Views by default. Individual Views can override these settings.",
- ),
- )
- .setHeading();
-
- // Global filter container
- const globalFilterContainer = containerEl.createDiv({
- cls: "global-filter-container",
- });
-
- // Global filter component
- let globalFilterComponent: TaskFilterComponent | null = null;
-
- // Sortable instances for view management
let topSortable: Sortable | null = null;
let bottomSortable: Sortable | null = null;
-
- // Initialize global filter component
- const initializeGlobalFilter = () => {
- if (globalFilterComponent) {
- globalFilterComponent.onunload();
- }
-
- // Pre-save the global filter state to localStorage so TaskFilterComponent can load it
- if (settingTab.plugin.settings.globalFilterRules.advancedFilter) {
- settingTab.app.saveLocalStorage(
- "task-genius-view-filter-global-filter",
- settingTab.plugin.settings.globalFilterRules.advancedFilter,
- );
- }
-
- globalFilterComponent = new TaskFilterComponent(
- globalFilterContainer,
- settingTab.app,
- "global-filter", // Use a special leafId for global filter
- settingTab.plugin,
- );
-
- // Load the component
- globalFilterComponent.onload();
-
- // Listen for filter changes
- const handleGlobalFilterChange = (filterState: any) => {
- if (globalFilterComponent) {
- // Update global filter rules in settings
- settingTab.plugin.settings.globalFilterRules = {
- ...settingTab.plugin.settings.globalFilterRules,
- advancedFilter: filterState,
- };
- settingTab.applySettingsUpdate();
-
- // 触发视图刷新以应用新的全局筛选器
- // 使用插件的triggerViewUpdate方法刷新所有TaskView
- settingTab.plugin.triggerViewUpdate();
- }
- };
-
- // Register event listener for global filter changes
- settingTab.plugin.registerEvent(
- settingTab.app.workspace.on(
- "task-genius:filter-changed",
- (filterState, leafId) => {
- if (leafId === "global-filter") {
- handleGlobalFilterChange(filterState);
- }
- },
- ),
- );
- };
-
- // Initialize the global filter component
- initializeGlobalFilter();
-
- // Store cleanup function for later use
- (containerEl as any).cleanupGlobalFilter = () => {
- if (globalFilterComponent) {
- globalFilterComponent.onunload();
- globalFilterComponent = null;
- }
- // Also cleanup sortables
- if (topSortable) {
- topSortable.destroy();
- topSortable = null;
- }
- if (bottomSortable) {
- bottomSortable.destroy();
- bottomSortable = null;
- }
- };
+ (containerEl as any).cleanupViewSortables = () => { topSortable?.destroy(); bottomSortable?.destroy(); topSortable = null; bottomSortable = null; };
// --- New View Management Section ---
new Setting(containerEl)
diff --git a/src/components/features/settings/tabs/WorkflowSettingsTab.ts b/src/components/features/settings/tabs/WorkflowSettingsTab.ts
index 5699163c9..b048883fe 100644
--- a/src/components/features/settings/tabs/WorkflowSettingsTab.ts
+++ b/src/components/features/settings/tabs/WorkflowSettingsTab.ts
@@ -1,3 +1,4 @@
+import { t as settingsText } from "@/translations/helper";
import { Setting, Modal } from "obsidian";
import { t } from "@/translations/helper";
import { TaskProgressBarSettingTab } from "@/setting";
@@ -297,9 +298,7 @@ export function renderWorkflowSettingsTab(
const content = modal.contentEl.createDiv();
content.setText(
- t(
- `Are you sure you want to delete the '${workflow.name}' workflow?`
- )
+ settingsText("Are you sure you want to delete the '{{value0}}' workflow?", { interpolation: { value0: String(workflow.name) } })
);
const buttonContainer = modal.contentEl.createDiv({
diff --git a/src/components/features/table/TableRenderer.ts b/src/components/features/table/TableRenderer.ts
index 7efe24cba..452581158 100644
--- a/src/components/features/table/TableRenderer.ts
+++ b/src/components/features/table/TableRenderer.ts
@@ -1,3 +1,4 @@
+import { getTaskStatusGroup } from "@/utils/status-cycle-resolver";
import { Component, setIcon, Menu, App } from "obsidian";
import { TableColumn, TableRow, TableCell } from "./TableTypes";
import { TableSpecificConfig } from "../../../common/setting-definition";
@@ -55,6 +56,8 @@ export class TableRenderer extends Component {
) => void;
// Callback for row expansion
+ public onColumnResize?: (columnId: string, width: number) => void;
+
public onRowExpand?: (rowId: string) => void;
// Callback for cell value changes
@@ -225,6 +228,8 @@ export class TableRenderer extends Component {
*/
private renderHeader() {
this.headerEl.empty();
+ for (const column of this.columns) if (column.id === "status") column.width = Math.max(112, column.width);
+ this.tableEl.style.minWidth = `${this.columns.reduce((sum, column) => sum + column.width, 0)}px`;
const headerRow = this.headerEl.createEl("tr", "task-table-header-row");
@@ -232,7 +237,7 @@ export class TableRenderer extends Component {
const th = headerRow.createEl("th", "task-table-header-cell");
th.dataset.columnId = column.id;
th.style.width = `${column.width}px`;
- th.style.minWidth = `${Math.min(column.width, 50)}px`;
+ th.style.minWidth = `${column.id === "status" ? 112 : Math.min(column.width, 50)}px`;
// Create header content container
const headerContent = th.createDiv("task-table-header-content");
@@ -766,29 +771,10 @@ export class TableRenderer extends Component {
const statusIcon = statusContainer.createSpan("task-table-status-icon");
const status = cell.value as string;
- switch (status) {
- case "x":
- case "X":
- setIcon(statusIcon, "check-circle");
- statusContainer.addClass("completed");
- break;
- case "/":
- case ">":
- setIcon(statusIcon, "clock");
- statusContainer.addClass("in-progress");
- break;
- case "-":
- setIcon(statusIcon, "x-circle");
- statusContainer.addClass("abandoned");
- break;
- case "?":
- setIcon(statusIcon, "help-circle");
- statusContainer.addClass("planned");
- break;
- default:
- setIcon(statusIcon, "circle");
- statusContainer.addClass("not-started");
- }
+ const group = getTaskStatusGroup(status, this.plugin.settings) || "archived";
+ const appearance: Record = { completed: ["check-circle", "completed"], inProgress: ["clock", "in-progress"], abandoned: ["x-circle", "abandoned"], planned: ["help-circle", "planned"], notStarted: ["circle", "not-started"], archived: ["pause", "paused"], paused: ["pause", "paused"], pause: ["pause", "paused"] };
+ const [icon, cls] = appearance[group] || appearance.archived;
+ setIcon(statusIcon, icon); statusContainer.addClass(cls);
// Add status text
const statusText = statusContainer.createSpan("task-table-status-text");
@@ -1460,7 +1446,9 @@ export class TableRenderer extends Component {
private handleMouseUp() {
if (!this.isResizing) return;
+ const column = this.columns.find(column => column.id === this.resizeColumn);
this.isResizing = false;
+ if (column) this.onColumnResize?.(column.id, column.width);
this.resizeColumn = "";
document.body.style.cursor = "";
this.tableEl.removeClass("resizing");
@@ -1470,6 +1458,7 @@ export class TableRenderer extends Component {
* Update column width
*/
private updateColumnWidth(columnId: string, newWidth: number) {
+ if (columnId === "status") newWidth = Math.max(112, newWidth);
// Update header
const headerCell = this.headerEl.querySelector(
`th[data-column-id="${columnId}"]`,
@@ -1494,6 +1483,7 @@ export class TableRenderer extends Component {
if (column) {
column.width = newWidth;
}
+ this.tableEl.style.minWidth = `${this.columns.reduce((sum, item) => sum + item.width, 0)}px`;
}
/**
diff --git a/src/components/features/table/TableView.ts b/src/components/features/table/TableView.ts
index 463739521..76239b98d 100644
--- a/src/components/features/table/TableView.ts
+++ b/src/components/features/table/TableView.ts
@@ -76,9 +76,12 @@ export class TableView extends Component {
private plugin: TaskProgressBarPlugin,
private parentEl: HTMLElement,
private config: TableSpecificConfig,
- private callbacks: TableViewCallbacks = {}
+ private callbacks: TableViewCallbacks = {},
+ private viewId = "table"
) {
super();
+ this.config.columnWidths ||= {};
+ this.config.visibleColumns ||= ["status", "content", "priority", "dueDate", "project"];
this.setupCallbacks();
this.initializeConfig();
}
@@ -104,7 +107,7 @@ export class TableView extends Component {
{
id: "rowNumber",
title: "#",
- width: 60,
+ width: 44,
sortable: false,
resizable: false,
type: "number",
@@ -113,7 +116,7 @@ export class TableView extends Component {
{
id: "status",
title: t("Status"),
- width: this.config.columnWidths.status || 80,
+ width: Math.max(112, this.config.columnWidths.status || 112),
sortable: this.config.sortableColumns,
resizable: this.config.resizableColumns,
type: "status",
@@ -122,7 +125,7 @@ export class TableView extends Component {
{
id: "content",
title: t("Content"),
- width: this.config.columnWidths.content || 300,
+ width: this.config.columnWidths.content || 420,
sortable: this.config.sortableColumns,
resizable: this.config.resizableColumns,
type: "text",
@@ -131,7 +134,7 @@ export class TableView extends Component {
{
id: "priority",
title: t("Priority"),
- width: this.config.columnWidths.priority || 100,
+ width: this.config.columnWidths.priority || 72,
sortable: this.config.sortableColumns,
resizable: this.config.resizableColumns,
type: "priority",
@@ -293,6 +296,10 @@ export class TableView extends Component {
this.app,
this.plugin
);
+ this.renderer.onColumnResize = (id, width) => {
+ this.config.columnWidths[id] = width;
+ this.saveColumnConfiguration();
+ };
this.addChild(this.renderer);
// Set up date change callback
@@ -387,6 +394,8 @@ export class TableView extends Component {
/**
* Update the table with new task data
*/
+ public onShown(): void { this.refreshDisplay(); }
+
public updateTasks(tasks: Task[]) {
this.allTasks = tasks;
this.applyFiltersAndSort();
@@ -1145,7 +1154,7 @@ export class TableView extends Component {
if (this.plugin && this.plugin.settings) {
// Find the table view configuration
const tableViewConfig = this.plugin.settings.viewConfiguration.find(
- (view) => view.id === "table"
+ (view) => view.id === this.viewId
);
if (tableViewConfig && tableViewConfig.specificConfig) {
@@ -1156,7 +1165,7 @@ export class TableView extends Component {
...this.config.visibleColumns,
];
- // Save settings
+ tableConfig.columnWidths = { ...this.config.columnWidths };
this.plugin.saveSettings();
}
}
diff --git a/src/components/features/table/TableViewAdapter.ts b/src/components/features/table/TableViewAdapter.ts
index 95802e7e2..cab270e16 100644
--- a/src/components/features/table/TableViewAdapter.ts
+++ b/src/components/features/table/TableViewAdapter.ts
@@ -16,7 +16,8 @@ export class TableViewAdapter extends Component {
private plugin: TaskProgressBarPlugin,
private parentEl: HTMLElement,
private config: TableSpecificConfig,
- private callbacks: TableViewCallbacks
+ private callbacks: TableViewCallbacks,
+ private viewId = "table"
) {
super();
@@ -34,7 +35,8 @@ export class TableViewAdapter extends Component {
onTaskCompleted: this.callbacks.onTaskCompleted,
onTaskContextMenu: this.callbacks.onTaskContextMenu,
onTaskUpdated: this.callbacks.onTaskUpdated,
- }
+ },
+ this.viewId
);
}
@@ -51,6 +53,8 @@ export class TableViewAdapter extends Component {
/**
* Update tasks in the table view
*/
+ public onShown(): void { this.tableView.onShown(); }
+
public updateTasks(tasks: Task[]) {
this.tableView.updateTasks(tasks);
}
diff --git a/src/components/features/task/edit/MetadataEditor.ts b/src/components/features/task/edit/MetadataEditor.ts
index 8b89e7253..32acfb3c9 100644
--- a/src/components/features/task/edit/MetadataEditor.ts
+++ b/src/components/features/task/edit/MetadataEditor.ts
@@ -1,3 +1,5 @@
+import { attachDateTimePicker } from "@/utils/date/date-time-picker";
+import { parseOptionalDateTime, formatOptionalDateTime, taskDatePrecisions } from "@/utils/date/optional-date-time";
/**
* Task Metadata Editor Component
* Provides functionality to display and edit task metadata.
@@ -12,6 +14,7 @@ import {
TextAreaComponent,
} from "obsidian";
import { Task } from "@/types/task";
+import { renderTaskDependencies } from "./TaskDependencyPicker";
import TaskProgressBarPlugin from "@/index";
import { t } from "@/translations/helper";
import {
@@ -65,6 +68,9 @@ export class TaskMetadataEditor extends Component {
*/
showTask(task: Task): void {
this.task = task;
+ this.task.content = typeof task.content === "string" ? task.content : "";
+ this.task.metadata ||= { tags: [], children: [] };
+ this.task.metadata.datePrecision = taskDatePrecisions(this.task);
this.container.empty();
this.container.addClass("task-metadata-editor");
@@ -179,16 +185,14 @@ export class TaskMetadataEditor extends Component {
"cancelledDate",
this.getDateString(this.task.metadata.cancelledDate)
);
- this.createRecurrenceEditor(pane);
}
private populateDetailsTabContent(pane: HTMLElement): void {
+ this.createPointsEditor(pane);
this.createProjectEditor(pane);
this.createTagsEditor(pane);
this.createContextEditor(pane);
- this.createOnCompletionEditor(pane);
this.createDependsOnEditor(pane);
- this.createIdEditor(pane);
}
/**
@@ -204,6 +208,7 @@ export class TaskMetadataEditor extends Component {
});
// Project editor
+ this.createPointsEditor(metadataContainer);
this.createProjectEditor(metadataContainer);
// Tags editor
@@ -245,25 +250,31 @@ export class TaskMetadataEditor extends Component {
);
// Recurrence rule editor
- this.createRecurrenceEditor(metadataContainer);
// New fields
- this.createOnCompletionEditor(metadataContainer);
this.createDependsOnEditor(metadataContainer);
- this.createIdEditor(metadataContainer);
+ }
+
+ private createPointsEditor(container: HTMLElement): void {
+ const field = container.createDiv({ cls: "field-container task-points-field" });
+ field.createEl("label", { text: t("Task points") });
+ const input = new TextComponent(field.createDiv());
+ input.setPlaceholder(t("Default points"));
+ input.inputEl.type = "number";
+ input.inputEl.min = "0";
+ input.setValue(this.task.metadata.points == null ? "" : String(this.task.metadata.points));
+ input.onChange(value => {
+ const trimmed = value.trim();
+ const points = Number(trimmed);
+ if (!trimmed || Number.isFinite(points)) this.notifyMetadataChange("points", trimmed === "" ? undefined : Math.max(0, points));
+ });
}
/**
* Converts a date value to a string.
*/
private getDateString(dateValue: string | number | undefined): string {
- if (dateValue === undefined) return "";
- if (typeof dateValue === "number") {
- // For numeric timestamps, prefer helper for correct display across timezones
- return timestampToLocalDateString(dateValue);
- }
- // Already a YYYY-MM-DD string
- return dateValue;
+ return formatOptionalDateTime(dateValue);
}
/**
@@ -310,7 +321,7 @@ export class TaskMetadataEditor extends Component {
.addOption("4", "⏫ " + t("High"))
.addOption("5", "🔺 " + t("Highest"))
.onChange((value) => {
- this.notifyMetadataChange("priority", parseInt(value));
+ this.notifyMetadataChange("priority", value ? parseInt(value) : undefined);
});
priorityDropdown.selectEl.addClass("priority-select");
@@ -344,41 +355,15 @@ export class TaskMetadataEditor extends Component {
const fieldLabel = fieldContainer.createDiv({ cls: "field-label" });
fieldLabel.setText(label);
- const dateInput = fieldContainer.createEl("input", {
- cls: `date-input ${field}-input`,
- type: "date",
- });
-
- if (value) {
- // If already a YYYY-MM-DD string, use directly; else use helper for timestamp
- const isDateString =
- typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value);
- if (isDateString) {
- dateInput.value = value as string;
- } else {
- try {
- const asNum =
- typeof value === "number" ? value : Number(value);
- dateInput.value = timestampToLocalDateString(
- Number.isFinite(asNum) ? (asNum as number) : undefined
- );
- } catch (e) {
- console.error(`Cannot parse date: ${value}`, e);
- }
- }
- }
-
+ const dateInput = fieldContainer.createEl("input", { cls: `date-input ${field}-input`, type: "text", attr: { placeholder: "YYYY-MM-DD / YYYY-MM-DD HH:mm", "aria-label": label } });
+ dateInput.value = formatOptionalDateTime(this.task.metadata[field as keyof typeof this.task.metadata] as number, this.task.metadata.datePrecision?.[field]);
+ attachDateTimePicker(dateInput, label);
this.registerDomEvent(dateInput, "change", () => {
- const dateValue = dateInput.value;
- if (dateValue) {
- // Use helper to convert local date string to UTC noon timestamp
- const timestamp = localDateStringToTimestamp(dateValue);
- if (timestamp !== undefined) {
- this.notifyMetadataChange(field, timestamp);
- }
- } else {
- this.notifyMetadataChange(field, undefined);
- }
+ const value = dateInput.value.trim(), parsed = value ? parseOptionalDateTime(value) : null;
+ dateInput.setAttribute("aria-invalid", String(!!value && !parsed));
+ if (value && !parsed) return;
+ this.notifyMetadataChange("datePrecision", { ...this.task.metadata.datePrecision, [field]: parsed?.precision });
+ this.notifyMetadataChange(field, parsed?.timestamp);
});
}
@@ -393,17 +378,12 @@ export class TaskMetadataEditor extends Component {
fieldLabel.setText(t("Project"));
const effectiveProject = getEffectiveProject(this.task);
- const isReadonly = isProjectReadonly(this.task);
+ const isReadonly = false;
const projectInput = new TextComponent(fieldContainer)
.setPlaceholder(t("Project name"))
.setValue(effectiveProject || "")
- .setDisabled(isReadonly)
- .onChange((value) => {
- if (!isReadonly) {
- this.notifyMetadataChange("project", value);
- }
- });
+ .setDisabled(isReadonly);
// Add visual indicator for tgProject - only show if no user-set project exists
if (
@@ -421,7 +401,7 @@ export class TaskMetadataEditor extends Component {
}
this.registerDomEvent(projectInput.inputEl, "blur", () => {
- if (!isReadonly) {
+ if (projectInput.inputEl.value.trim() !== (effectiveProject || "").trim()) {
this.notifyMetadataChange(
"project",
projectInput.inputEl.value
@@ -476,9 +456,7 @@ export class TaskMetadataEditor extends Component {
const contextInput = new TextComponent(fieldContainer)
.setPlaceholder(t("e.g. @home, @work"))
.setValue(
- Array.isArray(this.task.metadata.context)
- ? this.task.metadata.context.join(", ")
- : ""
+ Array.isArray(this.task.metadata.context) ? this.task.metadata.context.join(", ") : this.task.metadata.context || ""
);
this.registerDomEvent(contextInput.inputEl, "blur", () => {
@@ -486,7 +464,7 @@ export class TaskMetadataEditor extends Component {
.split(",")
.map((ctx) => ctx.trim())
.filter((ctx) => ctx);
- this.notifyMetadataChange("context", contexts);
+ this.notifyMetadataChange("context", contexts.join(", "));
});
new ContextSuggest(this.app, contextInput.inputEl, this.plugin);
@@ -588,28 +566,10 @@ export class TaskMetadataEditor extends Component {
* Creates a dependsOn editor.
*/
private createDependsOnEditor(container: HTMLElement): void {
- const fieldContainer = container.createDiv({
- cls: "field-container dependson-container",
- });
- const fieldLabel = fieldContainer.createDiv({ cls: "field-label" });
- fieldLabel.setText(t("Depends On"));
-
- const dependsOnInput = new TextComponent(fieldContainer)
- .setPlaceholder(t("Task IDs separated by commas"))
- .setValue(
- Array.isArray(this.task.metadata.dependsOn)
- ? this.task.metadata.dependsOn.join(", ")
- : ""
- );
-
- this.registerDomEvent(dependsOnInput.inputEl, "blur", () => {
- const dependsOnValue = dependsOnInput.inputEl.value;
- const dependsOnArray = dependsOnValue
- .split(",")
- .map((id) => id.trim())
- .filter((id) => id.length > 0);
- this.notifyMetadataChange("dependsOn", dependsOnArray);
- });
+ const task = this.task;
+ const root = container.createDiv({ cls: "field-container dependson-container" });
+ root.createDiv({ cls: "field-label", text: t("Depends On") });
+ renderTaskDependencies(this.app, this.plugin, root, task, ids => { if (this.task === task) this.notifyMetadataChange("dependsOn", ids); });
}
/**
diff --git a/src/components/features/task/edit/TaskDependencyPicker.ts b/src/components/features/task/edit/TaskDependencyPicker.ts
new file mode 100644
index 000000000..bb5523056
--- /dev/null
+++ b/src/components/features/task/edit/TaskDependencyPicker.ts
@@ -0,0 +1,66 @@
+import { App, FuzzySuggestModal, Notice, setIcon } from "obsidian";
+import type TaskProgressBarPlugin from "@/index";
+import type { Task } from "@/types/task";
+import { t } from "@/translations/helper";
+
+export function renderTaskDependencies(app: App, plugin: TaskProgressBarPlugin, root: HTMLElement, task: Task, onChange: (ids: string[]) => void): { getValue: () => string[] } {
+ let selected = [...(task.metadata.dependsOn || [])], tasks = plugin.preloadedTasks || [];
+ const chips = root.createDiv({ cls: "tg-dependency-chips" });
+ const render = () => {
+ chips.empty();
+ for (const id of selected) {
+ const target = tasks.find(item => item.metadata.id === id || item.id === id);
+ const chip = chips.createDiv({ cls: "tg-dependency-chip" }); chip.createSpan({ text: target?.content || t("Task no longer available") });
+ const remove = chip.createEl("button", { cls: "clickable-icon", attr: { "aria-label": t("Remove dependency") } }); setIcon(remove, "x");
+ remove.addEventListener("click", () => { selected = selected.filter(value => value !== id); onChange([...selected]); render(); });
+ }
+ }; render();
+ const add = root.createEl("button", { text: t("Search and select task") });
+ add.addEventListener("click", async event => {
+ event.preventDefault(); event.stopPropagation(); add.disabled = true;
+ try {
+ tasks = await plugin.dataflowOrchestrator?.getQueryAPI().getAllTasks() || tasks;
+ if (!root.isConnected) return;
+ new TaskDependencyPicker(app, plugin, { ...task, metadata: { ...task.metadata, dependsOn: selected } }, tasks, id => {
+ selected = [...new Set([...selected, id])]; onChange([...selected]); render();
+ }).open();
+ } catch (error) { new Notice(String(error)); } finally { add.disabled = false; }
+ });
+ void plugin.dataflowOrchestrator?.getQueryAPI().getAllTasks().then(items => { if (root.isConnected) { tasks = items; render(); } }).catch(console.error);
+ return { getValue: () => [...selected] };
+}
+
+export function isDependencyTask(task: Task): boolean {
+ return !(task as any).isFileTask && !task.id.startsWith("file-source:") && task.metadata?.source !== "file-source" && task.metadata?.sourceType !== "file" && !task.metadata?.projectPlan && (task.metadata?.source as any)?.type !== "ics";
+}
+
+export function dependencyWouldCycle(tasks: Task[], source: Task, target: Task): boolean {
+ const byId = new Map(tasks.flatMap(task => [[task.id, task] as const, ...(task.metadata.id ? [[task.metadata.id, task] as const] : [])]));
+ const seen = new Set();
+ const visit = (task: Task): boolean => {
+ if (task.id === source.id) return true;
+ if (seen.has(task.id)) return false; seen.add(task.id);
+ return (task.metadata.dependsOn || []).some(id => { const next = byId.get(id); return next ? visit(next) : false; });
+ }; return visit(target);
+}
+
+export class TaskDependencyPicker extends FuzzySuggestModal {
+ constructor(app: App, private plugin: TaskProgressBarPlugin, private source: Task, private tasks: Task[], private onSelected: (id: string) => void) {
+ super(app); this.setPlaceholder(t("Search for a task to depend on"));
+ }
+ getItems(): Task[] { return this.tasks.filter(task => task.id !== this.source.id && isDependencyTask(task) && !(this.source.metadata.dependsOn || []).includes(task.metadata.id || task.id)); }
+ getItemText(task: Task): string { return task.content; }
+ async onChooseItem(task: Task): Promise {
+ if (dependencyWouldCycle(this.tasks, this.source, task)) { new Notice(t("These tasks would depend on each other.")); return; }
+ try {
+ let id = task.metadata.id;
+ if (!id) {
+ id = `tg-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
+ const result = await this.plugin.writeAPI?.updateTask({ taskId: task.id, updates: { metadata: { ...task.metadata, id } } });
+ if (!result?.success) throw new Error(result?.error || t("Failed to update task"));
+ task.metadata = { ...task.metadata, id };
+ }
+ this.onSelected(id);
+ } catch (error) { new Notice(String(error)); }
+ }
+}
diff --git a/src/components/features/task/edit/TaskDetailsModal.ts b/src/components/features/task/edit/TaskDetailsModal.ts
index 1c1ae3b75..b95b758b3 100644
--- a/src/components/features/task/edit/TaskDetailsModal.ts
+++ b/src/components/features/task/edit/TaskDetailsModal.ts
@@ -1,136 +1,77 @@
-/**
- * Task Details Modal Component
- * Used in mobile environments to display the full task details and editing interface.
- */
-
-import { App, Modal, TFile, MarkdownView, ButtonComponent } from "obsidian";
-import { Task } from "@/types/task";
-import TaskProgressBarPlugin from "@/index";
-import { TaskMetadataEditor } from "./MetadataEditor";
+import { App, Notice } from "obsidian";
+import type { Task } from "@/types/task";
+import type TaskProgressBarPlugin from "@/index";
+import { QuickCaptureModal } from "@/components/features/quick-capture/modals/QuickCaptureModalWithSwitch";
+import { taskDatePrecisions } from "@/utils/date/optional-date-time";
import { t } from "@/translations/helper";
-export class TaskDetailsModal extends Modal {
+/** Editing uses the actual capture form, editor, preview and footer. */
+export class TaskDetailsModal extends QuickCaptureModal {
private task: Task;
- private plugin: TaskProgressBarPlugin;
- private metadataEditor: TaskMetadataEditor;
- private onTaskUpdated: (task: Task) => Promise;
-
- constructor(
- app: App,
- plugin: TaskProgressBarPlugin,
- task: Task,
- onTaskUpdated?: (task: Task) => Promise
- ) {
- super(app);
- this.task = task;
- this.plugin = plugin;
- this.onTaskUpdated = onTaskUpdated || (async () => {});
-
- // Set modal style
- this.modalEl.addClass("task-details-modal");
- this.titleEl.setText(t("Edit Task"));
- }
-
- onOpen() {
- const { contentEl } = this;
- contentEl.empty();
-
- // Create metadata editor, use full mode
- this.metadataEditor = new TaskMetadataEditor(
- contentEl,
- this.app,
- this.plugin,
- false // Full mode, not compact mode
- );
-
- // Initialize editor and display task
- this.metadataEditor.onload();
- this.metadataEditor.showTask(this.task);
-
- new ButtonComponent(this.contentEl)
- .setIcon("check")
- .setTooltip(t("Save"))
- .onClick(async () => {
- await this.onTaskUpdated(this.task);
- this.close();
- });
-
- // Listen for metadata change events
- this.metadataEditor.onMetadataChange = async (event) => {
- // Determine if the field is a top-level task property or metadata property
- const topLevelFields = ["status", "completed", "content"];
- const isTopLevelField = topLevelFields.includes(event.field);
-
- // Create a base task object with the updated field
- const updatedTask = {
- ...this.task,
- line: this.task.line - 1,
- id: `${this.task.filePath}-L${this.task.line - 1}`,
- };
-
- if (isTopLevelField) {
- // Update top-level task property
- (updatedTask as any)[event.field] = event.value;
- } else {
- // Update metadata property
- updatedTask.metadata = {
- ...this.task.metadata,
- [event.field]: event.value,
- };
- }
-
- // Handle special status field logic
- if (
- event.field === "status" &&
- (event.value === "x" || event.value === "X")
- ) {
- updatedTask.completed = true;
- updatedTask.metadata = {
- ...updatedTask.metadata,
- completedDate: Date.now(),
- };
- // Remove cancelled date if task is completed
- const { cancelledDate, ...metadataWithoutCancelledDate } =
- updatedTask.metadata;
- updatedTask.metadata = metadataWithoutCancelledDate;
- } else if (event.field === "status" && event.value === "-") {
- // If status is changing to cancelled, mark as not completed and add cancelled date
- updatedTask.completed = false;
- const { completedDate, ...metadataWithoutCompletedDate } =
- updatedTask.metadata;
- updatedTask.metadata = {
- ...metadataWithoutCompletedDate,
- cancelledDate: Date.now(),
- };
- } else if (event.field === "status") {
- // If status is changing to something else, mark as not completed
- updatedTask.completed = false;
- const {
- completedDate,
- cancelledDate,
- ...metadataWithoutDates
- } = updatedTask.metadata;
- updatedTask.metadata = metadataWithoutDates;
- }
-
- this.task = updatedTask;
- };
+ private closed = false;
+ private saving = false;
+ constructor(app: App, plugin: TaskProgressBarPlugin, task: Task, private onTaskUpdated?: (task: Task) => Promise) {
+ super(app, plugin, {}, true);
+ this.task = this.clone(task);
+ this.rememberCaptureMode = false;
+ this.currentMode = "checkbox"; this.inlineModeAvailable = true; this.fileModeAvailable = false;
+ this.setTitle(t("Edit Task"));
}
-
- onClose() {
- const { contentEl } = this;
- if (this.metadataEditor) {
- this.metadataEditor.onunload();
+ private clone(task: Task): Task { return { ...task, content: typeof task.content === "string" ? task.content : "", metadata: structuredClone(task.metadata || { tags: [], children: [] }) }; }
+ async onOpen(): Promise {
+ this.closed = false;
+ const query = this.plugin.dataflowOrchestrator?.getQueryAPI();
+ if (query) {
+ let tasks: Task[];
+ try { await this.plugin.dataflowOrchestrator?.refreshFile?.(this.task.filePath); tasks = await query.getAllTasks(true); }
+ catch (error) { if (!this.closed) { new Notice(String(error)); this.close(); } return; }
+ const latest = tasks.find(task => task.id === this.task.id) || tasks.filter(task => task.filePath === this.task.filePath && task.originalMarkdown === this.task.originalMarkdown).filter((_, index, matches) => matches.length === 1)[0];
+ if (this.closed) return;
+ if (!latest) { new Notice(t("This task no longer exists. Refresh the task list.")); this.close(); return; }
+ this.task = this.clone(latest);
}
- contentEl.empty();
+ this.sourceTask = this.task;
+ const metadata = this.task.metadata;
+ const date = (value: unknown) => value == null ? undefined : new Date(value as number);
+ this.taskMetadata = { status: this.task.status, priority: metadata.priority, project: typeof metadata.project === "string" ? metadata.project : undefined, context: metadata.context, tags: [...(metadata.tags || [])], points: metadata.points, dependsOn: [...(metadata.dependsOn || [])], startDate: date(metadata.startDate), dueDate: date(metadata.dueDate), scheduledDate: date(metadata.scheduledDate), datePrecision: taskDatePrecisions(this.task), manuallySet: { startDate: true, dueDate: true, scheduledDate: true } };
+ this.capturedContent = this.task.content;
+ this.contentEl.empty(); super.onOpen();
}
-
- /**
- * Updates a task field.
- */
- private updateTaskField(field: string, value: any) {
- if (field in this.task) {
- (this.task as any)[field] = value;
- }
+ protected createTargetFileSelector(root: HTMLElement): void {
+ if (this.taskMetadata.project && this.taskMetadata.project !== this.task?.metadata.project) { super.createTargetFileSelector(root); return; }
+ root.createDiv({ cls: "quick-capture-section-title", text: t("Capture to:") });
+ root.createDiv({ cls: "quick-capture-target", text: this.task?.filePath || "" });
+ }
+ protected createFooter(): void {
+ super.createFooter();
+ this.footerContainer?.querySelector(".quick-capture-footer-left")?.empty();
+ const button = this.footerContainer?.querySelector(".mod-cta"); if (button) button.textContent = t("Save");
+ }
+ protected async handleSubmit(): Promise { await this.save(); }
+ private async save(): Promise {
+ const content = this.markdownEditor?.value ?? this.capturedContent;
+ if (this.saving || !content.trim()) return;
+ this.saving = true;
+ try {
+ if (this.contentEl.querySelector('[aria-invalid="true"]')) throw new Error(t("Enter a valid date, optionally followed by HH:mm."));
+ const form = this.taskMetadata, status = form.status ?? this.task.status;
+ const metadata = { ...this.task.metadata, priority: form.priority, project: form.project, context: form.context, tags: [...(form.tags || [])], points: form.points, dependsOn: [...(form.dependsOn || [])], startDate: form.startDate?.getTime(), dueDate: form.dueDate?.getTime(), scheduledDate: form.scheduledDate?.getTime(), datePrecision: { ...this.task.metadata.datePrecision, ...form.datePrecision, startDate: form.datePrecision?.startDate, dueDate: form.datePrecision?.dueDate, scheduledDate: form.datePrecision?.scheduledDate } };
+ let completed = this.task.completed;
+ if (status !== this.task.status) {
+ completed = (this.plugin.settings.taskStatuses?.completed || "x").split("|").includes(status);
+ metadata.completedDate = completed ? metadata.completedDate || Date.now() : undefined;
+ metadata.cancelledDate = (this.plugin.settings.taskStatuses?.abandoned || "-").split("|").includes(status) ? metadata.cancelledDate || Date.now() : undefined;
+ }
+ const updated = { ...this.task, content, status, completed, metadata };
+ if (this.onTaskUpdated) await this.onTaskUpdated(updated);
+ else {
+ if (!this.plugin.writeAPI) throw new Error(t("Task writer is unavailable"));
+ const result = await this.plugin.writeAPI.updateTask({ taskId: this.task.id, updates: updated });
+ if (!result.success) throw new Error(result.error || t("Failed to update task"));
+ }
+ this.close();
+ } catch (error) { new Notice(String(error)); }
+ finally { this.saving = false; }
}
+ onClose(): void { this.closed = true; super.onClose(); }
}
diff --git a/src/components/features/task/edit/TaskDetailsPopover.ts b/src/components/features/task/edit/TaskDetailsPopover.ts
deleted file mode 100644
index 54f511573..000000000
--- a/src/components/features/task/edit/TaskDetailsPopover.ts
+++ /dev/null
@@ -1,278 +0,0 @@
-/**
- * Task Details Popover Component
- * Used in desktop environments to display task details in a menu popover.
- */
-
-import {
- App,
- debounce,
- MarkdownView,
- TFile,
- Component,
- CloseableComponent,
-} from "obsidian";
-import { createPopper, Instance as PopperInstance } from "@popperjs/core";
-import { Task } from "@/types/task";
-import TaskProgressBarPlugin from "@/index";
-import { TaskMetadataEditor } from "./MetadataEditor";
-import { t } from "@/translations/helper";
-
-export class TaskDetailsPopover
- extends Component
- implements CloseableComponent
-{
- private task: Task;
- private plugin: TaskProgressBarPlugin;
- private app: App;
- private popoverRef: HTMLDivElement | null = null;
- private metadataEditor: TaskMetadataEditor;
- private win: Window;
- private scrollParent: HTMLElement | Window;
- private popperInstance: PopperInstance | null = null;
-
- constructor(app: App, plugin: TaskProgressBarPlugin, task: Task) {
- super();
- this.app = app;
- this.plugin = plugin;
- this.task = task;
- this.win = app.workspace.containerEl.win || window;
- // Determine a reasonable scroll parent.
- const scrollEl = app.workspace.containerEl.closest(".cm-scroller");
- if (scrollEl instanceof HTMLElement) {
- this.scrollParent = scrollEl;
- } else {
- this.scrollParent = this.win;
- }
- }
-
- debounceUpdateTask = debounce(async (task: Task) => {
- // Use WriteAPI if dataflow is enabled
- if (this.plugin.writeAPI) {
- const result = await this.plugin.writeAPI.updateTask({
- taskId: task.id,
- updates: task
- });
- if (!result.success) {
- console.error("Failed to update task:", result.error);
- }
- } else {
- console.error("WriteAPI not available");
- }
- }, 200);
-
- /**
- * Shows the task details popover at the given position.
- */
- showAtPosition(position: { x: number; y: number }) {
- if (this.popoverRef) {
- this.close();
- }
-
- // Create content container
- const contentEl = createDiv({ cls: "task-popover-content" });
-
- // Create metadata editor, use compact mode
- this.metadataEditor = new TaskMetadataEditor(
- contentEl,
- this.app,
- this.plugin,
- true // Compact mode
- );
-
- // Initialize editor and display task
- this.metadataEditor.onload();
- this.metadataEditor.showTask(this.task);
-
- // Listen for metadata change events
- this.metadataEditor.onMetadataChange = async (event) => {
- // Determine if the field is a top-level task property or metadata property
- const topLevelFields = ["status", "completed", "content"];
- const isTopLevelField = topLevelFields.includes(event.field);
-
- // Create a base task object with the updated field
- const updatedTask = { ...this.task };
-
- if (isTopLevelField) {
- // Update top-level task property
- (updatedTask as any)[event.field] = event.value;
- } else {
- // Update metadata property
- updatedTask.metadata = {
- ...this.task.metadata,
- [event.field]: event.value,
- };
- }
-
- // Handle special status field logic
- if (
- event.field === "status" &&
- (event.value === "x" || event.value === "X")
- ) {
- updatedTask.completed = true;
- updatedTask.metadata = {
- ...updatedTask.metadata,
- completedDate: Date.now(),
- };
- // Remove cancelled date if task is completed
- const { cancelledDate, ...metadataWithoutCancelledDate } =
- updatedTask.metadata;
- updatedTask.metadata = metadataWithoutCancelledDate;
- } else if (event.field === "status" && event.value === "-") {
- // If status is changing to cancelled, mark as not completed and add cancelled date
- updatedTask.completed = false;
- const { completedDate, ...metadataWithoutCompletedDate } =
- updatedTask.metadata;
- updatedTask.metadata = {
- ...metadataWithoutCompletedDate,
- cancelledDate: Date.now(),
- };
- } else if (event.field === "status") {
- // If status is changing to something else, mark as not completed
- updatedTask.completed = false;
- const {
- completedDate,
- cancelledDate,
- ...metadataWithoutDates
- } = updatedTask.metadata;
- updatedTask.metadata = metadataWithoutDates;
- }
-
- // Update the internal task reference
- this.task = updatedTask;
-
- // Update the task with all changes
- this.debounceUpdateTask(updatedTask);
- };
-
- // Create the popover
- this.popoverRef = this.app.workspace.containerEl.createDiv({
- cls: "task-details-popover tg-menu bm-menu", // Borrowing some classes from IconMenu
- });
- this.popoverRef.appendChild(contentEl);
-
- // Add a title bar to the popover
- const titleBar = this.popoverRef.createDiv({
- cls: "tg-popover-titlebar",
- text: t("Task Details"),
- });
- // Prepend titleBar to popoverRef so it's at the top
- this.popoverRef.insertBefore(titleBar, this.popoverRef.firstChild);
-
- document.body.appendChild(this.popoverRef);
-
- // Create a virtual element for Popper.js
- const virtualElement = {
- getBoundingClientRect: () => ({
- width: 0,
- height: 0,
- top: position.y,
- right: position.x,
- bottom: position.y,
- left: position.x,
- x: position.x,
- y: position.y,
- toJSON: function () {
- return this;
- },
- }),
- };
-
- if (this.popoverRef) {
- this.popperInstance = createPopper(
- virtualElement,
- this.popoverRef,
- {
- placement: "bottom-start",
- modifiers: [
- {
- name: "offset",
- options: {
- offset: [0, 8], // Offset the popover slightly
- },
- },
- {
- name: "preventOverflow",
- options: {
- padding: 10, // Padding from viewport edges
- },
- },
- {
- name: "flip",
- options: {
- fallbackPlacements: [
- "top-start",
- "right-start",
- "left-start",
- ],
- padding: 10,
- },
- },
- ],
- }
- );
- }
-
- // Use timeout to ensure popover is rendered before adding listeners
- this.win.setTimeout(() => {
- this.win.addEventListener("click", this.clickOutside);
- this.scrollParent.addEventListener(
- "scroll",
- this.scrollHandler,
- true
- ); // Use capture for scroll
- }, 10);
- }
-
- private clickOutside = (e: MouseEvent) => {
- if (this.popoverRef && !this.popoverRef.contains(e.target as Node)) {
- this.close();
- }
- };
-
- private scrollHandler = (e: Event) => {
- if (this.popoverRef) {
- if (
- e.target instanceof Node &&
- this.popoverRef.contains(e.target)
- ) {
- const targetElement = e.target as HTMLElement;
- if (
- targetElement.scrollHeight > targetElement.clientHeight ||
- targetElement.scrollWidth > targetElement.clientWidth
- ) {
- // If the scroll event is within the popover and the popover itself is scrollable,
- // do not close it. This allows scrolling within the popover content.
- return;
- }
- }
- // For other scroll events (e.g., scrolling the main window), close the popover.
- this.close();
- }
- };
-
- /**
- * Closes the popover.
- */
- close() {
- if (this.popperInstance) {
- this.popperInstance.destroy();
- this.popperInstance = null;
- }
-
- if (this.popoverRef) {
- this.popoverRef.remove();
- this.popoverRef = null;
- }
-
- this.win.removeEventListener("click", this.clickOutside);
- this.scrollParent.removeEventListener(
- "scroll",
- this.scrollHandler,
- true
- );
-
- if (this.metadataEditor) {
- this.metadataEditor.onunload();
- }
- }
-}
diff --git a/src/components/features/task/filter/in-view/filter-pill.ts b/src/components/features/task/filter/in-view/filter-pill.ts
index 79648472e..a11e6bfbb 100644
--- a/src/components/features/task/filter/in-view/filter-pill.ts
+++ b/src/components/features/task/filter/in-view/filter-pill.ts
@@ -1,3 +1,4 @@
+import { t as settingsText } from "@/translations/helper";
import { Component, ExtraButtonComponent } from "obsidian";
import { ActiveFilter, FilterPillOptions } from "./filter-type";
@@ -37,7 +38,7 @@ export class FilterPill extends Component {
// Create the remove button
const removeButton = pill.createEl("span", {
cls: "filter-pill-remove",
- attr: { "aria-label": "Remove filter" },
+ attr: { "aria-label": settingsText("Remove filter") },
});
// Create and append the remove icon span inside the button
diff --git a/src/components/features/task/view/BulkOperationsMenu.ts b/src/components/features/task/view/BulkOperationsMenu.ts
index bc526b663..5ac265293 100644
--- a/src/components/features/task/view/BulkOperationsMenu.ts
+++ b/src/components/features/task/view/BulkOperationsMenu.ts
@@ -17,6 +17,7 @@ import { BulkDateOffsetModal } from "@/components/ui/date-picker/BulkDateOffsetM
import { addDays } from "date-fns";
import { getCachedData } from "@/components/ui/inputs/AutoComplete";
import { getAllStatusMarks } from "@/utils/status-cycle-resolver";
+import { ProjectFileManager } from "@/managers/project-file-manager";
/**
* Create and show bulk operations menu
@@ -715,21 +716,26 @@ async function executeBulkMoveToProject(
onOperationComplete: () => void,
): Promise {
const tasks = selectionManager.getSelectedTasks();
-
- const result = await executeBulkOperation(
- tasks,
- (task) => {
- return {
- metadata: {
- ...task.metadata,
- project,
- },
- };
- },
- plugin,
- );
-
- showOperationResult(result, `Moved to project "${project}"`);
+ try {
+ const prefixes = Object.values(plugin.settings.projectTagPrefix || {}).map(String);
+ const manager = new ProjectFileManager(plugin.app, prefixes.length ? prefixes : ["project"]);
+ const projectNote = await manager.create(project);
+ if (!projectNote) throw new Error(t("Could not create project note"));
+ const canvasTasks = tasks.filter(task => task.metadata?.sourceType === "canvas" || task.filePath.toLowerCase().endsWith(".canvas"));
+ const markdownTasks = tasks.filter(task => !canvasTasks.includes(task));
+ let movedCount = await manager.moveTasks(markdownTasks, project);
+ for (const task of canvasTasks) {
+ const result = await plugin.writeAPI?.updateTask({
+ taskId: task.id,
+ updates: { metadata: { ...task.metadata, project } as any },
+ });
+ if (result?.success) movedCount++;
+ }
+ new Notice(`${t('Moved to project')} "${project}": ${movedCount} ${t("tasks")}`);
+ } catch (error) {
+ console.error("Bulk move to project failed", error);
+ new Notice(t("Failed to move project tasks"));
+ }
selectionManager.exitSelectionMode("operation_complete");
onOperationComplete();
}
diff --git a/src/components/features/task/view/InlineEditor.ts b/src/components/features/task/view/InlineEditor.ts
index 3c6d21e28..8dfbd2bde 100644
--- a/src/components/features/task/view/InlineEditor.ts
+++ b/src/components/features/task/view/InlineEditor.ts
@@ -1,3 +1,5 @@
+import { renderTaskDependencies } from "@/components/features/task/edit/TaskDependencyPicker";
+import { t as settingsText } from "@/translations/helper";
import { App, Component, debounce, setIcon, Menu } from "obsidian";
import { StandardTaskMetadata, Task } from "@/types/task";
import TaskProgressBarPlugin from "@/index";
@@ -587,7 +589,7 @@ export class InlineEditor extends Component {
// Add priority options
const options = [
- { value: "", text: "None" },
+ { value: "", text: settingsText("None") },
{ value: "1", text: "⏬️ Lowest" },
{ value: "2", text: "🔽 Low" },
{ value: "3", text: "🔼 Medium" },
@@ -749,51 +751,12 @@ export class InlineEditor extends Component {
modal.open();
}
- private createDependsOnEditor(
- container: HTMLElement,
- currentValue?: string
- ): void {
- const input = container.createEl("input", {
- type: "text",
- cls: "inline-dependson-input",
- value:
- currentValue ||
- (this.task.metadata.dependsOn
- ? this.task.metadata.dependsOn.join(", ")
- : ""),
- placeholder: "Task IDs separated by commas",
+ private createDependsOnEditor(container: HTMLElement, currentValue?: string): void {
+ renderTaskDependencies(this.app, this.plugin, container, this.task, ids => {
+ this.task.metadata.dependsOn = ids;
+ const target = container.closest(".inline-metadata-editor")?.parentElement as HTMLElement;
+ if (target) void this.finishMetadataEdit(target, "dependsOn");
});
-
- this.activeInput = input;
-
- // Prevent event bubbling on input element
- this.registerDomEvent(
- input,
- "click",
- this.boundHandlers.stopPropagation
- );
- this.registerDomEvent(
- input,
- "mousedown",
- this.boundHandlers.stopPropagation
- );
-
- const updateDependsOn = (value: string) => {
- if (value.trim()) {
- this.task.metadata.dependsOn = value
- .split(",")
- .map((id) => id.trim())
- .filter((id) => id.length > 0);
- } else {
- this.task.metadata.dependsOn = undefined;
- }
- };
-
- this.setupInputEvents(input, updateDependsOn, "dependsOn");
-
- // Focus and select
- input.focus();
- input.select();
}
private createIdEditor(
@@ -995,19 +958,17 @@ export class InlineEditor extends Component {
const menu = new Menu();
const availableFields = [
- { key: "project", label: "Project", icon: "folder" },
- { key: "tags", label: "Tags", icon: "tag" },
- { key: "context", label: "Context", icon: "at-sign" },
- { key: "dueDate", label: "Due Date", icon: "calendar" },
- { key: "startDate", label: "Start Date", icon: "play" },
- { key: "scheduledDate", label: "Scheduled Date", icon: "clock" },
+ { key: "project", label: settingsText("Project"), icon: "folder" },
+ { key: "tags", label: settingsText("Tags"), icon: "tag" },
+ { key: "context", label: settingsText("Context"), icon: "at-sign" },
+ { key: "dueDate", label: settingsText("Due Date"), icon: "calendar" },
+ { key: "startDate", label: settingsText("Start Date"), icon: "play" },
+ { key: "scheduledDate", label: settingsText("Scheduled Date"), icon: "clock" },
{ key: "cancelledDate", label: "Cancelled Date", icon: "x" },
{ key: "completedDate", label: "Completed Date", icon: "check" },
- { key: "priority", label: "Priority", icon: "alert-triangle" },
- { key: "recurrence", label: "Recurrence", icon: "repeat" },
- { key: "onCompletion", label: "On Completion", icon: "flag" },
+ { key: "priority", label: settingsText("Priority"), icon: "alert-triangle" },
+ { key: "onCompletion", label: settingsText("On Completion"), icon: "flag" },
{ key: "dependsOn", label: "Depends On", icon: "link" },
- { key: "id", label: "Task ID", icon: "hash" },
];
// Filter out fields that already have values
diff --git a/src/components/features/task/view/ProjectTreeComponent.ts b/src/components/features/task/view/ProjectTreeComponent.ts
index 268c7f15c..ff0b4e8ee 100644
--- a/src/components/features/task/view/ProjectTreeComponent.ts
+++ b/src/components/features/task/view/ProjectTreeComponent.ts
@@ -1,3 +1,4 @@
+import { ProjectFileManager } from "@/managers/project-file-manager";
import { Component, App } from "obsidian";
import { TreeNode, ProjectNodeData } from "@/types/tree";
import { TreeComponent } from "@/components/ui/tree/TreeComponent";
@@ -49,6 +50,9 @@ export class ProjectTreeComponent extends Component {
text: node.name,
});
+ const manager = new ProjectFileManager(this.app), color = manager.find(node.fullPath)?.color;
+ if (color) nameEl.style.color = color;
+ manager.bindReorder(contentEl, node.fullPath, () => manager.list().sort((a, b) => manager.compareNames(a.name, b.name)).map(project => project.name), () => { if (this.projectTree) this.setTree(this.projectTree, this.allTasks); void this.plugin.triggerViewUpdate(); });
// Task count badges
const countsEl = contentEl.createSpan({
cls: "project-tree-item-counts",
@@ -187,11 +191,13 @@ export class ProjectTreeComponent extends Component {
* Set the project tree directly (instead of building from tasks)
*/
public setTree(tree: TreeNode, tasks: Task[]): void {
- this.projectTree = tree;
+ const manager = new ProjectFileManager(this.app);
+ const ordered = (node: TreeNode): TreeNode => ({ ...node, children: node.children.map(ordered).sort((a, b) => manager.compareNames(a.fullPath, b.fullPath)) });
+ this.projectTree = ordered(tree);
this.allTasks = tasks;
// Set tree in component
- this.treeComponent.setTree(tree);
+ this.treeComponent.setTree(this.projectTree);
}
/**
diff --git a/src/components/features/task/view/TaskList.ts b/src/components/features/task/view/TaskList.ts
index 42598a12d..6655696af 100644
--- a/src/components/features/task/view/TaskList.ts
+++ b/src/components/features/task/view/TaskList.ts
@@ -1,3 +1,4 @@
+import { buildVisibleTaskTree } from "@/utils/ui/tree-view-utils";
import { App, Component } from "obsidian";
import { Task } from "@/types/task";
import { TaskListItemComponent } from "./listItem";
@@ -76,7 +77,8 @@ export class TaskListRendererComponent extends Component {
); // Show error
return;
}
- this.renderTreeView(tasks, this.allTasksMap); // Pass the map
+ const visible = buildVisibleTaskTree(tasks);
+ this.renderTreeView([...visible.taskMap.values()], visible.taskMap); // Pass the map
} else {
this.renderListView(tasks);
}
diff --git a/src/components/features/task/view/TaskStatusIndicator.ts b/src/components/features/task/view/TaskStatusIndicator.ts
index 445539b74..ec998feb0 100644
--- a/src/components/features/task/view/TaskStatusIndicator.ts
+++ b/src/components/features/task/view/TaskStatusIndicator.ts
@@ -1,4 +1,5 @@
-import { Component, Menu } from "obsidian";
+import { getTaskStatusGroup } from "@/utils/status-cycle-resolver";
+import { Component, Menu, setIcon } from "obsidian";
import TaskProgressBarPlugin from "@/index";
import { Task } from "@/types/task";
@@ -224,6 +225,9 @@ export class TaskStatusIndicator extends Component {
? `, next: ${context.nextStatus}`
: "";
+ this.element.querySelector(".task-status-indicator__icon")?.remove();
+ const paused = getTaskStatusGroup(context.currentMark, this.plugin.settings) === "archived";
+ if (paused) { const icon = this.element.createSpan({ cls: "task-status-indicator__icon" }); setIcon(icon, "pause"); this.element.insertBefore(icon, this.statusTextEl); }
this.statusTextEl.setText(context.displayName);
this.element.setAttribute("data-status", context.statusSlug);
this.element.setAttribute("data-status-mark", context.currentMark);
@@ -454,6 +458,7 @@ export class TaskStatusIndicator extends Component {
}
private formatStatusKey(key: string): string {
+ if (["archived", "paused", "pause"].includes(key.toLowerCase())) return "Paused";
return key
.replace(/([a-z])([A-Z])/g, "$1 $2")
.replace(/[-_]+/g, " ")
diff --git a/src/components/features/task/view/content.ts b/src/components/features/task/view/content.ts
index e56a74c80..19024a274 100644
--- a/src/components/features/task/view/content.ts
+++ b/src/components/features/task/view/content.ts
@@ -9,7 +9,7 @@ import {
import { Task } from "@/types/task";
import { TaskListItemComponent } from "./listItem"; // Re-import needed components
import { ViewMode, getViewSettingOrDefault } from "@/common/setting-definition"; // 导入 SortCriterion
-import { tasksToTree } from "@/utils/ui/tree-view-utils"; // Re-import needed utils
+import { tasksToTree, buildVisibleTaskTree } from "@/utils/ui/tree-view-utils"; // Re-import needed utils
import { TaskTreeItemComponent } from "./treeItem"; // Re-import needed components
import { t } from "@/translations/helper";
import TaskProgressBarPlugin from "@/index";
@@ -90,10 +90,20 @@ export class ContentComponent extends Component {
private selectedProjectForView: string | null = null; // Keep track if a specific project is filtered (for project view)
private focusFilter: string | null = null; // Keep focus filter if needed
private isTreeView: boolean = false;
+ private externallyFiltered = false;
+ private searchQuery = "";
+ public setSearchQuery(query: string): void {
+ if (this.searchQuery === query) return;
+ this.searchQuery = query; this.pendingForceRefresh = true;
+ this.debounceRefreshTaskList();
+ }
private isRendering: boolean = false; // Guard against concurrent renders
private pendingForceRefresh: boolean = false; // Track if a force refresh is pending
private pendingVisibilityRetry: boolean = false; // Queue a retry when container becomes visible
private visibilityRetryCount: number = 0; // Limit visibility retry loop
+ private refreshFrame: number | null = null;
+ private visibilityRetryTimer: number | null = null;
+ private disposed = false;
private lastAllTasksSignature = "";
private lastNotFilteredTasksSignature = "";
constructor(
@@ -106,6 +116,7 @@ export class ContentComponent extends Component {
}
onload() {
+ this.disposed = false;
// Create main content container
this.containerEl = this.parentEl.createDiv({ cls: "task-content" });
@@ -123,6 +134,22 @@ export class ContentComponent extends Component {
// Set up intersection observer for lazy loading
this.initializeVirtualList();
+ if (typeof ResizeObserver !== "undefined") {
+ const observer = new ResizeObserver(() => {
+ if (this.pendingForceRefresh && this.isContainerVisible()) this.debounceRefreshTaskList();
+ });
+ observer.observe(this.containerEl);
+ this.register(() => observer.disconnect());
+ }
+ this.registerEvent(this.app.workspace.on("active-leaf-change", () => {
+ if (this.pendingForceRefresh) this.debounceRefreshTaskList();
+ }));
+ }
+
+ public onShown(): void {
+ if (this.disposed) return;
+ this.pendingForceRefresh = true;
+ this.debounceRefreshTaskList();
}
private createContentHeader() {
@@ -217,6 +244,10 @@ export class ContentComponent extends Component {
}
private toggleViewMode() {
+ if (this.topNavigation) {
+ this.topNavigation.selectViewMode(this.isTreeView ? "list" : "tree");
+ return;
+ }
this.isTreeView = !this.isTreeView;
const viewToggleBtn = this.headerEl.querySelector(
".view-toggle-btn"
@@ -234,6 +265,7 @@ export class ContentComponent extends Component {
public setIsTreeView(isTree: boolean) {
if (this.isTreeView !== isTree) {
this.isTreeView = isTree;
+ this.pendingForceRefresh = true;
const viewToggleBtn = this.headerEl?.querySelector(
".view-toggle-btn"
) as HTMLElement;
@@ -311,6 +343,7 @@ export class ContentComponent extends Component {
* Apply grouping to filtered tasks
*/
private applyGrouping() {
+ this.cleanupGroupRenderers();
if (this.groupByDimension === "none") {
this.taskGroups = [];
return;
@@ -367,7 +400,7 @@ export class ContentComponent extends Component {
sectionEl.setAttribute("data-level", level.toString());
// Restore expanded state from localStorage
- group.isExpanded = getGroupExpandedState(this.currentViewId, group.key);
+ group.isExpanded = !!this.searchQuery.trim() || getGroupExpandedState(this.currentViewId, group.key);
// Section header
const headerEl = sectionEl.createDiv({
@@ -537,19 +570,24 @@ export class ContentComponent extends Component {
* Cleanup group renderers
*/
private cleanupGroupRenderers() {
- this.taskGroups.forEach((group) => {
- if (group.renderer) {
- this.removeChild(group.renderer);
- group.renderer = undefined;
+ const cleanup = (groups: TaskGroup[]) => {
+ for (const group of groups) {
+ if (group.children) cleanup(group.children);
+ if (group.renderer) { this.removeChild(group.renderer); group.renderer = undefined; }
}
- });
+ };
+ cleanup(this.taskGroups);
}
public setTasks(
tasks: Task[],
notFilteredTasks: Task[],
- forceRefresh: boolean = false
+ forceRefresh: boolean = false,
+ externallyFiltered: boolean = false
) {
+ if (this.externallyFiltered !== externallyFiltered) forceRefresh = true;
+ this.externallyFiltered = externallyFiltered;
+ if (tasks.length && this.taskListEl && !this.taskListEl.querySelector(".task-item, .task-tree-item, .task-group, .group-section")) forceRefresh = true;
const updateSignatures = () => {
this.lastAllTasksSignature = this.computeTaskSignature(tasks);
this.lastNotFilteredTasksSignature =
@@ -560,7 +598,6 @@ export class ContentComponent extends Component {
if (forceRefresh) {
console.log("ContentComponent: Forced refresh requested");
// Cancel any ongoing rendering if force refresh is requested
- this.isRendering = false;
this.pendingForceRefresh = true;
this.allTasks = tasks;
this.notFilteredTasks = notFilteredTasks;
@@ -574,20 +611,13 @@ export class ContentComponent extends Component {
return;
}
- // If a force refresh is pending, skip non-forced updates
- if (this.pendingForceRefresh) {
- console.log(
- "ContentComponent: Skipping non-forced update, force refresh is pending"
- );
- return;
- }
-
const nextAllSignature = this.computeTaskSignature(tasks);
const nextNotFilteredSignature =
this.computeTaskSignature(notFilteredTasks);
if (
nextAllSignature === this.lastAllTasksSignature &&
- nextNotFilteredSignature === this.lastNotFilteredTasksSignature
+ nextNotFilteredSignature === this.lastNotFilteredTasksSignature &&
+ !this.pendingForceRefresh
) {
console.log(
"ContentComponent: Task signatures unchanged, skipping refresh"
@@ -610,6 +640,7 @@ export class ContentComponent extends Component {
// Updated method signature
public setViewMode(viewId: ViewMode, project?: string | null) {
const previousViewId = this.currentViewId;
+ const sameContext = previousViewId === viewId && this.selectedProjectForView === (project ?? null);
this.currentViewId = viewId;
this.selectedProjectForView = project === undefined ? null : project;
@@ -618,9 +649,10 @@ export class ContentComponent extends Component {
let title = t(viewConfig.name);
this.titleEl.setText(title);
+ if (sameContext) return;
// Re-initialize view mode for the new view
- this.initializeViewMode();
+ if (previousViewId !== viewId) this.initializeViewMode();
// Re-initialize Group By for the new view
this.initializeGroupBy();
@@ -642,6 +674,10 @@ export class ContentComponent extends Component {
* Set the TopNavigation reference and register buttons
*/
public setTopNavigation(nav: TopNavigation | null): void {
+ if (this.topNavigation === nav) {
+ if (nav) { this.registerGroupByButton(); this.registerWorkingOnButtons(); }
+ return;
+ }
// Unregister old buttons if exists
if (this.topNavigation) {
this.unregisterGroupByButton();
@@ -818,7 +854,7 @@ export class ContentComponent extends Component {
private applyFilters() {
// Call the centralized filter utility
- this.filteredTasks = filterTasks(
+ this.filteredTasks = this.externallyFiltered ? [...this.allTasks] : filterTasks(
this.allTasks,
this.currentViewId,
this.plugin,
@@ -835,6 +871,7 @@ export class ContentComponent extends Component {
this.plugin.settings
);
} else {
+ const collator = new Intl.Collator(undefined, {usage:"sort", sensitivity:"base", numeric:true});
// Default sorting: completed tasks last, then by priority, due date, content,
// with lowest-priority tie-breakers: filePath -> line
this.filteredTasks.sort((a, b) => {
@@ -853,11 +890,7 @@ export class ContentComponent extends Component {
if (dueA !== dueB) return dueA - dueB;
// Content compare (case-insensitive numeric aware)
- const collator = new Intl.Collator(undefined, {
- usage: "sort",
- sensitivity: "base",
- numeric: true,
- });
+
const contentCmp = collator.compare(
a.content ?? "",
b.content ?? ""
@@ -921,16 +954,23 @@ export class ContentComponent extends Component {
private isContainerVisible(): boolean {
if (!this.containerEl) return false;
- const inDom = document.body.contains(this.containerEl);
+ const inDom = this.containerEl.isConnected;
if (!inDom) return false;
if (!this.containerEl.isShown()) return false;
const rect = this.containerEl.getBoundingClientRect();
return rect.width > 0 && rect.height > 0;
}
- private debounceRefreshTaskList = debounce(this.refreshTaskList, 150);
+ private debounceRefreshTaskList = () => {
+ if (this.disposed || this.refreshFrame !== null) return;
+ this.refreshFrame = window.requestAnimationFrame(() => {
+ this.refreshFrame = null;
+ if (!this.disposed) this.refreshTaskList();
+ });
+ };
private refreshTaskList() {
+ if (this.disposed) return;
console.log("refreshing");
// Defer rendering if container is not visible yet (e.g., view hidden during init)
if (!this.isContainerVisible()) {
@@ -938,6 +978,8 @@ export class ContentComponent extends Component {
if (!this.pendingVisibilityRetry) {
this.pendingVisibilityRetry = true;
const tryAgain = () => {
+ this.visibilityRetryTimer = null;
+ if (this.disposed) return;
if (this.isContainerVisible()) {
this.pendingVisibilityRetry = false;
this.visibilityRetryCount = 0;
@@ -949,7 +991,7 @@ export class ContentComponent extends Component {
}
if (this.visibilityRetryCount < 30) {
this.visibilityRetryCount++;
- setTimeout(tryAgain, 100);
+ this.visibilityRetryTimer = window.setTimeout(tryAgain, 100);
} else {
this.pendingVisibilityRetry = false;
this.visibilityRetryCount = 0;
@@ -969,6 +1011,7 @@ export class ContentComponent extends Component {
return;
}
+ this.pendingForceRefresh = false;
this.isRendering = true;
// Capture scroll state to mitigate scrollbar jumping
@@ -1016,12 +1059,8 @@ export class ContentComponent extends Component {
const renderTarget = document.createDocumentFragment();
if (this.isTreeView) {
- const taskMap = new Map();
- // Add all non-filtered tasks to the taskMap
- this.notFilteredTasks.forEach((task) =>
- taskMap.set(task.id, task)
- );
- this.rootTasks = tasksToTree(this.filteredTasks); // Calculate root tasks
+ const { taskMap, roots } = buildVisibleTaskTree(this.filteredTasks);
+ this.rootTasks = roots;
// Sort roots according to view's sort criteria (fallback to sensible defaults)
const viewSortCriteria =
this.plugin.settings.viewConfiguration.find(
@@ -1085,15 +1124,8 @@ export class ContentComponent extends Component {
// Restore scroll state after render
this.restoreScrollState(prevScrollState);
} finally {
- // Reset rendering flag after completion
- setTimeout(() => {
- this.isRendering = false;
- // If a refresh was queued during rendering, process it now
- if (this.pendingForceRefresh) {
- this.pendingForceRefresh = false;
- this.refreshTaskList();
- }
- }, 50); // Small delay to prevent immediate re-entry
+ this.isRendering = false;
+ if (this.pendingForceRefresh) this.debounceRefreshTaskList();
}
}
@@ -1208,18 +1240,9 @@ export class ContentComponent extends Component {
const start = this.nextRootTaskIndex;
const end = Math.min(start + countToLoad, this.rootTasks.length);
- // Make sure all non-filtered tasks are in the taskMap
- this.notFilteredTasks.forEach((task) => {
- if (!taskMap.has(task.id)) {
- taskMap.set(task.id, task);
- }
- });
-
for (let i = start; i < end; i++) {
const rootTask = this.rootTasks[i];
- const childTasks = this.notFilteredTasks.filter(
- (task) => task.metadata.parent === rootTask.id
- );
+ const childTasks = (rootTask.metadata.children || []).map(id => taskMap.get(id)).filter((task): task is Task => !!task);
const treeComponent = new TaskTreeItemComponent(
rootTask,
@@ -1680,6 +1703,11 @@ export class ContentComponent extends Component {
}
onunload() {
+ this.disposed = true;
+ if (this.refreshFrame !== null) window.cancelAnimationFrame(this.refreshFrame);
+ if (this.visibilityRetryTimer !== null) window.clearTimeout(this.visibilityRetryTimer);
+ this.refreshFrame = null;
+ this.visibilityRetryTimer = null;
// Unregister Group By button from TopNavigation
this.unregisterGroupByButton();
diff --git a/src/components/features/task/view/details.ts b/src/components/features/task/view/details.ts
index 8b7f15218..bce4fe816 100644
--- a/src/components/features/task/view/details.ts
+++ b/src/components/features/task/view/details.ts
@@ -1,3 +1,4 @@
+import { renderTaskDependencies } from "@/components/features/task/edit/TaskDependencyPicker";
import {
Component,
ExtraButtonComponent,
@@ -25,7 +26,6 @@ import {
getEffectiveProject,
isProjectReadonly,
} from "@/utils/task/task-operations";
-import { OnCompletionConfigurator } from "@/components/features/on-completion/OnCompletionConfigurator";
import {
timestampToLocalDateString,
localDateStringToTimestamp,
@@ -44,9 +44,12 @@ function getStatus(task: Task, settings: TaskProgressBarSettings) {
planned: "Planned",
completed: "Completed",
inProgress: "In Progress",
+ archived: "Paused",
+ paused: "Paused",
+ pause: "Paused",
};
- return statusTextMap[status as keyof typeof statusTextMap] || "No status";
+ return statusTextMap[status as keyof typeof statusTextMap] || "Paused";
}
export function getStatusText(
@@ -59,9 +62,12 @@ export function getStatusText(
planned: "Planned",
completed: "Completed",
inProgress: "In Progress",
+ archived: "Paused",
+ paused: "Paused",
+ pause: "Paused",
};
- return statusTextMap[status as keyof typeof statusTextMap] || "No status";
+ return statusTextMap[status as keyof typeof statusTextMap] || "Paused";
}
function mapTextStatusToSymbol(status: string): string {
@@ -74,6 +80,8 @@ function mapTextStatusToSymbol(status: string): string {
"in-progress": "/",
"in progress": "/",
doing: "/",
+ pause: "p",
+ paused: "p",
planned: "?",
todo: "?",
cancelled: "-",
@@ -355,7 +363,7 @@ export class TaskDetailsComponent extends Component {
// Get effective project and readonly status
const effectiveProject = getEffectiveProject(task);
- const isReadonly = isProjectReadonly(task);
+ const isReadonly = isProjectReadonly(task) && task.metadata?.sourceType !== "file";
const projectInput = new TextComponent(projectField);
projectInput.setValue(effectiveProject || "");
@@ -543,9 +551,6 @@ export class TaskDetailsComponent extends Component {
addTagFromInput();
});
- tagsField
- .createSpan({ cls: "field-description" })
- .setText(t("Click + to add tags. Click × on a tag to remove it."));
renderTags();
@@ -639,12 +644,6 @@ export class TaskDetailsComponent extends Component {
);
}
- // On completion action
- const onCompletionField = this.createFormField(
- this.editFormEl,
- t("On Completion")
- );
-
// Create a debounced save function
const saveTask = debounce(async () => {
// Create updated task object
@@ -759,24 +758,8 @@ export class TaskDetailsComponent extends Component {
// onCompletion is now handled by OnCompletionConfigurator
// Update dependencies
- const dependsOnValue = dependsOnInput.getValue();
- metadata.dependsOn = dependsOnValue
- ? dependsOnValue
- .split(",")
- .map((id) => id.trim())
- .filter((id) => id)
- : undefined;
+ metadata.dependsOn = dependencyPicker.getValue();
- const onCompletionValue = onCompletionConfigurator.getValue();
- metadata.onCompletion = onCompletionValue || undefined;
-
- // Update task ID
- const taskIdValue = taskIdInput.getValue();
- metadata.id = taskIdValue || undefined;
-
- // Update recurrence
- const recurrenceValue = recurrenceInput.getValue();
- metadata.recurrence = recurrenceValue || undefined;
// Assign updated metadata back to task
updatedTask.metadata = metadata;
@@ -803,88 +786,9 @@ export class TaskDetailsComponent extends Component {
requestSave = () => saveTask();
// Use OnCompletionConfigurator directly
- const onCompletionConfigurator = new OnCompletionConfigurator(
- onCompletionField,
- this.plugin,
- {
- initialValue: task.metadata.onCompletion || "",
- onChange: (value) => {
- console.log(value, "onCompletion value changed");
- // Use smarter save logic: allow basic configurations to save immediately
- // and allow partial configurations for complex types
- const config = onCompletionConfigurator.getConfig();
- const shouldSave = this.shouldTriggerOnCompletionSave(
- config,
- value
- );
-
- if (shouldSave) {
- // Trigger save - the saveTask function will get the latest value
- // from onCompletionConfigurator.getValue() to avoid data races
- saveTask();
- }
- },
- onValidationChange: (isValid, error) => {
- // Show validation feedback
- const existingMessage = onCompletionField.querySelector(
- ".oncompletion-validation-message"
- );
- if (existingMessage) {
- existingMessage.remove();
- }
-
- if (error) {
- const messageEl = onCompletionField.createDiv({
- cls: "oncompletion-validation-message error",
- text: error,
- });
- } else if (isValid) {
- const messageEl = onCompletionField.createDiv({
- cls: "oncompletion-validation-message success",
- text: t("Configuration is valid"),
- });
- }
- },
- }
- );
-
- this.addChild(onCompletionConfigurator);
-
- // Dependencies
- const dependsOnField = this.createFormField(
- this.editFormEl,
- t("Depends On")
- );
- const dependsOnInput = new TextComponent(dependsOnField);
- dependsOnInput.setValue(
- Array.isArray(task.metadata.dependsOn)
- ? task.metadata.dependsOn.join(", ")
- : task.metadata.dependsOn || ""
- );
- dependsOnField
- .createSpan({ cls: "field-description" })
- .setText(
- t("Comma-separated list of task IDs this task depends on")
- );
-
- // Task ID
- const taskIdField = this.createFormField(this.editFormEl, t("Task ID"));
- const taskIdInput = new TextComponent(taskIdField);
- taskIdInput.setValue(task.metadata.id || "");
- taskIdField
- .createSpan({ cls: "field-description" })
- .setText(t("Unique identifier for this task"));
-
- // Recurrence pattern
- const recurrenceField = this.createFormField(
- this.editFormEl,
- t("Recurrence")
- );
- const recurrenceInput = new TextComponent(recurrenceField);
- recurrenceInput.setValue(task.metadata.recurrence || "");
- recurrenceField
- .createSpan({ cls: "field-description" })
- .setText(t("e.g. every day, every 2 weeks"));
+ // Dependencies are selected by task title; identifiers are managed internally.
+ const dependsOnField = this.createFormField(this.editFormEl, t("Depends On"));
+ const dependencyPicker = renderTaskDependencies(this.app, this.plugin, dependsOnField, task, () => saveTask());
// Register blur events for all input elements
const registerBlurEvent = (
@@ -913,9 +817,6 @@ export class TaskDetailsComponent extends Component {
// registerBlurEvent(startDateInput);
// registerBlurEvent(scheduledDateInput);
// onCompletion input is now handled by OnCompletionConfigurator or in fallback
- registerBlurEvent(dependsOnInput.inputEl);
- registerBlurEvent(taskIdInput.inputEl);
- registerBlurEvent(recurrenceInput.inputEl);
// Register change events for date inputs
registerDateChangeEvent(dueDateInput);
diff --git a/src/components/features/task/view/forecast.ts b/src/components/features/task/view/forecast.ts
index 9a64e320f..5475786cb 100644
--- a/src/components/features/task/view/forecast.ts
+++ b/src/components/features/task/view/forecast.ts
@@ -753,10 +753,7 @@ export class ForecastComponent extends Component {
title: title,
date: date,
tasks: tasks,
- isExpanded: this.shouldExpandFutureSection(
- date,
- this.currentDate
- ), // Expand based on relation to today
+ isExpanded: true,
});
});
@@ -1137,11 +1134,7 @@ export class ForecastComponent extends Component {
title: title,
date: date,
tasks: tasks,
- // Expand based on relation to the selected date
- isExpanded: this.shouldExpandFutureSection(
- date,
- this.selectedDate
- ),
+ isExpanded: true,
});
});
@@ -1204,20 +1197,6 @@ export class ForecastComponent extends Component {
return `${prefix}${dayOfWeek}, ${formattedDate}`;
}
- // Helper to decide if a future section should be expanded relative to a comparison date
- private shouldExpandFutureSection(
- sectionDate: Date,
- compareDate: Date
- ): boolean {
- const compareTimestamp = new Date(compareDate).setHours(0, 0, 0, 0);
- const sectionTimestamp = new Date(sectionDate).setHours(0, 0, 0, 0);
- // Calculate difference in days from the comparison date
- const dayDiff = Math.round(
- (sectionTimestamp - compareTimestamp) / (1000 * 3600 * 24)
- );
- // Expand if the section date is within the next 7 days *after* the comparison date
- return dayDiff > 0 && dayDiff <= 7;
- }
// Renaming getTasksForDate to be more specific about its check
private getTasksForRelevantDate(date: Date): Task[] {
diff --git a/src/components/features/task/view/listItem.ts b/src/components/features/task/view/listItem.ts
index 1d57155c4..e25418338 100644
--- a/src/components/features/task/view/listItem.ts
+++ b/src/components/features/task/view/listItem.ts
@@ -1,3 +1,5 @@
+import { taskDatePrecisions } from "@/utils/date/optional-date-time";
+import { t as settingsText } from "@/translations/helper";
import {
App,
Component,
@@ -733,6 +735,8 @@ export class TaskListItemComponent extends Component {
dateEl.classList.add(cssClass);
}
+ const precision = taskDatePrecisions(this.task)[`${type}Date`];
+ if (precision === "datetime" || precision !== "date" && (date.getHours() || date.getMinutes())) dateText += ` ${String(date.getHours()).padStart(2,"0")}:${String(date.getMinutes()).padStart(2,"0")}`;
dateEl.textContent = dateText;
dateEl.setAttribute("aria-label", date.toLocaleDateString());
@@ -960,19 +964,17 @@ export class TaskListItemComponent extends Component {
const menu = new Menu();
const availableFields = [
- { key: "project", label: "Project", icon: "folder" },
- { key: "tags", label: "Tags", icon: "tag" },
- { key: "context", label: "Context", icon: "at-sign" },
- { key: "dueDate", label: "Due Date", icon: "calendar" },
- { key: "startDate", label: "Start Date", icon: "play" },
- { key: "scheduledDate", label: "Scheduled Date", icon: "clock" },
+ { key: "project", label: settingsText("Project"), icon: "folder" },
+ { key: "tags", label: settingsText("Tags"), icon: "tag" },
+ { key: "context", label: settingsText("Context"), icon: "at-sign" },
+ { key: "dueDate", label: settingsText("Due Date"), icon: "calendar" },
+ { key: "startDate", label: settingsText("Start Date"), icon: "play" },
+ { key: "scheduledDate", label: settingsText("Scheduled Date"), icon: "clock" },
{ key: "cancelledDate", label: "Cancelled Date", icon: "x" },
{ key: "completedDate", label: "Completed Date", icon: "check" },
- { key: "priority", label: "Priority", icon: "alert-triangle" },
- { key: "recurrence", label: "Recurrence", icon: "repeat" },
- { key: "onCompletion", label: "On Completion", icon: "flag" },
+ { key: "priority", label: settingsText("Priority"), icon: "alert-triangle" },
+ { key: "onCompletion", label: settingsText("On Completion"), icon: "flag" },
{ key: "dependsOn", label: "Depends On", icon: "link" },
- { key: "id", label: "Task ID", icon: "hash" },
];
// Filter out fields that already have values
diff --git a/src/components/features/task/view/projects.ts b/src/components/features/task/view/projects.ts
index 078c54082..3c831ba36 100644
--- a/src/components/features/task/view/projects.ts
+++ b/src/components/features/task/view/projects.ts
@@ -1,3 +1,4 @@
+import { projectFolderContainer } from "@/components/features/fluent/components/ProjectFolders";
import {
App,
Component,
@@ -25,6 +26,7 @@ import {
ProgressData,
} from "@/editor-extensions/ui-widgets/progress-bar-widget";
import { QuickCaptureModal } from "@/components/features/quick-capture/modals/QuickCaptureModalWithSwitch";
+import { ProjectFileManager, ProjectCreateModal, ProjectArchiveModal, ProjectEditModal } from "@/managers/project-file-manager";
interface SelectedProjects {
projects: string[];
@@ -33,6 +35,8 @@ interface SelectedProjects {
}
export class ProjectsComponent extends Component {
+ private searchQuery = "";
+ setSearchQuery(query: string): void { this.searchQuery = query.trim().toLocaleLowerCase(); }
// UI Elements
public containerEl: HTMLElement;
private projectsHeaderEl: HTMLElement;
@@ -181,6 +185,8 @@ export class ProjectsComponent extends Component {
const headerButtons = headerEl.createDiv({
cls: "projects-sidebar-header-btn-group",
});
+ new ExtraButtonComponent(headerButtons).setIcon("plus").setTooltip(t("New project")).onClick(() => new ProjectCreateModal(this.app, new ProjectFileManager(this.app), () => this.setTasks(this.sourceTasks, this.allTasks)).open());
+ new ExtraButtonComponent(headerButtons).setIcon("archive").setTooltip(t("Archived projects")).onClick(() => new ProjectArchiveModal(this.app, new ProjectFileManager(this.app), () => this.setTasks(this.sourceTasks, this.allTasks)).open());
// Add view toggle button for tree/list
const treeToggleBtn = headerButtons.createDiv({
@@ -351,18 +357,29 @@ export class ProjectsComponent extends Component {
private buildProjectsIndex() {
// Clear existing index
this.allProjectsMap.clear();
+ const projectFiles = new ProjectFileManager(this.app);
+ const projectNotes = projectFiles.list();
+ const archivedProjects = new Set(
+ projectNotes.filter(project => project.archived).map(project => project.name.toLocaleLowerCase()),
+ );
// Build a map of projects to task IDs using sourceTasks (filtered tasks)
// This ensures the sidebar only shows projects that have matching tasks
this.sourceTasks.forEach((task) => {
const effectiveProject = getEffectiveProject(task);
- if (effectiveProject) {
+ if (effectiveProject && !archivedProjects.has(effectiveProject.toLocaleLowerCase())) {
if (!this.allProjectsMap.has(effectiveProject)) {
this.allProjectsMap.set(effectiveProject, new Set());
}
this.allProjectsMap.get(effectiveProject)?.add(task.id);
}
});
+ // Include active project notes even when a project has no tasks yet.
+ for (const project of projectNotes) {
+ if (!project.archived && !this.allProjectsMap.has(project.name) && (!this.searchQuery || project.name.toLocaleLowerCase().includes(this.searchQuery))) {
+ this.allProjectsMap.set(project.name, new Set());
+ }
+ }
// Build project tree if in tree view
if (this.isProjectTreeView) {
@@ -378,7 +395,7 @@ export class ProjectsComponent extends Component {
// Clear existing list
this.projectsListEl.empty();
- if (this.isProjectTreeView && this.projectTree) {
+ if (this.isProjectTreeView && this.projectTree && !new ProjectFileManager(this.app).list().some(project => project.folder)) {
// Render as tree
if (this.projectTreeComponent) {
this.projectTreeComponent.unload();
@@ -439,8 +456,9 @@ export class ProjectsComponent extends Component {
// Sort projects alphabetically
const sortedProjects = Array.from(
this.allProjectsMap.keys(),
- ).sort();
+ ).sort((a, b) => new ProjectFileManager(this.app).compareNames(a, b));
+ const folder = projectFolderContainer(this.projectsListEl, this.app);
// Render each project
sortedProjects.forEach((project) => {
// Get tasks for this project
@@ -459,15 +477,17 @@ export class ProjectsComponent extends Component {
}
// Create project item
- const projectItem = this.projectsListEl.createDiv({
+ const projectItem = folder(new ProjectFileManager(this.app).find(project)?.folder || "").createDiv({
cls: "project-list-item",
});
+ new ProjectFileManager(this.app).bindReorder(projectItem, project, () => sortedProjects, () => { this.renderProjectsList(); void this.plugin.triggerViewUpdate(); });
// Project icon
const projectIconEl = projectItem.createDiv({
cls: "project-icon",
});
setIcon(projectIconEl, "folder");
+ const color = new ProjectFileManager(this.app).find(project)?.color; if (color) projectIconEl.style.color = color;
// Project name
const projectNameEl = projectItem.createDiv({
@@ -1186,6 +1206,15 @@ export class ProjectsComponent extends Component {
/** Create or update the tgProject info button in the right header */
private updateTgProjectPropsButton(selectedProject: string | null): void {
+ const manager = new ProjectFileManager(this.app);
+ const projectNote = selectedProject ? manager.find(selectedProject) : undefined;
+ if (projectNote && this.headerTopRightRowEl) {
+ this.teardownProjectPropsUI(); this.projectPropsBtnEl?.remove();
+ const button = this.headerTopRightRowEl.createDiv({ cls: "projects-props-btn", attr: { "aria-label": t("Edit project details") } });
+ setIcon(button, "pencil"); this.projectPropsBtnEl = button;
+ button.addEventListener("click", () => new ProjectEditModal(this.app, manager, projectNote, () => this.setTasks(this.sourceTasks, this.allTasks)).open());
+ return;
+ }
if (!this.headerTopRightRowEl) return;
// No selection: remove button and popover
if (!selectedProject) {
diff --git a/src/components/features/task/view/treeItem.ts b/src/components/features/task/view/treeItem.ts
index 42d371716..b065f1479 100644
--- a/src/components/features/task/view/treeItem.ts
+++ b/src/components/features/task/view/treeItem.ts
@@ -1,3 +1,4 @@
+import { t as settingsText } from "@/translations/helper";
import {
App,
Component,
@@ -1038,19 +1039,17 @@ export class TaskTreeItemComponent extends Component {
const menu = new Menu();
const availableFields = [
- { key: "project", label: "Project", icon: "folder" },
- { key: "tags", label: "Tags", icon: "tag" },
- { key: "context", label: "Context", icon: "at-sign" },
- { key: "dueDate", label: "Due Date", icon: "calendar" },
- { key: "startDate", label: "Start Date", icon: "play" },
- { key: "scheduledDate", label: "Scheduled Date", icon: "clock" },
+ { key: "project", label: settingsText("Project"), icon: "folder" },
+ { key: "tags", label: settingsText("Tags"), icon: "tag" },
+ { key: "context", label: settingsText("Context"), icon: "at-sign" },
+ { key: "dueDate", label: settingsText("Due Date"), icon: "calendar" },
+ { key: "startDate", label: settingsText("Start Date"), icon: "play" },
+ { key: "scheduledDate", label: settingsText("Scheduled Date"), icon: "clock" },
{ key: "cancelledDate", label: "Cancelled Date", icon: "x" },
{ key: "completedDate", label: "Completed Date", icon: "check" },
- { key: "priority", label: "Priority", icon: "alert-triangle" },
- { key: "recurrence", label: "Recurrence", icon: "repeat" },
- { key: "onCompletion", label: "On Completion", icon: "flag" },
+ { key: "priority", label: settingsText("Priority"), icon: "alert-triangle" },
+ { key: "onCompletion", label: settingsText("On Completion"), icon: "flag" },
{ key: "dependsOn", label: "Depends On", icon: "link" },
- { key: "id", label: "Task ID", icon: "hash" },
];
// Filter out fields that already have values
diff --git a/src/components/ui/behavior/ViewComponentManager.ts b/src/components/ui/behavior/ViewComponentManager.ts
index 321961bea..7f171b471 100644
--- a/src/components/ui/behavior/ViewComponentManager.ts
+++ b/src/components/ui/behavior/ViewComponentManager.ts
@@ -1,6 +1,8 @@
+import { TaskPlanner } from "@/components/features/planner/TaskPlanner";
import { App, Component } from "obsidian";
import { Task } from "@/types/task";
import TaskProgressBarPlugin from "@/index";
+import type { TableSpecificConfig } from "@/common/setting-definition";
import {
ViewMode,
getViewSettingOrDefault,
@@ -19,6 +21,7 @@ interface ViewComponentInterface {
setTasks?: (tasks: Task[], allTasks?: Task[]) => void;
updateTasks?: (tasks: Task[]) => void;
setViewMode?: (viewId: ViewMode, project?: string | null) => void;
+ onShown?: () => void;
load?: () => void;
unload?: () => void;
}
@@ -49,6 +52,7 @@ class ViewComponentFactory {
const viewConfig = getViewSettingOrDefault(plugin, viewId);
switch (viewType) {
+ case "planner": return new TaskPlanner(plugin, parentEl);
case "kanban":
return new KanbanComponent(
app,
@@ -73,7 +77,9 @@ class ViewComponentFactory {
{
onTaskSelected: handlers.onTaskSelected,
onTaskCompleted: handlers.onTaskCompleted,
- onEventContextMenu: handlers.onEventContextMenu,
+ // Task pages and legacy calendar pages use different callback names.
+ onEventContextMenu:
+ handlers.onEventContextMenu ?? handlers.onTaskContextMenu,
},
viewId,
);
@@ -111,12 +117,12 @@ class ViewComponentFactory {
});
case "table":
- if (viewConfig.specificConfig?.viewType === "table") {
+ {
return new TableViewAdapter(
app,
plugin,
parentEl,
- viewConfig.specificConfig,
+ viewConfig.specificConfig as TableSpecificConfig,
{
onTaskSelected: handlers.onTaskSelected,
onTaskCompleted: handlers.onTaskCompleted,
@@ -140,6 +146,7 @@ class ViewComponentFactory {
}
},
},
+ viewId
);
}
return null;
@@ -186,6 +193,7 @@ class ViewComponentFactory {
// 统一的视图组件管理器
export class ViewComponentManager extends Component {
+ private configurationSignatures = new Map();
private components: Map = new Map();
private parentComponent: Component;
private app: App;
@@ -212,13 +220,22 @@ export class ViewComponentManager extends Component {
* 获取或创建指定视图的组件
*/
getOrCreateComponent(viewId: string): ViewComponentInterface | null {
- // 如果组件已存在,直接返回
- if (this.components.has(viewId)) {
- return this.components.get(viewId)!;
- }
-
- // 获取视图配置
const viewConfig = getViewSettingOrDefault(this.plugin, viewId);
+ const signature = JSON.stringify(viewConfig.specificConfig ?? null);
+ const existing = this.components.get(viewId);
+ if (existing && this.configurationSignatures.get(viewId) === signature) return existing;
+ if (existing && typeof (existing as any).refreshConfiguration === "function" &&
+ JSON.parse(this.configurationSignatures.get(viewId) || "null")?.viewType === viewConfig.specificConfig?.viewType) {
+ (existing as any).refreshConfiguration();
+ this.configurationSignatures.set(viewId, signature);
+ return existing;
+ }
+ if (existing) {
+ if (existing instanceof Component) this.parentComponent.removeChild(existing);
+ else existing.unload?.();
+ existing.containerEl.remove();
+ this.components.delete(viewId);
+ }
const specificViewType = viewConfig.specificConfig?.viewType;
// 确定视图类型
@@ -233,6 +250,7 @@ export class ViewComponentManager extends Component {
"forecast",
"table",
"quadrant",
+ "planner",
].includes(viewId)
) {
viewType = viewId;
@@ -268,6 +286,7 @@ export class ViewComponentManager extends Component {
// 缓存组件
this.components.set(viewId, component);
+ this.configurationSignatures.set(viewId, signature);
}
return component;
@@ -289,6 +308,7 @@ export class ViewComponentManager extends Component {
const component = this.getOrCreateComponent(viewId);
if (component) {
component.containerEl.show();
+ requestAnimationFrame(() => { if (this.components.get(viewId) === component && component.containerEl.isShown()) component.onShown?.(); });
}
return component;
}
@@ -304,14 +324,14 @@ export class ViewComponentManager extends Component {
"isSpecialView",
viewId,
specificViewType,
- ["calendar", "kanban", "gantt", "forecast", "table"].includes(
+ ["calendar", "kanban", "gantt", "forecast", "table", "quadrant", "planner"].includes(
viewId,
),
);
return !!(
specificViewType ||
- ["calendar", "kanban", "gantt", "forecast", "table"].includes(
+ ["calendar", "kanban", "gantt", "forecast", "table", "quadrant", "planner"].includes(
viewId,
)
);
@@ -325,11 +345,12 @@ export class ViewComponentManager extends Component {
if (component instanceof Component) {
this.parentComponent.removeChild(component);
}
- if (component.unload) {
+ else if (component.unload) {
component.unload();
}
});
this.components.clear();
+ this.configurationSignatures.clear();
}
/**
diff --git a/src/components/ui/date-picker/BulkDateOffsetModal.ts b/src/components/ui/date-picker/BulkDateOffsetModal.ts
index 8f6a8452f..a544fba20 100644
--- a/src/components/ui/date-picker/BulkDateOffsetModal.ts
+++ b/src/components/ui/date-picker/BulkDateOffsetModal.ts
@@ -1,3 +1,4 @@
+import { t as settingsText } from "@/translations/helper";
/**
* Bulk Date Offset Modal
* Modal for postponing/advancing dates by a relative offset for bulk operations
@@ -104,7 +105,7 @@ export class BulkDateOffsetModal extends Modal {
customInput.max = "365";
new ButtonComponent(customInputContainer)
- .setButtonText("Apply")
+ .setButtonText(settingsText("Apply"))
.setCta()
.onClick(() => {
const days = parseInt(customInput.value) || 0;
diff --git a/src/components/ui/feedback/StatusIndicator.ts b/src/components/ui/feedback/StatusIndicator.ts
index 87cddcc35..02a8bf25c 100644
--- a/src/components/ui/feedback/StatusIndicator.ts
+++ b/src/components/ui/feedback/StatusIndicator.ts
@@ -65,7 +65,7 @@ export class StatusComponent extends Component {
// Create checkbox-like element or icon for the status
let interactiveElement: HTMLElement = statusEl;
if (this.plugin.settings.enableTaskGeniusIcons) {
- setIcon(interactiveElement, status.status);
+ setIcon(interactiveElement, ["archived", "paused", "pause"].includes(status.status) ? "pause" : status.status);
} else {
// Create checkbox-like element for the status
interactiveElement = createTaskCheckbox(
@@ -79,21 +79,15 @@ export class StatusComponent extends Component {
evt.stopPropagation();
evt.preventDefault();
- const options = {
- ...this.task,
- status: status.text,
- };
-
- if (status.text === "x" && !this.task.completed) {
- options.completed = true;
- options.metadata.completedDate = new Date().getTime();
- }
-
+ const completed = (this.plugin.settings.taskStatuses?.completed || "x").split("|").includes(status.text);
+ const options = { ...this.task, status: status.text, completed, metadata: { ...(this.task.metadata || {}) } };
+ options.metadata.completedDate = completed ? options.metadata.completedDate || Date.now() : undefined;
+ options.metadata.cancelledDate = (this.plugin.settings.taskStatuses?.abandoned || "-").split("|").includes(status.text) ? options.metadata.cancelledDate || Date.now() : undefined;
this.params.onTaskUpdate?.(this.task, options);
this.params.onTaskStatusSelected?.(status.text);
// Update the current task status to reflect the change
- this.task = { ...this.task, status: status.text };
+ this.task = options;
// Update the visual state
this.containerEl
diff --git a/src/components/ui/modals/CalendarViewConfigModal.ts b/src/components/ui/modals/CalendarViewConfigModal.ts
index bd3a5f3ea..2f8af679f 100644
--- a/src/components/ui/modals/CalendarViewConfigModal.ts
+++ b/src/components/ui/modals/CalendarViewConfigModal.ts
@@ -1,3 +1,4 @@
+import { t as settingsText } from "@/translations/helper";
import {
App,
Modal,
@@ -22,13 +23,13 @@ import { attachIconMenu } from "@/components/ui/menus/IconMenu";
* Days of the week for custom day filter
*/
const WEEKDAYS = [
- { value: 0, label: "Sunday", short: "Sun" },
- { value: 1, label: "Monday", short: "Mon" },
- { value: 2, label: "Tuesday", short: "Tue" },
- { value: 3, label: "Wednesday", short: "Wed" },
- { value: 4, label: "Thursday", short: "Thu" },
- { value: 5, label: "Friday", short: "Fri" },
- { value: 6, label: "Saturday", short: "Sat" },
+ { value: 0, label: settingsText("Sunday"), short: "Sun" },
+ { value: 1, label: settingsText("Monday"), short: "Mon" },
+ { value: 2, label: settingsText("Tuesday"), short: "Tue" },
+ { value: 3, label: settingsText("Wednesday"), short: "Wed" },
+ { value: 4, label: settingsText("Thursday"), short: "Thu" },
+ { value: 5, label: settingsText("Friday"), short: "Fri" },
+ { value: 6, label: settingsText("Saturday"), short: "Sat" },
];
/**
diff --git a/src/components/ui/modals/IframeModal.ts b/src/components/ui/modals/IframeModal.ts
index c826f06f0..90a22997c 100644
--- a/src/components/ui/modals/IframeModal.ts
+++ b/src/components/ui/modals/IframeModal.ts
@@ -1,3 +1,4 @@
+import { t as settingsText } from "@/translations/helper";
import { App, Modal, setIcon } from "obsidian";
export class IframeModal extends Modal {
@@ -21,8 +22,8 @@ export class IframeModal extends Modal {
const externalLinkBtn = headerActions.createEl('button', {
cls: 'clickable-icon task-genius-external-link-btn',
attr: {
- 'aria-label': 'Open in external browser',
- 'title': 'Open in external browser'
+ 'aria-label': settingsText('Open in external browser'),
+ 'title': settingsText('Open in external browser')
}
});
diff --git a/src/components/ui/modals/McpLogModal.ts b/src/components/ui/modals/McpLogModal.ts
index df0e3f961..7b4e5f24e 100644
--- a/src/components/ui/modals/McpLogModal.ts
+++ b/src/components/ui/modals/McpLogModal.ts
@@ -1,3 +1,4 @@
+import { t as settingsText } from "@/translations/helper";
import { Modal, ButtonComponent, ExtraButtonComponent } from "obsidian";
import TaskProgressBarPlugin from "@/index";
import { McpLogEntry } from "@/mcp/McpServer";
@@ -22,7 +23,7 @@ export class McpLogModal extends Modal {
}
onOpen() {
- this.titleEl.setText("MCP Server Logs");
+ this.titleEl.setText(settingsText("MCP Server Logs"));
this.modalEl.addClass("mcp-log-modal");
// Header section with search and clear
@@ -34,14 +35,14 @@ export class McpLogModal extends Modal {
});
this.searchInput = searchContainer.createEl("input", {
type: "text",
- placeholder: "Search logs...",
+ placeholder: settingsText("Search logs..."),
cls: "mcp-log-search-input",
});
this.searchInput.addEventListener("input", () => this.filterLogs());
// Clear logs button
new ButtonComponent(headerEl)
- .setButtonText("Clear Logs")
+ .setButtonText(settingsText("Clear Logs"))
.setIcon("trash")
.setWarning()
.onClick(() => {
@@ -68,7 +69,7 @@ export class McpLogModal extends Modal {
cls: "modal-button-container",
});
- new ButtonComponent(footerEl).setButtonText("Refresh").onClick(() => {
+ new ButtonComponent(footerEl).setButtonText(settingsText("Refresh")).onClick(() => {
if (this.plugin.mcpServerManager?.getServer()) {
this.logs =
this.plugin.mcpServerManager.getServer()?.getLogs() || [];
@@ -76,7 +77,7 @@ export class McpLogModal extends Modal {
}
});
- new ButtonComponent(footerEl).setButtonText("Close").onClick(() => {
+ new ButtonComponent(footerEl).setButtonText(settingsText("Close")).onClick(() => {
this.close();
});
}
@@ -107,7 +108,7 @@ export class McpLogModal extends Modal {
const statsText = container.createDiv({ cls: "mcp-log-stats-text" });
statsText.setText(
- `Total: ${totalLogs} | Success: ${successCount} | Errors: ${errorCount}`
+ settingsText("Total: {{value0}} | Success: {{value1}} | Errors: {{value2}}", { interpolation: { value0: String(totalLogs), value1: String(successCount), value2: String(errorCount) } })
);
}
@@ -121,8 +122,8 @@ export class McpLogModal extends Modal {
emptyEl.createEl("p", {
text:
this.logs.length === 0
- ? "No logs yet. Tool calls will appear here."
- : "No logs match your search.",
+ ? settingsText("No logs yet. Tool calls will appear here.")
+ : settingsText("No logs match your search."),
});
return;
}
@@ -151,7 +152,7 @@ export class McpLogModal extends Modal {
// Duration
const duration = headerRow.createDiv({ cls: "mcp-log-duration" });
- duration.setText(`${log.duration}ms`);
+ duration.setText(settingsText("{{value0}}ms", { interpolation: { value0: String(log.duration) } }));
// Session ID (if available)
if (log.sessionId) {
@@ -184,7 +185,7 @@ export class McpLogModal extends Modal {
});
argsSection.createEl("div", {
cls: "mcp-log-section-title",
- text: "Arguments:",
+ text: settingsText("Arguments:"),
});
const argsContent = argsSection.createEl("pre", {
cls: "mcp-log-section-content",
@@ -199,7 +200,7 @@ export class McpLogModal extends Modal {
});
errorSection.createEl("div", {
cls: "mcp-log-section-title mcp-log-error-title",
- text: "Error:",
+ text: settingsText("Error:"),
});
const errorContent = errorSection.createEl("pre", {
cls: "mcp-log-section-content mcp-log-error-content",
@@ -211,13 +212,13 @@ export class McpLogModal extends Modal {
});
const resultTitle = resultSection.createEl("div", {
cls: "mcp-log-section-title",
- text: "Result:",
+ text: settingsText("Result:"),
});
if (log.truncated) {
resultTitle.createEl("span", {
cls: "mcp-log-truncated-badge",
- text: " (truncated)",
+ text: settingsText(" (truncated)"),
});
}
diff --git a/src/dataflow/Orchestrator.ts b/src/dataflow/Orchestrator.ts
index 0caca6244..f974e8e59 100644
--- a/src/dataflow/Orchestrator.ts
+++ b/src/dataflow/Orchestrator.ts
@@ -1,3 +1,4 @@
+import { snapshotIndexSettings } from "./settings-signature";
import { App, TFile, Vault, MetadataCache, EventRef, debounce } from "obsidian";
import type { Task, TgProject } from "../types/task";
import type { ProjectConfigManagerOptions } from "../managers/project-config-manager";
@@ -22,7 +23,7 @@ import { getConfig } from "../common/task-parser-config";
import { parseFileMeta } from "./parsers/FileMetaEntry";
import { ConfigurableTaskParser } from "./core/ConfigurableTaskParser";
import { MetadataParseMode } from "../types/TaskParserConfig";
-import { TimeParsingService } from "../services/time-parsing-service";
+import { TimeParsingService, DEFAULT_TIME_PARSING_CONFIG } from "../services/time-parsing-service";
import type { EnhancedTimeParsingConfig } from "../types/time-parsing";
/**
@@ -52,6 +53,8 @@ export class DataflowOrchestrator {
// Processing queue for throttling
private processingQueue = new Map();
+ private fileProcessing = new Map>();
+ private disposed = false;
private readonly DEBOUNCE_DELAY = 300; // ms
// Lightweight bookkeeping for filter-based pruning/restoration
@@ -64,6 +67,9 @@ export class DataflowOrchestrator {
// Track last processed sequence to avoid infinite loops
private lastProcessedSeq: number = 0;
+ private indexSettingsSignature: string;
+ private fileFilterSignature: string | undefined;
+ private settingsUpdateQueue: Promise = Promise.resolve();
constructor(
private app: App,
@@ -72,6 +78,8 @@ export class DataflowOrchestrator {
private plugin: any, // Plugin instance for parser access
projectOptions?: Partial,
) {
+ this.indexSettingsSignature = snapshotIndexSettings(plugin.settings);
+ this.fileFilterSignature = JSON.stringify(plugin.settings?.fileFilter);
// Initialize components
this.queryAPI = new QueryAPI(app, vault, metadataCache);
this.repository = this.queryAPI.getRepository();
@@ -204,32 +212,8 @@ export class DataflowOrchestrator {
// Initialize ICS event source
this.icsSource = new IcsSource(app, () => this.plugin.getIcsManager());
- // Initialize TimeParsingService with plugin settings
- this.timeParsingService = new TimeParsingService(
- this.plugin.settings?.timeParsing ||
- ({
- enabled: true,
- supportedLanguages: ["en", "zh"],
- dateKeywords: {
- start: ["start", "begin", "from"],
- due: ["due", "deadline", "by", "until"],
- scheduled: ["scheduled", "on", "at"],
- },
- removeOriginalText: true,
- perLineProcessing: true,
- realTimeReplacement: true,
- timePatterns: {
- singleTime: [],
- timeRange: [],
- rangeSeparators: ["-", "~", "~"],
- },
- timeDefaults: {
- preferredFormat: "24h",
- defaultPeriod: "AM",
- midnightCrossing: "next-day",
- },
- } as EnhancedTimeParsingConfig),
- );
+ // One shared built-in parser policy for capture, indexing and migrations.
+ this.timeParsingService = new TimeParsingService(DEFAULT_TIME_PARSING_CONFIG);
// Initialize FileSource (conditionally based on settings)
if (this.plugin.settings?.fileSource?.enabled) {
@@ -461,6 +445,10 @@ export class DataflowOrchestrator {
);
if (reason === "delete") {
+ const pending = this.processingQueue.get(path);
+ if (pending) clearTimeout(pending);
+ this.processingQueue.delete(path);
+ this.projectResolver.clearCache(path);
// Remove file from index
await this.repository.removeFile(path);
} else {
@@ -469,6 +457,11 @@ export class DataflowOrchestrator {
path,
) as TFile;
if (file) {
+ if (reason !== "error") {
+ this.projectResolver.clearCache(path);
+ this.augmentor.clearCache();
+ await this.storage.clearFile(path);
+ }
await this.processFile(file);
}
}
@@ -524,18 +517,14 @@ export class DataflowOrchestrator {
`[DataflowOrchestrator] WRITE_OPERATION_COMPLETE: ${path}, taskId: ${taskId}`,
);
- // If we have a taskId, it means a specific task was updated
- // We'll handle this through TASK_UPDATED event instead
- if (!taskId) {
- // No specific task, process the entire file
- const file = this.vault.getAbstractFileByPath(
- path,
- ) as TFile;
- if (file) {
- // Process immediately without debounce for WriteAPI operations
- // Pass true to force cache invalidation
- await this.processFileImmediate(file, true);
- }
+ // A specific task id does not imply TASK_UPDATED will be emitted.
+ // Reparse the actual saved file for every completed write.
+ const file = this.vault.getAbstractFileByPath(path) as TFile | null;
+ if (file) {
+ const pending = this.processingQueue.get(path);
+ if (pending) clearTimeout(pending);
+ this.processingQueue.delete(path);
+ await this.processFileImmediate(file, true);
}
},
),
@@ -636,10 +625,25 @@ export class DataflowOrchestrator {
* @param file The file to process
* @param forceInvalidate Force cache invalidation (for WriteAPI operations)
*/
- private async processFileImmediate(
+ public async refreshFile(filePath: string): Promise {
+ const file = this.vault.getAbstractFileByPath(filePath) as TFile | null;
+ if (file) await this.processFileImmediate(file, true);
+ }
+
+ private async processFileImmediate(file: TFile, forceInvalidate = false): Promise {
+ if (this.disposed) return;
+ const previous = this.fileProcessing.get(file.path) || Promise.resolve();
+ const next = previous.catch(() => {}).then(() => this.processFileSnapshot(file, forceInvalidate));
+ this.fileProcessing.set(file.path, next);
+ try { await next; }
+ finally { if (this.fileProcessing.get(file.path) === next) this.fileProcessing.delete(file.path); }
+ }
+
+ private async processFileSnapshot(
file: TFile,
forceInvalidate: boolean = false,
): Promise {
+ if (this.disposed) return;
const filePath = file.path;
try {
@@ -650,7 +654,7 @@ export class DataflowOrchestrator {
// Step 2: Check cache and parse if needed
const rawCached = await this.storage.loadRaw(filePath);
const augmentedCached = await this.storage.loadAugmented(filePath);
- const fileContent = await this.vault.cachedRead(file);
+ const fileContent = forceInvalidate ? await this.vault.read(file) : await this.vault.cachedRead(file);
console.log("[DataflowOrchestrator] processFileImmediate start", {
filePath,
forceInvalidate,
@@ -784,10 +788,9 @@ export class DataflowOrchestrator {
);
if (includeInlineParse) {
// Parse the file using workers (single-file path)
- rawTasks = await this.workerOrchestrator.parseFileTasks(
- file,
- "high",
- );
+ rawTasks = forceInvalidate
+ ? await this.parseFile(file, projectData.tgProject, true)
+ : await this.workerOrchestrator.parseFileTasks(file, "high");
} else {
rawTasks = [];
}
@@ -822,6 +825,8 @@ export class DataflowOrchestrator {
augmentedTasks = await this.augmentor.merge(augmentContext);
}
+ if (this.disposed || !this.vault.getAbstractFileByPath(filePath)) return;
+
// Step 3: Update repository (index + storage + events)
// Generate a unique sequence for this operation
this.lastProcessedSeq = Seq.next();
@@ -848,7 +853,14 @@ export class DataflowOrchestrator {
/**
* Update settings and propagate to components
*/
- updateSettings(settings: any): void {
+ updateSettings(settings: any): Promise {
+ this.settingsUpdateQueue = this.settingsUpdateQueue.catch(() => {}).then(() => this.applySettings(settings));
+ return this.settingsUpdateQueue;
+ }
+
+ private async applySettings(settings: any): Promise {
+ const indexSignature = snapshotIndexSettings(settings);
+ const filterSignature = JSON.stringify(settings?.fileFilter);
// Update worker processing setting
const enableWorkerProcessing =
settings?.fileSource?.performance?.enableWorkerProcessing ??
@@ -893,7 +905,7 @@ export class DataflowOrchestrator {
// Update TimeParsingService configuration
if (settings.timeParsing && this.timeParsingService) {
- this.timeParsingService.updateConfig(settings.timeParsing);
+ this.timeParsingService.updateConfig(DEFAULT_TIME_PARSING_CONFIG);
}
// Sync inheritance toggle to augmentor so it can respect disabling file frontmatter inheritance
@@ -1002,7 +1014,7 @@ export class DataflowOrchestrator {
(this.repository as any).setFileFilterManager?.(
this.fileFilterManager,
);
- fileFilterChanged = true;
+ fileFilterChanged = filterSignature !== this.fileFilterSignature;
}
if (fileFilterChanged) {
@@ -1030,6 +1042,13 @@ export class DataflowOrchestrator {
});
this.restoreByFilterDebounced?.();
}
+ if (indexSignature !== this.indexSettingsSignature) {
+ await this.onSettingsChange(["parser", "augment", "project"]);
+ } else {
+ emit(this.app, Events.SETTINGS_CHANGED, { scopes: [], timestamp: Date.now() });
+ }
+ this.indexSettingsSignature = indexSignature;
+ this.fileFilterSignature = filterSignature;
}
/**
@@ -1315,6 +1334,7 @@ export class DataflowOrchestrator {
private async parseFile(
file: TFile,
tgProject?: TgProject,
+ fresh = false,
): Promise {
const extension = file.extension.toLowerCase();
@@ -1323,7 +1343,7 @@ export class DataflowOrchestrator {
if (extension === "md") {
// Use ConfigurableTaskParser for markdown files
- const content = await this.vault.cachedRead(file);
+ const content = fresh ? await this.vault.read(file) : await this.vault.cachedRead(file);
const fileCache = this.metadataCache.getFileCache(file);
const fileMetadata = fileCache?.frontmatter || {};
@@ -1702,6 +1722,8 @@ export class DataflowOrchestrator {
* Clear all data and rebuild
*/
async rebuild(): Promise {
+ this.projectResolver.clearCache();
+ this.augmentor.clearCache();
// Clear all data
await this.repository.clear();
@@ -1722,6 +1744,7 @@ export class DataflowOrchestrator {
// Persist the rebuilt index
await this.repository.persist();
+ await this.queryAPI.refreshCache();
// Emit ready event
emit(this.app, Events.CACHE_READY, {
@@ -1744,6 +1767,7 @@ export class DataflowOrchestrator {
await this.storage.clearNamespace("augmented");
await this.storage.clearNamespace("project");
this.projectResolver.clearCache();
+ this.augmentor.clearCache();
}
if (scopes.includes("index")) {
@@ -1830,6 +1854,7 @@ export class DataflowOrchestrator {
* Cleanup resources
*/
async cleanup(): Promise {
+ this.disposed = true;
// Clear all pending timeouts
for (const timeout of this.processingQueue.values()) {
clearTimeout(timeout);
diff --git a/src/dataflow/api/QueryAPI.ts b/src/dataflow/api/QueryAPI.ts
index e7b551c4e..d5e73ee1b 100644
--- a/src/dataflow/api/QueryAPI.ts
+++ b/src/dataflow/api/QueryAPI.ts
@@ -33,29 +33,21 @@ export class QueryAPI {
/**
* Get all tasks with deduplication for concurrent requests
*/
- async getAllTasks(): Promise {
- // If there's already a pending request, return the same promise
- if (this.pendingPromise) {
- return this.pendingPromise;
- }
-
- // Create new promise and cache it
- this.pendingPromise = this.repository.all().then(tasks => {
- // Update synchronous cache with fresh data
- this.taskCache = tasks;
- this.cacheTimestamp = Date.now();
-
- // Clear pending promise after completion
- this.pendingPromise = null;
-
+ async getAllTasks(fresh = false): Promise {
+ if (this.pendingPromise && !fresh) return this.pendingPromise;
+ const request = (async () => {
+ let revision: number;
+ let tasks: Task[];
+ do {
+ revision = this.repository.getRevision();
+ tasks = await this.repository.all();
+ } while (revision !== this.repository.getRevision());
+ this.taskCache = tasks; this.cacheTimestamp = Date.now();
return tasks;
- }).catch(error => {
- // Clear pending promise on error
- this.pendingPromise = null;
- throw error;
- });
-
- return this.pendingPromise;
+ })();
+ this.pendingPromise = request;
+ try { return await request; }
+ finally { if (this.pendingPromise === request) this.pendingPromise = null; }
}
/**
@@ -208,8 +200,13 @@ export class QueryAPI {
/**
* Update the synchronous cache with fresh data
*/
+ /** Refresh synchronous readers after a repository rebuild. */
+ public async refreshCache(): Promise {
+ await this.updateCache();
+ }
+
private async updateCache(): Promise {
- this.taskCache = await this.repository.all();
+ this.taskCache = await this.getAllTasks(true);
this.cacheTimestamp = Date.now();
}
diff --git a/src/dataflow/api/WriteAPI.ts b/src/dataflow/api/WriteAPI.ts
index 2edabe42a..0da009690 100644
--- a/src/dataflow/api/WriteAPI.ts
+++ b/src/dataflow/api/WriteAPI.ts
@@ -22,6 +22,7 @@ import {
} from "@/utils/file/file-operations";
import { Events, emit } from "../events/Events";
import { CanvasTaskUpdater } from "@/parsers/canvas-task-updater";
+import { ProjectFileManager } from "@/managers/project-file-manager";
import { rrulestr } from "rrule";
import { EMOJI_TAG_REGEX, TOKEN_CONTEXT_REGEX } from "@/common/regex-define";
import { BulkOperationResult } from "@/types/selection";
@@ -324,8 +325,13 @@ export class WriteAPI {
return { success: false, error: "Task not found" };
}
- // Check if this is a Canvas task
+ // Canvas checkboxes live inside JSON nodes, so project assignment must
+ // convert them to Markdown instead of writing a project tag into Canvas.
if (CanvasTaskUpdater.isCanvasTask(originalTask)) {
+ const requestedCanvasProject = args.updates.metadata?.project?.trim();
+ if (requestedCanvasProject && (requestedCanvasProject !== originalTask.metadata?.project || !originalTask.filePath.toLowerCase().endsWith(".md"))) {
+ return this.moveCanvasTaskToProject(originalTask, requestedCanvasProject);
+ }
return this.updateCanvasTask(args);
}
@@ -341,6 +347,26 @@ export class WriteAPI {
);
}
+ const requestedProject = args.updates.metadata?.project?.trim();
+ const prefixes = Object.values(this.plugin.settings.projectTagPrefix || {}).map(String);
+ const projectFiles = requestedProject
+ ? new ProjectFileManager(this.app, prefixes.length ? prefixes : ["project"])
+ : null;
+ const projectMove = !!requestedProject && projectFiles?.find(requestedProject)?.file.path !== originalTask.filePath;
+ if (projectFiles && requestedProject) {
+ const destination = await projectFiles.create(requestedProject);
+ if (!destination) return { success: false, error: "Could not create project note" };
+ // New membership belongs to the destination note's frontmatter.
+ args = {
+ ...args,
+ updates: {
+ ...args.updates,
+ metadata: { ...args.updates.metadata, project: undefined,
+ tags: (args.updates.metadata?.tags || originalTask.metadata?.tags || []).filter(tag => !["project", ...prefixes].some(prefix => tag.replace(/^#/, "").startsWith(`${prefix}/`))) } as any,
+ },
+ };
+ }
+
const file = this.vault.getAbstractFileByPath(
originalTask.filePath,
) as TFile;
@@ -489,6 +515,7 @@ export class WriteAPI {
esc2(projectKey2),
esc2(contextKey2),
"priority",
+ "points",
"repeat",
"start",
"scheduled",
@@ -558,6 +585,7 @@ export class WriteAPI {
"project",
"context",
"priority",
+ "points",
"repeat",
"startDate",
"dueDate",
@@ -616,6 +644,7 @@ export class WriteAPI {
esc(dvProjectKey),
esc(dvContextKey),
"priority",
+ "points",
"repeat",
"start",
"scheduled",
@@ -714,8 +743,9 @@ export class WriteAPI {
? !!args.updates.completed
: !!originalTask.completed;
const newMetadata = this.generateMetadata({
- tags: mergedMd.tags,
- project: mergedMd.project,
+ tags: typeof this.metadataCache.getFileCache(file)?.frontmatter?.project === "string"
+ ? (mergedMd.tags || []).filter((tag: string) => !["project", ...prefixes].some(prefix => tag.replace(/^#/, "").startsWith(`${prefix}/`))) : mergedMd.tags,
+ project: typeof this.metadataCache.getFileCache(file)?.frontmatter?.project === "string" ? undefined : mergedMd.project,
context: mergedMd.context,
priority: mergedMd.priority,
startDate: mergedMd.startDate,
@@ -727,6 +757,8 @@ export class WriteAPI {
onCompletion: mergedMd.onCompletion,
dependsOn: mergedMd.dependsOn,
id: mergedMd.id,
+ points: mergedMd.points,
+ datePrecision: mergedMd.datePrecision,
});
taskLine = `${checkboxPrefix}${taskContent}${
newMetadata ? ` ${newMetadata}` : ""
@@ -789,6 +821,18 @@ export class WriteAPI {
originalMarkdown: taskLine,
};
+ if (projectMove && requestedProject && projectFiles) {
+ try {
+ const moved = await projectFiles.moveTask(updatedTaskObj, requestedProject);
+ if (!moved) throw new Error("Could not move task to project note");
+ } catch (moveError) {
+ // Treat updating the task and moving it as one operation. If the
+ // destination write fails, restore the source file snapshot.
+ await this.vault.modify(file, content);
+ throw moveError;
+ }
+ }
+
// Emit write operation complete
emit(this.app, Events.WRITE_OPERATION_COMPLETE, {
path: file.path,
@@ -1299,6 +1343,14 @@ export class WriteAPI {
args: CreateTaskArgs,
): Promise<{ success: boolean; task?: Task; error?: string }> {
try {
+ if (args.project?.trim()) {
+ const prefixes = Object.values(this.plugin.settings.projectTagPrefix || {}).map(String);
+ const manager = new ProjectFileManager(this.app, prefixes.length ? prefixes : ["project"]);
+ const project = await manager.create(args.project);
+ if (!project) return { success: false, error: "Could not create project note" };
+ args = { ...args, filePath: project.file.path, parent: undefined, project: undefined,
+ tags: args.tags?.filter(tag => !["project", ...prefixes].some(prefix => tag.replace(/^#/, "").startsWith(`${prefix}/`))) };
+ }
let filePath = args.filePath;
if (!filePath) {
@@ -1831,6 +1883,7 @@ export class WriteAPI {
}): Promise<{ success: boolean; error?: string }> {
try {
// Get or create daily note
+ if (args.project?.trim()) return this.createTask({ ...args });
let dailyNoteFile: TFile | null;
const hasDailyNotesPlugin = appHasDailyNotesPluginLoaded();
@@ -1999,6 +2052,14 @@ export class WriteAPI {
completedDate?: string;
}): Promise<{ filePath: string; success: boolean }> {
try {
+ if (args.project.trim()) {
+ const prefixes = Object.values(this.plugin.settings.projectTagPrefix || {}).map(String);
+ const manager = new ProjectFileManager(this.app, prefixes.length ? prefixes : ["project"]);
+ const project = await manager.create(args.project);
+ if (!project) return { filePath: "", success: false };
+ const result = await this.createTask({ ...args, filePath: project.file.path });
+ return { filePath: project.file.path, success: result.success };
+ }
const qc = this.plugin.settings.quickCapture;
if (!qc) {
throw new Error("Quick Capture settings not found");
@@ -2057,14 +2118,16 @@ export class WriteAPI {
private formatDateForWrite(
timestamp: number | string | Date | undefined | null,
+ precision?: "date" | "datetime",
): string {
- return formatDateSmart(timestamp, { includeSeconds: false });
+ return formatDateSmart(timestamp, { includeSeconds: false, forceFormat: precision === "datetime" ? "date-time" : precision === "date" ? "date-only" : undefined });
}
/**
* Generate metadata string based on format preference
*/
private generateMetadata(args: {
+ datePrecision?: Record;
tags?: string[];
project?: string;
context?: string;
@@ -2078,10 +2141,12 @@ export class WriteAPI {
onCompletion?: string;
dependsOn?: string[] | string;
id?: string;
+ points?: number;
}): string {
const metadata: string[] = [];
const useDataviewFormat =
this.plugin.settings.preferMetadataFormat === "dataview";
+ if (typeof args.points === "number" && Number.isFinite(args.points) && args.points >= 0) metadata.push(`[points:: ${args.points}]`);
// Tags
if (args.tags?.length) {
@@ -2198,7 +2263,7 @@ export class WriteAPI {
// Start Date
if (args.startDate) {
- const dateStr = this.formatDateForWrite(args.startDate);
+ const dateStr = this.formatDateForWrite(args.startDate, args.datePrecision?.startDate);
if (dateStr) {
metadata.push(
useDataviewFormat
@@ -2210,7 +2275,7 @@ export class WriteAPI {
// Scheduled Date
if (args.scheduledDate) {
- const dateStr = this.formatDateForWrite(args.scheduledDate);
+ const dateStr = this.formatDateForWrite(args.scheduledDate, args.datePrecision?.scheduledDate);
if (dateStr) {
metadata.push(
useDataviewFormat
@@ -2222,7 +2287,7 @@ export class WriteAPI {
// Due Date
if (args.dueDate) {
- const dateStr = this.formatDateForWrite(args.dueDate);
+ const dateStr = this.formatDateForWrite(args.dueDate, args.datePrecision?.dueDate);
if (dateStr) {
metadata.push(
useDataviewFormat ? `[due:: ${dateStr}]` : `📅 ${dateStr}`,
@@ -2232,7 +2297,7 @@ export class WriteAPI {
// Completion Date
if (args.completed && args.completedDate) {
- const dateStr = this.formatDateForWrite(args.completedDate);
+ const dateStr = this.formatDateForWrite(args.completedDate, args.datePrecision?.completedDate);
if (dateStr) {
metadata.push(
useDataviewFormat
@@ -2372,7 +2437,46 @@ export class WriteAPI {
return base.getTime();
}
- // ===== Canvas Task Methods =====
+ private async moveCanvasTaskToProject(task: Task, projectName: string): Promise<{ success: boolean; task?: Task; error?: string }> {
+ const prefixes = Object.values(this.plugin.settings.projectTagPrefix || {}).map(String);
+ const manager = new ProjectFileManager(this.app, prefixes.length ? prefixes : ["project"]);
+ let block = "";
+ try {
+ const project = await manager.create(projectName);
+ if (!project) return { success: false, error: "Could not create project note" };
+ const descendants: Task[] = [];
+ const seen = new Set([task.id]);
+ const queue = [...(task.metadata?.children || [])];
+ while (queue.length) {
+ const childId = queue.shift()!;
+ if (seen.has(childId)) continue;
+ seen.add(childId);
+ const child = await Promise.resolve(this.getTaskById(childId));
+ if (!child) continue;
+ if (!CanvasTaskUpdater.isCanvasTask(child) || child.filePath !== task.filePath) {
+ return { success: false, error: "Canvas subtasks cannot be moved safely as one project task." };
+ }
+ descendants.push(child);
+ queue.push(...(child.metadata?.children || []));
+ }
+ const ordered = [task, ...descendants].sort((a, b) => a.line - b.line);
+ block = ordered.map(item => manager.stripProjectMarkers(item.originalMarkdown, projectName)).filter(Boolean).join("\n");
+ if (!block || !(await manager.appendTaskBlock(projectName, ordered.map(item => item.originalMarkdown)))) {
+ return { success: false, error: "Could not write Canvas task to the project note" };
+ }
+ const deleted = await this.deleteCanvasTask({ taskId: task.id, deleteChildren: descendants.length > 0 });
+ if (!deleted.success) {
+ await manager.removeTaskBlock(projectName, block);
+ block = "";
+ return { success: false, error: deleted.error || "Could not remove Canvas task after moving" };
+ }
+ return { success: true, task: { ...task, filePath: project.file.path, metadata: { ...task.metadata, project: projectName }, originalMarkdown: block.split("\n")[0] } };
+ } catch (error) {
+ if (block) await manager.removeTaskBlock(projectName, block).catch(() => undefined);
+ return { success: false, error: String(error) };
+ }
+ }
+// ===== Canvas Task Methods =====
/**
* Update a Canvas task
diff --git a/src/dataflow/api/__tests__/QueryAPI.freshness.test.ts b/src/dataflow/api/__tests__/QueryAPI.freshness.test.ts
new file mode 100644
index 000000000..8aac0e2e1
--- /dev/null
+++ b/src/dataflow/api/__tests__/QueryAPI.freshness.test.ts
@@ -0,0 +1,12 @@
+import { QueryAPI } from "../QueryAPI";
+const deferred = () => { let resolve!: (value: any) => void, reject!: (reason: unknown) => void; const promise=new Promise((yes,no)=>{resolve=yes;reject=no;});return {promise,resolve,reject}; };
+test("a snapshot read retries when the repository changed while the read was pending",async()=>{
+ const old=deferred();let revision=0;const api=Object.create(QueryAPI.prototype) as any;
+ api.repository={getRevision:()=>revision,all:jest.fn().mockImplementationOnce(()=>old.promise).mockResolvedValue([{id:"new"}])};
+ const read=api.getAllTasks();revision=1;old.resolve([{id:"old"}]);expect(await read).toEqual([{id:"new"}]);expect(api.taskCache).toEqual([{id:"new"}]);expect(api.repository.all).toHaveBeenCalledTimes(2);
+});
+test("a fresh view read bypasses an older pending read, and the old request cannot clear the new pending read",async()=>{
+ const a=deferred(),b=deferred();const api=Object.create(QueryAPI.prototype) as any;api.repository={getRevision:()=>0,all:jest.fn().mockReturnValueOnce(a.promise).mockReturnValueOnce(b.promise)};
+ const old=api.getAllTasks().catch(()=>{}),fresh=api.getAllTasks(true);a.reject(new Error("old failure"));await old;
+ const shared=api.getAllTasks();expect(api.repository.all).toHaveBeenCalledTimes(2);b.resolve([{id:"new"}]);expect(await shared).toEqual([{id:"new"}]);expect(await fresh).toEqual([{id:"new"}]);
+});
diff --git a/src/dataflow/augment/Augmentor.ts b/src/dataflow/augment/Augmentor.ts
index 8e268ebbe..ef35ae4d9 100644
--- a/src/dataflow/augment/Augmentor.ts
+++ b/src/dataflow/augment/Augmentor.ts
@@ -85,6 +85,11 @@ export class Augmentor {
}
}
+ /** Discard derived dates after source metadata or settings change. */
+ public clearCache(): void {
+ this.dateInheritanceAugmentor?.clearCache();
+ }
+
/**
* Update settings from plugin to control inheritance behavior
*/
@@ -401,6 +406,7 @@ export class Augmentor {
"createdDate",
];
for (const field of dateFields) {
+ if (field !== "createdDate" && typeof ctx.fileMeta?.project === "string" && ctx.fileMeta.project.trim()) continue;
if (metadata[field] === undefined || metadata[field] === null) {
// Try file first, then project
const fileValue = ctx.fileMeta?.[field];
diff --git a/src/dataflow/core/ConfigurableTaskParser.ts b/src/dataflow/core/ConfigurableTaskParser.ts
index 2c089d3ff..a798f8528 100644
--- a/src/dataflow/core/ConfigurableTaskParser.ts
+++ b/src/dataflow/core/ConfigurableTaskParser.ts
@@ -1482,6 +1482,7 @@ export class MarkdownTaskParser {
originalMarkdown: enhancedTask.originalMarkdown,
children: enhancedTask.children || [],
metadata: {
+ ...(["startDate", "dueDate", "scheduledDate", "completedDate", "cancelledDate"].some(field => /\d{1,2}:\d{2}/.test(String(enhancedTask.metadata[field] || ""))) ? { datePrecision: Object.fromEntries(["startDate", "dueDate", "scheduledDate", "completedDate", "cancelledDate"].filter(field => enhancedTask.metadata[field]).map(field => [field, /\d{1,2}:\d{2}/.test(String(enhancedTask.metadata[field])) ? "datetime" : "date"])) } : {}),
tags:
enhancedTask.tags ||
(enhancedTask.metadata.tags
@@ -1803,7 +1804,15 @@ export class MarkdownTaskParser {
!this.config.fileMetadataInheritance
?.inheritFromFrontmatterForSubtasks
) {
- // Legacy behavior: do not inherit for subtasks
+ // Keep general frontmatter inheritance disabled for subtasks, but
+ // project membership is a file-level relationship and must follow a
+ // task when its parent and children move into a project note.
+ const projectKey =
+ this.config.projectConfig?.metadataConfig?.metadataKey || "project";
+ const projectValue = this.fileMetadata?.[projectKey] ?? this.fileMetadata?.project;
+ if (projectValue !== undefined && projectValue !== null && String(projectValue).trim()) {
+ inherited.project = String(projectValue).trim();
+ }
return inherited;
}
@@ -1832,6 +1841,11 @@ export class MarkdownTaskParser {
"comment",
"metadata", // Prevent recursive metadata inheritance
]);
+ // Project dates describe the project, never implicit deadlines of its tasks.
+ const projectKey = this.config.projectConfig?.metadataConfig?.metadataKey || "project";
+ if (String(this.fileMetadata?.[projectKey] ?? this.fileMetadata?.project ?? "").trim()) {
+ for (const field of ["due", "dueDate", "start", "startDate", "scheduled", "scheduledDate"]) nonInheritableFields.add(field);
+ }
// LEGACY: Inherit from file metadata (frontmatter) if available
if (this.fileMetadata) {
diff --git a/src/dataflow/core/__tests__/project-frontmatter-inheritance.test.ts b/src/dataflow/core/__tests__/project-frontmatter-inheritance.test.ts
new file mode 100644
index 000000000..dadd904a3
--- /dev/null
+++ b/src/dataflow/core/__tests__/project-frontmatter-inheritance.test.ts
@@ -0,0 +1,21 @@
+import { ConfigurableTaskParser } from "../ConfigurableTaskParser";
+
+describe("project-note task membership", () => {
+ test("frontmatter project membership reaches subtasks without enabling general inheritance", () => {
+ const parser = new ConfigurableTaskParser({
+ fileMetadataInheritance: {
+ enabled: true,
+ inheritFromFrontmatter: true,
+ inheritFromFrontmatterForSubtasks: false,
+ },
+ } as any);
+ const tasks = parser.parse(
+ "- [ ] Parent\n - [ ] Child",
+ "Projects/Research.md",
+ { project: "Research" },
+ );
+ expect(tasks).toHaveLength(2);
+ expect(tasks[0].metadata.project).toBe("Research");
+ expect(tasks[1].metadata.project).toBe("Research");
+ });
+});
diff --git a/src/dataflow/indexer/Repository.ts b/src/dataflow/indexer/Repository.ts
index ed9ab3d63..174ca36bd 100644
--- a/src/dataflow/indexer/Repository.ts
+++ b/src/dataflow/indexer/Repository.ts
@@ -1,3 +1,4 @@
+import { removeBlankTasks } from "@/utils/task/removeBlankTasks";
import type {
Task,
TaskCache,
@@ -18,6 +19,7 @@ export class Repository {
private indexer: TaskIndexer;
private storage: Storage;
private lastSequence: number = 0;
+ public getRevision(): number { return this.lastSequence; }
private sourceSeq: number = 0; // Track source sequence to differentiate events
private icsEvents: Task[] = []; // Store ICS events separately
private fileTasks = new Map(); // Store file-level tasks
@@ -84,6 +86,22 @@ export class Repository {
`[Repository] Found persisted snapshot with ${snapshotTaskCount} tasks, restoring...`
);
await this.indexer.restoreFromSnapshot(consolidated.data);
+ // Old snapshots can contain empty placeholders even when no file has
+ // changed since the upgrade. Normalize before publishing CACHE_READY.
+ const restored = await this.indexer.getAllTasks();
+ const byFile = new Map();
+ for (const task of restored) {
+ if (!byFile.has(task.filePath)) byFile.set(task.filePath, []);
+ byFile.get(task.filePath)!.push(task);
+ }
+ for (const [filePath, tasks] of byFile) {
+ const normalized = removeBlankTasks(tasks);
+ if (normalized !== tasks) {
+ await this.indexer.updateIndexWithTasks(filePath, normalized);
+ await this.storage.storeAugmented(filePath, normalized);
+ }
+ }
+
const taskCount = await this.indexer.getTotalTaskCount();
console.log(
@@ -135,6 +153,7 @@ export class Repository {
sourceSeq?: number,
options?: { persist?: boolean; forceEmit?: boolean }
): Promise {
+ tasks = removeBlankTasks(tasks);
const persist = options?.persist !== false; // default true
const forceEmit = options?.forceEmit === true;
// Check if tasks have actually changed relative to storage
@@ -190,7 +209,8 @@ export class Repository {
let hasActualChanges = false;
// Process each file update and check for actual changes
- for (const [filePath, tasks] of updates) {
+ for (const [filePath, incomingTasks] of updates) {
+ const tasks = removeBlankTasks(incomingTasks);
// Check if tasks have actually changed relative to storage
const existingAugmented = await this.storage.loadAugmented(
filePath
@@ -517,6 +537,7 @@ export class Repository {
* Clear all data
*/
async clear(): Promise {
+ this.lastSequence = Seq.next();
await this.indexer.clearIndex();
await this.storage.clear();
}
diff --git a/src/dataflow/settings-signature.ts b/src/dataflow/settings-signature.ts
new file mode 100644
index 000000000..a8dbe88b3
--- /dev/null
+++ b/src/dataflow/settings-signature.ts
@@ -0,0 +1,21 @@
+/** Parser and inheritance settings that require rebuilding existing tasks. */
+export const INDEX_SETTING_FIELDS = [
+ "taskStatuses", "fileParsingConfig", "timeParsing", "preferMetadataFormat",
+ "enableCustomDateFormats", "customDateFormats", "projectTagPrefix",
+ "contextTagPrefix", "areaTagPrefix", "useDailyNotePathAsDate",
+ "dailyNoteFormat", "useAsDateType", "dailyNotePath", "ignoreHeading", "focusHeading",
+ "fileSource.recognitionStrategies", "fileSource.fileTaskProperties",
+ "fileSource.relationships", "fileMetadataInheritance", "projectConfig",
+] as const;
+
+/** Capture values, rather than references, because settings are edited in place. */
+export function snapshotIndexSettings(settings: unknown): string {
+ return JSON.stringify(INDEX_SETTING_FIELDS.map(field => {
+ let value = settings;
+ for (const key of field.split(".")) {
+ value = value && typeof value === "object"
+ ? (value as Record)[key] : undefined;
+ }
+ return value;
+ }));
+}
diff --git a/src/dataflow/sources/__tests__/obsidian-source.test.ts b/src/dataflow/sources/__tests__/obsidian-source.test.ts
new file mode 100644
index 000000000..83c8e93dd
--- /dev/null
+++ b/src/dataflow/sources/__tests__/obsidian-source.test.ts
@@ -0,0 +1,29 @@
+import { App, TFile } from "obsidian";
+import { ObsidianSource } from "../ObsidianSource";
+import { Events } from "../../events/Events";
+
+describe("Obsidian Tasks interoperability", () => {
+ beforeEach(() => jest.useFakeTimers());
+ afterEach(() => jest.useRealTimers());
+
+ test("ordinary Markdown task edits enter the Task Genius reindex pipeline", () => {
+ const app = new App() as any;
+ const file = Object.assign(new TFile(), { path: "Daily.md", extension: "md" });
+ const vaultEvents: Record = {};
+ const vault = {
+ on: jest.fn((event: string, handler: Function) => { vaultEvents[event] = handler; return { unload: jest.fn() }; }),
+ };
+ const metadataCache = { on: jest.fn(() => ({ unload: jest.fn() })) };
+ const events: Array<[string, any]> = [];
+ app.workspace.on = jest.fn(() => ({ unload: jest.fn() }));
+ app.workspace.trigger = (name: string, payload: any) => events.push([name, payload]);
+ const source = new ObsidianSource(app, vault as any, metadataCache as any);
+ source.initialize();
+
+ vaultEvents.modify(file);
+ jest.advanceTimersByTime(301);
+
+ expect(events).toContainEqual([Events.FILE_UPDATED, expect.objectContaining({ path: "Daily.md", reason: "modify" })]);
+ expect(vault.on).toHaveBeenCalledWith("modify", expect.any(Function));
+ });
+});
diff --git a/src/editor-extensions/core/quick-capture-panel.ts b/src/editor-extensions/core/quick-capture-panel.ts
index 8869fbe53..d19a9c1d2 100644
--- a/src/editor-extensions/core/quick-capture-panel.ts
+++ b/src/editor-extensions/core/quick-capture-panel.ts
@@ -87,6 +87,7 @@ export const quickCaptureState = StateField.define({
// Configuration options for the quick capture panel
export interface QuickCaptureOptions {
+ dailyNoteDate?: string;
targetFile?: string;
placeholder?: string;
appendToFile?: "append" | "prepend" | "replace";
diff --git a/src/editor-extensions/task-operations/gutter-marker.ts b/src/editor-extensions/task-operations/gutter-marker.ts
index 7bbf8b75a..adbab8249 100644
--- a/src/editor-extensions/task-operations/gutter-marker.ts
+++ b/src/editor-extensions/task-operations/gutter-marker.ts
@@ -10,7 +10,7 @@ import { App, Platform, ExtraButtonComponent } from "obsidian";
import { Task } from "@/types/task";
import TaskProgressBarPlugin from "@/index";
import { TaskDetailsModal } from "@/components/features/task/edit/TaskDetailsModal";
-import { TaskDetailsPopover } from "@/components/features/task/edit/TaskDetailsPopover";
+
import { MarkdownTaskParser } from "@/dataflow/core/ConfigurableTaskParser";
// @ts-ignore - This import is necessary but TypeScript can't find it
import { syntaxTree, tokenClassNodeProp } from "@codemirror/language";
@@ -108,29 +108,7 @@ const showTaskDetails = (
task: Task,
extraSettingsEl: HTMLElement
) => {
- // Task update callback function
- const onTaskUpdated = async (updatedTask: Task) => {
- if (plugin.writeAPI) {
- await plugin.writeAPI.updateTask({
- taskId: updatedTask.id,
- updates: updatedTask,
- });
- }
- };
-
- if (Platform.isDesktop) {
- // Desktop environment - show Popover
- const popover = new TaskDetailsPopover(app, plugin, task);
- const rect = extraSettingsEl.getBoundingClientRect();
- popover.showAtPosition({
- x: rect.left,
- y: rect.bottom + 10,
- });
- } else {
- // Mobile environment - show Modal
- const modal = new TaskDetailsModal(app, plugin, task, onTaskUpdated);
- modal.open();
- }
+ new TaskDetailsModal(app, plugin, task).open();
};
// Task parser instance
diff --git a/src/icon.ts b/src/icon.ts
index 21b83e292..3076091c1 100644
--- a/src/icon.ts
+++ b/src/icon.ts
@@ -10,9 +10,11 @@ export function getTaskGeniusIcon() {
}
export function getStatusIcon(
- status: "notStarted" | "inProgress" | "completed" | "abandoned" | "planned"
+ status: "notStarted" | "inProgress" | "completed" | "abandoned" | "planned" | "archived" | "paused" | "pause"
) {
switch (status) {
+ case "archived": case "paused": case "pause":
+ return ``;
case "notStarted":
return `