diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b28ebd22c..d5ef12412 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,9 +2,9 @@ name: CI on: push: - branches: [master, main] + branches: [master, main, "legacy/**"] pull_request: - branches: [master, main] + branches: [master, main, "legacy/**"] jobs: build: @@ -13,6 +13,8 @@ jobs: steps: - name: Checkout uses: actions/checkout@v4 + with: + submodules: true - name: Setup Node.js uses: actions/setup-node@v4 @@ -22,7 +24,7 @@ jobs: - name: Setup pnpm uses: pnpm/action-setup@v4 with: - version: 10 + version: 10.26.0 - name: Get pnpm store directory shell: bash @@ -38,10 +40,16 @@ jobs: ${{ runner.os }}-pnpm-store- - name: Install dependencies - run: pnpm install + run: pnpm install --frozen-lockfile --ignore-scripts - name: Build - run: pnpm run build + run: pnpm build:release + + - name: Run habits tests + run: pnpm test:habits + + - name: Run UI regression tests + run: pnpm test:ui - name: Run tests - run: pnpm run test --passWithNoTests + run: pnpm exec jest --runInBand --passWithNoTests diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a90a75f12..b1d2c3a79 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -16,6 +16,7 @@ jobs: uses: actions/checkout@v4 with: fetch-depth: 0 + submodules: true - name: Setup Node.js uses: actions/setup-node@v4 @@ -25,7 +26,7 @@ jobs: - name: Setup pnpm uses: pnpm/action-setup@v4 with: - version: 10 + version: 10.26.0 - name: Get pnpm store directory shell: bash @@ -41,10 +42,13 @@ jobs: ${{ runner.os }}-pnpm-store- - name: Install dependencies - run: pnpm install + run: pnpm install --frozen-lockfile --ignore-scripts + + - name: Verify tag matches plugin version + run: node scripts/check-release-version.cjs "${GITHUB_REF_NAME}" - name: Build - run: pnpm run build + run: pnpm build:release - name: Get version from tag id: get_version diff --git a/.gitignore b/.gitignore index 603faad9a..5c8a2046b 100644 --- a/.gitignore +++ b/.gitignore @@ -53,3 +53,15 @@ packages/*/node_modules # Documentation site (separate repository) docs-site + +# Local habit integration verification artifacts +habits-*.log +habits-*-jest.json + +# Local UI audit verification +/audit-*.log +/audit-*.json + +# Independent local browser layout artifacts +/output/playwright/ +/.playwright-cli/ diff --git a/README.md b/README.md index 785e9e4f2..c9b6bc044 100644 --- a/README.md +++ b/README.md @@ -77,3 +77,8 @@ Join our active community for help, tips, and feature discussions: [FSL-1.1-ALv2](./LICENSE) Feel free to use any part in the `src/components`, such as the Inline Markdown Editor or the Kanban component. +## 旧布局维护分支 + +`legacy/9.13.1` 从官方 9.13.1 标签维护,保留原设置导航与布局。设置中文、状态菜单和索引刷新修复在此分支独立实现。 + +发布步骤见 [RELEASING.zh-CN.md](RELEASING.zh-CN.md)。使用 `pnpm build:release` 生成 `dist/main.js`、`dist/manifest.json`、`dist/styles.css`,随后由仓库所有者自行创建 GitHub Release。PR 或构建成功本身不会发布 Release。 diff --git a/RELEASING.zh-CN.md b/RELEASING.zh-CN.md new file mode 100644 index 000000000..1f3f07d86 --- /dev/null +++ b/RELEASING.zh-CN.md @@ -0,0 +1,45 @@ +# 自行发布旧布局版本 + +本维护分支从官方 `9.13.1` 标签建立,保留旧设置布局。新 PR 合并目标是 `legacy/9.13.1`,与仓库原来的 `master` 分开。当前准备发布的插件版本是 **9.13.2**。 + +## 第一次发布:通过 GitHub 网页 + +1. 合并本 PR 到 `legacy/9.13.1`。 +2. 打开仓库右侧的 **Releases**,点击 **Draft a new release**。 +3. 在 **Choose a tag** 输入 `9.13.2`,选择创建新标签。在 **Target** 选择 `legacy/9.13.1`。标签与 `manifest.json` 中的版本号保持一致,不要加 `v`。 +4. 标题填写 `9.13.2:旧布局设置中文完善`,说明中写本次改动。 +5. 在附件区域上传构建生成的 **main.js、manifest.json、styles.css**。可以额外上传 `task-genius-9.13.2.zip`,但 BRAT 所需的三个文件仍应分别作为附件提供。 +6. 自测版本可以勾选 **This is a pre-release**。确认可用、希望 BRAT 的 `latest` 自动获取时,发布正式版本并选择 **Set as latest release**。 +7. 最后点击 **Publish release**。发布后检查附件列表是否真的有三个独立文件;GitHub 自动提供的 Source code 压缩包只是源码。 + +官方网页操作说明:https://docs.github.com/en/repositories/releasing-projects-on-github/managing-releases-in-a-repository + +## 怎样从源码生成附件 + +需要 Git、Node.js 20 及 pnpm 10.26.0。在终端执行: + +```powershell +git clone --branch legacy/9.13.1 --recurse-submodules https://github.com/Platinum1154/taskgenius-plugin.git +cd taskgenius-plugin +pnpm install --frozen-lockfile --ignore-scripts +pnpm build:release +node scripts/zip.mjs +``` + +三个发布文件和可选压缩包都在 `dist` 文件夹。`build:release` 会先构建工作区组件,再检查翻译、版本号与 TypeScript,最后生成插件文件。构建不负责发布,也不要求 GitHub token。 + +`packages/calendar` 已固定为官方仍可下载的提交;不要用空目录代替子模块,也不要从其他 fork 拷贝编译产物。 + +## 以后发布下一版 + +例如发布 `9.13.3`,先在维护分支修改: + +- `package.json` 的 `version` 为 `9.13.3`。 +- `manifest.json` 的 `version` 为 `9.13.3`。 +- 在 `versions.json` 中添加 `"9.13.3": "0.15.2"`;最低 Obsidian 版本沿用 manifest 的实际值。 + +提交并推送这些更改,再重新构建。创建 Release 时也使用 `9.13.3`,上传这次新构建的附件。只改 Release 标题或标签,不会改变插件文件中的版本号。 + +标签推送还会运行仓库的 Release workflow;它会核对版本、构建并上传附件。网页上传仍可直接提供本地验证过的构建文件。CI 会保留原版完整测试的真实结果,不会为通过检查而跳过既有失败用例。 + +这条旧版维护分支没有更改默认分支。若通过 `release-it` 发布,原有脚本限制分支为 master;请按本指南的构建及网页发布步骤操作。 diff --git a/VALIDATION.zh-CN.md b/VALIDATION.zh-CN.md new file mode 100644 index 000000000..9b8e1a3e6 --- /dev/null +++ b/VALIDATION.zh-CN.md @@ -0,0 +1,37 @@ +# 验证记录:旧布局 9.13.2 + +基线:官方 9.13.1 标签,提交 `7d8e83bddfa4e8ba95de4be40247ee38d42658b8`。新增实现未移植 zm4341 fork 的改动。 + +## 通过的检查 + +- `pnpm build:release`:工作区组件构建、翻译检查、版本一致性检查、TypeScript 检查与生产打包通过。 +- 设置检查覆盖 1,800 个英文/中文条目,插值占位符一致。新增翻译来自此次旧版补齐工作。 +- 新增 4 组、18 项回归测试全部通过,覆盖中文/英文文本、空任务处理、右键状态切换、嵌套设置变更、失败重试与顺序处理。 +- `node scripts/zip.mjs`:成功生成发布压缩包。 +- `git diff --check`:通过。 + +## 全量测试的实际结果 + +相同依赖环境下分别运行未修改的 9.13.1 与本 PR: + +| 项目 | 原版 9.13.1 | 本 PR | +| --- | ---: | ---: | +| 通过测试 | 1,331 | 1,350 | +| 失败测试 | 147 | 146 | +| 失败测试套件 | 38 | 38 | + +按测试完整名称比较,本 PR 新增失败为 0。原版有一项性能阈值测试在本次通过,结果可能有时序波动,不将其视为已修复的问题。原有失败包括主动抛错的调试测试及旧测试夹具问题;本次没有删除、跳过或放宽这些测试来制造全绿结果。 + +因此,完整测试套件**尚未全绿**。CI 继续展示真实结果。发布前请先试用本源码构建的插件文件。 + +## 界面验证的范围 + +本次翻译补充曾在运行中的旧版 Obsidian 插件中用原生设置渲染器检查全部 26 页:当前配置与展开选项各一轮,共 52 次渲染、569 行设置;普通文案无英文残留,主题/客户端名称及格式示例保留原文。 + +上述界面验证使用的是旧版本地补丁。本 PR 是从官方标签重新整理的源码构建,且为修复不可获取的依赖提交而更新了 calendar 固定版本;没有用新的构建覆盖正在使用的 Obsidian。源码构建仍需要安装试用,不能把先前界面验证当成这个新构建的完整人工验收。 + +## 依赖与发布 + +原版 calendar 固定提交 `3107a754e650b64cb5dd68101ebbad99ac422f27` 已无法从官方仓库取得。本 PR 固定到官方可获取的 `3cb570633ae01ab569b26a956639fc167da398ba`,并明确构建工作区包,使构建可以重现。 + +版本元数据已统一为 `9.13.2`。没有创建或发布 GitHub Release。自行发布说明见 [RELEASING.zh-CN.md](RELEASING.zh-CN.md)。 diff --git a/docs/audit-2026-11-08-inventory.json b/docs/audit-2026-11-08-inventory.json new file mode 100644 index 000000000..9b36d0d3e --- /dev/null +++ b/docs/audit-2026-11-08-inventory.json @@ -0,0 +1,5383 @@ +{ + "purpose": "Repository-wide static review inventory. Signals are review prompts, not confirmed bugs.", + "roots": [ + "src", + "packages/calendar/src", + "scripts", + "tests", + ".github/workflows" + ], + "totals": { + "files": 711, + "lines": 311764, + "testFiles": 126, + "typescriptFiles": 604 + }, + "files": [ + { + "path": ".github/workflows/ci.yml", + "lines": 56, + "bytes": 1547, + "test": false, + "signals": {} + }, + { + "path": ".github/workflows/cla.yml", + "lines": 23, + "bytes": 959, + "test": false, + "signals": {} + }, + { + "path": ".github/workflows/release.yml", + "lines": 73, + "bytes": 2257, + "test": false, + "signals": {} + }, + { + "path": "packages/calendar/src/adapters/DateAdapter.ts", + "lines": 6, + "bytes": 175, + "test": false, + "signals": {} + }, + { + "path": "packages/calendar/src/adapters/DateFnsAdapter.ts", + "lines": 201, + "bytes": 5973, + "test": false, + "signals": {} + }, + { + "path": "packages/calendar/src/adapters/DayJsAdapter.ts", + "lines": 115, + "bytes": 3210, + "test": false, + "signals": {} + }, + { + "path": "packages/calendar/src/adapters/index.ts", + "lines": 9, + "bytes": 304, + "test": false, + "signals": {} + }, + { + "path": "packages/calendar/src/adapters/MomentAdapter.ts", + "lines": 173, + "bytes": 5073, + "test": false, + "signals": {} + }, + { + "path": "packages/calendar/src/adapters/NativeDateAdapter.ts", + "lines": 279, + "bytes": 8680, + "test": false, + "signals": {} + }, + { + "path": "packages/calendar/src/constants/formats.ts", + "lines": 38, + "bytes": 1147, + "test": false, + "signals": {} + }, + { + "path": "packages/calendar/src/constants/index.ts", + "lines": 5, + "bytes": 124, + "test": false, + "signals": {} + }, + { + "path": "packages/calendar/src/core/Calendar.ts", + "lines": 861, + "bytes": 26350, + "test": false, + "signals": {} + }, + { + "path": "packages/calendar/src/core/DragController.ts", + "lines": 843, + "bytes": 29048, + "test": false, + "signals": { + "directDomListener": 2 + } + }, + { + "path": "packages/calendar/src/core/EventManager.ts", + "lines": 109, + "bytes": 2159, + "test": false, + "signals": {} + }, + { + "path": "packages/calendar/src/core/index.ts", + "lines": 8, + "bytes": 240, + "test": false, + "signals": {} + }, + { + "path": "packages/calendar/src/core/InteractionController.ts", + "lines": 651, + "bytes": 18838, + "test": false, + "signals": { + "directDomListener": 8 + } + }, + { + "path": "packages/calendar/src/engines/index.ts", + "lines": 6, + "bytes": 126, + "test": false, + "signals": {} + }, + { + "path": "packages/calendar/src/engines/MonthEngine.ts", + "lines": 364, + "bytes": 11595, + "test": false, + "signals": {} + }, + { + "path": "packages/calendar/src/engines/TimeEngine.ts", + "lines": 746, + "bytes": 23232, + "test": false, + "signals": {} + }, + { + "path": "packages/calendar/src/index.ts", + "lines": 141, + "bytes": 3760, + "test": false, + "signals": {} + }, + { + "path": "packages/calendar/src/presets.ts", + "lines": 242, + "bytes": 7012, + "test": false, + "signals": {} + }, + { + "path": "packages/calendar/src/renderers/index.ts", + "lines": 6, + "bytes": 129, + "test": false, + "signals": {} + }, + { + "path": "packages/calendar/src/renderers/MonthRenderer.ts", + "lines": 710, + "bytes": 22593, + "test": false, + "signals": { + "timer": 1, + "directDomListener": 4 + } + }, + { + "path": "packages/calendar/src/renderers/TimeRenderer.ts", + "lines": 892, + "bytes": 28520, + "test": false, + "signals": { + "timer": 3, + "directDomListener": 5 + } + }, + { + "path": "packages/calendar/src/styles/base.css", + "lines": 139, + "bytes": 2836, + "test": false, + "signals": {} + }, + { + "path": "packages/calendar/src/styles/events.css", + "lines": 273, + "bytes": 6637, + "test": false, + "signals": {} + }, + { + "path": "packages/calendar/src/styles/index.ts", + "lines": 42, + "bytes": 1419, + "test": false, + "signals": {} + }, + { + "path": "packages/calendar/src/styles/month.css", + "lines": 190, + "bytes": 3979, + "test": false, + "signals": {} + }, + { + "path": "packages/calendar/src/styles/styles.css", + "lines": 15, + "bytes": 355, + "test": false, + "signals": {} + }, + { + "path": "packages/calendar/src/styles/time.css", + "lines": 125, + "bytes": 2798, + "test": false, + "signals": {} + }, + { + "path": "packages/calendar/src/types/index.ts", + "lines": 769, + "bytes": 25316, + "test": false, + "signals": { + "htmlAssignment": 1 + } + }, + { + "path": "packages/calendar/src/utils/dom.ts", + "lines": 138, + "bytes": 3470, + "test": false, + "signals": { + "directDomListener": 1, + "htmlAssignment": 1 + } + }, + { + "path": "packages/calendar/src/utils/index.ts", + "lines": 5, + "bytes": 63, + "test": false, + "signals": {} + }, + { + "path": "packages/calendar/src/utils/presets.ts", + "lines": 291, + "bytes": 7082, + "test": false, + "signals": {} + }, + { + "path": "packages/calendar/src/views/BaseView.ts", + "lines": 233, + "bytes": 6591, + "test": false, + "signals": {} + }, + { + "path": "packages/calendar/src/views/index.ts", + "lines": 24, + "bytes": 568, + "test": false, + "signals": {} + }, + { + "path": "packages/calendar/src/views/MonthView.ts", + "lines": 108, + "bytes": 2747, + "test": false, + "signals": {} + }, + { + "path": "packages/calendar/src/views/TimeView.ts", + "lines": 162, + "bytes": 3974, + "test": false, + "signals": {} + }, + { + "path": "packages/calendar/src/views/ViewRegistry.ts", + "lines": 238, + "bytes": 6208, + "test": false, + "signals": {} + }, + { + "path": "scripts/audit-source-map.cjs", + "lines": 34, + "bytes": 1708, + "test": false, + "signals": {} + }, + { + "path": "scripts/changelog-transformer.mjs", + "lines": 164, + "bytes": 4328, + "test": false, + "signals": {} + }, + { + "path": "scripts/check-habits-i18n.cjs", + "lines": 41, + "bytes": 2090, + "test": false, + "signals": {} + }, + { + "path": "scripts/check-release-version.cjs", + "lines": 9, + "bytes": 700, + "test": false, + "signals": {} + }, + { + "path": "scripts/check-settings-i18n.cjs", + "lines": 34, + "bytes": 2157, + "test": false, + "signals": {} + }, + { + "path": "scripts/custom-changelog.mjs", + "lines": 245, + "bytes": 6743, + "test": false, + "signals": {} + }, + { + "path": "scripts/extract-translations.cjs", + "lines": 240, + "bytes": 5628, + "test": false, + "signals": {} + }, + { + "path": "scripts/generate-locale-files.cjs", + "lines": 125, + "bytes": 3396, + "test": false, + "signals": { + "dynamicEvaluation": 1 + } + }, + { + "path": "scripts/ob-bumper.mjs", + "lines": 125, + "bytes": 4114, + "test": false, + "signals": {} + }, + { + "path": "scripts/ob.esbuild.mjs", + "lines": 45, + "bytes": 1362, + "test": false, + "signals": {} + }, + { + "path": "scripts/scope-habits-css.mjs", + "lines": 24, + "bytes": 1067, + "test": false, + "signals": {} + }, + { + "path": "scripts/smart-beta-release.mjs", + "lines": 109, + "bytes": 3898, + "test": false, + "signals": {} + }, + { + "path": "scripts/zip.mjs", + "lines": 30, + "bytes": 1005, + "test": false, + "signals": {} + }, + { + "path": "src/__mocks__/codemirror-language.ts", + "lines": 6, + "bytes": 192, + "test": false, + "signals": {} + }, + { + "path": "src/__mocks__/codemirror-search.ts", + "lines": 8, + "bytes": 179, + "test": false, + "signals": {} + }, + { + "path": "src/__mocks__/codemirror-state.ts", + "lines": 296, + "bytes": 6445, + "test": false, + "signals": {} + }, + { + "path": "src/__mocks__/codemirror-view.ts", + "lines": 100, + "bytes": 1644, + "test": false, + "signals": {} + }, + { + "path": "src/__mocks__/dom-helpers.ts", + "lines": 2, + "bytes": 20, + "test": false, + "signals": {} + }, + { + "path": "src/__mocks__/moment.js", + "lines": 132, + "bytes": 2885, + "test": false, + "signals": {} + }, + { + "path": "src/__mocks__/obsidian.ts", + "lines": 510, + "bytes": 10552, + "test": false, + "signals": { + "timer": 1, + "directDomListener": 1 + } + }, + { + "path": "src/__mocks__/ProjectData.worker.ts", + "lines": 48, + "bytes": 1052, + "test": false, + "signals": { + "timer": 1 + } + }, + { + "path": "src/__mocks__/styleMock.js", + "lines": 3, + "bytes": 46, + "test": false, + "signals": {} + }, + { + "path": "src/__tests__/ArchiveActionExecutor.canvas.test.ts", + "lines": 771, + "bytes": 23694, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/ArchiveActionExecutor.markdown.test.ts", + "lines": 366, + "bytes": 11676, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/autoCompleteParent.test.ts", + "lines": 823, + "bytes": 26297, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/autoDateManager.debug.test.ts", + "lines": 115, + "bytes": 4136, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/autoDateManager.final.test.ts", + "lines": 100, + "bytes": 3430, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/autoDateManager.improved.test.ts", + "lines": 215, + "bytes": 7156, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/autoDateManager.integration.test.ts", + "lines": 101, + "bytes": 2866, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/autoDateManager.pause-conflict.test.ts", + "lines": 147, + "bytes": 5161, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/autoDateManager.realworld.test.ts", + "lines": 101, + "bytes": 3473, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/autoDateManager.research.test.ts", + "lines": 156, + "bytes": 5654, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/autoDateManager.simple.test.ts", + "lines": 67, + "bytes": 2081, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/autoDateManager.test.ts", + "lines": 258, + "bytes": 9051, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/autoDateManager.tracing.test.ts", + "lines": 100, + "bytes": 4059, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/badge-date-comparison.test.ts", + "lines": 239, + "bytes": 8509, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/badge-date-parsing.test.ts", + "lines": 252, + "bytes": 7858, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/badge-debug-helper.test.ts", + "lines": 491, + "bytes": 13328, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/calendar-badge-rendering.test.ts", + "lines": 694, + "bytes": 18826, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/calendar-performance.test.ts", + "lines": 372, + "bytes": 11355, + "test": true, + "signals": { + "weakRandom": 1 + } + }, + { + "path": "src/__tests__/calendar-view-integration.test.ts", + "lines": 610, + "bytes": 16795, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/CanvasFileMonitoring.test.ts", + "lines": 279, + "bytes": 9661, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/CanvasIntegration.test.ts", + "lines": 332, + "bytes": 12591, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/CanvasParser.test.ts", + "lines": 281, + "bytes": 9962, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/CanvasTaskMatching.integration.test.ts", + "lines": 524, + "bytes": 14739, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/CanvasTaskOperationUtils.test.ts", + "lines": 501, + "bytes": 12311, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/CanvasTaskUpdater.test.ts", + "lines": 828, + "bytes": 34285, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/chinese-tag-performance.test.ts", + "lines": 198, + "bytes": 6586, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/CompleteActionExecutor.test.ts", + "lines": 503, + "bytes": 13424, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/cycleCompleteStatus.test.ts", + "lines": 1388, + "bytes": 44869, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/date-display-helper.test.ts", + "lines": 101, + "bytes": 3646, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/DateInheritanceIntegration.test.ts", + "lines": 394, + "bytes": 13032, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/DateInheritancePerformance.test.ts", + "lines": 370, + "bytes": 12370, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/DateInheritanceService.test.ts", + "lines": 594, + "bytes": 17895, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/dateTemplates.test.ts", + "lines": 98, + "bytes": 3220, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/dateUtil.test.ts", + "lines": 63, + "bytes": 2647, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/debug.test.ts", + "lines": 74, + "bytes": 2126, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/DeleteActionExecutor.canvas.test.ts", + "lines": 308, + "bytes": 7768, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/DeleteActionExecutor.test.ts", + "lines": 418, + "bytes": 11120, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/DuplicateActionExecutor.canvas.test.ts", + "lines": 451, + "bytes": 13089, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/edge-case-tests.js", + "lines": 214, + "bytes": 8240, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/EnhancedTimeParsingEdgeCases.test.ts", + "lines": 537, + "bytes": 19100, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/EnhancedTimeParsingIntegration.test.ts", + "lines": 796, + "bytes": 25649, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/EnhancedTimeParsingPerformance.test.ts", + "lines": 811, + "bytes": 27564, + "test": true, + "signals": { + "weakRandom": 3 + } + }, + { + "path": "src/__tests__/EnhancedTimeParsingService.test.ts", + "lines": 261, + "bytes": 9847, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/file-source/FileSource.basic.test.ts", + "lines": 439, + "bytes": 13771, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/file-source/FileSourceConfig.test.ts", + "lines": 318, + "bytes": 9814, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/file-source/status-mapping.test.ts", + "lines": 259, + "bytes": 9193, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/file-task-manager/frontmatter-title-protection.test.ts", + "lines": 274, + "bytes": 9248, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/FileFilterManager.test.ts", + "lines": 259, + "bytes": 8079, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/FileMetadataInheritance.test.ts", + "lines": 518, + "bytes": 17216, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/FileMetadataInheritanceDebug.test.ts", + "lines": 51, + "bytes": 1854, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/FileMetadataInheritanceSettings.test.ts", + "lines": 316, + "bytes": 10748, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/FileMetadataTaskParser.test.ts", + "lines": 509, + "bytes": 13144, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/FileTaskManagerTimeIntegration.test.ts", + "lines": 395, + "bytes": 12298, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/findContinuousTaskBlocks.test.ts", + "lines": 156, + "bytes": 4699, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/findParentWorkflow.test.ts", + "lines": 128, + "bytes": 3478, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/fluent-status-menu-regression.test.ts", + "lines": 56, + "bytes": 3567, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/forceReindex.integration.test.ts", + "lines": 235, + "bytes": 7353, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/ics-badge-integration.test.ts", + "lines": 270, + "bytes": 7757, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/ics-integration.test.ts", + "lines": 470, + "bytes": 14049, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/ics-manager.test.ts", + "lines": 672, + "bytes": 17891, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/ics-parser-performance.test.ts", + "lines": 179, + "bytes": 6125, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/ics-parser.test.ts", + "lines": 297, + "bytes": 8499, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/ics-timeout-fix.test.ts", + "lines": 206, + "bytes": 5801, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/IcsEventTimeHandling.integration.test.ts", + "lines": 261, + "bytes": 8154, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/IcsManagerTimeIntegration.test.ts", + "lines": 495, + "bytes": 15974, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/InlineTaskTimeIntegration.test.ts", + "lines": 257, + "bytes": 11276, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/integration-test.js", + "lines": 209, + "bytes": 7945, + "test": true, + "signals": { + "timer": 2 + } + }, + { + "path": "src/__tests__/integration/FileFilterIntegration.test.ts", + "lines": 316, + "bytes": 13519, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/legacy-settings-invalidation.test.ts", + "lines": 41, + "bytes": 2926, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/legacy-settings-language.test.ts", + "lines": 31, + "bytes": 1654, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/mockUtils.ts", + "lines": 730, + "bytes": 19830, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/MoveActionExecutor.canvas.test.ts", + "lines": 479, + "bytes": 13506, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/MoveActionExecutor.test.ts", + "lines": 851, + "bytes": 23743, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/onCompletion-boundary-fix.test.ts", + "lines": 112, + "bytes": 4324, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/onCompletion-integration.test.ts", + "lines": 768, + "bytes": 20695, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/OnCompletionManager.test.ts", + "lines": 667, + "bytes": 19042, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/ParentTaskDateInheritance.test.ts", + "lines": 495, + "bytes": 16489, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/priority-user-scenario.test.ts", + "lines": 299, + "bytes": 10188, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/ProjectConfigManager.cache.test.ts", + "lines": 261, + "bytes": 9041, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/ProjectConfigManager.test.ts", + "lines": 740, + "bytes": 19782, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/ProjectDataWorkerManager.test.ts", + "lines": 278, + "bytes": 8463, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/ProjectDetectionFixes.test.ts", + "lines": 419, + "bytes": 13122, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/ProjectSourceDisplay.test.ts", + "lines": 464, + "bytes": 12353, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/ProjectSourceWorkerFix.test.ts", + "lines": 318, + "bytes": 8886, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/projectTreeBuilder.test.ts", + "lines": 303, + "bytes": 8647, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/projectUtils.test.ts", + "lines": 644, + "bytes": 14659, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/QuickCaptureModal.integration.test.ts", + "lines": 494, + "bytes": 14665, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/removeBlankTasks.test.ts", + "lines": 31, + "bytes": 1822, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/SettingsMigration.test.ts", + "lines": 222, + "bytes": 10176, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/SettingsSearch.test.ts", + "lines": 308, + "bytes": 9527, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/sortTasks.test.ts", + "lines": 266, + "bytes": 7949, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/SuggestBackwardCompatibility.test.ts", + "lines": 303, + "bytes": 8556, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/SuggestPerformance.test.ts", + "lines": 281, + "bytes": 8003, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/TagParsingEdgeCases.test.ts", + "lines": 262, + "bytes": 9554, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/TagsInheritanceInvestigation.test.ts", + "lines": 67, + "bytes": 2564, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/TaskIndexer.mtime.test.ts", + "lines": 173, + "bytes": 4618, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/taskMarkCleanup.test.ts", + "lines": 111, + "bytes": 3810, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/TaskMetadataUtils.test.ts", + "lines": 348, + "bytes": 11306, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/TaskMigrationService.test.ts", + "lines": 394, + "bytes": 11453, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/taskParser.test.ts", + "lines": 986, + "bytes": 33273, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/TaskParsingService.integration.test.ts", + "lines": 1376, + "bytes": 39770, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/taskTimer.pause-fix.test.ts", + "lines": 105, + "bytes": 3650, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/TaskTimerSegments.test.ts", + "lines": 205, + "bytes": 5951, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/TaskWorkerManager.mtime.test.ts", + "lines": 270, + "bytes": 7784, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/test-tree-view-fix.js", + "lines": 140, + "bytes": 4578, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/TimelineCanvasIntegration.test.ts", + "lines": 325, + "bytes": 12161, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/TimelineEventEnhancement.test.ts", + "lines": 1023, + "bytes": 29383, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/TimelineSidebarView.test.ts", + "lines": 382, + "bytes": 14198, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/timeout-verification.test.ts", + "lines": 120, + "bytes": 3391, + "test": true, + "signals": { + "timer": 2 + } + }, + { + "path": "src/__tests__/TimeParsingService.test.ts", + "lines": 452, + "bytes": 15730, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/TimeParsingServiceDebug.test.ts", + "lines": 59, + "bytes": 1909, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/TimeParsingSettingsIntegration.test.ts", + "lines": 321, + "bytes": 9863, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/types.d.ts", + "lines": 9, + "bytes": 490, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/UniversalSuggest.test.ts", + "lines": 256, + "bytes": 7454, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/viewModeUtils.test.ts", + "lines": 168, + "bytes": 5702, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/webcal-integration.test.ts", + "lines": 355, + "bytes": 11960, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/worker-processing-control.test.ts", + "lines": 158, + "bytes": 5370, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/workflow.test.ts", + "lines": 1095, + "bytes": 32241, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/workflowDecorator.test.ts", + "lines": 743, + "bytes": 22673, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/workflowOptimization.test.ts", + "lines": 496, + "bytes": 12360, + "test": true, + "signals": {} + }, + { + "path": "src/__tests__/writeapi-links-preserve.test.ts", + "lines": 213, + "bytes": 6389, + "test": true, + "signals": {} + }, + { + "path": "src/cache/local-storage-cache.ts", + "lines": 393, + "bytes": 10264, + "test": false, + "signals": {} + }, + { + "path": "src/cache/project-data-cache.ts", + "lines": 597, + "bytes": 15702, + "test": false, + "signals": { + "timer": 1 + } + }, + { + "path": "src/commands/completedTaskMover.ts", + "lines": 1778, + "bytes": 49867, + "test": false, + "signals": { + "directNoteWrite": 2 + } + }, + { + "path": "src/commands/sortTaskCommands.ts", + "lines": 958, + "bytes": 31671, + "test": false, + "signals": {} + }, + { + "path": "src/commands/taskCycleCommands.ts", + "lines": 161, + "bytes": 4456, + "test": false, + "signals": {} + }, + { + "path": "src/commands/taskMover.ts", + "lines": 586, + "bytes": 15721, + "test": false, + "signals": { + "directNoteWrite": 1 + } + }, + { + "path": "src/commands/workflowCommands.ts", + "lines": 375, + "bytes": 10005, + "test": false, + "signals": {} + }, + { + "path": "src/common/default-symbol.ts", + "lines": 52, + "bytes": 1103, + "test": false, + "signals": {} + }, + { + "path": "src/common/noise.ts", + "lines": 82, + "bytes": 2943, + "test": false, + "signals": { + "htmlAssignment": 1 + } + }, + { + "path": "src/common/regex-define.ts", + "lines": 146, + "bytes": 5386, + "test": false, + "signals": {} + }, + { + "path": "src/common/setting-definition.ts", + "lines": 2020, + "bytes": 58791, + "test": false, + "signals": {} + }, + { + "path": "src/common/settings-metadata.ts", + "lines": 895, + "bytes": 35802, + "test": false, + "signals": {} + }, + { + "path": "src/common/task-parser-config.ts", + "lines": 125, + "bytes": 3425, + "test": false, + "signals": {} + }, + { + "path": "src/common/task-status/AnuPpuccinThemeCollection.ts", + "lines": 43, + "bytes": 1539, + "test": false, + "signals": {} + }, + { + "path": "src/common/task-status/AuraThemeCollection.ts", + "lines": 34, + "bytes": 1219, + "test": false, + "signals": {} + }, + { + "path": "src/common/task-status/BorderThemeCollection.ts", + "lines": 34, + "bytes": 1197, + "test": false, + "signals": {} + }, + { + "path": "src/common/task-status/EbullientworksThemeCollection.ts", + "lines": 22, + "bytes": 789, + "test": false, + "signals": {} + }, + { + "path": "src/common/task-status/index.ts", + "lines": 23, + "bytes": 657, + "test": false, + "signals": {} + }, + { + "path": "src/common/task-status/ITSThemeCollection.ts", + "lines": 53, + "bytes": 1824, + "test": false, + "signals": {} + }, + { + "path": "src/common/task-status/LYTModeThemeCollection.ts", + "lines": 37, + "bytes": 1362, + "test": false, + "signals": {} + }, + { + "path": "src/common/task-status/MinimalThemeCollection.ts", + "lines": 38, + "bytes": 1406, + "test": false, + "signals": {} + }, + { + "path": "src/common/task-status/StatusCollections.d.ts", + "lines": 15, + "bytes": 662, + "test": false, + "signals": {} + }, + { + "path": "src/common/task-status/ThingsThemeCollection.ts", + "lines": 39, + "bytes": 1400, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/calendar/algorithm.ts", + "lines": 54, + "bytes": 1991, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/calendar/index.ts", + "lines": 1997, + "bytes": 58665, + "test": false, + "signals": { + "timer": 5 + } + }, + { + "path": "src/components/features/calendar/rendering/event-renderer.ts", + "lines": 382, + "bytes": 10717, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/calendar/views/agenda-view.ts", + "lines": 157, + "bytes": 5421, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/calendar/views/base-view.ts", + "lines": 99, + "bytes": 3314, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/calendar/views/day-view.ts", + "lines": 127, + "bytes": 4209, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/calendar/views/month-view.ts", + "lines": 467, + "bytes": 16144, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/calendar/views/tg-agenda-view.ts", + "lines": 371, + "bytes": 10152, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/calendar/views/tg-year-view.ts", + "lines": 564, + "bytes": 14821, + "test": false, + "signals": { + "directDomListener": 4 + } + }, + { + "path": "src/components/features/calendar/views/week-view.ts", + "lines": 389, + "bytes": 13462, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/calendar/views/year-view.ts", + "lines": 360, + "bytes": 12338, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/changelog/ChangelogView.ts", + "lines": 161, + "bytes": 3412, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/fluent/components/FluentSidebar.ts", + "lines": 1039, + "bytes": 29610, + "test": false, + "signals": { + "timer": 1, + "directDomListener": 2 + } + }, + { + "path": "src/components/features/fluent/components/FluentTopNavigation.ts", + "lines": 703, + "bytes": 18472, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/fluent/components/ProjectList.ts", + "lines": 1105, + "bytes": 28872, + "test": false, + "signals": { + "timer": 1, + "directDomListener": 2 + } + }, + { + "path": "src/components/features/fluent/components/ProjectPopover.ts", + "lines": 985, + "bytes": 24718, + "test": false, + "signals": { + "timer": 8, + "directDomListener": 16, + "weakRandom": 2 + } + }, + { + "path": "src/components/features/fluent/components/WorkspaceSelector.ts", + "lines": 249, + "bytes": 6654, + "test": false, + "signals": { + "timer": 1, + "directDomListener": 1 + } + }, + { + "path": "src/components/features/fluent/events/ui-event.ts", + "lines": 193, + "bytes": 5203, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/fluent/FluentIntegration.ts", + "lines": 245, + "bytes": 6956, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/fluent/managers/FluentActionHandlers.ts", + "lines": 1195, + "bytes": 31659, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/fluent/managers/FluentComponentManager.ts", + "lines": 1243, + "bytes": 36412, + "test": false, + "signals": { + "directDomListener": 2 + } + }, + { + "path": "src/components/features/fluent/managers/FluentDataManager.ts", + "lines": 584, + "bytes": 18494, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/fluent/managers/FluentGestureManager.ts", + "lines": 126, + "bytes": 3529, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/fluent/managers/FluentLayoutManager.ts", + "lines": 650, + "bytes": 17064, + "test": false, + "signals": { + "timer": 3, + "directDomListener": 1 + } + }, + { + "path": "src/components/features/fluent/managers/FluentWorkspaceStateManager.ts", + "lines": 402, + "bytes": 10683, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/fluent/managers/WorkspaceManager.ts", + "lines": 1078, + "bytes": 31640, + "test": false, + "signals": { + "weakRandom": 1 + } + }, + { + "path": "src/components/features/gantt/gantt.ts", + "lines": 1182, + "bytes": 37996, + "test": false, + "signals": { + "timer": 2 + } + }, + { + "path": "src/components/features/gantt/grid-background.ts", + "lines": 174, + "bytes": 4755, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/gantt/task-renderer.ts", + "lines": 344, + "bytes": 11067, + "test": false, + "signals": { + "directDomListener": 3 + } + }, + { + "path": "src/components/features/gantt/timeline-header.ts", + "lines": 290, + "bytes": 8166, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/habit/components/HabitEditDialog.ts", + "lines": 775, + "bytes": 19789, + "test": false, + "signals": { + "directDomListener": 3, + "weakRandom": 1 + } + }, + { + "path": "src/components/features/habit/components/HabitSettingList.ts", + "lines": 230, + "bytes": 5931, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/habit/habit.ts", + "lines": 306, + "bytes": 9616, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/habit/habitcard/counthabitcard.ts", + "lines": 89, + "bytes": 2649, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/habit/habitcard/dailyhabitcard.ts", + "lines": 95, + "bytes": 2948, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/habit/habitcard/habitcard.ts", + "lines": 327, + "bytes": 9891, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/habit/habitcard/index.ts", + "lines": 6, + "bytes": 262, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/habit/habitcard/mappinghabitcard.ts", + "lines": 130, + "bytes": 3888, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/habit/habitcard/scheduledhabitcard.ts", + "lines": 169, + "bytes": 5460, + "test": false, + "signals": { + "htmlAssignment": 1 + } + }, + { + "path": "src/components/features/habit/modals/HabitChartModal.ts", + "lines": 265, + "bytes": 8083, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/habit/modals/RewardModal.ts", + "lines": 98, + "bytes": 2600, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/kanban/kanban-card.ts", + "lines": 389, + "bytes": 11724, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/kanban/kanban-column.ts", + "lines": 314, + "bytes": 9050, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/kanban/kanban.ts", + "lines": 1989, + "bytes": 58681, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/on-completion/OnCompletionConfigurator.ts", + "lines": 702, + "bytes": 21191, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/on-completion/OnCompletionModal.ts", + "lines": 138, + "bytes": 3421, + "test": false, + "signals": { + "directDomListener": 3 + } + }, + { + "path": "src/components/features/on-completion/OnCompletionSuggesters.ts", + "lines": 245, + "bytes": 6256, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/onboarding/modals/FileFilterRuleEditorModal.ts", + "lines": 309, + "bytes": 8184, + "test": false, + "signals": { + "directDomListener": 3 + } + }, + { + "path": "src/components/features/onboarding/OnboardingController.ts", + "lines": 461, + "bytes": 11101, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/onboarding/OnboardingLayout.ts", + "lines": 210, + "bytes": 5256, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/onboarding/OnboardingView.ts", + "lines": 445, + "bytes": 12199, + "test": false, + "signals": { + "timer": 1 + } + }, + { + "path": "src/components/features/onboarding/previews/ComponentPreviewFactory.ts", + "lines": 459, + "bytes": 13422, + "test": false, + "signals": { + "directDomListener": 2 + } + }, + { + "path": "src/components/features/onboarding/steps/CompleteStep.ts", + "lines": 199, + "bytes": 5691, + "test": false, + "signals": { + "directDomListener": 2 + } + }, + { + "path": "src/components/features/onboarding/steps/ConfigPreviewStep.ts", + "lines": 102, + "bytes": 2828, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/onboarding/steps/FileFilterStep.ts", + "lines": 492, + "bytes": 13625, + "test": false, + "signals": { + "directDomListener": 7 + } + }, + { + "path": "src/components/features/onboarding/steps/FluentComponentsStep.ts", + "lines": 244, + "bytes": 6895, + "test": false, + "signals": { + "directDomListener": 1 + } + }, + { + "path": "src/components/features/onboarding/steps/FluentMainNavigationStep.ts", + "lines": 56, + "bytes": 1751, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/onboarding/steps/FluentOtherViewsStep.ts", + "lines": 56, + "bytes": 1700, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/onboarding/steps/FluentOverviewStep.ts", + "lines": 47, + "bytes": 1783, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/onboarding/steps/FluentProjectSectionStep.ts", + "lines": 58, + "bytes": 1876, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/onboarding/steps/FluentTopNavigationStep.ts", + "lines": 51, + "bytes": 1545, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/onboarding/steps/FluentWorkspaceSelectorStep.ts", + "lines": 58, + "bytes": 1971, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/onboarding/steps/guide/FormatExamples.ts", + "lines": 120, + "bytes": 3236, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/onboarding/steps/guide/QuickCaptureDemo.ts", + "lines": 52, + "bytes": 1424, + "test": false, + "signals": { + "directDomListener": 1 + } + }, + { + "path": "src/components/features/onboarding/steps/intro/ConfigCheckTransition.ts", + "lines": 95, + "bytes": 2157, + "test": false, + "signals": { + "timer": 1 + } + }, + { + "path": "src/components/features/onboarding/steps/intro/TransitionMessage.ts", + "lines": 86, + "bytes": 2059, + "test": false, + "signals": { + "timer": 2 + } + }, + { + "path": "src/components/features/onboarding/steps/intro/TypingAnimation.ts", + "lines": 164, + "bytes": 3959, + "test": false, + "signals": { + "timer": 6, + "weakRandom": 1 + } + }, + { + "path": "src/components/features/onboarding/steps/IntroStep.ts", + "lines": 89, + "bytes": 2448, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/onboarding/steps/ModeSelectionStep.ts", + "lines": 147, + "bytes": 3838, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/onboarding/steps/PlacementStep.ts", + "lines": 199, + "bytes": 5491, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/onboarding/steps/preview/ChangesPreview.ts", + "lines": 141, + "bytes": 3496, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/onboarding/steps/preview/ConfigSummary.ts", + "lines": 40, + "bytes": 1101, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/onboarding/steps/preview/SettingsList.ts", + "lines": 125, + "bytes": 2791, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/onboarding/steps/preview/ViewsGrid.ts", + "lines": 28, + "bytes": 711, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/onboarding/steps/SettingsCheckStep.ts", + "lines": 166, + "bytes": 5183, + "test": false, + "signals": { + "directDomListener": 2 + } + }, + { + "path": "src/components/features/onboarding/steps/TaskGuideStep.ts", + "lines": 37, + "bytes": 961, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/onboarding/steps/UserLevelStep.ts", + "lines": 88, + "bytes": 2259, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/onboarding/TaskCreationGuide.ts", + "lines": 274, + "bytes": 8791, + "test": false, + "signals": { + "directDomListener": 2 + } + }, + { + "path": "src/components/features/onboarding/ui/Alert.ts", + "lines": 72, + "bytes": 1521, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/onboarding/ui/Badge.ts", + "lines": 31, + "bytes": 670, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/onboarding/ui/FeatureList.ts", + "lines": 62, + "bytes": 1320, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/onboarding/ui/ProgressDots.ts", + "lines": 99, + "bytes": 2178, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/onboarding/ui/SelectableCard.ts", + "lines": 189, + "bytes": 4400, + "test": false, + "signals": { + "directDomListener": 2 + } + }, + { + "path": "src/components/features/quadrant/quadrant-card.ts", + "lines": 542, + "bytes": 14729, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/quadrant/quadrant-column.ts", + "lines": 1031, + "bytes": 28365, + "test": false, + "signals": { + "timer": 9, + "directDomListener": 1 + } + }, + { + "path": "src/components/features/quadrant/quadrant.ts", + "lines": 1043, + "bytes": 30066, + "test": false, + "signals": { + "timer": 4 + } + }, + { + "path": "src/components/features/quick-capture/components/FileNameInput.ts", + "lines": 327, + "bytes": 8399, + "test": false, + "signals": { + "directDomListener": 1 + } + }, + { + "path": "src/components/features/quick-capture/modals/BaseQuickCaptureModal.ts", + "lines": 982, + "bytes": 27510, + "test": false, + "signals": { + "directDomListener": 4 + } + }, + { + "path": "src/components/features/quick-capture/modals/MinimalQuickCaptureModal.ts", + "lines": 898, + "bytes": 26590, + "test": false, + "signals": { + "timer": 2, + "directDomListener": 7 + } + }, + { + "path": "src/components/features/quick-capture/modals/MinimalQuickCaptureModalWithSwitch.ts", + "lines": 832, + "bytes": 24138, + "test": false, + "signals": { + "timer": 2, + "directDomListener": 6 + } + }, + { + "path": "src/components/features/quick-capture/modals/QuickCaptureModal.ts", + "lines": 1255, + "bytes": 36356, + "test": false, + "signals": { + "timer": 3, + "directDomListener": 4 + } + }, + { + "path": "src/components/features/quick-capture/modals/QuickCaptureModalWithSwitch.ts", + "lines": 1034, + "bytes": 29138, + "test": false, + "signals": { + "timer": 3 + } + }, + { + "path": "src/components/features/quick-capture/suggest/MinimalQuickCaptureSuggest.ts", + "lines": 264, + "bytes": 7738, + "test": false, + "signals": { + "timer": 1 + } + }, + { + "path": "src/components/features/read-mode/ReadModeProgressBarWidget.ts", + "lines": 1403, + "bytes": 41397, + "test": false, + "signals": { + "timer": 4 + } + }, + { + "path": "src/components/features/read-mode/ReadModeTextMark.ts", + "lines": 420, + "bytes": 12010, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/settings/components/FileSourceSettingsSection.ts", + "lines": 1078, + "bytes": 30558, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/settings/components/SettingsSearchComponent.ts", + "lines": 497, + "bytes": 13775, + "test": false, + "signals": { + "timer": 3 + } + }, + { + "path": "src/components/features/settings/components/WorkspaceSettingsSelector.ts", + "lines": 149, + "bytes": 4047, + "test": false, + "signals": { + "directDomListener": 1 + } + }, + { + "path": "src/components/features/settings/core/SettingsIndexer.ts", + "lines": 362, + "bytes": 9073, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/settings/index.ts", + "lines": 21, + "bytes": 1502, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/settings/tabs/AboutSettingsTab.ts", + "lines": 175, + "bytes": 4866, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/settings/tabs/BasesSettingsTab.ts", + "lines": 83, + "bytes": 2590, + "test": false, + "signals": { + "timer": 3 + } + }, + { + "path": "src/components/features/settings/tabs/BetaTestSettingsTab.ts", + "lines": 69, + "bytes": 1883, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/settings/tabs/CalendarViewSettingTab.ts", + "lines": 478, + "bytes": 12911, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/settings/tabs/DatePrioritySettingsTab.ts", + "lines": 90, + "bytes": 2619, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/settings/tabs/DesktopIntegrationSettingsTab.ts", + "lines": 207, + "bytes": 5868, + "test": false, + "signals": { + "timer": 1 + } + }, + { + "path": "src/components/features/settings/tabs/FileFilterSettingsTab.ts", + "lines": 384, + "bytes": 11165, + "test": false, + "signals": { + "timer": 2, + "directDomListener": 3 + } + }, + { + "path": "src/components/features/settings/tabs/HabitSettingsTab.ts", + "lines": 59, + "bytes": 2045, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/settings/tabs/IcsSettingsTab.ts", + "lines": 1577, + "bytes": 44285, + "test": false, + "signals": { + "timer": 3, + "weakRandom": 2 + } + }, + { + "path": "src/components/features/settings/tabs/IndexSettingsTab.ts", + "lines": 937, + "bytes": 29018, + "test": false, + "signals": { + "timer": 3, + "directDomListener": 2 + } + }, + { + "path": "src/components/features/settings/tabs/InterfaceSettingsTab.ts", + "lines": 277, + "bytes": 7956, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/settings/tabs/McpIntegrationSettingsTab.ts", + "lines": 1459, + "bytes": 43172, + "test": false, + "signals": { + "timer": 6 + } + }, + { + "path": "src/components/features/settings/tabs/ProgressSettingsTab.ts", + "lines": 764, + "bytes": 21531, + "test": false, + "signals": { + "timer": 1, + "directDomListener": 1 + } + }, + { + "path": "src/components/features/settings/tabs/ProjectSettingsTab.ts", + "lines": 821, + "bytes": 22925, + "test": false, + "signals": { + "timer": 5 + } + }, + { + "path": "src/components/features/settings/tabs/QuickCaptureSettingsTab.ts", + "lines": 699, + "bytes": 20436, + "test": false, + "signals": { + "timer": 7 + } + }, + { + "path": "src/components/features/settings/tabs/RewardSettingsTab.ts", + "lines": 295, + "bytes": 8697, + "test": false, + "signals": { + "timer": 5, + "weakRandom": 1 + } + }, + { + "path": "src/components/features/settings/tabs/TaskFilterSettingsTab.ts", + "lines": 397, + "bytes": 11177, + "test": false, + "signals": { + "directDomListener": 2 + } + }, + { + "path": "src/components/features/settings/tabs/TaskHandlerSettingsTab.ts", + "lines": 802, + "bytes": 24031, + "test": false, + "signals": { + "timer": 1 + } + }, + { + "path": "src/components/features/settings/tabs/TaskStatusSettingsTab.ts", + "lines": 1253, + "bytes": 37462, + "test": false, + "signals": { + "timer": 17, + "directDomListener": 9 + } + }, + { + "path": "src/components/features/settings/tabs/TaskTimerSettingsTab.ts", + "lines": 253, + "bytes": 8348, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/settings/tabs/TimelineSidebarSettingsTab.ts", + "lines": 133, + "bytes": 3549, + "test": false, + "signals": { + "timer": 1 + } + }, + { + "path": "src/components/features/settings/tabs/TimeParsingSettingsTab.ts", + "lines": 361, + "bytes": 11363, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/settings/tabs/ViewSettingsTab.ts", + "lines": 677, + "bytes": 19443, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/settings/tabs/WorkflowSettingsTab.ts", + "lines": 404, + "bytes": 11257, + "test": false, + "signals": { + "timer": 3, + "directDomListener": 2 + } + }, + { + "path": "src/components/features/settings/tabs/WorkspaceSettingTab.ts", + "lines": 560, + "bytes": 14573, + "test": false, + "signals": { + "directDomListener": 2 + } + }, + { + "path": "src/components/features/table/index.ts", + "lines": 11, + "bytes": 379, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/table/TableEditor.ts", + "lines": 511, + "bytes": 12943, + "test": false, + "signals": { + "timer": 2 + } + }, + { + "path": "src/components/features/table/TableHeader.ts", + "lines": 271, + "bytes": 6619, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/table/TableRenderer.ts", + "lines": 1674, + "bytes": 47349, + "test": false, + "signals": { + "timer": 2, + "htmlAssignment": 1 + } + }, + { + "path": "src/components/features/table/TableTypes.ts", + "lines": 133, + "bytes": 2518, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/table/TableView.ts", + "lines": 1360, + "bytes": 36880, + "test": false, + "signals": { + "timer": 2 + } + }, + { + "path": "src/components/features/table/TableViewAdapter.ts", + "lines": 93, + "bytes": 2069, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/table/TreeManager.ts", + "lines": 527, + "bytes": 13563, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/table/VirtualScrollManager.ts", + "lines": 527, + "bytes": 13660, + "test": false, + "signals": { + "timer": 2 + } + }, + { + "path": "src/components/features/task/edit/MetadataEditor.ts", + "lines": 650, + "bytes": 17916, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/task/edit/TaskDetailsModal.ts", + "lines": 137, + "bytes": 3884, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/task/edit/TaskDetailsPopover.ts", + "lines": 279, + "bytes": 7527, + "test": false, + "signals": { + "timer": 1, + "directDomListener": 2 + } + }, + { + "path": "src/components/features/task/filter/filter-metadata-extractor.ts", + "lines": 258, + "bytes": 6941, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/task/filter/FilterConfigModal.ts", + "lines": 376, + "bytes": 9499, + "test": false, + "signals": { + "weakRandom": 1 + } + }, + { + "path": "src/components/features/task/filter/in-view/custom/scroll-to-date-button.ts", + "lines": 27, + "bytes": 685, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/task/filter/in-view/filter-dropdown.ts", + "lines": 458, + "bytes": 13857, + "test": false, + "signals": { + "timer": 3 + } + }, + { + "path": "src/components/features/task/filter/in-view/filter-pill.ts", + "lines": 70, + "bytes": 1910, + "test": false, + "signals": { + "timer": 1 + } + }, + { + "path": "src/components/features/task/filter/in-view/filter-type.ts", + "lines": 34, + "bytes": 715, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/task/filter/in-view/filter.css", + "lines": 250, + "bytes": 5110, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/task/filter/in-view/filter.ts", + "lines": 412, + "bytes": 13037, + "test": false, + "signals": { + "weakRandom": 1 + } + }, + { + "path": "src/components/features/task/filter/index.ts", + "lines": 12, + "bytes": 375, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/task/filter/ViewTaskFilter.ts", + "lines": 1190, + "bytes": 30120, + "test": false, + "signals": { + "timer": 3, + "weakRandom": 1 + } + }, + { + "path": "src/components/features/task/filter/ViewTaskFilterModal.ts", + "lines": 65, + "bytes": 1538, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/task/filter/ViewTaskFilterPopover.ts", + "lines": 204, + "bytes": 5025, + "test": false, + "signals": { + "timer": 1, + "directDomListener": 2 + } + }, + { + "path": "src/components/features/task/selection/LongPressDetector.ts", + "lines": 162, + "bytes": 3939, + "test": false, + "signals": { + "timer": 1 + } + }, + { + "path": "src/components/features/task/selection/TaskSelectionManager.ts", + "lines": 229, + "bytes": 5320, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/task/view/BulkOperationsMenu.ts", + "lines": 914, + "bytes": 21614, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/task/view/calendar.ts", + "lines": 444, + "bytes": 11789, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/task/view/content.ts", + "lines": 1714, + "bytes": 52091, + "test": false, + "signals": { + "timer": 3 + } + }, + { + "path": "src/components/features/task/view/details.ts", + "lines": 1158, + "bytes": 33135, + "test": false, + "signals": { + "timer": 1 + } + }, + { + "path": "src/components/features/task/view/forecast.ts", + "lines": 1313, + "bytes": 38678, + "test": false, + "signals": { + "timer": 1 + } + }, + { + "path": "src/components/features/task/view/InlineEditor.ts", + "lines": 1494, + "bytes": 39578, + "test": false, + "signals": { + "timer": 3 + } + }, + { + "path": "src/components/features/task/view/InlineEditorManager.ts", + "lines": 242, + "bytes": 6422, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/task/view/listItem.ts", + "lines": 1359, + "bytes": 37467, + "test": false, + "signals": { + "timer": 1 + } + }, + { + "path": "src/components/features/task/view/modals/ViewConfigModal.ts", + "lines": 2141, + "bytes": 61091, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/task/view/projects.ts", + "lines": 1593, + "bytes": 47447, + "test": false, + "signals": { + "timer": 1 + } + }, + { + "path": "src/components/features/task/view/ProjectTreeComponent.ts", + "lines": 305, + "bytes": 8064, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/task/view/ProjectViewComponent.ts", + "lines": 420, + "bytes": 11904, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/task/view/review.ts", + "lines": 1286, + "bytes": 38526, + "test": false, + "signals": { + "timer": 1, + "directDomListener": 4 + } + }, + { + "path": "src/components/features/task/view/sidebar.ts", + "lines": 301, + "bytes": 8389, + "test": false, + "signals": { + "timer": 1 + } + }, + { + "path": "src/components/features/task/view/tags.ts", + "lines": 908, + "bytes": 26066, + "test": false, + "signals": { + "timer": 1 + } + }, + { + "path": "src/components/features/task/view/TagViewComponent.ts", + "lines": 531, + "bytes": 14738, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/task/view/TaskList.ts", + "lines": 355, + "bytes": 11373, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/task/view/TaskPropertyTwoColumnView.ts", + "lines": 376, + "bytes": 10846, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/task/view/TaskStatusIndicator.ts", + "lines": 543, + "bytes": 13412, + "test": false, + "signals": {} + }, + { + "path": "src/components/features/task/view/TimerStatisticsPanel.ts", + "lines": 539, + "bytes": 14337, + "test": false, + "signals": { + "timer": 1 + } + }, + { + "path": "src/components/features/task/view/treeItem.ts", + "lines": 1748, + "bytes": 49083, + "test": false, + "signals": { + "timer": 1 + } + }, + { + "path": "src/components/features/task/view/TwoColumnViewBase.ts", + "lines": 489, + "bytes": 13810, + "test": false, + "signals": { + "timer": 1 + } + }, + { + "path": "src/components/features/timeline-sidebar/TimelineSidebarView.ts", + "lines": 1460, + "bytes": 45782, + "test": false, + "signals": { + "timer": 7 + } + }, + { + "path": "src/components/features/workflow/modals/QuickWorkflowModal.ts", + "lines": 328, + "bytes": 9854, + "test": false, + "signals": { + "directDomListener": 2 + } + }, + { + "path": "src/components/features/workflow/modals/StageEditModal.ts", + "lines": 497, + "bytes": 13115, + "test": false, + "signals": { + "timer": 1, + "directDomListener": 6, + "weakRandom": 1 + } + }, + { + "path": "src/components/features/workflow/modals/WorkflowDefinitionModal.ts", + "lines": 396, + "bytes": 10609, + "test": false, + "signals": { + "directDomListener": 3, + "weakRandom": 1 + } + }, + { + "path": "src/components/features/workflow/widgets/WorkflowProgressIndicator.ts", + "lines": 270, + "bytes": 8268, + "test": false, + "signals": {} + }, + { + "path": "src/components/ui/base/ViewComponent.ts", + "lines": 45, + "bytes": 1762, + "test": false, + "signals": {} + }, + { + "path": "src/components/ui/behavior/DragManager.ts", + "lines": 483, + "bytes": 17712, + "test": false, + "signals": {} + }, + { + "path": "src/components/ui/behavior/index.ts", + "lines": 2, + "bytes": 71, + "test": false, + "signals": {} + }, + { + "path": "src/components/ui/behavior/ViewComponentManager.ts", + "lines": 358, + "bytes": 9438, + "test": false, + "signals": {} + }, + { + "path": "src/components/ui/date-picker/BulkDateOffsetModal.ts", + "lines": 126, + "bytes": 3450, + "test": false, + "signals": {} + }, + { + "path": "src/components/ui/date-picker/BulkDatePickerModal.ts", + "lines": 82, + "bytes": 1958, + "test": false, + "signals": {} + }, + { + "path": "src/components/ui/date-picker/DatePickerComponent.ts", + "lines": 306, + "bytes": 7919, + "test": false, + "signals": {} + }, + { + "path": "src/components/ui/date-picker/DatePickerModal.ts", + "lines": 57, + "bytes": 1297, + "test": false, + "signals": {} + }, + { + "path": "src/components/ui/date-picker/DatePickerPopover.ts", + "lines": 190, + "bytes": 4608, + "test": false, + "signals": { + "timer": 1, + "directDomListener": 2 + } + }, + { + "path": "src/components/ui/date-picker/index.ts", + "lines": 6, + "bytes": 245, + "test": false, + "signals": {} + }, + { + "path": "src/components/ui/feedback/index.ts", + "lines": 1, + "bytes": 34, + "test": false, + "signals": {} + }, + { + "path": "src/components/ui/feedback/StatusIndicator.ts", + "lines": 192, + "bytes": 5373, + "test": false, + "signals": {} + }, + { + "path": "src/components/ui/index.ts", + "lines": 15, + "bytes": 602, + "test": false, + "signals": {} + }, + { + "path": "src/components/ui/inputs/AutoComplete.ts", + "lines": 586, + "bytes": 15307, + "test": false, + "signals": { + "directDomListener": 2 + } + }, + { + "path": "src/components/ui/inputs/index.ts", + "lines": 1, + "bytes": 31, + "test": false, + "signals": {} + }, + { + "path": "src/components/ui/menus/IconMenu.ts", + "lines": 238, + "bytes": 6610, + "test": false, + "signals": { + "timer": 4, + "directDomListener": 7 + } + }, + { + "path": "src/components/ui/menus/index.ts", + "lines": 1, + "bytes": 27, + "test": false, + "signals": {} + }, + { + "path": "src/components/ui/modals/CalendarViewConfigModal.ts", + "lines": 644, + "bytes": 17853, + "test": false, + "signals": {} + }, + { + "path": "src/components/ui/modals/ConfirmModal.ts", + "lines": 64, + "bytes": 1509, + "test": false, + "signals": {} + }, + { + "path": "src/components/ui/modals/IframeModal.ts", + "lines": 55, + "bytes": 1471, + "test": false, + "signals": { + "directDomListener": 1 + } + }, + { + "path": "src/components/ui/modals/index.ts", + "lines": 3, + "bytes": 95, + "test": false, + "signals": {} + }, + { + "path": "src/components/ui/modals/ListConfigModal.ts", + "lines": 148, + "bytes": 3760, + "test": false, + "signals": { + "directDomListener": 2 + } + }, + { + "path": "src/components/ui/modals/McpLogModal.ts", + "lines": 239, + "bytes": 6957, + "test": false, + "signals": { + "directDomListener": 1 + } + }, + { + "path": "src/components/ui/modals/TextPromptModal.ts", + "lines": 123, + "bytes": 3376, + "test": false, + "signals": { + "timer": 1, + "directDomListener": 1 + } + }, + { + "path": "src/components/ui/modals/WorkspaceModals.ts", + "lines": 372, + "bytes": 8695, + "test": false, + "signals": { + "directDomListener": 6 + } + }, + { + "path": "src/components/ui/popovers/taskProgressPopover.ts", + "lines": 80, + "bytes": 1732, + "test": false, + "signals": {} + }, + { + "path": "src/components/ui/renderers/index.ts", + "lines": 1, + "bytes": 35, + "test": false, + "signals": {} + }, + { + "path": "src/components/ui/renderers/MarkdownRenderer.ts", + "lines": 547, + "bytes": 16284, + "test": false, + "signals": { + "timer": 1 + } + }, + { + "path": "src/components/ui/suggest/index.ts", + "lines": 15, + "bytes": 426, + "test": false, + "signals": {} + }, + { + "path": "src/components/ui/suggest/SpecialCharacterSuggests.ts", + "lines": 508, + "bytes": 16184, + "test": false, + "signals": {} + }, + { + "path": "src/components/ui/suggest/SuggestManager.ts", + "lines": 238, + "bytes": 6231, + "test": false, + "signals": {} + }, + { + "path": "src/components/ui/suggest/UniversalEditorSuggest.ts", + "lines": 207, + "bytes": 4851, + "test": false, + "signals": {} + }, + { + "path": "src/components/ui/tree/index.ts", + "lines": 2, + "bytes": 69, + "test": false, + "signals": {} + }, + { + "path": "src/components/ui/tree/TreeComponent.ts", + "lines": 462, + "bytes": 10503, + "test": false, + "signals": {} + }, + { + "path": "src/components/ui/tree/TreeItemRenderer.ts", + "lines": 305, + "bytes": 7665, + "test": false, + "signals": {} + }, + { + "path": "src/core/goal/edit-mode.ts", + "lines": 54, + "bytes": 1653, + "test": false, + "signals": {} + }, + { + "path": "src/core/goal/read-mode.ts", + "lines": 81, + "bytes": 2634, + "test": false, + "signals": {} + }, + { + "path": "src/core/goal/regex-goal.ts", + "lines": 2, + "bytes": 134, + "test": false, + "signals": {} + }, + { + "path": "src/core/project-filter.ts", + "lines": 20, + "bytes": 882, + "test": false, + "signals": {} + }, + { + "path": "src/core/project-tree-builder.ts", + "lines": 285, + "bytes": 7575, + "test": false, + "signals": {} + }, + { + "path": "src/core/task-indexer.ts", + "lines": 1260, + "bytes": 35071, + "test": false, + "signals": { + "timer": 1, + "weakRandom": 1 + } + }, + { + "path": "src/core/workflow-converter.ts", + "lines": 337, + "bytes": 8820, + "test": false, + "signals": {} + }, + { + "path": "src/dataflow/api/QueryAPI.ts", + "lines": 444, + "bytes": 11005, + "test": false, + "signals": {} + }, + { + "path": "src/dataflow/api/WriteAPI.ts", + "lines": 2996, + "bytes": 87069, + "test": false, + "signals": { + "directNoteWrite": 8 + } + }, + { + "path": "src/dataflow/augment/Augmentor.ts", + "lines": 696, + "bytes": 20203, + "test": false, + "signals": {} + }, + { + "path": "src/dataflow/augment/DateInheritanceAugmentor.ts", + "lines": 458, + "bytes": 13499, + "test": false, + "signals": {} + }, + { + "path": "src/dataflow/core/CanvasParser.ts", + "lines": 323, + "bytes": 8656, + "test": false, + "signals": {} + }, + { + "path": "src/dataflow/core/ConfigurableTaskParser.ts", + "lines": 2024, + "bytes": 57457, + "test": false, + "signals": {} + }, + { + "path": "src/dataflow/createDataflow.ts", + "lines": 56, + "bytes": 1713, + "test": false, + "signals": {} + }, + { + "path": "src/dataflow/events/Events.ts", + "lines": 72, + "bytes": 2444, + "test": false, + "signals": {} + }, + { + "path": "src/dataflow/indexer/Repository.ts", + "lines": 717, + "bytes": 20322, + "test": false, + "signals": { + "timer": 1 + } + }, + { + "path": "src/dataflow/Orchestrator.ts", + "lines": 1905, + "bytes": 58000, + "test": false, + "signals": { + "timer": 2 + } + }, + { + "path": "src/dataflow/parsers/FileMetaEntry.ts", + "lines": 32, + "bytes": 1111, + "test": false, + "signals": {} + }, + { + "path": "src/dataflow/parsers/MarkdownEntry.ts", + "lines": 31, + "bytes": 980, + "test": false, + "signals": {} + }, + { + "path": "src/dataflow/persistence/Storage.ts", + "lines": 542, + "bytes": 13343, + "test": false, + "signals": {} + }, + { + "path": "src/dataflow/project/Resolver.ts", + "lines": 133, + "bytes": 4123, + "test": false, + "signals": {} + }, + { + "path": "src/dataflow/settings-signature.ts", + "lines": 22, + "bytes": 999, + "test": false, + "signals": {} + }, + { + "path": "src/dataflow/sources/FileSource.ts", + "lines": 1474, + "bytes": 38898, + "test": false, + "signals": { + "timer": 1 + } + }, + { + "path": "src/dataflow/sources/FileSourceConfig.ts", + "lines": 652, + "bytes": 19738, + "test": false, + "signals": {} + }, + { + "path": "src/dataflow/sources/IcsSource.ts", + "lines": 181, + "bytes": 4735, + "test": false, + "signals": { + "timer": 1 + } + }, + { + "path": "src/dataflow/sources/ObsidianSource.ts", + "lines": 426, + "bytes": 10815, + "test": false, + "signals": { + "timer": 2 + } + }, + { + "path": "src/dataflow/workers/deferred-promise.ts", + "lines": 23, + "bytes": 571, + "test": false, + "signals": {} + }, + { + "path": "src/dataflow/workers/ProjectData.worker.ts", + "lines": 370, + "bytes": 9724, + "test": false, + "signals": {} + }, + { + "path": "src/dataflow/workers/ProjectDataWorkerManager.ts", + "lines": 715, + "bytes": 18034, + "test": false, + "signals": { + "timer": 1 + } + }, + { + "path": "src/dataflow/workers/task-index-message.ts", + "lines": 310, + "bytes": 7705, + "test": false, + "signals": {} + }, + { + "path": "src/dataflow/workers/TaskIndex.worker.ts", + "lines": 537, + "bytes": 14577, + "test": false, + "signals": {} + }, + { + "path": "src/dataflow/workers/TaskWorkerManager.ts", + "lines": 1035, + "bytes": 26870, + "test": false, + "signals": { + "timer": 2 + } + }, + { + "path": "src/dataflow/workers/worker.d.ts", + "lines": 12, + "bytes": 266, + "test": false, + "signals": {} + }, + { + "path": "src/dataflow/workers/WorkerOrchestrator.ts", + "lines": 576, + "bytes": 15985, + "test": false, + "signals": { + "timer": 2 + } + }, + { + "path": "src/editor-extensions/autocomplete/parent-task-updater.ts", + "lines": 789, + "bytes": 22805, + "test": false, + "signals": {} + }, + { + "path": "src/editor-extensions/autocomplete/task-metadata-suggest.ts", + "lines": 480, + "bytes": 13620, + "test": false, + "signals": {} + }, + { + "path": "src/editor-extensions/core/extended-gutter.ts", + "lines": 694, + "bytes": 20379, + "test": false, + "signals": { + "directDomListener": 1 + } + }, + { + "path": "src/editor-extensions/core/markdown-editor.ts", + "lines": 358, + "bytes": 9344, + "test": false, + "signals": {} + }, + { + "path": "src/editor-extensions/core/quick-capture-panel.ts", + "lines": 733, + "bytes": 21284, + "test": false, + "signals": { + "timer": 2, + "directDomListener": 8 + } + }, + { + "path": "src/editor-extensions/core/regex-cursor.ts", + "lines": 121, + "bytes": 3959, + "test": false, + "signals": {} + }, + { + "path": "src/editor-extensions/core/task-filter-panel.ts", + "lines": 1437, + "bytes": 41495, + "test": false, + "signals": { + "timer": 2, + "directDomListener": 1, + "weakRandom": 1 + } + }, + { + "path": "src/editor-extensions/date-time/date-manager.ts", + "lines": 1071, + "bytes": 31251, + "test": false, + "signals": {} + }, + { + "path": "src/editor-extensions/date-time/date-picker-utils.ts", + "lines": 391, + "bytes": 9937, + "test": false, + "signals": {} + }, + { + "path": "src/editor-extensions/date-time/date-picker.ts", + "lines": 655, + "bytes": 15845, + "test": false, + "signals": { + "directDomListener": 1 + } + }, + { + "path": "src/editor-extensions/date-time/task-timer.ts", + "lines": 1312, + "bytes": 38656, + "test": false, + "signals": { + "timer": 1, + "directDomListener": 2 + } + }, + { + "path": "src/editor-extensions/task-operations/completion-monitor.ts", + "lines": 327, + "bytes": 10382, + "test": false, + "signals": {} + }, + { + "path": "src/editor-extensions/task-operations/gutter-marker.ts", + "lines": 242, + "bytes": 6347, + "test": false, + "signals": {} + }, + { + "path": "src/editor-extensions/task-operations/mark-cleanup.ts", + "lines": 143, + "bytes": 4406, + "test": false, + "signals": {} + }, + { + "path": "src/editor-extensions/task-operations/status-cycler.ts", + "lines": 908, + "bytes": 27474, + "test": false, + "signals": {} + }, + { + "path": "src/editor-extensions/task-operations/status-switcher.ts", + "lines": 672, + "bytes": 17651, + "test": false, + "signals": { + "directDomListener": 2 + } + }, + { + "path": "src/editor-extensions/ui-widgets/priority-picker.ts", + "lines": 808, + "bytes": 20699, + "test": false, + "signals": { + "timer": 1, + "directDomListener": 1 + } + }, + { + "path": "src/editor-extensions/ui-widgets/progress-bar-widget.ts", + "lines": 1607, + "bytes": 45305, + "test": false, + "signals": { + "dynamicEvaluation": 1 + } + }, + { + "path": "src/editor-extensions/ui-widgets/workflow-decorator.ts", + "lines": 514, + "bytes": 14287, + "test": false, + "signals": { + "timer": 1, + "directDomListener": 1 + } + }, + { + "path": "src/editor-extensions/workflow/workflow-enter-handler.ts", + "lines": 721, + "bytes": 18854, + "test": false, + "signals": {} + }, + { + "path": "src/editor-extensions/workflow/workflow-handler.ts", + "lines": 1621, + "bytes": 43546, + "test": false, + "signals": {} + }, + { + "path": "src/executors/completion/archive-executor.ts", + "lines": 384, + "bytes": 11826, + "test": false, + "signals": { + "directNoteWrite": 3 + } + }, + { + "path": "src/executors/completion/base-executor.ts", + "lines": 124, + "bytes": 3632, + "test": false, + "signals": {} + }, + { + "path": "src/executors/completion/canvas-operation-utils.ts", + "lines": 304, + "bytes": 7238, + "test": false, + "signals": { + "directNoteWrite": 1, + "weakRandom": 1 + } + }, + { + "path": "src/executors/completion/complete-executor.ts", + "lines": 140, + "bytes": 3984, + "test": false, + "signals": {} + }, + { + "path": "src/executors/completion/delete-executor.ts", + "lines": 136, + "bytes": 3812, + "test": false, + "signals": { + "directNoteWrite": 1 + } + }, + { + "path": "src/executors/completion/duplicate-executor.ts", + "lines": 323, + "bytes": 9618, + "test": false, + "signals": { + "directNoteWrite": 3 + } + }, + { + "path": "src/executors/completion/keep-executor.ts", + "lines": 46, + "bytes": 1373, + "test": false, + "signals": {} + }, + { + "path": "src/executors/completion/move-executor.ts", + "lines": 344, + "bytes": 10319, + "test": false, + "signals": { + "directNoteWrite": 3 + } + }, + { + "path": "src/icon.ts", + "lines": 43, + "bytes": 3802, + "test": false, + "signals": {} + }, + { + "path": "src/index.ts", + "lines": 2285, + "bytes": 65194, + "test": false, + "signals": { + "timer": 4 + } + }, + { + "path": "src/integrations/habits/ai-summary.ts", + "lines": 276, + "bytes": 9263, + "test": false, + "signals": {} + }, + { + "path": "src/integrations/habits/comment-log.ts", + "lines": 158, + "bytes": 5071, + "test": false, + "signals": {} + }, + { + "path": "src/integrations/habits/comment-text.ts", + "lines": 205, + "bytes": 5967, + "test": false, + "signals": { + "directDomListener": 2 + } + }, + { + "path": "src/integrations/habits/compat.d.ts", + "lines": 5, + "bytes": 132, + "test": false, + "signals": {} + }, + { + "path": "src/integrations/habits/habit-store.ts", + "lines": 1434, + "bytes": 43545, + "test": false, + "signals": {} + }, + { + "path": "src/integrations/habits/i18n/de.ts", + "lines": 658, + "bytes": 39426, + "test": false, + "signals": {} + }, + { + "path": "src/integrations/habits/i18n/es.ts", + "lines": 653, + "bytes": 38273, + "test": false, + "signals": {} + }, + { + "path": "src/integrations/habits/i18n/fr.ts", + "lines": 657, + "bytes": 39761, + "test": false, + "signals": {} + }, + { + "path": "src/integrations/habits/i18n/index.ts", + "lines": 62, + "bytes": 1577, + "test": false, + "signals": {} + }, + { + "path": "src/integrations/habits/i18n/ja.ts", + "lines": 644, + "bytes": 41316, + "test": false, + "signals": {} + }, + { + "path": "src/integrations/habits/i18n/ko.ts", + "lines": 645, + "bytes": 38581, + "test": false, + "signals": {} + }, + { + "path": "src/integrations/habits/i18n/zh.ts", + "lines": 658, + "bytes": 37772, + "test": false, + "signals": {} + }, + { + "path": "src/integrations/habits/legacy-import.ts", + "lines": 97, + "bytes": 4576, + "test": false, + "signals": {} + }, + { + "path": "src/integrations/habits/main.ts", + "lines": 459, + "bytes": 12590, + "test": false, + "signals": { + "timer": 1 + } + }, + { + "path": "src/integrations/habits/note-habit.ts", + "lines": 376, + "bytes": 12377, + "test": false, + "signals": {} + }, + { + "path": "src/integrations/habits/reminders.ts", + "lines": 476, + "bytes": 15950, + "test": false, + "signals": {} + }, + { + "path": "src/integrations/habits/scoped.css", + "lines": 3227, + "bytes": 89699, + "test": false, + "signals": {} + }, + { + "path": "src/integrations/habits/settings.ts", + "lines": 1283, + "bytes": 41384, + "test": false, + "signals": { + "directDomListener": 5 + } + }, + { + "path": "src/integrations/habits/stats.ts", + "lines": 867, + "bytes": 28305, + "test": false, + "signals": {} + }, + { + "path": "src/integrations/habits/task-genius-host.ts", + "lines": 94, + "bytes": 3248, + "test": false, + "signals": {} + }, + { + "path": "src/integrations/habits/task-genius.css", + "lines": 18, + "bytes": 797, + "test": false, + "signals": {} + }, + { + "path": "src/integrations/habits/types.ts", + "lines": 346, + "bytes": 12990, + "test": false, + "signals": {} + }, + { + "path": "src/integrations/habits/ui/chart-setup.ts", + "lines": 33, + "bytes": 677, + "test": false, + "signals": {} + }, + { + "path": "src/integrations/habits/ui/color-utils.ts", + "lines": 61, + "bytes": 2484, + "test": false, + "signals": {} + }, + { + "path": "src/integrations/habits/ui/comment-suggest.ts", + "lines": 347, + "bytes": 10022, + "test": false, + "signals": { + "timer": 1, + "directDomListener": 2 + } + }, + { + "path": "src/integrations/habits/ui/confirm-modal.ts", + "lines": 66, + "bytes": 1819, + "test": false, + "signals": {} + }, + { + "path": "src/integrations/habits/ui/dashboard.ts", + "lines": 2007, + "bytes": 61071, + "test": false, + "signals": { + "timer": 2, + "weakRandom": 5 + } + }, + { + "path": "src/integrations/habits/ui/day-status.ts", + "lines": 369, + "bytes": 10384, + "test": false, + "signals": { + "timer": 1 + } + }, + { + "path": "src/integrations/habits/ui/emoji-suggest-modal.ts", + "lines": 144, + "bytes": 8137, + "test": false, + "signals": {} + }, + { + "path": "src/integrations/habits/ui/export-modal.ts", + "lines": 1434, + "bytes": 38897, + "test": false, + "signals": { + "timer": 1, + "directDomListener": 3 + } + }, + { + "path": "src/integrations/habits/ui/groups-modal.ts", + "lines": 501, + "bytes": 14928, + "test": false, + "signals": { + "directDomListener": 7 + } + }, + { + "path": "src/integrations/habits/ui/habit-metrics.ts", + "lines": 1764, + "bytes": 52404, + "test": false, + "signals": {} + }, + { + "path": "src/integrations/habits/ui/habit-modal.ts", + "lines": 1419, + "bytes": 44904, + "test": false, + "signals": { + "directDomListener": 9, + "weakRandom": 2 + } + }, + { + "path": "src/integrations/habits/ui/habits-block.ts", + "lines": 42, + "bytes": 1359, + "test": false, + "signals": {} + }, + { + "path": "src/integrations/habits/ui/habits-compact.ts", + "lines": 290, + "bytes": 14829, + "test": false, + "signals": {} + }, + { + "path": "src/integrations/habits/ui/habits-heatmap.ts", + "lines": 450, + "bytes": 12533, + "test": false, + "signals": {} + }, + { + "path": "src/integrations/habits/ui/habits-table.ts", + "lines": 562, + "bytes": 16087, + "test": false, + "signals": {} + }, + { + "path": "src/integrations/habits/ui/heatmap.ts", + "lines": 265, + "bytes": 7944, + "test": false, + "signals": {} + }, + { + "path": "src/integrations/habits/ui/icon-suggest-modal.ts", + "lines": 71, + "bytes": 1886, + "test": false, + "signals": {} + }, + { + "path": "src/integrations/habits/ui/metrics-suggest.ts", + "lines": 113, + "bytes": 3414, + "test": false, + "signals": {} + }, + { + "path": "src/integrations/habits/ui/missed-habits-modal.ts", + "lines": 195, + "bytes": 5381, + "test": false, + "signals": { + "directDomListener": 1 + } + }, + { + "path": "src/integrations/habits/ui/panel-view.ts", + "lines": 953, + "bytes": 26688, + "test": false, + "signals": {} + }, + { + "path": "src/integrations/habits/ui/stats-view.ts", + "lines": 513, + "bytes": 15312, + "test": false, + "signals": { + "directDomListener": 4 + } + }, + { + "path": "src/integrations/habits/ui/vault-suggest.ts", + "lines": 62, + "bytes": 1604, + "test": false, + "signals": {} + }, + { + "path": "src/integrations/habits/upstream.css", + "lines": 3226, + "bytes": 68363, + "test": false, + "signals": {} + }, + { + "path": "src/integrations/habits/utils.ts", + "lines": 614, + "bytes": 18715, + "test": false, + "signals": { + "timer": 1 + } + }, + { + "path": "src/managers/changelog-manager.ts", + "lines": 196, + "bytes": 5470, + "test": false, + "signals": {} + }, + { + "path": "src/managers/completion-manager.ts", + "lines": 309, + "bytes": 8352, + "test": false, + "signals": {} + }, + { + "path": "src/managers/desktop-integration-manager.ts", + "lines": 1148, + "bytes": 33429, + "test": false, + "signals": { + "timer": 6 + } + }, + { + "path": "src/managers/electron-quick-capture.ts", + "lines": 1453, + "bytes": 41538, + "test": false, + "signals": { + "timer": 4, + "directDomListener": 8, + "htmlAssignment": 1 + } + }, + { + "path": "src/managers/file-filter-manager.ts", + "lines": 455, + "bytes": 11234, + "test": false, + "signals": {} + }, + { + "path": "src/managers/file-task-manager.ts", + "lines": 1130, + "bytes": 31535, + "test": false, + "signals": { + "directNoteWrite": 1, + "weakRandom": 1 + } + }, + { + "path": "src/managers/habit-manager.ts", + "lines": 853, + "bytes": 24599, + "test": false, + "signals": {} + }, + { + "path": "src/managers/icon-manager.ts", + "lines": 375, + "bytes": 10591, + "test": false, + "signals": {} + }, + { + "path": "src/managers/ics-manager.ts", + "lines": 1304, + "bytes": 36562, + "test": false, + "signals": { + "timer": 2 + } + }, + { + "path": "src/managers/onboarding-manager.ts", + "lines": 499, + "bytes": 14917, + "test": false, + "signals": {} + }, + { + "path": "src/managers/project-config-manager.ts", + "lines": 1101, + "bytes": 31611, + "test": false, + "signals": {} + }, + { + "path": "src/managers/rebuild-progress-manager.ts", + "lines": 133, + "bytes": 3335, + "test": false, + "signals": { + "timer": 2 + } + }, + { + "path": "src/managers/reward-manager.ts", + "lines": 248, + "bytes": 8236, + "test": false, + "signals": { + "weakRandom": 2 + } + }, + { + "path": "src/managers/timer-manager.ts", + "lines": 745, + "bytes": 19621, + "test": false, + "signals": { + "weakRandom": 1 + } + }, + { + "path": "src/managers/tray-menu.ts", + "lines": 182, + "bytes": 4848, + "test": false, + "signals": {} + }, + { + "path": "src/managers/version-manager.ts", + "lines": 362, + "bytes": 9774, + "test": false, + "signals": {} + }, + { + "path": "src/mcp/auth/AuthMiddleware.ts", + "lines": 121, + "bytes": 3061, + "test": false, + "signals": {} + }, + { + "path": "src/mcp/bridge/DataflowBridge.ts", + "lines": 471, + "bytes": 11559, + "test": false, + "signals": {} + }, + { + "path": "src/mcp/McpServer.ts", + "lines": 1997, + "bytes": 51214, + "test": false, + "signals": { + "timer": 2, + "weakRandom": 1 + } + }, + { + "path": "src/mcp/McpServerManager.ts", + "lines": 253, + "bytes": 6583, + "test": false, + "signals": { + "timer": 1 + } + }, + { + "path": "src/mcp/types/mcp.d.ts", + "lines": 147, + "bytes": 2931, + "test": false, + "signals": {} + }, + { + "path": "src/pages/bases/index.ts", + "lines": 118, + "bytes": 3813, + "test": false, + "signals": {} + }, + { + "path": "src/pages/bases/registerBasesViews.ts", + "lines": 165, + "bytes": 4403, + "test": false, + "signals": {} + }, + { + "path": "src/pages/bases/TaskBasesView.ts", + "lines": 2321, + "bytes": 65298, + "test": false, + "signals": {} + }, + { + "path": "src/pages/FluentTaskView.ts", + "lines": 1332, + "bytes": 40471, + "test": false, + "signals": {} + }, + { + "path": "src/pages/LeftSidebarView.ts", + "lines": 79, + "bytes": 2378, + "test": false, + "signals": {} + }, + { + "path": "src/pages/RightDetailView.ts", + "lines": 112, + "bytes": 2907, + "test": false, + "signals": {} + }, + { + "path": "src/pages/TaskSpecificView.ts", + "lines": 1586, + "bytes": 47134, + "test": false, + "signals": { + "timer": 2 + } + }, + { + "path": "src/pages/TaskView.ts", + "lines": 2023, + "bytes": 59198, + "test": false, + "signals": { + "timer": 2 + } + }, + { + "path": "src/parsers/canvas-task-updater.ts", + "lines": 1143, + "bytes": 30075, + "test": false, + "signals": { + "directNoteWrite": 3, + "weakRandom": 1 + } + }, + { + "path": "src/parsers/context-detector.ts", + "lines": 267, + "bytes": 7281, + "test": false, + "signals": {} + }, + { + "path": "src/parsers/file-metadata-parser.ts", + "lines": 546, + "bytes": 15051, + "test": false, + "signals": {} + }, + { + "path": "src/parsers/file-metadata-updater.ts", + "lines": 355, + "bytes": 8813, + "test": false, + "signals": {} + }, + { + "path": "src/parsers/holiday-detector.ts", + "lines": 343, + "bytes": 8731, + "test": false, + "signals": {} + }, + { + "path": "src/parsers/ics-parser.ts", + "lines": 529, + "bytes": 15923, + "test": false, + "signals": {} + }, + { + "path": "src/parsers/ics-status-mapper.ts", + "lines": 427, + "bytes": 11043, + "test": false, + "signals": {} + }, + { + "path": "src/parsers/webcal-converter.ts", + "lines": 192, + "bytes": 5201, + "test": false, + "signals": {} + }, + { + "path": "src/patches/workspace-dnd-patch.ts", + "lines": 123, + "bytes": 3620, + "test": false, + "signals": { + "directDomListener": 2 + } + }, + { + "path": "src/services/date-inheritance-service.ts", + "lines": 1140, + "bytes": 33879, + "test": false, + "signals": {} + }, + { + "path": "src/services/settings-change-detector.ts", + "lines": 217, + "bytes": 7625, + "test": false, + "signals": {} + }, + { + "path": "src/services/task-migration-service.ts", + "lines": 326, + "bytes": 10029, + "test": false, + "signals": {} + }, + { + "path": "src/services/task-parsing-service.ts", + "lines": 747, + "bytes": 21275, + "test": false, + "signals": {} + }, + { + "path": "src/services/time-parsing-service.ts", + "lines": 1335, + "bytes": 38182, + "test": false, + "signals": {} + }, + { + "path": "src/services/timer-export-service.ts", + "lines": 550, + "bytes": 14821, + "test": false, + "signals": {} + }, + { + "path": "src/services/timer-format-service.ts", + "lines": 259, + "bytes": 7995, + "test": false, + "signals": {} + }, + { + "path": "src/services/timer-metadata-service.ts", + "lines": 117, + "bytes": 3297, + "test": false, + "signals": {} + }, + { + "path": "src/services/view-settings-signature.ts", + "lines": 10, + "bytes": 294, + "test": false, + "signals": {} + }, + { + "path": "src/setting.ts", + "lines": 929, + "bytes": 26372, + "test": false, + "signals": { + "timer": 1, + "directDomListener": 1 + } + }, + { + "path": "src/styles/base-view.css", + "lines": 230, + "bytes": 4801, + "test": false, + "signals": {} + }, + { + "path": "src/styles/beta-warning.css", + "lines": 36, + "bytes": 601, + "test": false, + "signals": {} + }, + { + "path": "src/styles/calendar-view-settings.css", + "lines": 385, + "bytes": 8013, + "test": false, + "signals": {} + }, + { + "path": "src/styles/calendar.css", + "lines": 162, + "bytes": 4237, + "test": false, + "signals": {} + }, + { + "path": "src/styles/calendar/badge.css", + "lines": 27, + "bytes": 504, + "test": false, + "signals": {} + }, + { + "path": "src/styles/calendar/event.css", + "lines": 20, + "bytes": 467, + "test": false, + "signals": {} + }, + { + "path": "src/styles/calendar/view.css", + "lines": 893, + "bytes": 25039, + "test": false, + "signals": {} + }, + { + "path": "src/styles/changelog.css", + "lines": 114, + "bytes": 2385, + "test": false, + "signals": {} + }, + { + "path": "src/styles/date-picker.css", + "lines": 230, + "bytes": 5860, + "test": false, + "signals": {} + }, + { + "path": "src/styles/file-filter-settings.css", + "lines": 256, + "bytes": 5449, + "test": false, + "signals": {} + }, + { + "path": "src/styles/fluent/fluent-content-header.css", + "lines": 150, + "bytes": 3299, + "test": false, + "signals": {} + }, + { + "path": "src/styles/fluent/fluent-main.css", + "lines": 1019, + "bytes": 20195, + "test": false, + "signals": {} + }, + { + "path": "src/styles/fluent/fluent-modern.css", + "lines": 179, + "bytes": 4331, + "test": false, + "signals": {} + }, + { + "path": "src/styles/fluent/fluent-project-popover.css", + "lines": 355, + "bytes": 7215, + "test": false, + "signals": {} + }, + { + "path": "src/styles/fluent/fluent-secondary.css", + "lines": 801, + "bytes": 16848, + "test": false, + "signals": {} + }, + { + "path": "src/styles/forecast.css", + "lines": 376, + "bytes": 7326, + "test": false, + "signals": {} + }, + { + "path": "src/styles/gantt/gantt.css", + "lines": 510, + "bytes": 10170, + "test": false, + "signals": {} + }, + { + "path": "src/styles/global-filter.css", + "lines": 524, + "bytes": 14426, + "test": false, + "signals": {} + }, + { + "path": "src/styles/global.css", + "lines": 72, + "bytes": 3011, + "test": false, + "signals": {} + }, + { + "path": "src/styles/group-by.css", + "lines": 207, + "bytes": 5072, + "test": false, + "signals": {} + }, + { + "path": "src/styles/habit-edit-dialog.css", + "lines": 249, + "bytes": 5273, + "test": false, + "signals": {} + }, + { + "path": "src/styles/habit-list.css", + "lines": 188, + "bytes": 3654, + "test": false, + "signals": {} + }, + { + "path": "src/styles/habit.css", + "lines": 573, + "bytes": 14549, + "test": false, + "signals": {} + }, + { + "path": "src/styles/ics-settings.css", + "lines": 551, + "bytes": 11063, + "test": false, + "signals": {} + }, + { + "path": "src/styles/index.css", + "lines": 251, + "bytes": 6782, + "test": false, + "signals": {} + }, + { + "path": "src/styles/inline-editor.css", + "lines": 340, + "bytes": 7749, + "test": false, + "signals": {} + }, + { + "path": "src/styles/kanban/kanban.css", + "lines": 452, + "bytes": 12345, + "test": false, + "signals": {} + }, + { + "path": "src/styles/layout-placement.css", + "lines": 104, + "bytes": 1797, + "test": false, + "signals": {} + }, + { + "path": "src/styles/mcp-integration.css", + "lines": 722, + "bytes": 14220, + "test": false, + "signals": {} + }, + { + "path": "src/styles/modal.css", + "lines": 310, + "bytes": 6464, + "test": false, + "signals": {} + }, + { + "path": "src/styles/modern.css", + "lines": 24, + "bytes": 551, + "test": false, + "signals": {} + }, + { + "path": "src/styles/noise.css", + "lines": 31, + "bytes": 1875, + "test": false, + "signals": {} + }, + { + "path": "src/styles/onboarding-components.css", + "lines": 331, + "bytes": 7282, + "test": false, + "signals": {} + }, + { + "path": "src/styles/onboarding.css", + "lines": 2087, + "bytes": 46133, + "test": false, + "signals": {} + }, + { + "path": "src/styles/onCompletion.css", + "lines": 302, + "bytes": 6088, + "test": false, + "signals": {} + }, + { + "path": "src/styles/progressbar.css", + "lines": 161, + "bytes": 3362, + "test": false, + "signals": {} + }, + { + "path": "src/styles/project-tree.css", + "lines": 289, + "bytes": 6497, + "test": false, + "signals": {} + }, + { + "path": "src/styles/project-view.css", + "lines": 357, + "bytes": 7234, + "test": false, + "signals": {} + }, + { + "path": "src/styles/property-view.css", + "lines": 211, + "bytes": 4265, + "test": false, + "signals": {} + }, + { + "path": "src/styles/quadrant/quadrant.css", + "lines": 983, + "bytes": 20556, + "test": false, + "signals": {} + }, + { + "path": "src/styles/quick-capture.css", + "lines": 639, + "bytes": 13656, + "test": false, + "signals": {} + }, + { + "path": "src/styles/review-view.css", + "lines": 413, + "bytes": 8179, + "test": false, + "signals": {} + }, + { + "path": "src/styles/reward.css", + "lines": 45, + "bytes": 1107, + "test": false, + "signals": {} + }, + { + "path": "src/styles/setting-v2.css", + "lines": 446, + "bytes": 10119, + "test": false, + "signals": {} + }, + { + "path": "src/styles/setting.css", + "lines": 1953, + "bytes": 42372, + "test": false, + "signals": {} + }, + { + "path": "src/styles/settings-migration.css", + "lines": 91, + "bytes": 2047, + "test": false, + "signals": {} + }, + { + "path": "src/styles/settings-search.css", + "lines": 285, + "bytes": 7178, + "test": false, + "signals": {} + }, + { + "path": "src/styles/table.css", + "lines": 990, + "bytes": 19509, + "test": false, + "signals": {} + }, + { + "path": "src/styles/tag-view.css", + "lines": 250, + "bytes": 4751, + "test": false, + "signals": {} + }, + { + "path": "src/styles/task-details.css", + "lines": 583, + "bytes": 11646, + "test": false, + "signals": {} + }, + { + "path": "src/styles/task-filter.css", + "lines": 134, + "bytes": 2495, + "test": false, + "signals": {} + }, + { + "path": "src/styles/task-gutter.css", + "lines": 170, + "bytes": 3825, + "test": false, + "signals": {} + }, + { + "path": "src/styles/task-list.css", + "lines": 377, + "bytes": 7607, + "test": false, + "signals": {} + }, + { + "path": "src/styles/task-selection.css", + "lines": 255, + "bytes": 5664, + "test": false, + "signals": {} + }, + { + "path": "src/styles/task-status-indicator.css", + "lines": 45, + "bytes": 992, + "test": false, + "signals": {} + }, + { + "path": "src/styles/task-status.css", + "lines": 166, + "bytes": 3579, + "test": false, + "signals": {} + }, + { + "path": "src/styles/task-timer.css", + "lines": 23, + "bytes": 454, + "test": false, + "signals": {} + }, + { + "path": "src/styles/taskgenius-calendar.css", + "lines": 684, + "bytes": 14991, + "test": false, + "signals": {} + }, + { + "path": "src/styles/timeline-sidebar.css", + "lines": 839, + "bytes": 22494, + "test": false, + "signals": {} + }, + { + "path": "src/styles/timer-statistics.css", + "lines": 336, + "bytes": 6870, + "test": false, + "signals": {} + }, + { + "path": "src/styles/tree-view.css", + "lines": 273, + "bytes": 5467, + "test": false, + "signals": {} + }, + { + "path": "src/styles/universal-suggest.css", + "lines": 93, + "bytes": 2015, + "test": false, + "signals": {} + }, + { + "path": "src/styles/view-config.css", + "lines": 142, + "bytes": 4011, + "test": false, + "signals": {} + }, + { + "path": "src/styles/view-setting-tab.css", + "lines": 145, + "bytes": 2673, + "test": false, + "signals": {} + }, + { + "path": "src/styles/view-two-column-base.css", + "lines": 232, + "bytes": 4772, + "test": false, + "signals": {} + }, + { + "path": "src/styles/view.css", + "lines": 708, + "bytes": 13304, + "test": false, + "signals": {} + }, + { + "path": "src/styles/workflow.css", + "lines": 50, + "bytes": 1155, + "test": false, + "signals": {} + }, + { + "path": "src/styles/workspace-icons.css", + "lines": 92, + "bytes": 1997, + "test": false, + "signals": {} + }, + { + "path": "src/styles/workspace-settings-selector.css", + "lines": 137, + "bytes": 3039, + "test": false, + "signals": {} + }, + { + "path": "src/test-setup.ts", + "lines": 31, + "bytes": 573, + "test": false, + "signals": {} + }, + { + "path": "src/translations/helper.ts", + "lines": 14, + "bytes": 475, + "test": false, + "signals": {} + }, + { + "path": "src/translations/locale/en-gb.ts", + "lines": 1930, + "bytes": 135200, + "test": false, + "signals": {} + }, + { + "path": "src/translations/locale/en.ts", + "lines": 3183, + "bytes": 186700, + "test": false, + "signals": {} + }, + { + "path": "src/translations/locale/ja.ts", + "lines": 2434, + "bytes": 161259, + "test": false, + "signals": {} + }, + { + "path": "src/translations/locale/pt-br.ts", + "lines": 1930, + "bytes": 142845, + "test": false, + "signals": {} + }, + { + "path": "src/translations/locale/ru.ts", + "lines": 1930, + "bytes": 156149, + "test": false, + "signals": {} + }, + { + "path": "src/translations/locale/uk.ts", + "lines": 1930, + "bytes": 167891, + "test": false, + "signals": {} + }, + { + "path": "src/translations/locale/zh-cn.ts", + "lines": 3000, + "bytes": 179926, + "test": false, + "signals": {} + }, + { + "path": "src/translations/locale/zh-tw.ts", + "lines": 2317, + "bytes": 130358, + "test": false, + "signals": {} + }, + { + "path": "src/translations/manager.ts", + "lines": 179, + "bytes": 4935, + "test": false, + "signals": {} + }, + { + "path": "src/translations/types.ts", + "lines": 36, + "bytes": 793, + "test": false, + "signals": {} + }, + { + "path": "src/types/bases.d.ts", + "lines": 319, + "bytes": 6944, + "test": false, + "signals": {} + }, + { + "path": "src/types/canvas.ts", + "lines": 130, + "bytes": 3937, + "test": false, + "signals": {} + }, + { + "path": "src/types/file-source.d.ts", + "lines": 229, + "bytes": 7115, + "test": false, + "signals": {} + }, + { + "path": "src/types/file-task.d.ts", + "lines": 138, + "bytes": 3823, + "test": false, + "signals": {} + }, + { + "path": "src/types/fluent-types.ts", + "lines": 40, + "bytes": 1021, + "test": false, + "signals": {} + }, + { + "path": "src/types/groupBy.d.ts", + "lines": 71, + "bytes": 1710, + "test": false, + "signals": {} + }, + { + "path": "src/types/habit-card.d.ts", + "lines": 105, + "bytes": 2859, + "test": false, + "signals": {} + }, + { + "path": "src/types/ics.ts", + "lines": 418, + "bytes": 11681, + "test": false, + "signals": {} + }, + { + "path": "src/types/obsidian-ex.d.ts", + "lines": 767, + "bytes": 16472, + "test": false, + "signals": {} + }, + { + "path": "src/types/onCompletion.ts", + "lines": 75, + "bytes": 1676, + "test": false, + "signals": {} + }, + { + "path": "src/types/selection.d.ts", + "lines": 110, + "bytes": 2582, + "test": false, + "signals": {} + }, + { + "path": "src/types/SettingsSearch.ts", + "lines": 22, + "bytes": 856, + "test": false, + "signals": {} + }, + { + "path": "src/types/task.d.ts", + "lines": 299, + "bytes": 8229, + "test": false, + "signals": {} + }, + { + "path": "src/types/TaskParserConfig.ts", + "lines": 195, + "bytes": 5362, + "test": false, + "signals": {} + }, + { + "path": "src/types/time-parsing.ts", + "lines": 125, + "bytes": 3550, + "test": false, + "signals": {} + }, + { + "path": "src/types/tree.d.ts", + "lines": 87, + "bytes": 2085, + "test": false, + "signals": {} + }, + { + "path": "src/types/workspace.ts", + "lines": 168, + "bytes": 4095, + "test": false, + "signals": {} + }, + { + "path": "src/utils.ts", + "lines": 234, + "bytes": 6099, + "test": false, + "signals": {} + }, + { + "path": "src/utils/adapters/TaskCalendarAdapter.ts", + "lines": 313, + "bytes": 9582, + "test": false, + "signals": {} + }, + { + "path": "src/utils/changelog-cache.ts", + "lines": 194, + "bytes": 4072, + "test": false, + "signals": {} + }, + { + "path": "src/utils/date/date-display-helper.ts", + "lines": 71, + "bytes": 2350, + "test": false, + "signals": {} + }, + { + "path": "src/utils/date/date-formatter.ts", + "lines": 202, + "bytes": 6110, + "test": false, + "signals": {} + }, + { + "path": "src/utils/date/date-helper.ts", + "lines": 65, + "bytes": 2242, + "test": false, + "signals": {} + }, + { + "path": "src/utils/date/date-utils.ts", + "lines": 62, + "bytes": 1569, + "test": false, + "signals": {} + }, + { + "path": "src/utils/dateOperations.ts", + "lines": 67, + "bytes": 1843, + "test": false, + "signals": {} + }, + { + "path": "src/utils/file/file-operations.ts", + "lines": 371, + "bytes": 11235, + "test": false, + "signals": {} + }, + { + "path": "src/utils/file/file-type-detector.ts", + "lines": 119, + "bytes": 2848, + "test": false, + "signals": {} + }, + { + "path": "src/utils/grouping/groupByStorage.ts", + "lines": 131, + "bytes": 3384, + "test": false, + "signals": {} + }, + { + "path": "src/utils/grouping/taskGrouping.ts", + "lines": 784, + "bytes": 20420, + "test": false, + "signals": {} + }, + { + "path": "src/utils/id-generator.ts", + "lines": 4, + "bytes": 123, + "test": false, + "signals": { + "weakRandom": 1 + } + }, + { + "path": "src/utils/ObsidianUriHandler.ts", + "lines": 434, + "bytes": 11960, + "test": false, + "signals": { + "timer": 4 + } + }, + { + "path": "src/utils/settings-migration.ts", + "lines": 164, + "bytes": 4507, + "test": false, + "signals": {} + }, + { + "path": "src/utils/SettingsMigration.ts", + "lines": 341, + "bytes": 11730, + "test": false, + "signals": {} + }, + { + "path": "src/utils/SettingsMigrationManager.ts", + "lines": 167, + "bytes": 4645, + "test": false, + "signals": {} + }, + { + "path": "src/utils/status-cycle-resolver.ts", + "lines": 451, + "bytes": 12713, + "test": false, + "signals": {} + }, + { + "path": "src/utils/task-metadata-utils.ts", + "lines": 247, + "bytes": 8646, + "test": false, + "signals": {} + }, + { + "path": "src/utils/task/curosr-priority-utils.ts", + "lines": 77, + "bytes": 2320, + "test": false, + "signals": {} + }, + { + "path": "src/utils/task/filter-compatibility.ts", + "lines": 58, + "bytes": 2374, + "test": false, + "signals": {} + }, + { + "path": "src/utils/task/priority-utils.ts", + "lines": 49, + "bytes": 1866, + "test": false, + "signals": {} + }, + { + "path": "src/utils/task/removeBlankTasks.ts", + "lines": 24, + "bytes": 1123, + "test": false, + "signals": {} + }, + { + "path": "src/utils/task/task-filter-utils.ts", + "lines": 880, + "bytes": 25996, + "test": false, + "signals": {} + }, + { + "path": "src/utils/task/task-migration.ts", + "lines": 131, + "bytes": 3247, + "test": false, + "signals": {} + }, + { + "path": "src/utils/task/task-operations.ts", + "lines": 652, + "bytes": 20271, + "test": false, + "signals": {} + }, + { + "path": "src/utils/ui/tree-view-utils.ts", + "lines": 68, + "bytes": 1861, + "test": false, + "signals": {} + }, + { + "path": "src/utils/ui/view-mode-utils.ts", + "lines": 63, + "bytes": 2031, + "test": false, + "signals": {} + }, + { + "path": "tests/habits/compact.test.mjs", + "lines": 354, + "bytes": 22768, + "test": true, + "signals": { + "timer": 1 + } + }, + { + "path": "tests/habits/dom-fixture.mjs", + "lines": 29, + "bytes": 1816, + "test": false, + "signals": { + "directDomListener": 1 + } + }, + { + "path": "tests/habits/integration.test.mjs", + "lines": 262, + "bytes": 18963, + "test": true, + "signals": {} + }, + { + "path": "tests/habits/limit-frequency.test.mjs", + "lines": 71, + "bytes": 4743, + "test": true, + "signals": {} + }, + { + "path": "tests/habits/obsidian-fixture.mjs", + "lines": 120, + "bytes": 7576, + "test": false, + "signals": { + "directDomListener": 3 + } + }, + { + "path": "tests/habits/styles.test.mjs", + "lines": 30, + "bytes": 1357, + "test": true, + "signals": {} + }, + { + "path": "tests/ui-audit/fixture.mjs", + "lines": 53, + "bytes": 2574, + "test": false, + "signals": { + "timer": 1, + "directDomListener": 3 + } + }, + { + "path": "tests/ui-audit/regressions.test.mjs", + "lines": 206, + "bytes": 18956, + "test": true, + "signals": { + "timer": 1, + "directDomListener": 1 + } + } + ] +} diff --git a/docs/audit-2026-11-08.md b/docs/audit-2026-11-08.md new file mode 100644 index 000000000..04bda9a55 --- /dev/null +++ b/docs/audit-2026-11-08.md @@ -0,0 +1,70 @@ +# Task Genius 旧布局版本审计与修复 + +## 结论 + +这些问题主要来自多套视图状态、异步初始化、缓存失效和生命周期管理没有统一衔接。旧版本持续叠加新组件增加了维护成本,但“代码较旧”本身不能解释每个问题,也不能据此认定整个系统无法使用。 + +本轮保留原有导航入口、任务状态顺序、习惯数据格式、页面结构和主设置布局。修复集中在数据与界面的同步、旧实例退出和已有关闭按钮的事件处理;不进行界面改版,不迁移用户笔记,不改写任务文件。 + +## 用户报告的八项问题 + +| 项目 | 代码问题与修复 | 验证 | +| --- | --- | --- | +| 列表、树状连续切换卡顿 | 内容区与顶部导航各自维护模式;刷新还重建未变化的标签。统一切换入口,明确下发当前模式,保留未变化的标签 DOM,取消同步渲染结束后的额外延迟锁。 | 连续切换、标签节点稳定性、强制刷新后连续更新 | +| 首次进入偶发空白 | 首次查询先于缓存事件订阅;初始化期间的变更被丢弃;旧查询可能覆盖新结果;隐藏待刷新时拒收新数据。订阅先于查询,保留初始化期间的待刷新状态,按请求顺序接收最新结果,重新可见后自动绘制。可见性判断使用元素所属文档。 | 隐藏后更新、初始化中更新、延迟查询乱序、卸载后查询完成 | +| 年份页不能向下滚动 | 实际承载年份网格的内层 `.tg-view-container` 设置了 `overflow:hidden`。保持十二月网格,修正该内层滚动口及父级 flex 最小高度。 | 真实 Obsidian 离屏测试:12 个月,滚动内容高度大于可视高度,`overflow-y:auto`,滚动位置可改变 | +| 日历翻页标题不更新 | 日历本体和外层标题使用两套日期;原来没有连接日期变化回调。连接内置、自定义日历的 `onDateChange` 并更新已有标题节点。 | 实际日历引擎的月、周、日、年往返导航 | +| 删除独立 Habits 提示 | 删除页面和设置中的提示调用,保留双插件共用记录时避免重复后台写入的处理。 | 源码检查、原习惯兼容测试 | +| 修改视图设置后页面不更新 | 部分设置仅保存配置;已缓存的组件没有比较配置变化。保存时对 UI 配置做值快照并通知视图,刷新导航和配置;日历配置更新保留当前日期,其他失效组件重新创建。工作区导航状态保存不触发全局配置刷新。 | 配置原地修改、导航状态保存、配置缓存失效、日期保留 | +| 创建习惯叉号无效 | 实机确认是新版 `.modal-header-button`,不是图标清除按钮,且没有视觉遮挡。为新旧原生关闭控件补充限定在本弹窗内的 pointer-up / 捕获阶段关闭处理,关闭时移除处理器。未把未经捕获的错误猜测写成已证实根因。 | 两种控件名称、文档 click 被拦截时关闭、处理器清理;实际使用仍需用户确认 | +| 项目快捷入口与项目总览冲突 | 总览主动禁用了侧栏项目入口;侧栏重绘遗留旧列表,旧异步结果可能回写;带引号的项目名会破坏 CSS 选择器。恢复入口可用性,同步当前项目,清理旧列表并拒绝其迟到结果,使用属性值比较定位项目。 | 总览/具体项目状态、特殊字符名称、旧列表卸载后异步结果 | + +## 审计覆盖与方法 + +全仓静态遍历覆盖 `src`、`packages/calendar/src`、构建脚本及 GitHub 工作流;文件和行数清单在 `audit-2026-11-08-inventory.json`,可用 `node scripts/audit-source-map.cjs` 重建。清单包含测试文件,静态信号不等于已确认缺陷,也不代表每一行都已逐行人工证明正确。 + +重点逐段检查的运行路径: + +| 模块 | 检查内容 | +| --- | --- | +| Fluent 页面及组件管理器 | 初始化、模式切换、空/加载状态、重复绘制、缓存组件 | +| 列表、树、分组 | 数据签名、隐藏视图恢复、渲染锁、分组子组件清理、排序开销 | +| 侧栏与项目 | 总览/快捷入口、重绘、异步请求、项目标识与 DOM 定位 | +| 主设置与视图设置 | 直接保存/完整应用的不同路径、配置快照、通知、工作区状态隔离 | +| 日历及日历库 | 内置/自定义视图、日期回调、年份布局、事件和容器生命周期 | +| Dataflow | 缓存就绪、增量更新、设置重建、项目缓存失效、持久化与关闭 | +| WriteAPI 与文件任务 | 文件接口、读改写流程、批量操作与行定位;不在真实笔记执行破坏测试 | +| 习惯、导入与 Reminder | 原数据兼容、重复导入、文件冲突、同步归属、弹窗和关闭 | +| AI 与导出 | 显式请求入口、统计摘要范围、缓存身份、PDF 生成 | +| MCP、桌面与配置迁移 | 监听地址/认证入口、令牌生成、迁移触发、旧版本兼容声明 | + +## 同时修正的其他问题 + +- 分组子渲染器递归释放,避免刷新后旧子组件仍监听事件。 +- 项目列表初次加载后重复绘制;现在保留一次绘制。 +- 相同顶部导航实例重新绑定时不再关闭正在查看的计时统计。 +- 默认排序复用一次 `Intl.Collator`,比较规则和排序结果保持原样。 +- 独立习惯页不再被“任务总数为零”的空任务界面遮盖。 +- AI 总结缓存纳入接口地址,切换同名模型的服务后不会复用另一接口的结果。 +- MCP 新令牌改用安全随机字节并保持原来的 32 位字母数字格式;已有令牌不变。 + +## 尚需独立处理的遗留风险 + +1. **原测试基线仍不干净。** 原有 Jest 在本机是 1,349 项通过、147 项失败。包含旧接口 mock、缺失模块路径和既有行为断言失败,不能把这些失败一概视为无害。本轮对失败测试的文件名和完整测试名逐项比对,没有新增失败,不删除或跳过原测试。 +2. **文件写入的并发风险。** `WriteAPI` 的多条路径使用“读取内容 → 修改字符串 → `vault.modify`”。未见统一覆盖所有写入入口的同文件串行控制;两个不同操作同时作用于同一笔记时值得专门做并发一致性测试。本轮不贸然重写任务写入引擎。 +3. **版本兼容声明落后于实际 API。** manifest 仍声明最低 Obsidian `0.15.2`,而引用的 `AbstractInputSuggest` 在类型说明中标注自 `1.4.10` 提供。这是历史兼容承诺问题,不能据 manifest 推断老客户端都能运行。未因此强制用户升级或改变当前安装方式。 +4. **部分日历任务完成状态仍硬编码默认符号。** 当前使用默认完成/未开始符号时不受影响;若换成非默认符号,需要独立覆盖日历写入与自定义状态的组合测试。 +5. **全局 DOM 引用与延迟回调仍分布于其他旧模块。** 本轮修复报告问题涉及的可见性、查询和组件销毁路径;其他多窗口、移动端和第三方集成场景不能仅凭静态扫描宣称全部验证完毕。 + +这些条目区分“已确认并修复的问题”和“有源码依据、尚需专门验证的风险”。本报告不是零缺陷或所有平台完全一致的保证。 + +## 验证与交付 + +- `pnpm test:ui`:页面/导航、日期、设置、项目、关闭按钮、令牌生成回归。 +- `pnpm test:habits`:原习惯交互、统计、导入、提醒、双插件共存、PDF 及模拟 AI 接口。 +- `pnpm check:i18n`:保留原有 1,800 个设置词条,检查习惯模块中英文占位符。 +- `pnpm build`:TypeScript 和生产 JavaScript/CSS 打包。 +- 原有 Jest 全量运行,与未修改版本的失败名单比对。 +- 实机离屏年份滚动验证没有切换用户当前页面、没有输入鼠标键盘动作、没有修改笔记。 + +实际安装和用户确认结果另存于本地安装记录,测试报告不会把未进行的实机交互写成已通过。 diff --git a/docs/fixes-9.13.4.md b/docs/fixes-9.13.4.md new file mode 100644 index 000000000..2fb323c4e --- /dev/null +++ b/docs/fixes-9.13.4.md @@ -0,0 +1,49 @@ +# Task Genius 9.13.4 修复说明 + +## 项目 + +在侧边栏右键项目,选择“删除项目”,或打开“编辑项目信息”,使用底部的删除按钮。删除会先确认,再将项目笔记和其中的任务移入 Obsidian 回收站。归档项目管理页也有删除入口。 + +项目中的“新增任务”使用统一的新建任务窗口,预选当前项目,并将任务写入项目笔记。项目内新增任务不会因为上一次使用“整页任务”而改为创建另一篇任务笔记。 + +## 习惯 + +习惯页默认使用原生卡片布局。使用布局下拉框切换到“仪表盘布局”,两种布局读取同一批习惯笔记。外层容器不再显示独立边框;移除文字按钮“创建习惯”,通过加号新增。 + +卡片展示近三十天记录。点击历史日期方格选中日期,再使用右侧按钮补打卡;计数习惯使用加减按钮。更多操作中可编辑、暂停、删除习惯,以及处理当天的打卡状态。 + +## 普通笔记中的任务 + +正常勾选任务完成时,自动写入 `✅ YYYY-MM-DD` 或当前设置的行内完成日期;已有完成日期保留,取消完成时移除完成日期。阅读模式的复选框修改也纳入同步。 + +启动、打开笔记、导入已完成的旧任务不会批量补写今天的日期。代码块中的示例复选框不会被改写。无法区分的同名重复任务采用保守处理,不猜测其历史完成时间。 + +## 预设筛选 + +标题栏中可直接选择“待办”“已完成”“已放弃”“本月任务”,以及自己保存的预设。预设筛选作用于当前页面范围;例如项目页仍保留当前项目范围。 + +在旁边的筛选菜单或设置的“预设筛选”中新增、编辑规则。状态、优先级、日期范围、项目和已有标签主要使用下拉选项。指定日期使用日期选择器;只有文字和路径条件需要输入文本。高级查询为可选项。 + +已移除标题栏中原来的“匹配全部过滤器组/添加过滤器组”入口。修复已完成任务在应用预设前被移除的问题,以及内容列表重复过滤、标签精确匹配、没有日期、带引号项目名称等问题。 + +## 标题栏与页面 + +搜索、预设、列表/树/看板/日历切换、所有周期、通知和设置统一放在 Obsidian 原有标题栏。较窄的窗口会自动换行。习惯、积分和奖励也使用标题栏搜索。 + +积分与奖励为两个独立页面。积分页包含加分项、流水和积分规则;奖励页用于管理愿望和兑换奖励,两者共用余额。 + +修复页面切换时积分页未隐藏的问题,以及重复更新表格和隐藏期间尺寸未刷新导致的空白问题。表格重新分配默认列宽;之后仍可拖动调整并保存。 + +## 项目甘特图、矩阵和依赖 + +“Project plans”改为“项目甘特图”。拖动项目条移动起止日期;拖动两端手柄调整开始或结束日期,写回项目笔记属性。拖动空白区域平移图表;使用放大、缩小、今天按钮,或 Ctrl 加滚轮缩放。 + +矩阵卡片的状态与任务文字放在同一行。任务依赖改为按名称搜索选择,自动生成稳定标识并阻止循环依赖。移除手工填写任务 ID 和重复规则的编辑入口,已有笔记内容保留。 + +## 设置与验证 + +保留原设置导航和行式布局。清理旧项目标记前缀、上下文前缀、索引技术开关、自定义日期兼容入口等;保留需要用户选择的设置,改用具体说明。 + +测试包含真实筛选流程、状态日期写入、项目删除、依赖选择、连续列表树切换、原生习惯卡片打卡,以及 SVG 甘特图拖动。界面自动测试使用独立测试环境,不接管用户鼠标键盘。 + +安装只替换插件代码文件,保留 Markdown 和插件配置,并在安装前备份。需要手动关闭、开启一次 Task Genius 才能加载新版本;不会自动重启 Obsidian。 diff --git a/docs/fixes-9.13.5.md b/docs/fixes-9.13.5.md new file mode 100644 index 000000000..2abae148c --- /dev/null +++ b/docs/fixes-9.13.5.md @@ -0,0 +1,15 @@ +# Task Genius 9.13.5 + +- 标题栏统一使用原生大小、间距和悬停样式;移除 Default Cycle 选择和单独的预设下拉框。预设仍可通过筛选图标菜单选择、编辑和清除。 +- 积分与奖励合回同一页。加分项与奖励兑换并列显示,积分流水、积分规则仍在同一页面中切换。 +- 原生卡片/仪表盘布局改在 **设置 → 习惯 → 布局 → 习惯页面布局** 中选择,不再在习惯页面显示布局下拉框。 +- 原生卡片使用 Habits 的目标、限额、计划、暂停、跳过、失败和补打卡规则。显示目标与单位、周期总量和每日目标;未完成在前,已完成在后。 +- 热力图按四种状态显示:未记录、已记录未达标、达标、达到两倍目标。限额型习惯另外标出超限,超过限额不会被当作超额完成。 +- 表格状态列至少保留完整状态文字所需的宽度,整表不再挤压状态列。列较多时可横向滚动。 +- 搜索会展开包含匹配任务的已折叠分组;被筛掉的父任务不再隐藏匹配子任务。缺少 children 信息、自引用或循环父子关系不会导致结果为空。 +- 事件视图排除项目笔记本身,保留项目内有日期的复选框任务。项目甘特图只修改项目日期;项目日期不再作为内部任务的默认日期,任务明确设置的截止日期保留。 +- 任务详情移除操作类型/完成后操作编辑和英文标签提示。依赖选择只列出任务,不列出整页任务或项目行,按任务名称搜索。 +- 修复矩阵筛选为空时旧卡片残留、追加空状态以及旧分批渲染覆盖新结果的问题。 +- 所有侧边栏视图,包括系统视图,均可通过右键“在侧边栏隐藏”。恢复显示可在设置的视图列表中操作。 + +升级首次加载会按现有版本检查流程自动刷新任务索引。原 Markdown 笔记与积分记录保留;安装前备份插件文件与配置,不自动重启 Obsidian。 diff --git a/docs/fixes-9.13.6.md b/docs/fixes-9.13.6.md new file mode 100644 index 000000000..486d31b85 --- /dev/null +++ b/docs/fixes-9.13.6.md @@ -0,0 +1,15 @@ +# Task Genius 9.13.6 + +本次对应七项反馈,保留原设置样式与原 Markdown 记录。 + +1. 顶栏:通知、设置、视图快捷操作和 Obsidian 原生操作共用右侧操作区。去除左右按钮组各自的底边与阴影,重绘时不会重复生成操作区。Default Cycle 不再出现。 +2. 习惯:原生卡片和紧凑列表使用两列,窄窗口自动一列。原生卡片显示所选日期、目标/限额、每日目标和周期进度;左右切换查看对应日期,日期按钮返回今天,日期输入可选任意一天。已完成习惯淡化并排列在未完成之后;限额型超限仍按失败显示,原记录和补打卡规则保留。 +3. 表格:拖动列宽后,在松开时保存到当前表格视图,重开恢复;不同自定义表格分别保存,状态列保留可读宽度。 +4. 拖动:矩阵和看板只拖动任务卡片,按钮和链接仍正常操作。看板按分组修改状态/优先级/标签/日期/项目等属性;标记完成同时写完成日期。矩阵拖动保存紧急/重要标签和显式象限标记 `#quadrant/象限ID`,避免截止日期推断把任务又送回原象限,不修改任务截止日期。写入失败恢复原状态。 +5. 积分与奖励:保留同一页面,移除“习惯/打卡记录”汇总卡。已完成且有完成日期的 Markdown 复选框任务计入相应日期,默认沿用“完成任务”打卡的每项积分(没有该规则时每项 1 分),任务自带积分优先。自动积分仅补足实际任务积分与当天既有任务打卡、任务奖励流水之间的差额;不改原打卡记录,不重复计分。不补造缺失的完成日期,项目计划和整页任务不计入。 +6. 布局:设置 → 习惯 → 布局只保留一个“习惯页面布局”选项,包含原生卡片、紧凑列表、网格、轮播、垂直滚动;保留原来选中的布局。 +7. 侧边栏:系统视图与自定义视图均可在上方、下方互相拖动并保存顺序,空区域也可接收。下方不再只展示前五项,也不再把其余视图藏进省略菜单;列表滚动展示。主动折叠侧栏后的图标栏同样完整显示并支持滚动。 + +安装只替换 main.js、styles.css、manifest.json;安装前备份插件、配置与习惯/积分源文件,不主动重启 Obsidian。已经打开的实例需要手动关闭再启用一次 Task Genius 才能加载新代码。 + +验证:界面回归 41 项通过,习惯回归 59 项通过;11 个相关 Jest 测试套件共 61 项通过。完整 Jest 测试共 1550 项,1401 项通过、149 项失败;其中 146 项与前版既有失败相同,另 3 项为跨午夜日期模拟问题,已在未修改的 9.13.5 副本中复现。未发现新增失败,完整历史测试集仍未全部通过。上述验证不代替用户在实际 Obsidian 窗口中的外观验收。 diff --git a/docs/fixes-9.13.7.md b/docs/fixes-9.13.7.md new file mode 100644 index 000000000..99e11852b --- /dev/null +++ b/docs/fixes-9.13.7.md @@ -0,0 +1,20 @@ +# Task Genius 9.13.7 + +对应本轮十二项反馈,原 Markdown 任务、习惯记录和积分文件保留。 + +1. 错过习惯:仪表盘、原生卡片、紧凑列表和 Habits 侧栏显示通知。逐日查看,可改期或忽略。忽略写入习惯笔记的 `ignoredMisses`,不改打卡记录;改期保存时重新检查原计划、既有记录和其他改期,阻止同日重复。每天都有计划的习惯可忽略或按原日期补记,不能占用另一个已到期日。 +2. 设置:删除“时间解析”设置入口,索引和捕获使用统一内置解析规则;移除错过习惯通知的实验开关,功能直接启用。保留其他设置原来的分类和视觉样式,不删除用户已有设置数据。 +3. 详情:统一为与新建任务相近的居中悬浮编辑窗,保存才落盘,取消不写文件。 +4. 身份与空值:详情编辑不再重写任务 ID 或把行号减一;打开时先刷新对应文件再查最新任务,无法唯一定位的旧任务会明确提示,不把 undefined 当任务内容写回。 +5. 暂停:原先显示 No status 的旧暂停组显示为“暂停”,使用暂停图标;不批量改变原状态符号。 +6. 日期时间:新建和详情都可填 `2026-11-12` 或 `2026-11-12 09:30`,自动识别是否包含时间,无需额外开关。支持明确的 `00:00`,无效日期不能保存;编辑其他字段会保留已有时间。 +7. 任务排期:侧边栏新增“任务排期”,可将未安排任务拖入日历,或在日期间拖动;写入计划日期,保留截止日期及已有具体时刻。拖回未安排区域可清除计划日期。 +8. 项目甘特图:只保留“今天、周、月、年”。周显示上周/本周/下周,月显示上月/本月/下月,年显示去年/今年/明年;移除内置过滤器与缩放按钮,保留原来项目日期拖动和甘特图滚动操作。 +9. 右栏:移除 Task Genius 的右侧详情栏、按钮、注册与相关实现;旧详情窗格会在布局就绪时关闭。任务详情改用浮窗。 +10. 刷新:修复带任务 ID 的写入完成事件被跳过、而普通写入又未发送单任务更新的通知缺口。保存后直接读取源文件重新索引;同文件解析按顺序执行,异步查询检查索引版本并重读,避免旧结果覆盖新结果;数据未变化但列表被清空时也会恢复绘制。 +11. 习惯外观:去掉第二个可见日期和热力图说明文字。设置 → 习惯 → 常规 → 习惯列数可选自适应或一至四列,默认自适应可用宽度。显示习惯/分组图标,已完成项更暗,加号靠右。使用独立关闭控件处理右上角叉号,不依赖主题中的原生按钮结构。 +12. 积分:自动完成任务积分及旧任务奖励流水不再出现在积分明细中,归入习惯积分的“完成任务”条目;原来打卡与自动补计合并展示,金额列右对齐并使用等宽数字。 + +安装仅替换 main.js、styles.css、manifest.json,安装前备份插件、配置及原始习惯/积分记录。不主动重启 Obsidian;保存当前编辑后,关闭再启用 Task Genius 一次加载本版。 + +验证:界面回归 52 项、习惯回归 63 项、13 个相关 Jest 套件共 67 项全部通过;完整 Jest 测试共 1556 项,其中 1410 项通过、146 项为此前已有失败,逐项核对无新增失败。中英文设置与习惯文本、版本一致性、类型检查和生产构建通过。实际 Obsidian 窗口中的外观仍需加载新版后验收。 diff --git a/docs/fixes-9.13.8.md b/docs/fixes-9.13.8.md new file mode 100644 index 000000000..28b65a141 --- /dev/null +++ b/docs/fixes-9.13.8.md @@ -0,0 +1,49 @@ +# Task Genius 9.13.8 试用说明 + +第 4 项“空格/双击项目弹窗”已按要求取消。 + +## 项目 + +- 项目可以拖动到另一项目上方或下方排序;侧边栏排序菜单可以选择“手动排序”。顺序记录在项目笔记的 `projectOrder` 属性中。 +- 右键项目 → 编辑项目详情,可选择项目颜色、父级文件夹,也可以填写新的父级文件夹名称。 +- 父级文件夹使用项目目录里的实际文件夹。移动项目时使用 Obsidian 文件管理接口;项目名及任务内容保留,侧边栏和项目页按文件夹展开。 +- 新建项目也可以选择父级文件夹及颜色。颜色记录在项目笔记的 `projectColor` 属性中。 +- 创建任务时选择项目,写入位置立即显示对应项目文件;任务保存到该项目笔记。 +- 甘特图拖动项目或两侧边缘时显示日期范围。修改项目时间不会移动项目内任务的截止日期。 + +## 日历和排期 + +- 日历顶部提供日记、周记、月记、年记入口。沿用已有 Periodic Notes、Calendar、Daily Notes 的文件夹、命名及模板;已有笔记直接打开,不覆盖内容。 +- 月历日期数字和周/日视图日期标题可以打开对应日记。顶部周期标题打开当前周期笔记。 +- 周数按日历年计算:1 月 1 日所在周为第 1 周,跨年重新计数,周起始日遵循日历设置。甘特图和习惯界面也显示周数。既有周记的文件命名格式保留。 +- 修复重叠事件错位,任务在独立列中显示;显示工作时段时,任务位置、点击和拖动的时间使用相同计算。 +- 日视图和周视图当天显示红色当前时间线,每分钟更新,不中断拖动。 +- 排期左侧未安排任务列表独立滚动,日期网格紧跟星期标题。拖入某天只修改计划日期,保留截止日期及已有时间。 + +## 任务窗口和筛选 + +- 编辑任务采用创建任务的左右布局和同一套 Markdown 编辑器,保留暂存、取消及保存行为。 +- 日期栏提供日期及时间选择器,时间留空即保存纯日期;选择 00:00 会保留明确的午夜时间。日记写入日期也可以直接选择。 +- 暂停状态统一使用暂停图标。 +- 每个侧边栏视图独立保存筛选预设和临时规则,顶部显示当前筛选名称。切换视图会恢复该视图的筛选。 +- 右上角“重置过滤器”用于清除当前页面临时筛选、预设及项目选择;它不是重建任务索引。其他窗口的筛选事件不再串入当前页面。 +- 已删除设置中的旧全局筛选配置、对应类型和执行逻辑。旧设置中残留的全局规则不再参与任务过滤。 + +## 习惯、积分与奖励 + +- 设置 → 习惯 → “忽略所有过去漏打卡的习惯”:一次忽略今天之前的漏打卡提醒。它只记录提醒截止点,保留全部习惯记录、周期和积分;未来漏打卡仍会正常提醒。 +- 积分与奖励保持同一页面并使用全宽。积分明细左侧为积分记录,右侧为习惯积分;数字统一右对齐。 +- 积分明细可以筛选最近 7 天和最近 30 天,范围包含今天。零积分习惯不显示。 +- 习惯积分按每日贡献汇总筛选,保留每周/每月额度规则,不会因筛选范围截断而重新计算错额度。 + +## 生效和验证范围 + +安装只替换插件的 main.js、styles.css、manifest.json。Obsidian 保持运行;保存正在编辑的内容后,手动关闭并重新开启 Task Genius 一次即可加载。 + +- 类型检查、发布构建和中英文覆盖检查通过。 +- 界面检查 68/68,习惯检查 64/64。 +- 完整 Jest 检查:1412 通过,146 项已有失败;与 9.13.7 逐项比较无新增失败。 +- 独立浏览器检查覆盖 1280px、640px 两种宽度,100 条未安排任务、重叠事件、工作时段、当前时间线、积分全宽和数字对齐。 +- 自动检查使用独立样例,没有连接正在使用的 Obsidian 界面;加载后的实际使用仍由你试用验收。 + +日历子模块修复保存在 `patches/calendar-layout.json`,绑定原始子模块版本。发布构建使用 `pnpm build:release` 自动应用并构建补丁;补丁可重复执行,遇到未知上游改动会停止,避免发布漏修版本。 diff --git a/docs/fixes-9.13.9.md b/docs/fixes-9.13.9.md new file mode 100644 index 000000000..cef2af42a --- /dev/null +++ b/docs/fixes-9.13.9.md @@ -0,0 +1,25 @@ +# Task Genius 9.13.9 试用说明 + +## 本次修改 + +1. 日历网格保留创建任务操作,打开周期笔记改为点击顶部日期标题。月视图标题打开月记,周视图标题打开周记,日视图标题打开日记,年视图标题打开年记。移除单独的四个笔记按钮,避免同一次点击既打开日记又弹出新任务窗口。 +2. 新建与编辑任务窗口加宽,日期和时间同排显示,日期标签保持完整;窄窗口可以滚动。 +3. 编辑任务直接继承新建任务表单,复用同一编辑器、预览、字段及布局。保存按钮仍用于更新原任务,保留原任务 ID 和未修改的信息。积分、标签、依赖位于双方共用的“更多属性”中;取消编辑不保存任务,也不改新建任务的模式偏好。 +4. 暂停状态统一使用暂停图标。即使关闭可选的 Task Genius 自定义任务图标,暂停图标仍会显示;原图标开关不被改动。 +5. 时间栏旁增加“× 清除时间”。清除后保留日期,保存和重新索引后仍为纯日期;正文的自然语言日期不会把手动清除的时间再填回来。清空表单也会同步清空可见的日期与时间控件。 +6. 顶部显示完整筛选名称,窄窗口不遮挡视图按钮。 +7. “忽略所有过去漏打卡的习惯”移入设置 → 习惯 → 常规,保留已有记录和积分。 +8. 积分明细筛选今天、最近 7 天、最近 30 天时,打卡记录数与积分使用相同时间范围。 +9. 选择项目后以项目笔记作为任务写入位置,任务预览和保存内容不再重复加入项目标签或行内项目字段。 + +## 加载新版 + +保存正在编辑的内容后,手动关闭并重新开启 Task Genius 一次即可。安装只替换 main.js、styles.css、manifest.json,并备份旧程序和现存原始记录;设置及记录文件保持不变。 + +## 验证 + +- 78 项界面检查、64 项习惯检查通过。 +- 完整 Jest 检查:1414 通过,145 项已有失败;与 9.13.8 比较没有新增失败测试或失败测试组。 +- 类型、翻译及发布构建检查通过。 +- 独立浏览器在 1280px、640px 宽度下检查:新建/编辑使用相同表单尺寸,日期与时间同排,弹窗高度可控,筛选名称完整且不与视图按钮重叠。 +- 验证使用独立测试样例,没有连接或控制你正在使用的 Obsidian 窗口。新版加载后的实际使用仍由你试用验收。 diff --git a/docs/habits-integration.md b/docs/habits-integration.md new file mode 100644 index 000000000..6f98cf7d1 --- /dev/null +++ b/docs/habits-integration.md @@ -0,0 +1,37 @@ +# Habits in Task Genius + +This integrates the complete Habits 1.12.1 implementation (MIT, James Clifford Spratt, commit `38c44bc`) into Task Genius's existing Habit view and legacy settings navigation. Vendored code and license are in `src/integrations/habits/`; no zm4341 fork code is used. + +## Supported features + +- Binary, repetition (including decimals), timed and note-backed habits; minimum targets and maximum limits. +- Daily, selected weekdays, monthly dates, fixed intervals, flexible weekly/monthly quotas, planned times, weekly/monthly goals. +- An additional completion-based interval mode: overdue habits remain actionable; completing one restarts the interval from that date. Maximum limits retain fixed scheduling. +- Carousel/grid/vertical/compact dashboards, sidebar panel, grouping, manual sorting, comments with tags/links, animations and mobile layouts. +- Individual metrics and comparisons, monthly/history views, vault heatmaps, weekly/monthly/custom statistics and trends. +- Pause/resume, fail/skip/undo, snooze, stop/resume tracking, missed-instance review and rescheduling. +- PDF export, opt-in AI summaries, Reminder bidirectional checkboxes, note-habit completion and Templater integration. The original experimental switches remain available. +- All original configurable frontmatter keys, plus `intervalMode`; Chinese and English string/placeholder coverage checks. + +## Data and compatibility + +Every habit is a Markdown note in the configurable **Habits folder**. Existing Habits notes are read directly. Changing the folder changes the data source; it does not move or delete files. First initialization reads the standalone plugin's compatible settings; API credentials and automatic Reminder writes are not imported. + +Task Genius's original daily-note-based cards and settings remain under **Existing Task Genius habits**. **Import existing records** previews the note count and destination, then creates notes through Obsidian's vault API. Every note includes a full `taskGeniusLegacy.source` snapshot; originals are untouched. Repeating an import skips matching identities, including renamed imports. Conflicting files are never overwritten. A scheduled habit becomes one binary note per event; mapping habits retain numeric values and their complete original mapping in the snapshot. Import is a snapshot, not continuous synchronization with old daily-note properties: continue recording in one system after importing. + +The new settings live under `habitsIntegration` in Task Genius's existing settings file. The embedded module never writes an independent plugin settings file. + +## Coexistence + +Task Genius always registers `tg-habits`, `tg-habit-metrics`, `tg-habits-table`, and `tg-habits-heatmap`. Its commands insert these prefixed blocks. Existing unprefixed languages are also registered if standalone Habits is disabled when Task Genius initializes. If disabling standalone Habits after Task Genius has loaded, reload Task Genius once to claim its old code blocks. Obsidian itself need not restart. + +While standalone Habits is enabled, Task Genius does not perform automatic note-habit or Reminder synchronization. This prevents duplicate background writes; the dashboard still shares and edits the same Markdown notes. To use Task Genius as the sole replacement, disable standalone Habits and enable the desired integrations in Task Genius. AI requests require a deliberate action and configured endpoint; no real user data was sent during development. + +## Validation + +- `pnpm test:habits`: upstream compact/dashboard interaction and frequency tests, plus integration tests for rolling intervals, folder changes, legacy import, coexistence, disposal, reminders, note completion, comments, mocked AI requests, actual PDF creation and settings rendering in both languages. +- `pnpm check:i18n`: original settings coverage and all statically translated habit strings, including matching placeholders. +- `pnpm build:release`: workspace packages, TypeScript and production JavaScript/CSS. +- Full original Jest suite has existing failures. Compare failures against the unchanged legacy release under the same dependencies; do not suppress or mark those tests skipped. + +Tests use isolated fixtures and a simulated browser document. Final interaction checks in a running Obsidian vault, canvas chart appearance, device-specific mobile rendering and real third-party plugin/network behavior remain manual acceptance checks. Development does not replace the installed plugin or alter live records. diff --git a/docs/native-checkin-9.13.3.md b/docs/native-checkin-9.13.3.md new file mode 100644 index 000000000..120ca7241 --- /dev/null +++ b/docs/native-checkin-9.13.3.md @@ -0,0 +1,48 @@ +# Native check-in, points, and project management + +## Points and rewards + +The main Points and rewards view and the settings tab use the same native component. The four tabs are Daily check-in, Bonuses and rewards, Points history, and Points rules. + +The existing Markdown points file remains the data source. `manualPointRecords`, `examplePropertyLeft`, `examplePropertyRight`, `defaultPointRule`, and `pointRules` are retained. Habit notes continue to own their `records` and `bravoPoints` fields. The default legacy file is discovered automatically; the data path can be changed under Points rules. + +Habit points are calculated from the notes whenever records or rules change. No historical habit points are copied into a second ledger. The precedence is a habit's `bravoPoints`, an explicit panel rule, then the default rule. Negative rates preserve the existing daily, weekly, or monthly allowance calculation. Manual additions and reward redemptions use the Markdown ledger. Existing task point transactions remain available alongside that ledger. + +Task points default to zero. A task can carry its own points value, or a default can be set explicitly. The former random-reward form is replaced; its stored configuration is retained for compatibility. Only rewards with an explicit point cost appear in the new catalog. + +## Habit schedules + +- **Every two days with catch-up:** choose Every N days, interval 2, From actual completion. A missed occurrence remains actionable; the next interval follows the actual completion. +- **Three active days in four:** choose Every N days, interval 4, Work and rest cycle, active days 3. The first three days each require a separate check-in; the fourth is a rest day. +- **Weekly quota with daily completion:** choose Weekly (any day), period target 3, daily completion target 1. A single creation finishes that day's card while the weekly total continues to accumulate. +- **Restart a cycle:** edit the habit and choose Restart cycle on. The restart is stored separately from the original start date and records, so earlier history is retained. + +The existing one-completion check-in window is a separate option from a work/rest cycle. + +## Projects and project plans + +Project notes are discovered by their `project` property, including notes in existing directories. New projects create Markdown notes in an existing `Tasks/Projects` folder, or otherwise in `Projects`. + +Task creation, project reassignment, and quick capture route tasks into the project's note. Inline project ownership markers are removed during transfer. Parent tasks retain their children and indented notes. A legacy project's context menu can consolidate its tasks into a note. Saved display preferences cannot recreate a project that no longer has a task or note. + +Project details can be edited from the sidebar and project overview. Name changes update the `project` property. Archive and restore are available through the project actions and archive manager. Archived project tasks are omitted from normal task views. Project plans uses the Gantt surface with one row per project note; clicking a row opens the note, and its context menu edits project dates or archives it. + +Review is hidden and no longer initialized in the Fluent interface. Stored review routes continue to resolve to projects. The onboarding restart control is removed. + +## Search and saved filters + +Task search remains available in specialized views. Tables receive the final filtered task collection. Saved filters can be created, edited, removed, and selected from the quick-filter menu. The condition builder supports AND/OR combinations; advanced queries also support NOT, parentheses, fields, priorities, missing dates, and local-day relative dates such as `due:today`. + +Points and habit pages provide their own search. The native points history also filters by today, earned points, and spent points. + +## Verification + +- Build, release-file consistency, and English/Chinese string checks pass. +- Habit integration: 54 tests pass. +- UI regression: 24 tests pass. +- Points, project transfers, project plans, query filters, and index notifications: 28 focused tests pass. +- The full Jest suite retains 39 failing suites and 147 failing tests, matching the previously observed baseline counts. It is not an all-green suite. + +`scripts/audit-native-points.cjs` compares the native calculation against the original check-in page for a compatible legacy vault and can write a local report of source-file hashes. Test fixtures and the public layout preview use example data. + +Installation replaces the plugin's code files after backup. Existing Markdown check-in data is read in place. A plugin reload is required to load the new code; an application restart is not required. diff --git a/docs/previews/native-checkin-and-points.svg b/docs/previews/native-checkin-and-points.svg new file mode 100644 index 000000000..a7ad435df --- /dev/null +++ b/docs/previews/native-checkin-and-points.svg @@ -0,0 +1,33 @@ + + + +积分与奖励 +签到、积累积分,再兑换你想要的奖励。 ++ 记录积分 + +可用积分240 + +今日积分实时更新 + +习惯 / 打卡记录18 / 365 + + +每日打卡 +加分与奖励 +积分流水 +积分规则 + +⌕ 搜索习惯、奖励和流水 + +加分项编辑 +读完一本书 + 20完成创作里程碑 + 50完成学习计划 + 30月度目标奖励 + 100 + +记录积分记录积分记录积分记录积分 + +奖励愿望编辑 +一日旅行学习课程一本新书新的游戏一杯咖啡 +500 积分300 积分200 积分 +兑换 · 80 +兑换 · 15 +布局预览 · 示例数据 · 直接使用原有习惯笔记和积分数据 + diff --git a/docs/previews/points-and-rewards-layout.svg b/docs/previews/points-and-rewards-layout.svg new file mode 100644 index 000000000..53af14616 --- /dev/null +++ b/docs/previews/points-and-rewards-layout.svg @@ -0,0 +1,15 @@ + + + +Task GeniusWORKSPACE +收件箱今天即将到期积分与奖励项目计划习惯 +积分与奖励完成任务、记录加分,并用积分兑换你设定的奖励+ 手动记一笔 + +可用积分1,280↑ 85 本周获得本月获得+420来自 36 项已完成任务奖励进度周末电影之夜720 / 900 积分 + +积分明细全部 获得 兑换 +完成:整理实习资料今天 10:42 · hzu 实习+20手动加分:额外运动昨天 19:10 · 备注可追溯+15兑换:咖啡休息11 月 6 日 · 手动兑换−80 +奖励商店用你的积分兑换奖励☕咖啡休息给自己一点放松时间80 积分兑换 +🎬周末电影之夜完成一周计划后的奖励900 积分差 180 +积分规则完成任务自动记分,避免重复入账。每个任务可设置积分,也支持手动加减。兑换记录与积分明细保存在同一账本。 + diff --git a/docs/release-9.13.9.md b/docs/release-9.13.9.md new file mode 100644 index 000000000..0aaaad5e6 --- /dev/null +++ b/docs/release-9.13.9.md @@ -0,0 +1,31 @@ +# Task Genius 9.13.9 + +汇总旧布局维护分支自 9.13.2 以来的习惯集成、项目管理、积分与奖励、任务视图和编辑修复。保留原设置导航与风格。发布源为 PR #3 合并后的 legacy/9.13.1,默认 master 分支不作切换。 + +## 功能与修复 + +- 集成 JamesCliffordSpratt/obsidian-habits 的 Markdown 习惯功能,保留 MIT 许可。支持每个习惯一个 MD、可配置路径、旧记录兼容、目标和上限、间隔与周期、补打卡、重新安排和忽略漏打卡。卡片列数可选,完成状态与图标更清晰。 +- 内置积分与奖励页面,保留原每日打卡与积分数据接入。每日完成任务计分;历史支持日期筛选、对应次数统计、左右对齐与零积分记录隐藏。 +- 项目使用项目笔记管理,支持归档、删除、颜色、手动排序、父文件夹及项目甘特图。向项目归入任务时移动到项目笔记,避免重复项目标签;移动项目时间不会改变成员任务的截止日期。 +- 修复初次打开空白、列表与树切换、视图设置同步、搜索与筛选结果刷新、矩阵旧结果残留。预设筛选跟随工作区和视图;矩阵与看板拖动更新任务属性,表格列宽保存。 +- 普通 Markdown 页面与 Task Genius 共用任务状态和完成日期同步;暂停图标统一。 +- 编辑与新建任务复用同一表单。日期与时间同排,可只填日期,可清除时间。积分、标签与可搜索任务依赖位于更多属性。 +- 日历网格操作用于任务,点击顶部日期标题打开对应日记、周记、月记或年记;移除冲突的额外周期笔记按钮。修复时间事件定位、当前时间线、排期布局与周数显示。 +- 精简无效或冗余设置,移除右侧栏和全局筛选配置,完善中英文翻译与可复现的日历依赖补丁构建。 + +完整修改过程保留在 PR 的逐次提交,以及 docs/native-checkin-9.13.3.md、docs/fixes-9.13.4.md 至 docs/fixes-9.13.9.md、docs/habits-integration.md 和审计记录中。 + +## 安装 + +BRAT 仓库:Platinum1154/taskgenius-plugin,版本:9.13.9。 + +手动安装:保存正在编辑的内容,下载 main.js、styles.css、manifest.json 放入现有插件目录后,手动关闭并开启 Task Genius 一次。也可下载 task-genius-9.13.9.zip。请保留原 data.json 和习惯、每日打卡、积分 Markdown 文件。 + +## 验证及已知限制 + +- 本地类型、翻译、版本检查与生产构建通过。78 项界面回归、64 项习惯回归通过。 +- 完整本地 Jest:1414 通过、145 失败;逐项与 9.13.8 报告比较,没有新增失败用例。另有 3 个套件不能加载,包含在失败套件数中。 +- 同一源码的 GitHub Ubuntu CI:构建和上述专项测试通过;完整 Jest 为 1409 通过、150 失败。CLA 自动检查另因继承的权限配置失败。 +- 完整测试未全绿。失败涉及测试环境缺失及尚未查清的状态、项目、索引、时间、Canvas 等行为;不能据此承诺整套功能没有问题。见 docs/test-failures-9.13.9.md。 +- 独立浏览器验证了宽窄窗口的新建/编辑表单布局;没有将此等同于当前版本在用户真实 Obsidian 环境中的完整验收。 +- 本地安装只替换程序文件,已有设置和记录已备份且校验未变;Release 不包含用户笔记、个人设置或 API 密钥。 diff --git a/docs/test-failures-9.13.9.md b/docs/test-failures-9.13.9.md new file mode 100644 index 000000000..afd95c950 --- /dev/null +++ b/docs/test-failures-9.13.9.md @@ -0,0 +1,568 @@ +# 9.13.9 既有测试失败核对 + +本报告读取保存的完整 Jest 报告,没有重新运行测试,没有修改插件或用户数据。 + +- 总计 1559 个测试:1414 个通过,145 个失败。 +- 130 个测试套件:91 个通过,39 个失败;其中 3 个套件未能加载,不计入上述 145 个失败用例。 +- 逐项对照 9.13.8 报告的测试文件与用例名,本次没有新增失败用例。 +- “既有”仅指此前 9.13.8 已失败;不代表已证明来自上游原版,也不代表不影响实际使用。 +- 本报告按功能归类。失败原因仍需逐项复现,不能仅凭日志全部判定为测试过时或真实缺陷。 + +| 范围 | 失败用例数 | +| --- | ---: | +| 状态切换、父任务联动和日期标记 | 25 | +| 项目识别、属性和日期继承 | 32 | +| 任务操作、Canvas 和工作流 | 43 | +| 文件过滤、索引和缓存 | 30 | +| 时间解析和时间格式 | 7 | +| 性能阈值 | 2 | +| 自动补全和设置迁移 | 4 | +| ICS 日历解析和超时 | 2 | + +## 可以从日志明确看到的情况 + +- 文件过滤的 18 个失败:测试环境中的 Obsidian normalizePath 不存在,未能验证实际过滤行为。 +- 索引的 8 个失败:测试对象没有 workspace.onLayoutReady。 +- 项目工作线程的 4 个失败:测试 vault 没有 getFileByPath。 +- Markdown 归档的 5 个失败:测试变量 mockDate 在初始化前被读取。 +- 上述合计 35 个用例存在明确的测试环境或测试代码问题,不能用它们证明相应功能已通过。 +- 其他失败包括项目识别结果不符、状态切换没有产生预期操作、时间解析时差或格式不符、Canvas 操作失败等,需要继续排查真实代码与测试预期。 +- 性能阈值失败包括中文标签解析超过 100 毫秒,以及重复时间解析未达到预期加速比例;单次结果受运行负载影响。 + +## GitHub 远端检查补充 + +远端 Ubuntu 检查(提交 de456d0,运行 42577368516):安装、生产构建、64 项习惯测试和 78 项界面测试通过。完整 Jest 为 1409 通过、150 失败,40 个套件失败;不能把本地 145 项失败的逐项对比结论直接套用于远端。CLA 检查另因缺少权限而失败,未代签 CLA、未关闭检查或修改分支保护。 + +## 逐项清单 + +### 状态切换、父任务联动和日期标记 + +**cycleCompleteStatus.test.ts:12 项** + +1. handleCycleCompleteStatusTransaction (Integration) should cycle from [ ] to [/] based on default settings + - 报错摘要:Error: expect(received).not.toBe(expected) // Object.is equality Expected: not {"annotation": [Function mockConstructor], "changes": {}, "docChanged": true, "effects": [], "isUserEvent": [Function mockConstructor], "newDoc": {"length": 10, "line": [Function mockConstructor], "lineAt": [Function mockConstructor], "lines": 1, "sliceString": [Function mockConstructor], "toString": [Function toString]}, "newSelection": {"anchor": 0, "empty": true, "from": 0, "head": 0, "to": 0}, "reconfigured": false, "scrollIntoView": false, "selection": {"anchor": 0, "empty": true, "from": 0, "head": 0, "to": 0}, "startState": {"_fields": Map {}, "doc": {"length": 10, "line": [Function mockConstructor], "lineAt": [Function mockConstructor], "lines": 1, "sliceString": [Function mockConstructor], "toString": [Function toString]}, "selection": {"anchor": 0, "empty": true, "from": 0, "head": 0, "to": 0}}, "state": {}} + +2. handleCycleCompleteStatusTransaction (Integration) should cycle from [/] to [x] based on default settings + - 报错摘要:Error: expect(received).not.toBe(expected) // Object.is equality Expected: not {"annotation": [Function mockConstructor], "changes": {}, "docChanged": true, "effects": [], "isUserEvent": [Function mockConstructor], "newDoc": {"length": 10, "line": [Function mockConstructor], "lineAt": [Function mockConstructor], "lines": 1, "sliceString": [Function mockConstructor], "toString": [Function toString]}, "newSelection": {"anchor": 0, "empty": true, "from": 0, "head": 0, "to": 0}, "reconfigured": false, "scrollIntoView": false, "selection": {"anchor": 0, "empty": true, "from": 0, "head": 0, "to": 0}, "startState": {"_fields": Map {}, "doc": {"length": 10, "line": [Function mockConstructor], "lineAt": [Function mockConstructor], "lines": 1, "sliceString": [Function mockConstructor], "toString": [Function toString]}, "selection": {"anchor": 0, "empty": true, "from": 0, "head": 0, "to": 0}}, "state": {}} + +3. handleCycleCompleteStatusTransaction (Integration) should cycle from [x] back to [ ] based on default settings + - 报错摘要:Error: expect(received).not.toBe(expected) // Object.is equality Expected: not {"annotation": [Function mockConstructor], "changes": {}, "docChanged": true, "effects": [], "isUserEvent": [Function mockConstructor], "newDoc": {"length": 10, "line": [Function mockConstructor], "lineAt": [Function mockConstructor], "lines": 1, "sliceString": [Function mockConstructor], "toString": [Function toString]}, "newSelection": {"anchor": 0, "empty": true, "from": 0, "head": 0, "to": 0}, "reconfigured": false, "scrollIntoView": false, "selection": {"anchor": 0, "empty": true, "from": 0, "head": 0, "to": 0}, "startState": {"_fields": Map {}, "doc": {"length": 10, "line": [Function mockConstructor], "lineAt": [Function mockConstructor], "lines": 1, "sliceString": [Function mockConstructor], "toString": [Function toString]}, "selection": {"anchor": 0, "empty": true, "from": 0, "head": 0, "to": 0}}, "state": {}} + +4. handleCycleCompleteStatusTransaction (Integration) should respect custom cycle and marks + - 报错摘要:Error: expect(received).not.toBe(expected) // Object.is equality Expected: not {"annotation": [Function mockConstructor], "changes": {}, "docChanged": true, "effects": [], "isUserEvent": [Function mockConstructor], "newDoc": {"length": 10, "line": [Function mockConstructor], "lineAt": [Function mockConstructor], "lines": 1, "sliceString": [Function mockConstructor], "toString": [Function toString]}, "newSelection": {"anchor": 0, "empty": true, "from": 0, "head": 0, "to": 0}, "reconfigured": false, "scrollIntoView": false, "selection": {"anchor": 0, "empty": true, "from": 0, "head": 0, "to": 0}, "startState": {"_fields": Map {}, "doc": {"length": 10, "line": [Function mockConstructor], "lineAt": [Function mockConstructor], "lines": 1, "sliceString": [Function mockConstructor], "toString": [Function toString]}, "selection": {"anchor": 0, "empty": true, "from": 0, "head": 0, "to": 0}}, "state": {}} + +5. handleCycleCompleteStatusTransaction (Integration) should skip excluded marks in the cycle + - 报错摘要:Error: expect(received).not.toBe(expected) // Object.is equality Expected: not {"annotation": [Function mockConstructor], "changes": {}, "docChanged": true, "effects": [], "isUserEvent": [Function mockConstructor], "newDoc": {"length": 10, "line": [Function mockConstructor], "lineAt": [Function mockConstructor], "lines": 1, "sliceString": [Function mockConstructor], "toString": [Function toString]}, "newSelection": {"anchor": 0, "empty": true, "from": 0, "head": 0, "to": 0}, "reconfigured": false, "scrollIntoView": false, "selection": {"anchor": 0, "empty": true, "from": 0, "head": 0, "to": 0}, "startState": {"_fields": Map {}, "doc": {"length": 10, "line": [Function mockConstructor], "lineAt": [Function mockConstructor], "lines": 1, "sliceString": [Function mockConstructor], "toString": [Function toString]}, "selection": {"anchor": 0, "empty": true, "from": 0, "head": 0, "to": 0}}, "state": {}} + +6. handleCycleCompleteStatusTransaction (Integration) should handle unknown starting mark by cycling to the first status + - 报错摘要:Error: expect(received).not.toBe(expected) // Object.is equality Expected: not {"annotation": [Function mockConstructor], "changes": {}, "docChanged": true, "effects": [], "isUserEvent": [Function mockConstructor], "newDoc": {"length": 10, "line": [Function mockConstructor], "lineAt": [Function mockConstructor], "lines": 1, "sliceString": [Function mockConstructor], "toString": [Function toString]}, "newSelection": {"anchor": 0, "empty": true, "from": 0, "head": 0, "to": 0}, "reconfigured": false, "scrollIntoView": false, "selection": {"anchor": 0, "empty": true, "from": 0, "head": 0, "to": 0}, "startState": {"_fields": Map {}, "doc": {"length": 10, "line": [Function mockConstructor], "lineAt": [Function mockConstructor], "lines": 1, "sliceString": [Function mockConstructor], "toString": [Function toString]}, "selection": {"anchor": 0, "empty": true, "from": 0, "head": 0, "to": 0}}, "state": {}} + +7. handleCycleCompleteStatusTransaction (Integration) should NOT cycle if the inserted mark matches the next mark in sequence + - 报错摘要:Error: expect(received).not.toBe(expected) // Object.is equality Expected: not {"annotation": [Function mockConstructor], "changes": {}, "docChanged": true, "effects": [], "isUserEvent": [Function mockConstructor], "newDoc": {"length": 10, "line": [Function mockConstructor], "lineAt": [Function mockConstructor], "lines": 1, "sliceString": [Function mockConstructor], "toString": [Function toString]}, "newSelection": {"anchor": 0, "empty": true, "from": 0, "head": 0, "to": 0}, "reconfigured": false, "scrollIntoView": false, "selection": {"anchor": 0, "empty": true, "from": 0, "head": 0, "to": 0}, "startState": {"_fields": Map {}, "doc": {"length": 10, "line": [Function mockConstructor], "lineAt": [Function mockConstructor], "lines": 1, "sliceString": [Function mockConstructor], "toString": [Function toString]}, "selection": {"anchor": 0, "empty": true, "from": 0, "head": 0, "to": 0}}, "state": {}} + +8. handleCycleCompleteStatusTransaction (Integration) should cycle task status when user selects and replaces the 'x' mark with any character + - 报错摘要:Error: expect(received).not.toBe(expected) // Object.is equality Expected: not {"annotation": [Function mockConstructor], "changes": {}, "docChanged": true, "effects": [], "isUserEvent": [Function mockConstructor], "newDoc": {"length": 10, "line": [Function mockConstructor], "lineAt": [Function mockConstructor], "lines": 1, "sliceString": [Function mockConstructor], "toString": [Function toString]}, "newSelection": {"anchor": 0, "empty": true, "from": 0, "head": 0, "to": 0}, "reconfigured": false, "scrollIntoView": false, "selection": {"anchor": 0, "empty": true, "from": 0, "head": 0, "to": 0}, "startState": {"_fields": Map {}, "doc": {"length": 10, "line": [Function mockConstructor], "lineAt": [Function mockConstructor], "lines": 1, "sliceString": [Function mockConstructor], "toString": [Function toString]}, "selection": {"anchor": 0, "empty": true, "from": 0, "head": 0, "to": 0}}, "state": {}} + +9. handleCycleCompleteStatusTransaction (Integration) should cycle task status when user selects and replaces any mark with any character + - 报错摘要:Error: expect(received).not.toBe(expected) // Object.is equality Expected: not {"annotation": [Function mockConstructor], "changes": {}, "docChanged": true, "effects": [], "isUserEvent": [Function mockConstructor], "newDoc": {"length": 10, "line": [Function mockConstructor], "lineAt": [Function mockConstructor], "lines": 1, "sliceString": [Function mockConstructor], "toString": [Function toString]}, "newSelection": {"anchor": 0, "empty": true, "from": 0, "head": 0, "to": 0}, "reconfigured": false, "scrollIntoView": false, "selection": {"anchor": 0, "empty": true, "from": 0, "head": 0, "to": 0}, "startState": {"_fields": Map {}, "doc": {"length": 10, "line": [Function mockConstructor], "lineAt": [Function mockConstructor], "lines": 1, "sliceString": [Function mockConstructor], "toString": [Function toString]}, "selection": {"anchor": 0, "empty": true, "from": 0, "head": 0, "to": 0}}, "state": {}} + +10. handleCycleCompleteStatusTransaction (Integration) should correctly detect the original mark in replacement operations + - 报错摘要:Error: expect(received).toHaveLength(expected) Expected length: 1 Received length: 0 Received array: [] + +11. handleCycleCompleteStatusTransaction (Integration) should handle replacement operations where fromA != toA + - 报错摘要:Error: expect(received).toHaveLength(expected) Expected length: 1 Received length: 0 Received array: [] + +12. handleCycleCompleteStatusTransaction (Integration) should test different replacement scenarios to identify the trigger + - 报错摘要:Error: expect(received).toHaveLength(expected) Expected length: 1 Received length: 0 Received array: [] + +**autoCompleteParent.test.ts:5 项** + +13. handleParentTaskUpdateTransaction (Integration) should mark parent as in progress when a child is unchecked (if setting enabled) + - 报错摘要:Error: expect(received).toEqual(expected) // deep equality - Expected - 6 + Received + 1 Array [ - Object { - "type": Object { - "of": [Function mockConstructor], - }, - "value": "autoCompleteParent.IN_PROGRESS", - }, + "autoCompleteParent.IN_PROGRESS", ] + +14. handleParentTaskUpdateTransaction (Integration) should mark parent as in progress when first child gets a status (if setting enabled) + - 报错摘要:Error: expect(received).toEqual(expected) // deep equality - Expected - 6 + Received + 1 Array [ - Object { - "type": Object { - "of": [Function mockConstructor], - }, - "value": "autoCompleteParent.IN_PROGRESS", - }, + "autoCompleteParent.IN_PROGRESS", ] + +15. handleParentTaskUpdateTransaction (Integration) should ignore changes triggered by its own annotation (complete) + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality - Expected - 40 + Received + 10 Object { - "annotation": [Function mockConstructor], - "changes": Object {}, - "docChanged": true, - "effects": Array [], - "isUserEvent": [Function mockConstructor], - "newDoc": Object { - "length": 25, - "line": [Function mockConstructor], - "lineAt": [Function mockConstructor], - "lines": 2, - "sliceString": [Function mockConstructor], - "toString": [Function toString], + "annotations": Array [ + "autoCompleteParent.DONE", + ], + "changes": Array [ + Object {}, + Object { + "from": 3, + "insert": "x", + "to": 4, }, - "newSelection": Object { - "anchor": 0, - "empty": true, - "from": 0, - "head": 0, - "to": 0, - }, - "reconfigured": false, - "scrollIntoView": false, - "selection": Object { - "anchor": 0, - "empty": true, - "from": 0, - "head": 0, - "to": 0, - }, - "startState": EditorState { - "_fields": Map {}, - "doc": Object { - "length": 25, - "line": [Function mockConstructor], - "lineAt": [Function mockConstructor], - "lines": 2, - "sliceString": [Function mockConstructor], - "toStrin + +16. handleParentTaskUpdateTransaction (Integration) should ignore changes triggered by its own annotation (in progress) + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality - Expected - 40 + Received + 10 Object { - "annotation": [Function mockConstructor], - "changes": Object {}, - "docChanged": true, - "effects": Array [], - "isUserEvent": [Function mockConstructor], - "newDoc": Object { - "length": 25, - "line": [Function mockConstructor], - "lineAt": [Function mockConstructor], - "lines": 2, - "sliceString": [Function mockConstructor], - "toString": [Function toString], + "annotations": Array [ + "autoCompleteParent.IN_PROGRESS", + ], + "changes": Array [ + Object {}, + Object { + "from": 3, + "insert": "/", + "to": 4, }, - "newSelection": Object { - "anchor": 0, - "empty": true, - "from": 0, - "head": 0, - "to": 0, - }, - "reconfigured": false, - "scrollIntoView": false, - "selection": Object { - "anchor": 0, - "empty": true, - "from": 0, - "head": 0, - "to": 0, - }, - "startState": EditorState { - "_fields": Map {}, - "doc": Object { - "length": 25, - "line": [Function mockConstructor], - "lineAt": [Function mockConstructor], - "lines": 2, - "sliceString": [Function mockConstructor], - " + +17. handleParentTaskUpdateTransaction (Integration) should mark parent as in progress when one child is completed but others remain incomplete + - 报错摘要:Error: expect(received).toEqual(expected) // deep equality - Expected - 6 + Received + 1 Array [ - Object { - "type": Object { - "of": [Function mockConstructor], - }, - "value": "autoCompleteParent.IN_PROGRESS", - }, + "autoCompleteParent.IN_PROGRESS", ] + +**autoDateManager.improved.test.ts:2 项** + +18. Improved Date Insertion Logic Metadata Positioning should insert cancelled date after start date + - 报错摘要:Error: expect(received).toBeGreaterThan(expected) Expected: > 24 Received: 24 + +19. Improved Date Insertion Logic Edge Cases should handle task with only spaces + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: 6 Received: 9 + +**autoDateManager.integration.test.ts:1 项** + +20. autoDateManager - Integration Test should handle cancelled date insertion with real transaction + - 报错摘要:Error: No status change found + +**autoDateManager.pause-conflict.test.ts:3 项** + +21. autoDateManager - Pause Timer Conflict should identify conflict when pausing timer changes status to abandoned + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: "abandoned" Received: "inProgress" + +22. autoDateManager - Pause Timer Conflict should show that '-' marker is ambiguous (used for both pause and abandoned) + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: "abandoned" Received: "inProgress" + +23. autoDateManager - Pause Timer Conflict should demonstrate the specific user scenario + - 报错摘要:Error: expect(received).toContainEqual(expected) // deep equality Expected value: {"dateType": "cancelled", "format": "YYYY-MM-DD", "type": "add"} Received array: [] + +**autoDateManager.realworld.test.ts:2 项** + +24. autoDateManager - Real World Test should handle user's exact case + - 报错摘要:Error: DEBUG INFO: - Line: - [-] 交流交底 🚀 2025-07-30 [stage::disclosure_communication] 🛫 2025-04-20 ^timer-161940-4775 - Position: 72 - Text before: "- [-] 交流交底 🚀 2025-07-30 [stage::disclosure_communication] 🛫 2025-04-20" - Text after: " ^timer-161940-4775" - Character at position: " " - Block ref index: 73 + +25. autoDateManager - Real World Test should test with debugging enabled + - 报错摘要:Error: expect(received).toBeGreaterThan(expected) Expected: > 24 Received: 24 + +### 项目识别、属性和日期继承 + +**TaskParsingService.integration.test.ts:3 项** + +26. TaskParsingService Integration Enhanced project parsing should parse tasks with config file-based projects + - 报错摘要:Error: expect(received).toEqual(expected) // deep equality - Expected - 2 + Received + 2 Object { "name": "Research Project", "readonly": true, - "source": "project.md", - "type": "config", + "source": "project", + "type": "metadata", } + +27. TaskParsingService Integration Metadata mappings should inherit project-level attributes to tasks + - 报错摘要:Error: expect(received).toEqual(expected) // deep equality - Expected - 2 + Received + 2 Object { "name": "Test Project", "readonly": true, - "source": "project.md", - "type": "config", + "source": "project", + "type": "metadata", } + +28. TaskParsingService Integration Priority order integration should prioritize path mappings over metadata and config + - 报错摘要:Error: expect(received).toEqual(expected) // deep equality - Expected - 3 + Received + 3 Object { - "name": "Path Priority Project", + "name": "Metadata Project", "readonly": true, - "source": "Priority", - "type": "path", + "source": "project", + "type": "metadata", } + +**ProjectConfigManager.test.ts:12 项** + +29. ProjectConfigManager Metadata-based project detection should detect project from file frontmatter + - 报错摘要:Error: expect(received).toEqual(expected) // deep equality Expected: {"name": "My Project", "readonly": true, "source": "project", "type": "metadata"} Received: undefined + +30. ProjectConfigManager Metadata-based project detection should use custom metadata key + - 报错摘要:Error: expect(received).toEqual(expected) // deep equality Expected: {"name": "Custom Project", "readonly": true, "source": "proj", "type": "metadata"} Received: undefined + +31. ProjectConfigManager Config file-based project detection should detect project from config file + - 报错摘要:Error: expect(received).toEqual(expected) // deep equality Expected: {"name": "Config Project", "readonly": true, "source": "project.md", "type": "config"} Received: undefined + +32. ProjectConfigManager Config file-based project detection should parse project from config file content + - 报错摘要:Error: expect(received).toEqual(expected) // deep equality Expected: {"name": "Content Project", "readonly": true, "source": "project.md", "type": "config"} Received: undefined + +33. ProjectConfigManager Metadata mappings should apply metadata mappings + - 报错摘要:Error: expect(received).toEqual(expected) // deep equality - Expected - 7 + Received + 1 - Object { - "due": 1704038400000, - "due_date": "2024-01-01", - "other": "value", - "proj": "Mapped Project", - "project": "Mapped Project", - } + Object {} + +34. ProjectConfigManager Metadata mappings should ignore disabled mappings + - 报错摘要:Error: expect(received).toEqual(expected) // deep equality - Expected - 3 + Received + 1 - Object { - "proj": "Should Not Map", - } + Object {} + +35. ProjectConfigManager Default project naming should use metadata value as project name + - 报错摘要:Error: expect(received).toEqual(expected) // deep equality Expected: {"name": "Global Project", "readonly": true, "source": "metadata", "type": "default"} Received: undefined + +36. ProjectConfigManager Priority order should prioritize metadata over config file + - 报错摘要:Error: expect(received).toEqual(expected) // deep equality Expected: {"name": "Metadata Project", "readonly": true, "source": "project", "type": "metadata"} Received: undefined + +37. ProjectConfigManager Priority order should prioritize config file over default naming + - 报错摘要:Error: expect(received).toEqual(expected) // deep equality - Expected - 3 + Received + 3 Object { - "name": "Config Project", + "name": "task", "readonly": true, - "source": "project.md", - "type": "config", + "source": "filename", + "type": "default", } + +38. ProjectConfigManager Caching should cache project config data + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: "Cached Project" Received: undefined + +39. ProjectConfigManager Caching should clear cache when options change + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: "Original Project" Received: undefined + +40. ProjectConfigManager Enhanced project feature flag should allow enabling/disabling enhanced project features + - 报错摘要:Error: expect(received).toEqual(expected) // deep equality Expected: {"project": "Test Project"} Received: null + +**ProjectDataWorkerManager.test.ts:4 项** + +41. ProjectDataWorkerManager Project Data Computation should get project data using cache first + - 报错摘要:TypeError: this.vault.getFileByPath is not a function + +42. ProjectDataWorkerManager Project Data Computation should handle batch project data requests + - 报错摘要:TypeError: this.vault.getFileByPath is not a function + +43. ProjectDataWorkerManager Project Data Computation should fallback to sync computation when workers fail + - 报错摘要:TypeError: this.vault.getFileByPath is not a function + +44. ProjectDataWorkerManager Cache Management should handle file events + - 报错摘要:TypeError: this.vault.getFileByPath is not a function + +**FileMetadataInheritanceDebug.test.ts:1 项** + +45. Debug File Metadata Inheritance should debug inheritance process + - 报错摘要:Error: Debug detailed info: Config enabled: true File metadata keys: priority, testField File metadata values: {"priority":"high","testField":"testValue"} Task metadata keys: tags, priority, startDate, dueDate, scheduledDate, completedDate, createdDate, cancelledDate, recurrence, project, context, area, id, dependsOn, onCompletion, children, heading, parent, tgProject Task metadata: {"tags":[],"priority":4,"children":[],"heading":[]} Task priority: 4 (type: number) Task testField: undefined (exists: false) Priority inherited: true TestField inherited: false + +**TagsInheritanceInvestigation.test.ts:1 项** + +46. Tags Inheritance Investigation should investigate what fields are being inherited incorrectly + - 报错摘要:Error: expect(received).toContain(expected) // indexOf Expected value: "mobility" Received array: ["#mobility"] + +**ProjectDetectionFixes.test.ts:6 项** + +47. Project Detection Fixes Metadata Detection Enable/Disable should detect project from frontmatter when metadata detection is enabled + - 报错摘要:Error: expect(received).toBeDefined() Received: undefined + +48. Project Detection Fixes Metadata Detection Enable/Disable should respect different metadata keys + - 报错摘要:Error: expect(received).toBeDefined() Received: undefined + +49. Project Detection Fixes Config File Detection Enable/Disable should detect project from config file when config file detection is enabled + - 报错摘要:Error: expect(received).toBeDefined() Received: undefined + +50. Project Detection Fixes Search Recursively Setting should search parent directories when searchRecursively is true + - 报错摘要:Error: expect(received).toBeDefined() Received: undefined + +51. Project Detection Fixes Detection Method Priority and Independence should fall back to metadata when path mapping is disabled + - 报错摘要:Error: expect(received).toBeDefined() Received: undefined + +52. Project Detection Fixes Detection Method Priority and Independence should fall back to config file when both path and metadata are disabled + - 报错摘要:Error: expect(received).toBeDefined() Received: undefined + +**DateInheritanceService.test.ts:1 项** + +53. DateInheritanceService metadata date parsing should handle invalid metadata dates gracefully + - 报错摘要:Error: expect(received).toBeNull() Received: undefined + +**DateInheritanceIntegration.test.ts:4 项** + +54. DateInheritanceService Integration file metadata parsing should handle invalid metadata gracefully + - 报错摘要:Error: expect(received).toBeNull() Received: undefined + +55. DateInheritanceService Integration integration scenarios should handle complex folder structures + - 报错摘要:Error: expect(received).toBeNull() Received: undefined + +56. DateInheritanceService Integration integration scenarios should handle files without dates gracefully + - 报错摘要:Error: expect(received).toBeNull() Received: undefined + +57. DateInheritanceService Integration integration scenarios should handle missing files gracefully + - 报错摘要:Error: expect(received).toBeNull() Received: undefined + +### 任务操作、Canvas 和工作流 + +**CompleteActionExecutor.test.ts:9 项** + +58. CompleteActionExecutor Task Completion should complete related tasks successfully + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: true Received: false + +59. CompleteActionExecutor Task Completion should skip already completed tasks + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: true Received: false + +60. CompleteActionExecutor Task Completion should handle task not found + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: true Received: false + +61. CompleteActionExecutor Task Completion should handle task update error + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: true Received: false + +62. CompleteActionExecutor Task Completion should handle no task manager available + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: "Task manager not available" Received: "Failed: Task not found: related-task-1, Task not found: related-task-2" + +63. CompleteActionExecutor Task Completion should preserve existing task metadata + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: true Received: false + +64. CompleteActionExecutor Error Handling should handle general execution error + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: "Failed: task1: Unexpected error" Received: "Failed: Task not found: task1" + +65. CompleteActionExecutor Edge Cases should handle single task completion + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: true Received: false + +66. CompleteActionExecutor Edge Cases should handle large number of tasks + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: true Received: false + +**ArchiveActionExecutor.canvas.test.ts:9 项** + +67. ArchiveActionExecutor - Canvas Tasks Canvas Task Archiving should successfully archive Canvas task to default archive file + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: true Received: false + +68. ArchiveActionExecutor - Canvas Tasks Canvas Task Archiving should successfully archive Canvas task to custom archive file + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: true Received: false + +69. ArchiveActionExecutor - Canvas Tasks Canvas Task Archiving should create archive file if it does not exist + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: true Received: false + +70. ArchiveActionExecutor - Canvas Tasks Canvas Task Archiving should handle Canvas deletion failure after successful archive + - 报错摘要:Error: expect(received).toContain(expected) // indexOf Expected substring: "Task archived successfully to Archive/Completed Tasks.md, but failed to remove from Canvas: Canvas node not found" Received string: "Error archiving Canvas task: Cannot read properties of undefined (reading 'deleteCanvasTask')" + +71. ArchiveActionExecutor - Canvas Tasks Canvas Task Archiving should create new section if section does not exist + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: true Received: false + +72. ArchiveActionExecutor - Canvas Tasks OnCompletion Metadata Cleanup should remove onCompletion metadata when archiving Canvas task + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: true Received: false + +73. ArchiveActionExecutor - Canvas Tasks OnCompletion Metadata Cleanup should remove onCompletion metadata in JSON format when archiving + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: true Received: false + +74. ArchiveActionExecutor - Canvas Tasks OnCompletion Metadata Cleanup should ensure task is marked as completed when archiving + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: true Received: false + +75. ArchiveActionExecutor - Canvas Tasks OnCompletion Metadata Cleanup should remove dataview format onCompletion when archiving + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: true Received: false + +**MoveActionExecutor.canvas.test.ts:5 项** + +76. MoveActionExecutor - Canvas Tasks Canvas to Canvas Movement should successfully move Canvas task to another Canvas file + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: true Received: false + +77. MoveActionExecutor - Canvas Tasks Canvas to Canvas Movement should handle Canvas to Canvas move failure + - 报错摘要:Error: expect(received).toContain(expected) // indexOf Expected substring: "Target Canvas file not found" Received string: "Error moving Canvas task: Cannot read properties of undefined (reading 'moveCanvasTask')" + +78. MoveActionExecutor - Canvas Tasks Canvas to Markdown Movement should successfully move Canvas task to Markdown file + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: true Received: false + +79. MoveActionExecutor - Canvas Tasks Canvas to Markdown Movement should create target Markdown file if it does not exist + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: true Received: false + +80. MoveActionExecutor - Canvas Tasks Canvas to Markdown Movement should handle Canvas deletion failure after successful move + - 报错摘要:Error: expect(received).toContain(expected) // indexOf Expected substring: "Task moved successfully to target.md, but failed to remove from Canvas: Canvas node not found" Received string: "Failed to move Canvas task to Markdown: Cannot read properties of undefined (reading 'deleteCanvasTask')" + +**DeleteActionExecutor.canvas.test.ts:4 项** + +81. DeleteActionExecutor - Canvas Tasks Canvas Task Deletion should successfully delete a Canvas task + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: true Received: false + +82. DeleteActionExecutor - Canvas Tasks Canvas Task Deletion should handle Canvas task deletion failure + - 报错摘要:Error: expect(received).toContain(expected) // indexOf Expected substring: "Canvas node not found" Received string: "Error deleting Canvas task: Cannot read properties of undefined (reading 'deleteCanvasTask')" + +83. DeleteActionExecutor - Canvas Tasks Canvas Task Deletion should handle Canvas task updater exceptions + - 报错摘要:Error: expect(received).toContain(expected) // indexOf Expected substring: "Error deleting Canvas task: Network error" Received string: "Error deleting Canvas task: Cannot read properties of undefined (reading 'deleteCanvasTask')" + +84. DeleteActionExecutor - Canvas Tasks Canvas Task Deletion should correctly identify Canvas tasks + - 报错摘要:Error: expect(jest.fn()).toHaveBeenCalled() Expected number of calls: >= 1 Received number of calls: 0 + +**CanvasTaskUpdater.test.ts:1 项** + +85. CanvasTaskUpdater updateCanvasTask should handle tasks with identical names and metadata correctly + - 报错摘要:Error: expect(received).toContain(expected) // indexOf Expected substring: "- [ ] Task In Canvas 📅 2025-06-21" Received string: "# Tasks with Same Names· - [x] Task In Canvas #SO/旅行 - [ ] Task In Canvas 🛫 2025-06-21 - [ ] Task In Canvas #SO/旅行 - [ ] Task In Canvas - [ ] A new day" + +**ArchiveActionExecutor.markdown.test.ts:5 项** + +86. ArchiveActionExecutor - Markdown Tasks Markdown Task Archiving should successfully archive Markdown task with onCompletion metadata cleanup + - 报错摘要:ReferenceError: Cannot access 'mockDate' before initialization + +87. ArchiveActionExecutor - Markdown Tasks Markdown Task Archiving should ensure incomplete Markdown task is marked as completed when archived + - 报错摘要:ReferenceError: Cannot access 'mockDate' before initialization + +88. ArchiveActionExecutor - Markdown Tasks Markdown Task Archiving should remove dataview format onCompletion from Markdown task + - 报错摘要:ReferenceError: Cannot access 'mockDate' before initialization + +89. ArchiveActionExecutor - Markdown Tasks Markdown Task Archiving should remove JSON format onCompletion from Markdown task + - 报错摘要:ReferenceError: Cannot access 'mockDate' before initialization + +90. ArchiveActionExecutor - Markdown Tasks Error Handling should handle source file not found + - 报错摘要:ReferenceError: Cannot access 'mockDate' before initialization + +**DuplicateActionExecutor.canvas.test.ts:3 项** + +91. DuplicateActionExecutor - Canvas Tasks Canvas to Canvas Duplication should successfully duplicate Canvas task within same file + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: true Received: false + +92. DuplicateActionExecutor - Canvas Tasks Canvas to Canvas Duplication should successfully duplicate Canvas task to different Canvas file + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: true Received: false + +93. DuplicateActionExecutor - Canvas Tasks Canvas to Canvas Duplication should handle Canvas duplication failure + - 报错摘要:Error: expect(received).toContain(expected) // indexOf Expected substring: "Target Canvas file not found" Received string: "Error duplicating Canvas task: Cannot read properties of undefined (reading 'duplicateCanvasTask')" + +**workflow.test.ts:7 项** + +94. Workflow Functionality processTimestampAndCalculateTime should calculate spent time and remove timestamp + - 报错摘要:TypeError: startTime.isValid is not a function + +95. Workflow Functionality processTimestampAndCalculateTime should calculate total time for final stage + - 报错摘要:TypeError: startTime.isValid is not a function + +96. Workflow Functionality determineTaskInsertionPoint should return line end when no child tasks + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: 50 Received: 17 + +97. Workflow Functionality Time Calculation Edge Cases should handle invalid timestamp format + - 报错摘要:TypeError: startTime.isValid is not a function + +98. Workflow Functionality Time Calculation Edge Cases should handle missing workflow definition during time calculation + - 报错摘要:TypeError: startTime.isValid is not a function + +99. Workflow Functionality Workflow Settings Integration should respect calculateSpentTime setting + - 报错摘要:TypeError: startTime.isValid is not a function + +100. Workflow Functionality Complex Document Structure Tests should handle workflow tasks with time tracking + - 报错摘要:TypeError: startTime.isValid is not a function + +### 文件过滤、索引和缓存 + +**FileFilterManager.test.ts:10 项** + +101. FileFilterManager Basic Filtering should allow all files when disabled + - 报错摘要:TypeError: (0 , obsidian_1.normalizePath) is not a function + +102. FileFilterManager Basic Filtering should filter files in blacklist mode + - 报错摘要:TypeError: (0 , obsidian_1.normalizePath) is not a function + +103. FileFilterManager Basic Filtering should filter files in whitelist mode + - 报错摘要:TypeError: (0 , obsidian_1.normalizePath) is not a function + +104. FileFilterManager Pattern Matching should match wildcard patterns + - 报错摘要:TypeError: (0 , obsidian_1.normalizePath) is not a function + +105. FileFilterManager Folder Hierarchy should match nested folders + - 报错摘要:TypeError: (0 , obsidian_1.normalizePath) is not a function + +106. FileFilterManager Rule Management should respect disabled rules + - 报错摘要:TypeError: (0 , obsidian_1.normalizePath) is not a function + +107. FileFilterManager Rule Management should update configuration dynamically + - 报错摘要:TypeError: (0 , obsidian_1.normalizePath) is not a function + +108. FileFilterManager Performance and Caching should cache filter results + - 报错摘要:TypeError: (0 , obsidian_1.normalizePath) is not a function + +109. FileFilterManager Performance and Caching should clear cache when configuration changes + - 报错摘要:TypeError: (0 , obsidian_1.normalizePath) is not a function + +110. FileFilterManager Statistics should provide accurate statistics + - 报错摘要:TypeError: (0 , obsidian_1.normalizePath) is not a function + +**FileFilterIntegration.test.ts:8 项** + +111. File Filter Integration Tests End-to-End Filtering Scenarios should handle typical vault structure with system folders excluded + - 报错摘要:TypeError: (0 , obsidian_1.normalizePath) is not a function + +112. File Filter Integration Tests End-to-End Filtering Scenarios should handle whitelist mode for focused project work + - 报错摘要:TypeError: (0 , obsidian_1.normalizePath) is not a function + +113. File Filter Integration Tests End-to-End Filtering Scenarios should handle complex pattern matching scenarios + - 报错摘要:TypeError: (0 , obsidian_1.normalizePath) is not a function + +114. File Filter Integration Tests Performance and Caching should demonstrate caching performance benefits + - 报错摘要:TypeError: (0 , obsidian_1.normalizePath) is not a function + +115. File Filter Integration Tests Performance and Caching should handle large numbers of files efficiently + - 报错摘要:TypeError: (0 , obsidian_1.normalizePath) is not a function + +116. File Filter Integration Tests Configuration Updates should handle dynamic configuration changes correctly + - 报错摘要:TypeError: (0 , obsidian_1.normalizePath) is not a function + +117. File Filter Integration Tests Edge Cases and Error Handling should handle empty and invalid paths gracefully + - 报错摘要:TypeError: (0 , obsidian_1.normalizePath) is not a function + +118. File Filter Integration Tests Edge Cases and Error Handling should handle disabled rules correctly + - 报错摘要:TypeError: (0 , obsidian_1.normalizePath) is not a function + +**TaskIndexer.mtime.test.ts:8 项** + +119. TaskIndexer mtime functionality mtime comparison should detect file changes when mtime is newer + - 报错摘要:TypeError: Cannot read properties of undefined (reading 'onLayoutReady') + +120. TaskIndexer mtime functionality mtime comparison should not detect changes when mtime is same + - 报错摘要:TypeError: Cannot read properties of undefined (reading 'onLayoutReady') + +121. TaskIndexer mtime functionality mtime comparison should detect changes for unknown files + - 报错摘要:TypeError: Cannot read properties of undefined (reading 'onLayoutReady') + +122. TaskIndexer mtime functionality cache validation should have valid cache when file hasn't changed and has tasks + - 报错摘要:TypeError: Cannot read properties of undefined (reading 'onLayoutReady') + +123. TaskIndexer mtime functionality cache validation should not have valid cache when file has changed + - 报错摘要:TypeError: Cannot read properties of undefined (reading 'onLayoutReady') + +124. TaskIndexer mtime functionality cache validation should not have valid cache when no tasks exist + - 报错摘要:TypeError: Cannot read properties of undefined (reading 'onLayoutReady') + +125. TaskIndexer mtime functionality cache cleanup should clean up file cache properly + - 报错摘要:TypeError: Cannot read properties of undefined (reading 'onLayoutReady') + +126. TaskIndexer mtime functionality cache consistency should validate and fix cache consistency + - 报错摘要:TypeError: Cannot read properties of undefined (reading 'onLayoutReady') + +**TaskWorkerManager.mtime.test.ts:4 项** + +127. TaskWorkerManager mtime optimization cache optimization should skip processing files with valid cache + - 报错摘要:TypeError: indexer.updateIndexWithTasks is not a function + +128. TaskWorkerManager mtime optimization cache optimization should process files when cache is invalid + - 报错摘要:TypeError: indexer.updateIndexWithTasks is not a function + +129. TaskWorkerManager mtime optimization cache optimization should optimize batch processing + - 报错摘要:TypeError: indexer.updateIndexWithTasks is not a function + +130. TaskWorkerManager mtime optimization configuration should respect mtime optimization setting + - 报错摘要:TypeError: indexer.updateIndexWithTasks is not a function + +### 时间解析和时间格式 + +**TimeParsingService.test.ts:2 项** + +131. TimeParsingService Chinese Time Expressions should parse "后天" + - 报错摘要:Error: expect(received).toBeLessThanOrEqual(expected) Expected: <= 2 Received: 5 + +132. TimeParsingService Multiple Date Types should parse multiple different date types + - 报错摘要:Error: expect(received).toBeGreaterThan(expected) Expected: > 1 Received: 1 + +**EnhancedTimeParsingEdgeCases.test.ts:2 项** + +133. Enhanced Time Parsing Edge Cases Edge Cases with Context should handle time expressions at start of text + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: 14 Received: undefined + +134. Enhanced Time Parsing Edge Cases Edge Cases with Context should handle multiple time expressions in one text + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: 14 Received: 16 + +**EnhancedTimeParsingIntegration.test.ts:1 项** + +135. Enhanced Time Parsing Integration Tests ICS Event Integration with Enhanced Time Parsing should handle ICS all-day events with time parsing from description + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: 9 Received: 17 + +**TaskMetadataUtils.test.ts:2 项** + +136. TaskMetadataUtils timestampToTimeComponent should convert timestamp to time component correctly + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: "14:30" Received: "14:30:45" + +137. TaskMetadataUtils timestampToTimeComponent should handle midnight correctly + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: 0 Received: undefined + +### 性能阈值 + +**chinese-tag-performance.test.ts:1 项** + +138. Chinese Tag Parsing Performance should efficiently parse large number of Chinese nested tags + - 报错摘要:Error: expect(received).toBeLessThan(expected) Expected: < 100 Received: 397.0059999999994 + +**EnhancedTimeParsingPerformance.test.ts:1 项** + +139. Enhanced Time Parsing Performance Tests Time Parsing Performance Impact should benefit from caching on repeated parsing + - 报错摘要:Error: expect(received).toBeLessThan(expected) Expected: < 1.6149500000001353 Received: 2.8995999999997366 + +### 自动补全和设置迁移 + +**SuggestBackwardCompatibility.test.ts:3 项** + +140. Backward Compatibility Tests should provide fallback suggestions when new system returns empty + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: 4 Received: 0 + +141. Backward Compatibility Tests should handle selectSuggestion with both new and legacy actions + - 报错摘要:Error: expect(jest.fn()).toHaveBeenCalledWith(...expected) - Expected + Received Object { - "ch": 4, + "ch": 3, "line": 0, }, Number of calls: 1 + +142. Backward Compatibility Tests should handle legacy modal-based actions + - 报错摘要:Error: expect(jest.fn()).toHaveBeenCalled() Expected number of calls: >= 1 Received number of calls: 0 + +**SettingsMigration.test.ts:1 项** + +143. Settings Migration runAllMigrations should not run cleanup if migration fails + - 报错摘要:Error: expect(received).toBe(expected) // Object.is equality Expected: false Received: true + +### ICS 日历解析和超时 + +**ics-parser.test.ts:1 项** + +144. ICS Parser Date Parsing should handle current year events + - 报错摘要:Error: expect(received).toBeGreaterThan(expected) Expected: > 0 Received: 0 + +**ics-timeout-fix.test.ts:1 项** + +145. ICS Timeout Fix Network Timeout should categorize timeout errors correctly + - 报错摘要:Error: expect(received).toContain(expected) // indexOf Expected substring: "timeout" Received string: "cannot read properties of undefined (reading 'status')" + +## 另外 3 个未能加载的测试套件 + +- **TimelineSidebarView.test.ts**:● Test suite failed to run Cannot find module '../components/MarkdownRenderer' from 'src/__tests__/TimelineSidebarView.test.ts' 56 | })); 57 | > 58 | jest.mock('../components/MarkdownRenderer', () => ({ | ^ 59 | MarkdownRendererComponent: class MockMarkdownRendererComponent {}, 60 | })); 61 | at Resolver._throwModNotFoundError (node_modules/.pnpm/jest-resolve@29.7.0/node_modules/jest-resolve/build/resolver.js:427:11) at Object. (src/__tests__/TimelineSidebarView.test.ts:58:6) + +- **QuickCaptureModal.integration.test.ts**:● Test suite failed to run Cannot find module '../components/AutoComplete' from 'src/__tests__/QuickCaptureModal.integration.test.ts' 119 | })); 120 | > 121 | jest.mock("../components/AutoComplete", () => ({ | ^ 122 | FileSuggest: jest.fn(), 123 | ContextSuggest: jest.fn(), 124 | ProjectSuggest: jest.fn(), at Resolver._throwModNotFoundError (node_modules/.pnpm/jest-resolve@29.7.0/node_modules/jest-resolve/build/resolver.js:427:11) at Object. (src/__tests__/QuickCaptureModal.integration.test.ts:121:6) + +- **dateTemplates.test.ts**:● Test suite failed to run TypeError: Class extends value undefined is not a constructor or null 282 | } 283 | > 284 | export class ProjectCreateModal extends Modal { | ^ 285 | constructor(app: App, private manager: ProjectFileManager, private onSave: () => void) { super(app); } 286 | onOpen() { 287 | this.setTitle(t("New project")); const folder = projectFolderPicker(this.contentEl, this.manager, ""); let name = "", description = "", color = "#5985b1"; at Object. (src/managers/project-file-manager.ts:284:41) at Object. (src/utils/file/file-operations.ts:4:1) at Object. (src/__tests__/dateTemplates.test.ts:1:1) + diff --git "a/docs/\344\271\240\346\203\257\345\212\237\350\203\275\344\275\277\347\224\250\346\214\207\345\215\227.md" "b/docs/\344\271\240\346\203\257\345\212\237\350\203\275\344\275\277\347\224\250\346\214\207\345\215\227.md" new file mode 100644 index 000000000..104952737 --- /dev/null +++ "b/docs/\344\271\240\346\203\257\345\212\237\350\203\275\344\275\277\347\224\250\346\214\207\345\215\227.md" @@ -0,0 +1,54 @@ +# Task Genius 习惯功能使用指南 + +## 开始使用 + +1. 打开 Task Genius 设置 → **习惯**,开启习惯功能。主设置的导航和旧布局保持不变。 +2. 在习惯设置的**常规**中指定**习惯文件夹**。每个习惯保存为一个 Markdown 文件。已有 Habits 文件可直接读取。 +3. 打开 Task Genius 的习惯页,点击**创建习惯**。也可以用命令面板中的 Task Genius: Habits 命令创建习惯、打开侧栏,或插入看板、统计、表格、热力图。 + +修改文件夹只切换读取位置,不会自动搬动旧文件。要搬家,请在 Obsidian 文件列表中移动习惯文件,再修改设置中的目录。 + +## 选择习惯类型和排期 + +| 需求 | 选择方式 | +| --- | --- | +| 每天阅读,做了就打卡 | 二元习惯 + 每天 | +| 每天喝水 2 升,每次增加 0.25 升 | 计数习惯,目标 2,步长 0.25,单位 L | +| 学习或运动累计多少分钟 | 计时习惯,目标使用分钟 | +| 每周任意三天健身 | 每周灵活目标,目标 3 次 | +| 每月累计一定数量 | 每月灵活目标 | +| 周一、周三、周五固定执行 | 每周,选择多个星期 | +| 隔一天健身,补做后继续隔一天 | 每隔 N 天,N=2,排期选择**从实际完成日期计算** | +| 戒除某事、控制摄入上限 | 上限目标;二元上限表示当天一次也不做 | +| 通过写笔记或完成笔记内清单打卡 | 在实验功能开启笔记习惯,再创建笔记类型 | + +固定间隔沿用开始日期。按实际完成日期间隔时,漏做会一直保留待办;例如 1 日完成、3 日漏做、4 日补做,下一次是 6 日。上限目标使用固定排期。 + +## 日常操作 + +切换日期可以补记历史数据。勾选或增加次数后,数值会写进对应习惯文件的记录属性;撤销打卡也会更新文件。计数支持小数。 + +右键或长按习惯可以编辑、打开原文件、暂停、跳过、标为失败、稍后提醒,或停止追踪。**停止追踪**保留历史;恢复后继续记录。删除操作有确认框。 + +评论可写标签和笔记链接,保存在习惯 Markdown 正文的日志区中。请保留日志区域的开始、结束标记。 + +布局可选轮播、网格、纵向或紧凑列表,并可设置分组、颜色、图标及排序。侧栏适合快速打卡;详情和统计页适合查看历史、趋势、连续记录和不同习惯的对比。统计页也可导出 PDF。 + +## 旧记录与原有 Habits 插件 + +已有 Habits 的习惯文件不需要转换。首次接入会读取它的目录、字段名称等兼容设置,不会复制 API 密钥,也不会自动开启对外写入。 + +原 Task Genius 的日记属性记录仍在**原有 Task Genius 习惯**中可用。点击**导入原有记录**,确认数量和目录后可转成独立习惯文件。原始数据不修改,完整来源快照也会写入新笔记;重复导入会跳过已导入项目。计划型旧习惯按事件拆分,映射型按数值导入,原选项定义保存在来源快照中。 + +导入是一次快照,之后请选择新习惯或旧日记属性中的一种方式继续记录,避免两套记录分叉。 + +独立 Habits 仍开启时,自动提醒和笔记同步由它负责。准备完全改用 Task Genius 时,关闭独立 Habits,再重新加载 Task Genius 一次,使旧笔记中的代码块也交给 Task Genius;无需重启 Obsidian。新插入的代码块使用 `tg-` 前缀,可在两者并存时使用。 + +## 可选集成 + +- **Reminder**:在常规设置启用,选择每日笔记或固定提醒文件,并给习惯设置时间。提醒清单的勾选和习惯记录双向同步。需要自行安装并启用 Reminder 才能获得其通知功能。 +- **笔记习惯 / Templater**:在实验功能开启。可按字数、清单全部完成、清单完成指定数量,或组合条件判定。模板使用 Templater 语法时需启用 Templater。 +- **漏做改期**:在实验功能开启,再通过漏做列表选择新的执行日期。 +- **AI 总结**:在实验功能开启,填写自己的兼容接口、模型和密钥。只有点击生成总结时才向所配置服务发送统计内容;这不是打卡必需功能。 + +文件变化应直接反映到习惯页。手动编辑时请保持 YAML 格式正确,并确保文件位于当前配置的目录;更改字段名称请使用高级设置中的“应用属性名修改”,让已有记录一起更新。 diff --git a/esbuild.config.mjs b/esbuild.config.mjs index 2a524ba61..844dc1954 100644 --- a/esbuild.config.mjs +++ b/esbuild.config.mjs @@ -89,7 +89,7 @@ const copyManifestPlugin = { const buildOptions = { banner: { - js: banner, + js: banner + "\n/*! Habits integration: " + fs.readFileSync("src/integrations/habits/LICENSE", "utf8") + " */\n", }, minify: prod ? true : false, entryPoints: ["src/index.ts"], diff --git a/manifest-beta.json b/manifest-beta.json index 0804ea3c9..a58ed6613 100644 --- a/manifest-beta.json +++ b/manifest-beta.json @@ -1,10 +1,10 @@ { - "id": "obsidian-task-progress-bar", - "name": "Task Genius", - "version": "9.13.1", - "minAppVersion": "0.15.2", - "description": "Comprehensive task management that includes progress bars, task status cycling, and advanced task tracking features.", - "author": "Boninall", - "authorUrl": "https://github.com/Quorafind", - "isDesktopOnly": false -} \ No newline at end of file + "id": "obsidian-task-progress-bar", + "name": "Task Genius", + "version": "9.13.15", + "minAppVersion": "0.15.2", + "description": "Comprehensive task management that includes progress bars, task status cycling, and advanced task tracking features.", + "author": "Boninall", + "authorUrl": "https://github.com/Quorafind", + "isDesktopOnly": false +} diff --git a/manifest.json b/manifest.json index fa2b10c63..a58ed6613 100644 --- a/manifest.json +++ b/manifest.json @@ -1,10 +1,10 @@ { "id": "obsidian-task-progress-bar", "name": "Task Genius", - "version": "9.13.1", + "version": "9.13.15", "minAppVersion": "0.15.2", "description": "Comprehensive task management that includes progress bars, task status cycling, and advanced task tracking features.", "author": "Boninall", "authorUrl": "https://github.com/Quorafind", "isDesktopOnly": false -} \ No newline at end of file +} diff --git a/package.json b/package.json index 781e2d9a3..99b84b755 100644 --- a/package.json +++ b/package.json @@ -1,11 +1,11 @@ { "name": "task-genius", - "version": "9.13.1", + "version": "9.13.15", "description": "Comprehensive task management plugin for Obsidian with progress bars, task status cycling, and advanced task tracking features.", "main": "main.js", "scripts": { "dev": "node esbuild.config.mjs", - "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", + "build": "node scripts/patch-calendar.cjs --check && pnpm check:i18n && pnpm check:release && tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && git add manifest.json manifest-beta.json versions.json", "e-t": "cross-env node scripts/extract-translations.cjs", "g-l": "cross-env node scripts/generate-locale-files.cjs", @@ -22,7 +22,13 @@ "release:beta:patch": "node scripts/smart-beta-release.mjs patch", "release:beta:minor": "node scripts/smart-beta-release.mjs minor", "release:beta:major": "node scripts/smart-beta-release.mjs major", - "release:beta:dry": "node scripts/smart-beta-release.mjs --dry-run" + "release:beta:dry": "node scripts/smart-beta-release.mjs --dry-run", + "check:i18n": "node scripts/check-settings-i18n.cjs && node scripts/check-habits-i18n.cjs", + "check:release": "node scripts/check-release-version.cjs", + "build:release": "node scripts/patch-calendar.cjs && pnpm --filter esbuild-plugin-inline-worker build && pnpm --filter @taskgenius/calendar build && pnpm build", + "test:habits": "node --test tests/habits/*.test.mjs", + "check:habits-css": "node scripts/scope-habits-css.mjs", + "test:ui": "node --test tests/ui-audit/*.test.mjs" }, "keywords": [ "obsidian", @@ -66,7 +72,9 @@ "semver": "^7.7.2", "ts-jest": "^29.1.0", "tslib": "2.4.0", - "typescript": "4.7.3" + "typescript": "4.7.3", + "postcss": "^8.5.6", + "postcss-selector-parser": "^7.1.0" }, "dependencies": { "@popperjs/core": "^2.11.8", @@ -79,6 +87,10 @@ "obsidian-daily-notes-interface": "^0.9.4", "regexp-match-indices": "^1.0.2", "rrule": "^2.8.1", - "sortablejs": "^1.15.6" - } + "sortablejs": "^1.15.6", + "chart.js": "^4.4.0", + "chartjs-chart-matrix": "^3.0.5", + "jspdf": "^4.2.1" + }, + "packageManager": "pnpm@10.26.0" } diff --git a/packages/calendar b/packages/calendar index 3107a754e..3cb570633 160000 --- a/packages/calendar +++ b/packages/calendar @@ -1 +1 @@ -Subproject commit 3107a754e650b64cb5dd68101ebbad99ac422f27 +Subproject commit 3cb570633ae01ab569b26a956639fc167da398ba diff --git a/patches/calendar-layout.json b/patches/calendar-layout.json new file mode 100644 index 000000000..10b10e399 --- /dev/null +++ b/patches/calendar-layout.json @@ -0,0 +1,99 @@ +{ + "upstream": "taskgenius/calendar@3cb570633ae01ab569b26a956639fc167da398ba", + "files": [ + { + "file": "src/renderers/TimeRenderer.ts", + "baseline": "f905eca7e49da57256610aff857f2a83a561664fffd30b7008c4c72df4dd55eb", + "result": "9561d07116f2559ffbd97193cafdeb017e6b841e3588f71ee681427e2a584542", + "steps": [ + { + "before": "\n for (const col of columns) {\n const cell = createElement(\"div\", \"tg-time-header-cell\");\n\n // Build filter context\n const dayOfWeek = this.adapter.day(col.date);\n", + "after": "\n for (const col of columns) {\n const cell = createElement(\"div\", \"tg-time-header-cell\");\n cell.dataset[\"date\"] = col.dateStr;\n\n // Build filter context\n const dayOfWeek = this.adapter.day(col.date);\n" + }, + { + "before": " ): HTMLElement {\n const col = createElement(\"div\", \"tg-day-column\");\n col.dataset[\"date\"] = colData.dateStr;\n\n // Set height via CSS custom property for dynamic time slots\n if (timeSlots && timeSlots.length > 0) {\n", + "after": " ): HTMLElement {\n const col = createElement(\"div\", \"tg-day-column\");\n col.dataset[\"date\"] = colData.dateStr;\n col.dataset[\"visibleHours\"] = JSON.stringify((timeSlots || []).map(slot => slot.hour));\n\n // Set height via CSS custom property for dynamic time slots\n if (timeSlots && timeSlots.length > 0) {\n" + }, + { + "before": " const layout = this.engine.calculateLayout(events, colData.dateStr);\n\n for (const item of layout) {\n const eventEl = this.renderEventBlock(\n item,\n dragController,\n", + "after": " const layout = this.engine.calculateLayout(events, colData.dateStr);\n\n for (const item of layout) {\n // Layout and hit testing must use the same compressed clock when hours are hidden.\n if (timeSlots) {\n const pixels = (minute: number) => timeSlots.reduce((sum, slot) => sum + Math.max(0, Math.min(60, minute - slot.hour * 60)) / 60 * this.theme.cellHeight, 0);\n const top = pixels(item.startMin), end = pixels(item.endMin);\n if (end <= top) continue;\n item.top = top; item.height = Math.max(1, end - top);\n }\n const eventEl = this.renderEventBlock(\n item,\n dragController,\n" + }, + { + "before": " }\n\n return col;\n }\n\n private renderEventBlock(\n", + "after": " }\n\n return col;\n }\n\n /** Update in place: the clock must not rerender or interrupt an active drag. */\n updateCurrentTime(container: HTMLElement, timeFilter?: (hour: number) => TimeFilterResult): void {\n container.querySelectorAll(\".tg-now-line\").forEach(line => line.remove());\n const now = new Date(), date = this.adapter.format(this.adapter.create(now), this.dateFormats.date);\n const column = Array.from(container.querySelectorAll(\".tg-day-column\")).find(col => col.dataset[\"date\"] === date);\n const slots = this.engine.generateTimeSlots(timeFilter), index = slots.findIndex(slot => slot.hour === now.getHours());\n if (!column || index < 0) return;\n const line = createElement(\"div\", \"tg-now-line\");\n line.setAttribute(\"aria-label\", `${String(now.getHours()).padStart(2, \"0\")}:${String(now.getMinutes()).padStart(2, \"0\")}`);\n line.style.top = `${(index + now.getMinutes() / 60) * this.theme.cellHeight}px`;\n column.appendChild(line);\n }\n\n private renderEventBlock(\n" + }, + { + "before": "\n // Use transform for GPU-accelerated positioning\n // translateX uses percentage for responsive width positioning\n el.style.transform = `translate(${item.leftPercent}%, ${item.top}px)`;\n el.style.width = `calc(${item.widthPercent}% - 2px)`;\n el.style.height = `${item.height}px`;\n el.style.backgroundColor = bgColor;\n", + "after": "\n // Use transform for GPU-accelerated positioning\n // translateX uses percentage for responsive width positioning\n el.style.left = `${item.leftPercent}%`;\n el.style.transform = `translateY(${item.top}px)`;\n el.style.width = `calc(${item.widthPercent}% - 2px)`;\n el.style.height = `${item.height}px`;\n el.style.backgroundColor = bgColor;\n" + } + ] + }, + { + "file": "src/views/TimeView.ts", + "baseline": "10fa830f6e1a7e04a1277450b4be841567cad60683278fb34e07d42d4c047ac8", + "result": "b20721d65d42e4d7d18abdc34ccb27b3bf5e1834454baf213fd49114bb57630c", + "steps": [ + { + "before": " protected engine!: TimeEngine;\n protected renderer!: TimeRenderer;\n protected timeViewType: ViewType = \"week\";\n\n /**\n * Initialize the view with context and create engine/renderer\n", + "after": " protected engine!: TimeEngine;\n protected renderer!: TimeRenderer;\n protected timeViewType: ViewType = \"week\";\n private nowTimer: ReturnType | undefined;\n override onUnmount(): void { if (this.nowTimer) clearInterval(this.nowTimer); this.nowTimer = undefined; super.onUnmount(); }\n\n /**\n * Initialize the view with context and create engine/renderer\n" + }, + { + "before": " | undefined,\n this.context.config.view.timeFormatter as TimeFormatter | undefined,\n );\n }\n\n /**\n", + "after": " | undefined,\n this.context.config.view.timeFormatter as TimeFormatter | undefined,\n );\n if (this.nowTimer) clearInterval(this.nowTimer);\n const updateClock = () => this.renderer.updateCurrentTime(container, this.context.config.view.timeFilter as ((hour: number) => TimeFilterResult) | undefined);\n updateClock(); this.nowTimer = setInterval(updateClock, 60_000);\n }\n\n /**\n" + } + ] + }, + { + "file": "src/styles/time.css", + "baseline": "911b15eea607c0173a361c86861f8c64ad9b7f74528fac28911d814982c7079a", + "result": "a84c1d69427b0e767894d2021d8d7d5d0bc0abc237a03c42e65ba703e5db4165", + "steps": [ + { + "before": " pointer-events: none;\n box-sizing: border-box;\n}\n", + "after": " pointer-events: none;\n box-sizing: border-box;\n}\n\n.tg-now-line { position:absolute; left:0; right:0; height:2px; background:#e5484d; z-index:70; pointer-events:none; }\n" + } + ] + }, + { + "file": "src/core/DragController.ts", + "baseline": "af1dd4d9c76303964ca9e11824a9ee03ccd1cddb8dfa793dfde50f3ca8934809", + "result": "e8c5126f060933b6fe56819387c25ca5da141166926e576a0c1628bc18d6791c", + "steps": [ + { + "before": " const rect = col.getBoundingClientRect();\n const relY = e.clientY - rect.top;\n\n const rawMins = (relY / this.cellHeight) * 60;\n const snapMinutes = this.config.dateOnly\n ? 1440 // Date-only mode: snap to full day (24 hours)\n : this.config.snapMinutes || 15;\n", + "after": " const rect = col.getBoundingClientRect();\n const relY = e.clientY - rect.top;\n\n const visible: number[] = JSON.parse(col.dataset[\"visibleHours\"] || \"[]\");\n const row = Math.max(0, Math.min(visible.length - 1, Math.floor(relY / this.cellHeight)));\n const rawMins = visible.length ? visible[row]! * 60 + Math.max(0, Math.min(60, (relY / this.cellHeight - row) * 60)) : (relY / this.cellHeight) * 60;\n const snapMinutes = this.config.dateOnly\n ? 1440 // Date-only mode: snap to full day (24 hours)\n : this.config.snapMinutes || 15;\n" + }, + { + "before": " if (!col) return;\n\n const startMin = this.adapter.hour(start) * 60 + this.adapter.minute(start);\n const top = startMin * (this.cellHeight / 60);\n const height =\n this.adapter.diff(end, start, \"minute\") * (this.cellHeight / 60);\n\n const ghost = createElement(\"div\", \"tg-ghost-event\");\n setStyles(ghost, {\n", + "after": " if (!col) return;\n\n const startMin = this.adapter.hour(start) * 60 + this.adapter.minute(start);\n const visible: number[] = JSON.parse(col.dataset[\"visibleHours\"] || \"[]\");\n const pixels = (minute: number) => visible.length ? visible.reduce((sum, hour) => sum + Math.max(0, Math.min(60, minute - hour * 60)) / 60 * this.cellHeight, 0) : minute / 60 * this.cellHeight;\n const top = pixels(startMin);\n const height = pixels(startMin + this.adapter.diff(end, start, \"minute\")) - top;\n\n const ghost = createElement(\"div\", \"tg-ghost-event\");\n setStyles(ghost, {\n" + } + ] + }, + { + "file": "src/core/InteractionController.ts", + "baseline": "00772cde1203ea64a31dfe5ec0e7a5e58db21916579b931145cfb080f265118e", + "result": "4555174dc53ba61461d8ea3ca7291f6ee837f9fc0c5d6aa0925503886dac3176", + "steps": [ + { + "before": "\t\tconst cellHeight = this.config.theme.cellHeight;\n\t\tconst snapMinutes = this.config.draggable.snapMinutes;\n\n\t\tconst rawMinutes = (relY / cellHeight) * 60;\n\t\tconst snappedMinutes = Math.max(\n\t\t\t0,\n\t\t\tMath.min(1440, Math.round(rawMinutes / snapMinutes) * snapMinutes),\n", + "after": "\t\tconst cellHeight = this.config.theme.cellHeight;\n\t\tconst snapMinutes = this.config.draggable.snapMinutes;\n\n\t\tconst visible: number[] = JSON.parse(colEl.dataset[\"visibleHours\"] || \"[]\");\n\t\tconst row = Math.max(0, Math.min(visible.length - 1, Math.floor(relY / cellHeight)));\n\t\tconst rawMinutes = visible.length ? visible[row]! * 60 + Math.max(0, Math.min(60, (relY / cellHeight - row) * 60)) : (relY / cellHeight) * 60;\n\t\tconst snappedMinutes = Math.max(\n\t\t\t0,\n\t\t\tMath.min(1440, Math.round(rawMinutes / snapMinutes) * snapMinutes),\n" + }, + { + "before": "\t\t\t\tthis.adapter.hour(endDate) * 60 + this.adapter.minute(endDate);\n\n\t\t\tconst cellHeight = this.config.theme.cellHeight;\n\t\t\tconst top = (startMin / 60) * cellHeight;\n\t\t\tconst height = ((endMin - startMin) / 60) * cellHeight;\n\n\t\t\tconst preview = createElement(\"div\", \"tg-time-range-preview\");\n\t\t\tsetStyles(preview, {\n", + "after": "\t\t\t\tthis.adapter.hour(endDate) * 60 + this.adapter.minute(endDate);\n\n\t\t\tconst cellHeight = this.config.theme.cellHeight;\n\t\t\tconst visible: number[] = JSON.parse(col.dataset[\"visibleHours\"] || \"[]\");\n\t\t\tconst pixels = (minute: number) => visible.length ? visible.reduce((sum, hour) => sum + Math.max(0, Math.min(60, minute - hour * 60)) / 60 * cellHeight, 0) : minute / 60 * cellHeight;\n\t\t\tconst top = pixels(startMin);\n\t\t\tconst height = pixels(endMin) - top;\n\n\t\t\tconst preview = createElement(\"div\", \"tg-time-range-preview\");\n\t\t\tsetStyles(preview, {\n" + } + ] + }, + { + "file": "src/engines/TimeEngine.ts", + "baseline": "8546bc9c54494322a123a2663bef9f004c3fc58e815d35921afba8d01b9661b2", + "result": "de9fddff464a7e410295866a12483a02c5837177d32ba13d4a1f7188545addf8", + "steps": [ + { + "before": "\n // Width multiplier determines how much each event extends into neighbor space\n // Adjust based on column count for better visual balance\n const widthMultiplier = numCols <= 3 ? 1.6 : numCols <= 5 ? 1.5 : 1.4;\n\n for (const ev of group) {\n const leftOffset = ev.colIndex * offsetPerCol;\n", + "after": "\n // Width multiplier determines how much each event extends into neighbor space\n // Adjust based on column count for better visual balance\n const widthMultiplier = 1; // Keep overlapping tasks in adjacent lanes, never covering another task.\n\n for (const ev of group) {\n const leftOffset = ev.colIndex * offsetPerCol;\n" + } + ] + } + ] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d12f410de..733f2b19b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -4,6 +4,10 @@ settings: autoInstallPeers: true excludeLinksFromLockfile: false +overrides: + obsidian-daily-notes-interface>obsidian: 1.10.3 + dompurify: ^3.4.16 + importers: .: @@ -17,12 +21,21 @@ importers: '@types/sortablejs': specifier: ^1.15.8 version: 1.15.9 + chart.js: + specifier: ^4.4.0 + version: 4.6.1 + chartjs-chart-matrix: + specifier: ^3.0.5 + version: 3.1.0(chart.js@4.6.1) chrono-node: specifier: ^2.7.6 version: 2.9.0 date-fns: specifier: ^4.1.0 version: 4.1.0 + jspdf: + specifier: ^4.2.1 + version: 4.2.1 localforage: specifier: ^1.10.0 version: 1.10.0 @@ -59,10 +72,10 @@ importers: version: 4.3.0 '@release-it/bumper': specifier: ^7.0.5 - version: 7.0.5(release-it@19.0.6(@types/node@16.18.126)(magicast@0.3.5)) + version: 7.0.5(release-it@19.0.6(@types/node@16.18.126)(magicast@0.3.5)(supports-color@10.2.2)) '@release-it/conventional-changelog': specifier: ^10.0.1 - version: 10.0.2(conventional-commits-filter@5.0.0)(conventional-commits-parser@6.2.1)(release-it@19.0.6(@types/node@16.18.126)(magicast@0.3.5)) + version: 10.0.2(conventional-commits-filter@5.0.0)(conventional-commits-parser@6.2.1)(release-it@19.0.6(@types/node@16.18.126)(magicast@0.3.5)(supports-color@10.2.2)) '@types/jest': specifier: ^29.5.0 version: 29.5.14 @@ -71,10 +84,10 @@ importers: version: 16.18.126 '@typescript-eslint/eslint-plugin': specifier: ^5.2.0 - version: 5.62.0(@typescript-eslint/parser@5.62.0(eslint@8.57.1)(typescript@4.7.3))(eslint@8.57.1)(typescript@4.7.3) + version: 5.62.0(@typescript-eslint/parser@5.62.0(eslint@8.57.1(supports-color@10.2.2))(supports-color@10.2.2)(typescript@4.7.3))(eslint@8.57.1(supports-color@10.2.2))(supports-color@10.2.2)(typescript@4.7.3) '@typescript-eslint/parser': specifier: ^5.2.0 - version: 5.62.0(eslint@8.57.1)(typescript@4.7.3) + version: 5.62.0(eslint@8.57.1(supports-color@10.2.2))(supports-color@10.2.2)(typescript@4.7.3) builtin-modules: specifier: ^3.2.0 version: 3.3.0 @@ -104,25 +117,31 @@ importers: version: 9.1.7 jest: specifier: ^29.5.0 - version: 29.7.0(@types/node@16.18.126) + version: 29.7.0(@types/node@16.18.126)(supports-color@10.2.2) jest-environment-jsdom: specifier: ^29.5.0 - version: 29.7.0 + version: 29.7.0(supports-color@10.2.2) jszip: specifier: ^3.10.1 version: 3.10.1 monkey-around: specifier: ^3.0.0 version: 3.0.0 + postcss: + specifier: ^8.5.6 + version: 8.5.6 + postcss-selector-parser: + specifier: ^7.1.0 + version: 7.1.7 release-it: specifier: ^19.0.4 - version: 19.0.6(@types/node@16.18.126)(magicast@0.3.5) + version: 19.0.6(@types/node@16.18.126)(magicast@0.3.5)(supports-color@10.2.2) semver: specifier: ^7.7.2 version: 7.7.3 ts-jest: specifier: ^29.1.0 - version: 29.4.5(@babel/core@7.28.5)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.28.5))(esbuild@0.25.9)(jest-util@29.7.0)(jest@29.7.0(@types/node@16.18.126))(typescript@4.7.3) + version: 29.4.5(@babel/core@7.28.5(supports-color@10.2.2))(@jest/transform@29.7.0(supports-color@10.2.2))(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.28.5(supports-color@10.2.2))(supports-color@10.2.2))(esbuild@0.25.9)(jest-util@29.7.0)(jest@29.7.0(@types/node@16.18.126)(supports-color@10.2.2))(typescript@4.7.3) tslib: specifier: 2.4.0 version: 2.4.0 @@ -141,7 +160,7 @@ importers: version: 20.19.25 '@vitest/coverage-v8': specifier: ^1.0.0 - version: 1.6.1(vitest@1.6.1) + version: 1.6.1(supports-color@10.2.2)(vitest@1.6.1) '@vitest/ui': specifier: ^1.0.0 version: 1.6.1(vitest@1.6.1) @@ -150,10 +169,10 @@ importers: version: 1.11.19 jsdom: specifier: ^23.0.0 - version: 23.2.0 + version: 23.2.0(supports-color@10.2.2) release-it: specifier: ^19.0.6 - version: 19.0.6(@types/node@20.19.25)(magicast@0.3.5) + version: 19.0.6(@types/node@20.19.25)(magicast@0.3.5)(supports-color@10.2.2) terser: specifier: ^5.26.0 version: 5.44.1 @@ -171,10 +190,10 @@ importers: version: 5.4.21(@types/node@20.19.25)(terser@5.44.1) vite-plugin-dts: specifier: ^3.6.0 - version: 3.9.1(@types/node@20.19.25)(rollup@4.53.3)(typescript@5.9.3)(vite@5.4.21(@types/node@20.19.25)(terser@5.44.1)) + version: 3.9.1(@types/node@20.19.25)(rollup@4.53.3)(supports-color@10.2.2)(typescript@5.9.3)(vite@5.4.21(@types/node@20.19.25)(terser@5.44.1)) vitest: specifier: ^1.0.0 - version: 1.6.1(@types/node@20.19.25)(@vitest/ui@1.6.1)(jsdom@23.2.0)(terser@5.44.1) + version: 1.6.1(@types/node@20.19.25)(@vitest/ui@1.6.1)(jsdom@23.2.0(supports-color@10.2.2))(supports-color@10.2.2)(terser@5.44.1) wrangler: specifier: ^4.51.0 version: 4.51.0 @@ -357,6 +376,10 @@ packages: peerDependencies: '@babel/core': ^7.0.0-0 + '@babel/runtime@7.29.13': + resolution: {integrity: sha512-v+oN26xP4YIlQsbQ/CbTH1WG5m/l/DjKKZNy/Kp3f/AFvbgt7Em/D0FeMM3O2hX0YzeN2M16W8lOpyhIkfCBcQ==} + engines: {node: '>=6.9.0'} + '@babel/template@7.27.2': resolution: {integrity: sha512-LPDZ85aEJyYSd18/DkjNh4/y1ntkE5KwUHWTiqgRxruuZL2F1yuHligVHLvcHY2vMHXttKFpJn6LwfI7cw7ODw==} engines: {node: '>=6.9.0'} @@ -425,7 +448,7 @@ packages: resolution: {integrity: sha512-p44TsNArL4IVXDTbapUmEkAlvWs2CFQbcfc0ymDsis1kH2wh0gcY96AS29c/vp2d0y2Tquk1EDSaawpzilUiAw==} '@codemirror/language@https://codeload.github.com/lishid/cm-language/tar.gz/a9c3c7efe17dd1d24395ee2a179fe12dd6ed1e76': - resolution: {tarball: https://codeload.github.com/lishid/cm-language/tar.gz/a9c3c7efe17dd1d24395ee2a179fe12dd6ed1e76} + resolution: {gitHosted: true, tarball: https://codeload.github.com/lishid/cm-language/tar.gz/a9c3c7efe17dd1d24395ee2a179fe12dd6ed1e76} version: 6.11.2 '@codemirror/lint@6.9.2': @@ -1010,67 +1033,79 @@ packages: resolution: {integrity: sha512-9B+taZ8DlyyqzZQnoeIvDVR/2F4EbMepXMc/NdVbkzsJbzkUjhXv/70GQJ7tdLA4YJgNP25zukcxpX2/SueNrA==} cpu: [arm64] os: [linux] + libc: [glibc] '@img/sharp-libvips-linux-arm@1.0.5': resolution: {integrity: sha512-gvcC4ACAOPRNATg/ov8/MnbxFDJqf/pDePbBnuBDcjsI8PssmjoKMAz4LtLaVi+OnSb5FK/yIOamqDwGmXW32g==} cpu: [arm] os: [linux] + libc: [glibc] '@img/sharp-libvips-linux-s390x@1.0.4': resolution: {integrity: sha512-u7Wz6ntiSSgGSGcjZ55im6uvTrOxSIS8/dgoVMoiGE9I6JAfU50yH5BoDlYA1tcuGS7g/QNtetJnxA6QEsCVTA==} cpu: [s390x] os: [linux] + libc: [glibc] '@img/sharp-libvips-linux-x64@1.0.4': resolution: {integrity: sha512-MmWmQ3iPFZr0Iev+BAgVMb3ZyC4KeFc3jFxnNbEPas60e1cIfevbtuyf9nDGIzOaW9PdnDciJm+wFFaTlj5xYw==} cpu: [x64] os: [linux] + libc: [glibc] '@img/sharp-libvips-linuxmusl-arm64@1.0.4': resolution: {integrity: sha512-9Ti+BbTYDcsbp4wfYib8Ctm1ilkugkA/uscUn6UXK1ldpC1JjiXbLfFZtRlBhjPZ5o1NCLiDbg8fhUPKStHoTA==} cpu: [arm64] os: [linux] + libc: [musl] '@img/sharp-libvips-linuxmusl-x64@1.0.4': resolution: {integrity: sha512-viYN1KX9m+/hGkJtvYYp+CCLgnJXwiQB39damAO7WMdKWlIhmYTfHjwSbQeUK/20vY154mwezd9HflVFM1wVSw==} cpu: [x64] os: [linux] + libc: [musl] '@img/sharp-linux-arm64@0.33.5': resolution: {integrity: sha512-JMVv+AMRyGOHtO1RFBiJy/MBsgz0x4AWrT6QoEVVTyh1E39TrCUpTRI7mx9VksGX4awWASxqCYLCV4wBZHAYxA==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [arm64] os: [linux] + libc: [glibc] '@img/sharp-linux-arm@0.33.5': resolution: {integrity: sha512-JTS1eldqZbJxjvKaAkxhZmBqPRGmxgu+qFKSInv8moZ2AmT5Yib3EQ1c6gp493HvrvV8QgdOXdyaIBrhvFhBMQ==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [arm] os: [linux] + libc: [glibc] '@img/sharp-linux-s390x@0.33.5': resolution: {integrity: sha512-y/5PCd+mP4CA/sPDKl2961b+C9d+vPAveS33s6Z3zfASk2j5upL6fXVPZi7ztePZ5CuH+1kW8JtvxgbuXHRa4Q==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [s390x] os: [linux] + libc: [glibc] '@img/sharp-linux-x64@0.33.5': resolution: {integrity: sha512-opC+Ok5pRNAzuvq1AG0ar+1owsu842/Ab+4qvU879ippJBHvyY5n2mxF1izXqkPYlGuP/M556uh53jRLJmzTWA==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [x64] os: [linux] + libc: [glibc] '@img/sharp-linuxmusl-arm64@0.33.5': resolution: {integrity: sha512-XrHMZwGQGvJg2V/oRSUfSAfjfPxO+4DkiRh6p2AFjLQztWUuY/o8Mq0eMQVIY7HJ1CDQUJlxGGZRw1a5bqmd1g==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [arm64] os: [linux] + libc: [musl] '@img/sharp-linuxmusl-x64@0.33.5': resolution: {integrity: sha512-WT+d/cgqKkkKySYmqoZ8y3pxx7lx9vVejxW/W4DOFMYVSkErR+w7mf2u8m/y4+xHe7yY9DAXQMWQhpnMuFfScw==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [x64] os: [linux] + libc: [musl] '@img/sharp-wasm32@0.33.5': resolution: {integrity: sha512-ykUW4LVGaMcU9lu9thv85CbRMAwfeadCJHRsg2GmeRa/cJxsVY9Rbd57JcMxBkKHag5U/x7TSBpScF4U8ElVzg==} @@ -1319,6 +1354,9 @@ packages: '@jridgewell/trace-mapping@0.3.9': resolution: {integrity: sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==} + '@kurkle/color@0.3.4': + resolution: {integrity: sha512-M5UknZPHRu3DEDWoipU6sE8PdkZ6Z/S+v4dD+Ke8IaNlpdSQah50lz1KtcFBa2vsdOnwbbnxJwVM4wty6udA5w==} + '@lezer/common@1.3.0': resolution: {integrity: sha512-L9X8uHCYU310o99L3/MpJKYxPzXPOS7S0NmBaM7UO/x2Kb2WbmMLSkfvdr1KxRIFYOpbY0Jhn7CfLSUDzL8arQ==} @@ -1491,56 +1529,67 @@ packages: resolution: {integrity: sha512-k9oD15soC/Ln6d2Wv/JOFPzZXIAIFLp6B+i14KhxAfnq76ajt0EhYc5YPeX6W1xJkAdItcVT+JhKl1QZh44/qw==} cpu: [arm] os: [linux] + libc: [glibc] '@rollup/rollup-linux-arm-musleabihf@4.53.3': resolution: {integrity: sha512-vTNlKq+N6CK/8UktsrFuc+/7NlEYVxgaEgRXVUVK258Z5ymho29skzW1sutgYjqNnquGwVUObAaxae8rZ6YMhg==} cpu: [arm] os: [linux] + libc: [musl] '@rollup/rollup-linux-arm64-gnu@4.53.3': resolution: {integrity: sha512-RGrFLWgMhSxRs/EWJMIFM1O5Mzuz3Xy3/mnxJp/5cVhZ2XoCAxJnmNsEyeMJtpK+wu0FJFWz+QF4mjCA7AUQ3w==} cpu: [arm64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-arm64-musl@4.53.3': resolution: {integrity: sha512-kASyvfBEWYPEwe0Qv4nfu6pNkITLTb32p4yTgzFCocHnJLAHs+9LjUu9ONIhvfT/5lv4YS5muBHyuV84epBo/A==} cpu: [arm64] os: [linux] + libc: [musl] '@rollup/rollup-linux-loong64-gnu@4.53.3': resolution: {integrity: sha512-JiuKcp2teLJwQ7vkJ95EwESWkNRFJD7TQgYmCnrPtlu50b4XvT5MOmurWNrCj3IFdyjBQ5p9vnrX4JM6I8OE7g==} cpu: [loong64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-ppc64-gnu@4.53.3': resolution: {integrity: sha512-EoGSa8nd6d3T7zLuqdojxC20oBfNT8nexBbB/rkxgKj5T5vhpAQKKnD+h3UkoMuTyXkP5jTjK/ccNRmQrPNDuw==} cpu: [ppc64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-riscv64-gnu@4.53.3': resolution: {integrity: sha512-4s+Wped2IHXHPnAEbIB0YWBv7SDohqxobiiPA1FIWZpX+w9o2i4LezzH/NkFUl8LRci/8udci6cLq+jJQlh+0g==} cpu: [riscv64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-riscv64-musl@4.53.3': resolution: {integrity: sha512-68k2g7+0vs2u9CxDt5ktXTngsxOQkSEV/xBbwlqYcUrAVh6P9EgMZvFsnHy4SEiUl46Xf0IObWVbMvPrr2gw8A==} cpu: [riscv64] os: [linux] + libc: [musl] '@rollup/rollup-linux-s390x-gnu@4.53.3': resolution: {integrity: sha512-VYsFMpULAz87ZW6BVYw3I6sWesGpsP9OPcyKe8ofdg9LHxSbRMd7zrVrr5xi/3kMZtpWL/wC+UIJWJYVX5uTKg==} cpu: [s390x] os: [linux] + libc: [glibc] '@rollup/rollup-linux-x64-gnu@4.53.3': resolution: {integrity: sha512-3EhFi1FU6YL8HTUJZ51imGJWEX//ajQPfqWLI3BQq4TlvHy4X0MOr5q3D2Zof/ka0d5FNdPwZXm3Yyib/UEd+w==} cpu: [x64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-x64-musl@4.53.3': resolution: {integrity: sha512-eoROhjcc6HbZCJr+tvVT8X4fW3/5g/WkGvvmwz/88sDtSJzO7r/blvoBDgISDiCjDRZmHpwud7h+6Q9JxFwq1Q==} cpu: [x64] os: [linux] + libc: [musl] '@rollup/rollup-openharmony-arm64@4.53.3': resolution: {integrity: sha512-OueLAWgrNSPGAdUdIjSWXw+u/02BRTcnfw9PN41D2vq/JSEPnJnVuBgw18VkN8wcd4fjUs+jFHVM4t9+kBSNLw==} @@ -1681,10 +1730,16 @@ packages: '@types/normalize-package-data@2.4.4': resolution: {integrity: sha512-37i+OaWTh9qeK4LSHPsyRC7NahnGotNuZvjLSgcPzblpHB3rrCJxAOgI5gCdKm7coonsaX1Of0ILiTcnZjbfxA==} + '@types/pako@2.0.4': + resolution: {integrity: sha512-VWDCbrLeVXJM9fihYodcLiIv0ku+AlOa/TQ1SvYOaBuyrSKgEcro95LJyIsJ4vSo6BXIxOKxiJAat04CmST9Fw==} + '@types/parse-path@7.1.0': resolution: {integrity: sha512-EULJ8LApcVEPbrfND0cRQqutIOdiIgJ1Mgrhpy755r14xMohPTEpkV/k28SJvuOs9bHRFW8x+KeDAEPiGQPB9Q==} deprecated: This is a stub types definition. parse-path provides its own type definitions, so you do not need this installed. + '@types/raf@3.4.3': + resolution: {integrity: sha512-c4YAvMedbPZ5tEyxzQdMoOhhJ4RD3rngZIdwC2/qDN3d7JpEhB6fiBRKVY1lg5B7Wk+uPBjn5f39j1/2MY1oOw==} + '@types/semver@7.7.1': resolution: {integrity: sha512-FmgJfu+MOcQ370SD0ev7EI8TlCAfKYU+B4m5T3yXc1CiRN94g/SZPtsCkk506aUDtlMnFZvasDwHHUcZUEaYuA==} @@ -1700,6 +1755,9 @@ packages: '@types/tough-cookie@4.0.5': resolution: {integrity: sha512-/Ad8+nIOV7Rl++6f1BdKxFSMgmoqEoYbHRpPcx3JEfv8VRsQe9Z4mCXeJBzxs7mbHY/XOZZuXlRNfhpVPbs6ZA==} + '@types/trusted-types@2.0.7': + resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==} + '@types/yargs-parser@21.0.3': resolution: {integrity: sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==} @@ -1766,6 +1824,7 @@ packages: '@ungap/structured-clone@1.3.0': resolution: {integrity: sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==} + deprecated: Potential CWE-502 - Update to 1.3.1 or higher '@vitest/coverage-v8@1.6.1': resolution: {integrity: sha512-6YeRZwuO4oTGKxD3bijok756oktHSIm3eczVVzNe3scqzuhLwltIF3S9ZL/vwOVIpURmU6SnZhziXXAfw8/Qlw==} @@ -1800,6 +1859,11 @@ packages: '@volar/typescript@1.11.1': resolution: {integrity: sha512-iU+t2mas/4lYierSnoFOeRFQUhAEMgsFuQxoxvwn5EdQopw43j+J27a4lt9LMInx1gLJBC6qL14WYGlgymaSMQ==} + peerDependencies: + typescript: '*' + peerDependenciesMeta: + typescript: + optional: true '@vue/compiler-core@3.5.25': resolution: {integrity: sha512-vay5/oQJdsNHmliWoZfHPoVZZRmnSWhug0BYT34njkYTPqClh3DNWLkZNJBVSjsNMrg0CCrBfoKkjZQPM/QVUw==} @@ -1943,6 +2007,10 @@ packages: balanced-match@1.0.2: resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} + base64-arraybuffer@1.0.2: + resolution: {integrity: sha512-I3yl4r9QB5ZRY3XuJVEPfc2XhZO6YweFPI+UovAzn+8/hb3oJ6lnysaFcjVpkCPfVWFUDvoZ8kmVDP7WyRtYtQ==} + engines: {node: '>= 0.6.0'} + baseline-browser-mapping@2.8.31: resolution: {integrity: sha512-a28v2eWrrRWPpJSzxc+mKwm0ZtVx/G8SepdQZDArnXYU/XS+IF6mp8aB/4E+hH1tyGCoDo3KlUCdlSxGDsRkAw==} hasBin: true @@ -1950,6 +2018,7 @@ packages: basic-ftp@5.0.5: resolution: {integrity: sha512-4Bcg1P8xhUuqcii/S0Z9wiHIrQVPMermM1any+MX5GeGD7faD3/msQUDGLol9wOcz4/jbg/WJnGqoJF6LiBdtg==} engines: {node: '>=10.0.0'} + deprecated: Security vulnerability fixed in 5.2.1, please upgrade before-after-hook@4.0.0: resolution: {integrity: sha512-q6tR3RPqIB1pMiTRMFcZwuG5T8vwp+vUvEG0vuI6B+Rikh5BfPp2fQ82c925FOs+b0lcFQ8CFrL+KbilfZFhOQ==} @@ -2027,6 +2096,10 @@ packages: caniuse-lite@1.0.30001757: resolution: {integrity: sha512-r0nnL/I28Zi/yjk1el6ilj27tKcdjLsNqAOZr0yVjWPrSQyHgKI2INaEWw21bAQSv2LXRt1XuCS/GomNpWOxsQ==} + canvg@3.0.11: + resolution: {integrity: sha512-5ON+q7jCTgMp9cjpu4Jo6XbvfYwSB2Ow3kzHKfIyJfaCAOHLbdKPQqGKgfED/R5B+3TFFfe8pegYA+b423SRyA==} + engines: {node: '>=10.0.0'} + chai@4.5.0: resolution: {integrity: sha512-RITGBfijLkBddZvnn8jdqoTypxvqbOLYQkGGxXzeFjVHvudaPw0HNFD9x928/eUwYWd2dPCugVqspGALTZZQKw==} engines: {node: '>=4'} @@ -2046,6 +2119,15 @@ packages: chardet@2.1.1: resolution: {integrity: sha512-PsezH1rqdV9VvyNhxxOW32/d75r01NY7TQCmOqomRo15ZSOKbpTFVsfjghxo6JloQUCGnH4k1LGu0R4yCLlWQQ==} + chart.js@4.6.1: + resolution: {integrity: sha512-hJyniucsFmq//EvXYvJ6c6mahPoI3kaxdjVH8awTaJ/fDNWeSqqqArixMJWkWNN6fcYvPU3HneSANFNYtRi61g==} + engines: {pnpm: '>=8'} + + chartjs-chart-matrix@3.1.0: + resolution: {integrity: sha512-pdo8DnhFXOisjbLDgfkzZH1w0xmjGqiaAMgkQSHCEMzxQENsXTgkXImIyweDiO7SqlE5PuzjhklyBCiorQhRmw==} + peerDependencies: + chart.js: '>=3.0.0' + check-error@1.0.3: resolution: {integrity: sha512-iKEoDYaRmd1mxM90a2OEfWhjsjPpYPuQ+lMYsoxB126+t8fw7ySEO48nmDg5COTjxDI65/Y2OWpeEHk3ZOe8zg==} @@ -2162,15 +2244,18 @@ packages: conventional-changelog-atom@5.0.0: resolution: {integrity: sha512-WfzCaAvSCFPkznnLgLnfacRAzjgqjLUjvf3MftfsJzQdDICqkOOpcMtdJF3wTerxSpv2IAAjX8doM3Vozqle3g==} engines: {node: '>=18'} + deprecated: This preset is deprecated. Please use conventional-changelog-conventionalcommits or conventional-changelog-angular instead. conventional-changelog-cli@5.0.0: resolution: {integrity: sha512-9Y8fucJe18/6ef6ZlyIlT2YQUbczvoQZZuYmDLaGvcSBP+M6h+LAvf7ON7waRxKJemcCII8Yqu5/8HEfskTxJQ==} engines: {node: '>=18'} + deprecated: This package is no longer maintained. Please use the conventional-changelog package instead. hasBin: true conventional-changelog-codemirror@5.0.0: resolution: {integrity: sha512-8gsBDI5Y3vrKUCxN6Ue8xr6occZ5nsDEc4C7jO/EovFGozx8uttCAyfhRrvoUAWi2WMm3OmYs+0mPJU7kQdYWQ==} engines: {node: '>=18'} + deprecated: This preset is deprecated. Please use conventional-changelog-conventionalcommits or conventional-changelog-angular instead. conventional-changelog-conventionalcommits@8.0.0: resolution: {integrity: sha512-eOvlTO6OcySPyyyk8pKz2dP4jjElYunj9hn9/s0OB+gapTO8zwS9UQWrZ1pmF2hFs3vw1xhonOLGcGjy/zgsuA==} @@ -2183,26 +2268,32 @@ packages: conventional-changelog-core@8.0.0: resolution: {integrity: sha512-EATUx5y9xewpEe10UEGNpbSHRC6cVZgO+hXQjofMqpy+gFIrcGvH3Fl6yk2VFKh7m+ffenup2N7SZJYpyD9evw==} engines: {node: '>=18'} + deprecated: Deprecated and no longer maintained. Please use conventional-changelog instead. conventional-changelog-ember@5.0.0: resolution: {integrity: sha512-RPflVfm5s4cSO33GH/Ey26oxhiC67akcxSKL8CLRT3kQX2W3dbE19sSOM56iFqUJYEwv9mD9r6k79weWe1urfg==} engines: {node: '>=18'} + deprecated: This preset is deprecated. Please use conventional-changelog-conventionalcommits or conventional-changelog-angular instead. conventional-changelog-eslint@6.0.0: resolution: {integrity: sha512-eiUyULWjzq+ybPjXwU6NNRflApDWlPEQEHvI8UAItYW/h22RKkMnOAtfCZxMmrcMO1OKUWtcf2MxKYMWe9zJuw==} engines: {node: '>=18'} + deprecated: This preset is deprecated. Please use conventional-changelog-conventionalcommits or conventional-changelog-angular instead. conventional-changelog-express@5.0.0: resolution: {integrity: sha512-D8Q6WctPkQpvr2HNCCmwU5GkX22BVHM0r4EW8vN0230TSyS/d6VQJDAxGb84lbg0dFjpO22MwmsikKL++Oo/oQ==} engines: {node: '>=18'} + deprecated: This preset is deprecated. Please use conventional-changelog-conventionalcommits or conventional-changelog-angular instead. conventional-changelog-jquery@6.0.0: resolution: {integrity: sha512-2kxmVakyehgyrho2ZHBi90v4AHswkGzHuTaoH40bmeNqUt20yEkDOSpw8HlPBfvEQBwGtbE+5HpRwzj6ac2UfA==} engines: {node: '>=18'} + deprecated: This preset is deprecated. Please use conventional-changelog-conventionalcommits or conventional-changelog-angular instead. conventional-changelog-jshint@5.0.0: resolution: {integrity: sha512-gGNphSb/opc76n2eWaO6ma4/Wqu3tpa2w7i9WYqI6Cs2fncDSI2/ihOfMvXveeTTeld0oFvwMVNV+IYQIk3F3g==} engines: {node: '>=18'} + deprecated: This preset is deprecated. Please use conventional-changelog-conventionalcommits or conventional-changelog-angular instead. conventional-changelog-preset-loader@5.0.0: resolution: {integrity: sha512-SetDSntXLk8Jh1NOAl1Gu5uLiCNSYenB5tm0YVeZKePRIgDW9lQImromTwLa3c/Gae298tsgOM+/CYT9XAl0NA==} @@ -2243,6 +2334,9 @@ packages: resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==} engines: {node: '>=18'} + core-js@3.51.0: + resolution: {integrity: sha512-7bDKx/5jm5MxzsXxc93g6Z2+4ZsuT/MddrfRmTDJNAkWsYWHU8EVNEsBiIEWnMAMCHMmRfUEjkuo3jeNBOIHRw==} + core-util-is@1.0.3: resolution: {integrity: sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==} @@ -2263,6 +2357,9 @@ packages: resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} engines: {node: '>= 8'} + css-line-break@2.1.0: + resolution: {integrity: sha512-FHcKFCZcAha3LwfVBhCQbW2nCNbkZXn7KVUJcsT5/P8YmfsVja0FMPJr0B903j/E69HUphKiV9iQArX8SDYA4w==} + css-select@5.2.2: resolution: {integrity: sha512-TizTzUddG/xYLA3NXodFM0fSbNizXjOKhqiQQwvhlspadZokn1KDy0NZFS0wuEubIYAV5/c1/lAr0TaaFXEXzw==} @@ -2274,6 +2371,11 @@ packages: resolution: {integrity: sha512-u/O3vwbptzhMs3L1fQE82ZSLHQQfto5gyZzwteVIEyeaY5Fc7R4dapF/BvRoSYFeqfBk4m0V1Vafq5Pjv25wvA==} engines: {node: '>= 6'} + cssesc@3.0.0: + resolution: {integrity: sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==} + engines: {node: '>=4'} + hasBin: true + cssom@0.3.8: resolution: {integrity: sha512-b0tGHbfegbhPJpxpiBPU2sCkigAqtM9O121le6bbOlgyV+NyGyCmVfJ6QW9eRjz8CpNfWEOYBIMIGRYkLwsIYg==} @@ -2405,6 +2507,9 @@ packages: resolution: {integrity: sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==} engines: {node: '>= 4'} + dompurify@3.4.17: + resolution: {integrity: sha512-B/pSlYVHQ58kqISD/yDjuJ1yfzI34m1gF4lAod2bwSRhiN4K5Cl3H8Af7hqB2PmTL911tdEudnnXn5FnhRoz0w==} + domutils@3.2.2: resolution: {integrity: sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==} @@ -2591,6 +2696,9 @@ packages: fast-levenshtein@2.0.6: resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==} + fast-png@6.4.0: + resolution: {integrity: sha512-kAqZq1TlgBjZcLr5mcN6NP5Rv4V2f22z00c3g8vRrwkcqjerx7BEhPbOnWCPqaHUl2XWQBJQvOT/FQhdMT7X/Q==} + fastq@1.19.1: resolution: {integrity: sha512-GwLTyxkCXjXbxqIhTsMI2Nui8huMPtnxg7krajPJAjnEG/iiOS7i+zCtWGZR9G0NBKbXKh6X9m9UIsYX/N6vvQ==} @@ -2708,11 +2816,13 @@ packages: git-raw-commits@5.0.0: resolution: {integrity: sha512-I2ZXrXeOc0KrCvC7swqtIFXFN+rbjnC7b2T943tvemIOVNl+XP8YnA9UVwqFhzzLClnSA60KR/qEjLpXzs73Qg==} engines: {node: '>=18'} + deprecated: Deprecated and no longer maintained. Use @conventional-changelog/git-client instead. hasBin: true git-semver-tags@8.0.0: resolution: {integrity: sha512-N7YRIklvPH3wYWAR2vysaqGLPRcpwQ0GKdlqTiVN5w1UmCdaeY3K8s6DMKRCh54DDdzyt/OAB6C8jgVtb7Y2Fg==} engines: {node: '>=18'} + deprecated: Deprecated and no longer maintained. Use @conventional-changelog/git-client instead. hasBin: true git-up@8.1.1: @@ -2734,7 +2844,7 @@ packages: glob@7.2.3: resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==} - deprecated: Glob versions prior to v9 are no longer supported + deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me globals@13.24.0: resolution: {integrity: sha512-AhO5QUcj8llrbG09iWhPU2B204J1xnPeL8kQmVorSsy+Sjj1sk8gIyh6cUocGmH4L0UuhAJy+hJMRA4mgA4mFQ==} @@ -2802,6 +2912,10 @@ packages: html-escaper@2.0.2: resolution: {integrity: sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==} + html2canvas@1.4.1: + resolution: {integrity: sha512-fPU6BHNpsyIhr8yyMpTLLxAbkaK8ArIBcmZIRiBLiDhjeqvXolaEmDGmELFuX9I4xDcaKKcJl+TKZLqruBbmWA==} + engines: {node: '>=8.0.0'} + htmlparser2@10.0.0: resolution: {integrity: sha512-TwAZM+zE5Tq3lrEHvOlvwgj1XLWQCtaaibSN11Q+gGBAS7Y1uZSWwXXRe4iF6OXnaq1riyQAPFOBtYc77Mxq0g==} @@ -2894,6 +3008,9 @@ packages: '@types/node': optional: true + iobuffer@5.4.0: + resolution: {integrity: sha512-DRebOWuqDvxunfkNJAlc3IzWIPD5xVxwUNbHr7xKB8E6aLJxIPfNX3CoMJghcFjpv6RWQsrcJbghtEwSPoJqMA==} + ip-address@10.1.0: resolution: {integrity: sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q==} engines: {node: '>= 12'} @@ -3215,6 +3332,9 @@ packages: jsonfile@4.0.0: resolution: {integrity: sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==} + jspdf@4.2.1: + resolution: {integrity: sha512-YyAXyvnmjTbR4bHQRLzex3CuINCDlQnBqoSYyjJwTP2x9jDLuKDzy7aKUl0hgx3uhcl7xzg32agn5vlie6HIlQ==} + jszip@3.10.1: resolution: {integrity: sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==} @@ -3520,13 +3640,6 @@ packages: '@codemirror/state': 6.5.0 '@codemirror/view': 6.38.6 - obsidian@https://codeload.github.com/obsidianmd/obsidian-api/tar.gz/53cf3bd402cec654bcf1d963b43cb01d05a6efdf: - resolution: {tarball: https://codeload.github.com/obsidianmd/obsidian-api/tar.gz/53cf3bd402cec654bcf1d963b43cb01d05a6efdf} - version: 1.10.3 - peerDependencies: - '@codemirror/state': 6.5.0 - '@codemirror/view': 6.38.6 - ohash@2.0.11: resolution: {integrity: sha512-RdR9FQrFwNBNXAr4GixM8YaRZRJ5PUWbKYbE5eOsrwAjJW0q2REGcf79oYPsLyskQCZG1PLN+S/K1V00joZAoQ==} @@ -3596,6 +3709,9 @@ packages: pako@1.0.11: resolution: {integrity: sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==} + pako@2.2.0: + resolution: {integrity: sha512-zJq6RP/5q+TO2OpFV3FHzlPnFjmkb7Nc99a5SNjJE+uu/PkpChs+NIZSSzbBoD+6kjiISXjfYdwj1ZRQ81dz/w==} + parent-module@1.0.1: resolution: {integrity: sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==} engines: {node: '>=6'} @@ -3669,6 +3785,9 @@ packages: perfect-debounce@2.0.0: resolution: {integrity: sha512-fkEH/OBiKrqqI/yIgjR92lMfs2K8105zt/VT6+7eTjNwisrsh47CeIED9z58zI7DfKdH3uHAn25ziRZn3kgAow==} + performance-now@2.1.0: + resolution: {integrity: sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow==} + picocolors@1.1.1: resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} @@ -3694,6 +3813,10 @@ packages: pkg-types@2.3.0: resolution: {integrity: sha512-SIqCzDRg0s9npO5XQ3tNZioRY1uK06lA41ynBC1YmFTmnY6FjUjVt6s4LoADmwoig1qqD0oK8h1p/8mlMx8Oig==} + postcss-selector-parser@7.1.7: + resolution: {integrity: sha512-wWBro/7hJ40ye6TPiXkUQoXKCw23xSsjriUvqd7Uls9Sso3oLiON1flc18cCdnjgCRXw4fBVqUJJeOdDTh3P3g==} + engines: {node: '>=4'} + postcss@8.5.6: resolution: {integrity: sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==} engines: {node: ^10 || ^12 || >=14} @@ -3739,6 +3862,9 @@ packages: queue-microtask@1.2.3: resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==} + raf@3.4.1: + resolution: {integrity: sha512-Sq4CW4QhwOHE8ucn6J34MqtZCeWFP2aQSmrlroYgqAV1PjStIhJXxYuTgUIfkEk7zTLjmIjLmU5q+fbD1NnOJA==} + rc9@2.1.2: resolution: {integrity: sha512-btXCnMmRIBINM2LDZoEmOogIZU7Qe7zn4BpomSKZ/ykbLObuBdvG+mFq11DL6fjH1DRwHhrlgtYWG96bJiC7Cg==} @@ -3764,6 +3890,9 @@ packages: resolution: {integrity: sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==} engines: {node: '>= 14.18.0'} + regenerator-runtime@0.13.11: + resolution: {integrity: sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==} + regexp-match-indices@1.0.2: resolution: {integrity: sha512-DwZuAkt8NF5mKwGGER1EGh2PRqyvhRhhLviH+R8y8dIuaQROlUfXjt4s9ZTXstIsSkptf06BSvwcEmmfheJJWQ==} @@ -3823,6 +3952,10 @@ packages: resolution: {integrity: sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==} engines: {iojs: '>=1.0.0', node: '>=0.10.0'} + rgbcolor@1.0.1: + resolution: {integrity: sha512-9aZLIrhRaD97sgVhtJOW6ckOEh6/GnvQtdVNfdZ6s67+3/XwLS9lBcQYzEEhYVeUowN7pRzMLsyGhK2i/xvWbw==} + engines: {node: '>= 0.8.15'} + rimraf@3.0.2: resolution: {integrity: sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==} deprecated: Rimraf versions prior to v4 are no longer supported @@ -3985,6 +4118,10 @@ packages: stackback@0.0.2: resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} + stackblur-canvas@2.7.0: + resolution: {integrity: sha512-yf7OENo23AGJhBriGx0QivY5JP6Y1HbrrDI6WLt6C5auYZXlQrheoY8hD4ibekFKz1HOfE48Ww8kMWMnJD/zcQ==} + engines: {node: '>=0.1.14'} + std-env@3.10.0: resolution: {integrity: sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==} @@ -4064,6 +4201,10 @@ packages: resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==} engines: {node: '>= 0.4'} + svg-pathdata@6.0.3: + resolution: {integrity: sha512-qsjeeq5YjBZ5eMdFuUa4ZosMLxgr5RZ+F+Y1OrDhuOCEInRMA3x74XdBtggJcj9kOeInz0WE+LgCPDkZFlBYJw==} + engines: {node: '>=12.0.0'} + symbol-tree@3.2.4: resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==} @@ -4084,6 +4225,9 @@ packages: resolution: {integrity: sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==} engines: {node: '>=8'} + text-segmentation@1.0.3: + resolution: {integrity: sha512-iOiPUo/BGnZ6+54OsWxZidGCsdU8YbE4PSpdPinp7DeMtUJNJBoJ/ouUSTJjHkh1KntHaltHl/gDs2FC4i5+Nw==} + text-table@0.2.0: resolution: {integrity: sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==} @@ -4296,6 +4440,9 @@ packages: util-deprecate@1.0.2: resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==} + utrie@1.0.2: + resolution: {integrity: sha512-1MLa5ouZiOmQzUbjbu9VmjLzn1QLXBhwpUa7kdLUQK+KQ5KA9I1vk5U4YHe/X2Ch7PYnJfWuWT+VbuxbGwljhw==} + v8-to-istanbul@9.3.0: resolution: {integrity: sha512-kiGUalWN+rgBJ/1OHZsBtU4rXZOfj/7rKQxULKlIzwzQSvMJUUNgPwJEEh7gU6xEVxC0ahoOBvN2YI8GH6FNgA==} engines: {node: '>=10.12.0'} @@ -4418,10 +4565,12 @@ packages: whatwg-encoding@2.0.0: resolution: {integrity: sha512-p41ogyeMUrw3jWclHWTQg1k05DSVXPLcVxRTYsXUk+ZooOCZLcoYgPZ/HL/D/N+uQPOtcp1me1WhBEaX02mhWg==} engines: {node: '>=12'} + deprecated: Use @exodus/bytes instead for a more spec-conformant and faster implementation whatwg-encoding@3.1.1: resolution: {integrity: sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==} engines: {node: '>=18'} + deprecated: Use @exodus/bytes instead for a more spec-conformant and faster implementation whatwg-mimetype@3.0.0: resolution: {integrity: sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==} @@ -4609,20 +4758,20 @@ snapshots: '@babel/compat-data@7.28.5': {} - '@babel/core@7.28.5': + '@babel/core@7.28.5(supports-color@10.2.2)': dependencies: '@babel/code-frame': 7.27.1 '@babel/generator': 7.28.5 '@babel/helper-compilation-targets': 7.27.2 - '@babel/helper-module-transforms': 7.28.3(@babel/core@7.28.5) + '@babel/helper-module-transforms': 7.28.3(@babel/core@7.28.5(supports-color@10.2.2))(supports-color@10.2.2) '@babel/helpers': 7.28.4 '@babel/parser': 7.28.5 '@babel/template': 7.27.2 - '@babel/traverse': 7.28.5 + '@babel/traverse': 7.28.5(supports-color@10.2.2) '@babel/types': 7.28.5 '@jridgewell/remapping': 2.3.5 convert-source-map: 2.0.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) gensync: 1.0.0-beta.2 json5: 2.2.3 semver: 6.3.1 @@ -4647,19 +4796,19 @@ snapshots: '@babel/helper-globals@7.28.0': {} - '@babel/helper-module-imports@7.27.1': + '@babel/helper-module-imports@7.27.1(supports-color@10.2.2)': dependencies: - '@babel/traverse': 7.28.5 + '@babel/traverse': 7.28.5(supports-color@10.2.2) '@babel/types': 7.28.5 transitivePeerDependencies: - supports-color - '@babel/helper-module-transforms@7.28.3(@babel/core@7.28.5)': + '@babel/helper-module-transforms@7.28.3(@babel/core@7.28.5(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@babel/core': 7.28.5 - '@babel/helper-module-imports': 7.27.1 + '@babel/core': 7.28.5(supports-color@10.2.2) + '@babel/helper-module-imports': 7.27.1(supports-color@10.2.2) '@babel/helper-validator-identifier': 7.28.5 - '@babel/traverse': 7.28.5 + '@babel/traverse': 7.28.5(supports-color@10.2.2) transitivePeerDependencies: - supports-color @@ -4680,98 +4829,100 @@ snapshots: dependencies: '@babel/types': 7.28.5 - '@babel/plugin-syntax-async-generators@7.8.4(@babel/core@7.28.5)': + '@babel/plugin-syntax-async-generators@7.8.4(@babel/core@7.28.5(supports-color@10.2.2))': dependencies: - '@babel/core': 7.28.5 + '@babel/core': 7.28.5(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.27.1 - '@babel/plugin-syntax-bigint@7.8.3(@babel/core@7.28.5)': + '@babel/plugin-syntax-bigint@7.8.3(@babel/core@7.28.5(supports-color@10.2.2))': dependencies: - '@babel/core': 7.28.5 + '@babel/core': 7.28.5(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.27.1 - '@babel/plugin-syntax-class-properties@7.12.13(@babel/core@7.28.5)': + '@babel/plugin-syntax-class-properties@7.12.13(@babel/core@7.28.5(supports-color@10.2.2))': dependencies: - '@babel/core': 7.28.5 + '@babel/core': 7.28.5(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.27.1 - '@babel/plugin-syntax-class-static-block@7.14.5(@babel/core@7.28.5)': + '@babel/plugin-syntax-class-static-block@7.14.5(@babel/core@7.28.5(supports-color@10.2.2))': dependencies: - '@babel/core': 7.28.5 + '@babel/core': 7.28.5(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.27.1 - '@babel/plugin-syntax-import-attributes@7.27.1(@babel/core@7.28.5)': + '@babel/plugin-syntax-import-attributes@7.27.1(@babel/core@7.28.5(supports-color@10.2.2))': dependencies: - '@babel/core': 7.28.5 + '@babel/core': 7.28.5(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.27.1 - '@babel/plugin-syntax-import-meta@7.10.4(@babel/core@7.28.5)': + '@babel/plugin-syntax-import-meta@7.10.4(@babel/core@7.28.5(supports-color@10.2.2))': dependencies: - '@babel/core': 7.28.5 + '@babel/core': 7.28.5(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.27.1 - '@babel/plugin-syntax-json-strings@7.8.3(@babel/core@7.28.5)': + '@babel/plugin-syntax-json-strings@7.8.3(@babel/core@7.28.5(supports-color@10.2.2))': dependencies: - '@babel/core': 7.28.5 + '@babel/core': 7.28.5(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.27.1 - '@babel/plugin-syntax-jsx@7.27.1(@babel/core@7.28.5)': + '@babel/plugin-syntax-jsx@7.27.1(@babel/core@7.28.5(supports-color@10.2.2))': dependencies: - '@babel/core': 7.28.5 + '@babel/core': 7.28.5(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.27.1 - '@babel/plugin-syntax-logical-assignment-operators@7.10.4(@babel/core@7.28.5)': + '@babel/plugin-syntax-logical-assignment-operators@7.10.4(@babel/core@7.28.5(supports-color@10.2.2))': dependencies: - '@babel/core': 7.28.5 + '@babel/core': 7.28.5(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.27.1 - '@babel/plugin-syntax-nullish-coalescing-operator@7.8.3(@babel/core@7.28.5)': + '@babel/plugin-syntax-nullish-coalescing-operator@7.8.3(@babel/core@7.28.5(supports-color@10.2.2))': dependencies: - '@babel/core': 7.28.5 + '@babel/core': 7.28.5(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.27.1 - '@babel/plugin-syntax-numeric-separator@7.10.4(@babel/core@7.28.5)': + '@babel/plugin-syntax-numeric-separator@7.10.4(@babel/core@7.28.5(supports-color@10.2.2))': dependencies: - '@babel/core': 7.28.5 + '@babel/core': 7.28.5(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.27.1 - '@babel/plugin-syntax-object-rest-spread@7.8.3(@babel/core@7.28.5)': + '@babel/plugin-syntax-object-rest-spread@7.8.3(@babel/core@7.28.5(supports-color@10.2.2))': dependencies: - '@babel/core': 7.28.5 + '@babel/core': 7.28.5(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.27.1 - '@babel/plugin-syntax-optional-catch-binding@7.8.3(@babel/core@7.28.5)': + '@babel/plugin-syntax-optional-catch-binding@7.8.3(@babel/core@7.28.5(supports-color@10.2.2))': dependencies: - '@babel/core': 7.28.5 + '@babel/core': 7.28.5(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.27.1 - '@babel/plugin-syntax-optional-chaining@7.8.3(@babel/core@7.28.5)': + '@babel/plugin-syntax-optional-chaining@7.8.3(@babel/core@7.28.5(supports-color@10.2.2))': dependencies: - '@babel/core': 7.28.5 + '@babel/core': 7.28.5(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.27.1 - '@babel/plugin-syntax-private-property-in-object@7.14.5(@babel/core@7.28.5)': + '@babel/plugin-syntax-private-property-in-object@7.14.5(@babel/core@7.28.5(supports-color@10.2.2))': dependencies: - '@babel/core': 7.28.5 + '@babel/core': 7.28.5(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.27.1 - '@babel/plugin-syntax-top-level-await@7.14.5(@babel/core@7.28.5)': + '@babel/plugin-syntax-top-level-await@7.14.5(@babel/core@7.28.5(supports-color@10.2.2))': dependencies: - '@babel/core': 7.28.5 + '@babel/core': 7.28.5(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.27.1 - '@babel/plugin-syntax-typescript@7.27.1(@babel/core@7.28.5)': + '@babel/plugin-syntax-typescript@7.27.1(@babel/core@7.28.5(supports-color@10.2.2))': dependencies: - '@babel/core': 7.28.5 + '@babel/core': 7.28.5(supports-color@10.2.2) '@babel/helper-plugin-utils': 7.27.1 + '@babel/runtime@7.29.13': {} + '@babel/template@7.27.2': dependencies: '@babel/code-frame': 7.27.1 '@babel/parser': 7.28.5 '@babel/types': 7.28.5 - '@babel/traverse@7.28.5': + '@babel/traverse@7.28.5(supports-color@10.2.2)': dependencies: '@babel/code-frame': 7.27.1 '@babel/generator': 7.28.5 @@ -4779,7 +4930,7 @@ snapshots: '@babel/parser': 7.28.5 '@babel/template': 7.27.2 '@babel/types': 7.28.5 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) transitivePeerDependencies: - supports-color @@ -5140,17 +5291,17 @@ snapshots: '@esbuild/win32-x64@0.25.9': optional: true - '@eslint-community/eslint-utils@4.9.0(eslint@8.57.1)': + '@eslint-community/eslint-utils@4.9.0(eslint@8.57.1(supports-color@10.2.2))': dependencies: - eslint: 8.57.1 + eslint: 8.57.1(supports-color@10.2.2) eslint-visitor-keys: 3.4.3 '@eslint-community/regexpp@4.12.2': {} - '@eslint/eslintrc@2.1.4': + '@eslint/eslintrc@2.1.4(supports-color@10.2.2)': dependencies: ajv: 6.12.6 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) espree: 9.6.1 globals: 13.24.0 ignore: 5.3.2 @@ -5163,10 +5314,10 @@ snapshots: '@eslint/js@8.57.1': {} - '@humanwhocodes/config-array@0.13.0': + '@humanwhocodes/config-array@0.13.0(supports-color@10.2.2)': dependencies: '@humanwhocodes/object-schema': 2.0.3 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) minimatch: 3.1.2 transitivePeerDependencies: - supports-color @@ -5519,12 +5670,12 @@ snapshots: jest-util: 29.7.0 slash: 3.0.0 - '@jest/core@29.7.0': + '@jest/core@29.7.0(supports-color@10.2.2)': dependencies: '@jest/console': 29.7.0 - '@jest/reporters': 29.7.0 + '@jest/reporters': 29.7.0(supports-color@10.2.2) '@jest/test-result': 29.7.0 - '@jest/transform': 29.7.0 + '@jest/transform': 29.7.0(supports-color@10.2.2) '@jest/types': 29.6.3 '@types/node': 16.18.126 ansi-escapes: 4.3.2 @@ -5533,15 +5684,15 @@ snapshots: exit: 0.1.2 graceful-fs: 4.2.11 jest-changed-files: 29.7.0 - jest-config: 29.7.0(@types/node@16.18.126) + jest-config: 29.7.0(@types/node@16.18.126)(supports-color@10.2.2) jest-haste-map: 29.7.0 jest-message-util: 29.7.0 jest-regex-util: 29.6.3 jest-resolve: 29.7.0 - jest-resolve-dependencies: 29.7.0 - jest-runner: 29.7.0 - jest-runtime: 29.7.0 - jest-snapshot: 29.7.0 + jest-resolve-dependencies: 29.7.0(supports-color@10.2.2) + jest-runner: 29.7.0(supports-color@10.2.2) + jest-runtime: 29.7.0(supports-color@10.2.2) + jest-snapshot: 29.7.0(supports-color@10.2.2) jest-util: 29.7.0 jest-validate: 29.7.0 jest-watcher: 29.7.0 @@ -5565,10 +5716,10 @@ snapshots: dependencies: jest-get-type: 29.6.3 - '@jest/expect@29.7.0': + '@jest/expect@29.7.0(supports-color@10.2.2)': dependencies: expect: 29.7.0 - jest-snapshot: 29.7.0 + jest-snapshot: 29.7.0(supports-color@10.2.2) transitivePeerDependencies: - supports-color @@ -5581,21 +5732,21 @@ snapshots: jest-mock: 29.7.0 jest-util: 29.7.0 - '@jest/globals@29.7.0': + '@jest/globals@29.7.0(supports-color@10.2.2)': dependencies: '@jest/environment': 29.7.0 - '@jest/expect': 29.7.0 + '@jest/expect': 29.7.0(supports-color@10.2.2) '@jest/types': 29.6.3 jest-mock: 29.7.0 transitivePeerDependencies: - supports-color - '@jest/reporters@29.7.0': + '@jest/reporters@29.7.0(supports-color@10.2.2)': dependencies: '@bcoe/v8-coverage': 0.2.3 '@jest/console': 29.7.0 '@jest/test-result': 29.7.0 - '@jest/transform': 29.7.0 + '@jest/transform': 29.7.0(supports-color@10.2.2) '@jest/types': 29.6.3 '@jridgewell/trace-mapping': 0.3.31 '@types/node': 16.18.126 @@ -5605,9 +5756,9 @@ snapshots: glob: 7.2.3 graceful-fs: 4.2.11 istanbul-lib-coverage: 3.2.2 - istanbul-lib-instrument: 6.0.3 + istanbul-lib-instrument: 6.0.3(supports-color@10.2.2) istanbul-lib-report: 3.0.1 - istanbul-lib-source-maps: 4.0.1 + istanbul-lib-source-maps: 4.0.1(supports-color@10.2.2) istanbul-reports: 3.2.0 jest-message-util: 29.7.0 jest-util: 29.7.0 @@ -5643,12 +5794,12 @@ snapshots: jest-haste-map: 29.7.0 slash: 3.0.0 - '@jest/transform@29.7.0': + '@jest/transform@29.7.0(supports-color@10.2.2)': dependencies: - '@babel/core': 7.28.5 + '@babel/core': 7.28.5(supports-color@10.2.2) '@jest/types': 29.6.3 '@jridgewell/trace-mapping': 0.3.31 - babel-plugin-istanbul: 6.1.1 + babel-plugin-istanbul: 6.1.1(supports-color@10.2.2) chalk: 4.1.2 convert-source-map: 2.0.0 fast-json-stable-stringify: 2.1.0 @@ -5668,7 +5819,7 @@ snapshots: '@jest/schemas': 29.6.3 '@types/istanbul-lib-coverage': 2.0.6 '@types/istanbul-reports': 3.0.4 - '@types/node': 16.18.126 + '@types/node': 24.10.1 '@types/yargs': 17.0.35 chalk: 4.1.2 @@ -5701,6 +5852,8 @@ snapshots: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.5.5 + '@kurkle/color@0.3.4': {} + '@lezer/common@1.3.0': {} '@lezer/highlight@1.2.3': @@ -5850,7 +6003,7 @@ snapshots: '@poppinss/exception@1.2.2': {} - '@release-it/bumper@7.0.5(release-it@19.0.6(@types/node@16.18.126)(magicast@0.3.5))': + '@release-it/bumper@7.0.5(release-it@19.0.6(@types/node@16.18.126)(magicast@0.3.5)(supports-color@10.2.2))': dependencies: '@iarna/toml': 3.0.0 cheerio: 1.1.2 @@ -5859,10 +6012,10 @@ snapshots: ini: 5.0.0 js-yaml: 4.1.1 lodash-es: 4.17.21 - release-it: 19.0.6(@types/node@16.18.126)(magicast@0.3.5) + release-it: 19.0.6(@types/node@16.18.126)(magicast@0.3.5)(supports-color@10.2.2) semver: 7.7.3 - '@release-it/conventional-changelog@10.0.2(conventional-commits-filter@5.0.0)(conventional-commits-parser@6.2.1)(release-it@19.0.6(@types/node@16.18.126)(magicast@0.3.5))': + '@release-it/conventional-changelog@10.0.2(conventional-commits-filter@5.0.0)(conventional-commits-parser@6.2.1)(release-it@19.0.6(@types/node@16.18.126)(magicast@0.3.5)(supports-color@10.2.2))': dependencies: '@conventional-changelog/git-client': 2.5.1(conventional-commits-filter@5.0.0)(conventional-commits-parser@6.2.1) concat-stream: 2.0.0 @@ -5870,7 +6023,7 @@ snapshots: conventional-changelog-angular: 8.1.0 conventional-changelog-conventionalcommits: 9.1.0 conventional-recommended-bump: 11.2.0 - release-it: 19.0.6(@types/node@16.18.126)(magicast@0.3.5) + release-it: 19.0.6(@types/node@16.18.126)(magicast@0.3.5)(supports-color@10.2.2) semver: 7.7.3 transitivePeerDependencies: - conventional-commits-filter @@ -6042,7 +6195,7 @@ snapshots: '@types/graceful-fs@4.1.9': dependencies: - '@types/node': 16.18.126 + '@types/node': 24.10.1 '@types/istanbul-lib-coverage@2.0.6': {} @@ -6083,10 +6236,15 @@ snapshots: '@types/normalize-package-data@2.4.4': {} + '@types/pako@2.0.4': {} + '@types/parse-path@7.1.0': dependencies: parse-path: 7.1.0 + '@types/raf@3.4.3': + optional: true + '@types/semver@7.7.1': {} '@types/sortablejs@1.15.9': {} @@ -6099,21 +6257,24 @@ snapshots: '@types/tough-cookie@4.0.5': {} + '@types/trusted-types@2.0.7': + optional: true + '@types/yargs-parser@21.0.3': {} '@types/yargs@17.0.35': dependencies: '@types/yargs-parser': 21.0.3 - '@typescript-eslint/eslint-plugin@5.62.0(@typescript-eslint/parser@5.62.0(eslint@8.57.1)(typescript@4.7.3))(eslint@8.57.1)(typescript@4.7.3)': + '@typescript-eslint/eslint-plugin@5.62.0(@typescript-eslint/parser@5.62.0(eslint@8.57.1(supports-color@10.2.2))(supports-color@10.2.2)(typescript@4.7.3))(eslint@8.57.1(supports-color@10.2.2))(supports-color@10.2.2)(typescript@4.7.3)': dependencies: '@eslint-community/regexpp': 4.12.2 - '@typescript-eslint/parser': 5.62.0(eslint@8.57.1)(typescript@4.7.3) + '@typescript-eslint/parser': 5.62.0(eslint@8.57.1(supports-color@10.2.2))(supports-color@10.2.2)(typescript@4.7.3) '@typescript-eslint/scope-manager': 5.62.0 - '@typescript-eslint/type-utils': 5.62.0(eslint@8.57.1)(typescript@4.7.3) - '@typescript-eslint/utils': 5.62.0(eslint@8.57.1)(typescript@4.7.3) - debug: 4.4.3 - eslint: 8.57.1 + '@typescript-eslint/type-utils': 5.62.0(eslint@8.57.1(supports-color@10.2.2))(supports-color@10.2.2)(typescript@4.7.3) + '@typescript-eslint/utils': 5.62.0(eslint@8.57.1(supports-color@10.2.2))(supports-color@10.2.2)(typescript@4.7.3) + debug: 4.4.3(supports-color@10.2.2) + eslint: 8.57.1(supports-color@10.2.2) graphemer: 1.4.0 ignore: 5.3.2 natural-compare-lite: 1.4.0 @@ -6124,13 +6285,13 @@ snapshots: transitivePeerDependencies: - supports-color - '@typescript-eslint/parser@5.62.0(eslint@8.57.1)(typescript@4.7.3)': + '@typescript-eslint/parser@5.62.0(eslint@8.57.1(supports-color@10.2.2))(supports-color@10.2.2)(typescript@4.7.3)': dependencies: '@typescript-eslint/scope-manager': 5.62.0 '@typescript-eslint/types': 5.62.0 - '@typescript-eslint/typescript-estree': 5.62.0(typescript@4.7.3) - debug: 4.4.3 - eslint: 8.57.1 + '@typescript-eslint/typescript-estree': 5.62.0(supports-color@10.2.2)(typescript@4.7.3) + debug: 4.4.3(supports-color@10.2.2) + eslint: 8.57.1(supports-color@10.2.2) optionalDependencies: typescript: 4.7.3 transitivePeerDependencies: @@ -6141,12 +6302,12 @@ snapshots: '@typescript-eslint/types': 5.62.0 '@typescript-eslint/visitor-keys': 5.62.0 - '@typescript-eslint/type-utils@5.62.0(eslint@8.57.1)(typescript@4.7.3)': + '@typescript-eslint/type-utils@5.62.0(eslint@8.57.1(supports-color@10.2.2))(supports-color@10.2.2)(typescript@4.7.3)': dependencies: - '@typescript-eslint/typescript-estree': 5.62.0(typescript@4.7.3) - '@typescript-eslint/utils': 5.62.0(eslint@8.57.1)(typescript@4.7.3) - debug: 4.4.3 - eslint: 8.57.1 + '@typescript-eslint/typescript-estree': 5.62.0(supports-color@10.2.2)(typescript@4.7.3) + '@typescript-eslint/utils': 5.62.0(eslint@8.57.1(supports-color@10.2.2))(supports-color@10.2.2)(typescript@4.7.3) + debug: 4.4.3(supports-color@10.2.2) + eslint: 8.57.1(supports-color@10.2.2) tsutils: 3.21.0(typescript@4.7.3) optionalDependencies: typescript: 4.7.3 @@ -6155,11 +6316,11 @@ snapshots: '@typescript-eslint/types@5.62.0': {} - '@typescript-eslint/typescript-estree@5.62.0(typescript@4.7.3)': + '@typescript-eslint/typescript-estree@5.62.0(supports-color@10.2.2)(typescript@4.7.3)': dependencies: '@typescript-eslint/types': 5.62.0 '@typescript-eslint/visitor-keys': 5.62.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) globby: 11.1.0 is-glob: 4.0.3 semver: 7.7.3 @@ -6169,15 +6330,15 @@ snapshots: transitivePeerDependencies: - supports-color - '@typescript-eslint/utils@5.62.0(eslint@8.57.1)(typescript@4.7.3)': + '@typescript-eslint/utils@5.62.0(eslint@8.57.1(supports-color@10.2.2))(supports-color@10.2.2)(typescript@4.7.3)': dependencies: - '@eslint-community/eslint-utils': 4.9.0(eslint@8.57.1) + '@eslint-community/eslint-utils': 4.9.0(eslint@8.57.1(supports-color@10.2.2)) '@types/json-schema': 7.0.15 '@types/semver': 7.7.1 '@typescript-eslint/scope-manager': 5.62.0 '@typescript-eslint/types': 5.62.0 - '@typescript-eslint/typescript-estree': 5.62.0(typescript@4.7.3) - eslint: 8.57.1 + '@typescript-eslint/typescript-estree': 5.62.0(supports-color@10.2.2)(typescript@4.7.3) + eslint: 8.57.1(supports-color@10.2.2) eslint-scope: 5.1.1 semver: 7.7.3 transitivePeerDependencies: @@ -6191,14 +6352,14 @@ snapshots: '@ungap/structured-clone@1.3.0': {} - '@vitest/coverage-v8@1.6.1(vitest@1.6.1)': + '@vitest/coverage-v8@1.6.1(supports-color@10.2.2)(vitest@1.6.1)': dependencies: '@ampproject/remapping': 2.3.0 '@bcoe/v8-coverage': 0.2.3 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) istanbul-lib-coverage: 3.2.2 istanbul-lib-report: 3.0.1 - istanbul-lib-source-maps: 5.0.6 + istanbul-lib-source-maps: 5.0.6(supports-color@10.2.2) istanbul-reports: 3.2.0 magic-string: 0.30.21 magicast: 0.3.5 @@ -6206,7 +6367,7 @@ snapshots: std-env: 3.10.0 strip-literal: 2.1.1 test-exclude: 6.0.0 - vitest: 1.6.1(@types/node@20.19.25)(@vitest/ui@1.6.1)(jsdom@23.2.0)(terser@5.44.1) + vitest: 1.6.1(@types/node@20.19.25)(@vitest/ui@1.6.1)(jsdom@23.2.0(supports-color@10.2.2))(supports-color@10.2.2)(terser@5.44.1) transitivePeerDependencies: - supports-color @@ -6241,7 +6402,7 @@ snapshots: pathe: 1.1.2 picocolors: 1.1.1 sirv: 2.0.4 - vitest: 1.6.1(@types/node@20.19.25)(@vitest/ui@1.6.1)(jsdom@23.2.0)(terser@5.44.1) + vitest: 1.6.1(@types/node@20.19.25)(@vitest/ui@1.6.1)(jsdom@23.2.0(supports-color@10.2.2))(supports-color@10.2.2)(terser@5.44.1) '@vitest/utils@1.6.1': dependencies: @@ -6258,10 +6419,12 @@ snapshots: dependencies: muggle-string: 0.3.1 - '@volar/typescript@1.11.1': + '@volar/typescript@1.11.1(typescript@5.9.3)': dependencies: '@volar/language-core': 1.11.1 path-browserify: 1.0.1 + optionalDependencies: + typescript: 5.9.3 '@vue/compiler-core@3.5.25': dependencies: @@ -6315,9 +6478,9 @@ snapshots: add-stream@1.0.0: {} - agent-base@6.0.2: + agent-base@6.0.2(supports-color@10.2.2): dependencies: - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) transitivePeerDependencies: - supports-color @@ -6373,25 +6536,25 @@ snapshots: asynckit@0.4.0: {} - babel-jest@29.7.0(@babel/core@7.28.5): + babel-jest@29.7.0(@babel/core@7.28.5(supports-color@10.2.2))(supports-color@10.2.2): dependencies: - '@babel/core': 7.28.5 - '@jest/transform': 29.7.0 + '@babel/core': 7.28.5(supports-color@10.2.2) + '@jest/transform': 29.7.0(supports-color@10.2.2) '@types/babel__core': 7.20.5 - babel-plugin-istanbul: 6.1.1 - babel-preset-jest: 29.6.3(@babel/core@7.28.5) + babel-plugin-istanbul: 6.1.1(supports-color@10.2.2) + babel-preset-jest: 29.6.3(@babel/core@7.28.5(supports-color@10.2.2)) chalk: 4.1.2 graceful-fs: 4.2.11 slash: 3.0.0 transitivePeerDependencies: - supports-color - babel-plugin-istanbul@6.1.1: + babel-plugin-istanbul@6.1.1(supports-color@10.2.2): dependencies: '@babel/helper-plugin-utils': 7.27.1 '@istanbuljs/load-nyc-config': 1.1.0 '@istanbuljs/schema': 0.1.3 - istanbul-lib-instrument: 5.2.1 + istanbul-lib-instrument: 5.2.1(supports-color@10.2.2) test-exclude: 6.0.0 transitivePeerDependencies: - supports-color @@ -6403,33 +6566,36 @@ snapshots: '@types/babel__core': 7.20.5 '@types/babel__traverse': 7.28.0 - babel-preset-current-node-syntax@1.2.0(@babel/core@7.28.5): - dependencies: - '@babel/core': 7.28.5 - '@babel/plugin-syntax-async-generators': 7.8.4(@babel/core@7.28.5) - '@babel/plugin-syntax-bigint': 7.8.3(@babel/core@7.28.5) - '@babel/plugin-syntax-class-properties': 7.12.13(@babel/core@7.28.5) - '@babel/plugin-syntax-class-static-block': 7.14.5(@babel/core@7.28.5) - '@babel/plugin-syntax-import-attributes': 7.27.1(@babel/core@7.28.5) - '@babel/plugin-syntax-import-meta': 7.10.4(@babel/core@7.28.5) - '@babel/plugin-syntax-json-strings': 7.8.3(@babel/core@7.28.5) - '@babel/plugin-syntax-logical-assignment-operators': 7.10.4(@babel/core@7.28.5) - '@babel/plugin-syntax-nullish-coalescing-operator': 7.8.3(@babel/core@7.28.5) - '@babel/plugin-syntax-numeric-separator': 7.10.4(@babel/core@7.28.5) - '@babel/plugin-syntax-object-rest-spread': 7.8.3(@babel/core@7.28.5) - '@babel/plugin-syntax-optional-catch-binding': 7.8.3(@babel/core@7.28.5) - '@babel/plugin-syntax-optional-chaining': 7.8.3(@babel/core@7.28.5) - '@babel/plugin-syntax-private-property-in-object': 7.14.5(@babel/core@7.28.5) - '@babel/plugin-syntax-top-level-await': 7.14.5(@babel/core@7.28.5) - - babel-preset-jest@29.6.3(@babel/core@7.28.5): - dependencies: - '@babel/core': 7.28.5 + babel-preset-current-node-syntax@1.2.0(@babel/core@7.28.5(supports-color@10.2.2)): + dependencies: + '@babel/core': 7.28.5(supports-color@10.2.2) + '@babel/plugin-syntax-async-generators': 7.8.4(@babel/core@7.28.5(supports-color@10.2.2)) + '@babel/plugin-syntax-bigint': 7.8.3(@babel/core@7.28.5(supports-color@10.2.2)) + '@babel/plugin-syntax-class-properties': 7.12.13(@babel/core@7.28.5(supports-color@10.2.2)) + '@babel/plugin-syntax-class-static-block': 7.14.5(@babel/core@7.28.5(supports-color@10.2.2)) + '@babel/plugin-syntax-import-attributes': 7.27.1(@babel/core@7.28.5(supports-color@10.2.2)) + '@babel/plugin-syntax-import-meta': 7.10.4(@babel/core@7.28.5(supports-color@10.2.2)) + '@babel/plugin-syntax-json-strings': 7.8.3(@babel/core@7.28.5(supports-color@10.2.2)) + '@babel/plugin-syntax-logical-assignment-operators': 7.10.4(@babel/core@7.28.5(supports-color@10.2.2)) + '@babel/plugin-syntax-nullish-coalescing-operator': 7.8.3(@babel/core@7.28.5(supports-color@10.2.2)) + '@babel/plugin-syntax-numeric-separator': 7.10.4(@babel/core@7.28.5(supports-color@10.2.2)) + '@babel/plugin-syntax-object-rest-spread': 7.8.3(@babel/core@7.28.5(supports-color@10.2.2)) + '@babel/plugin-syntax-optional-catch-binding': 7.8.3(@babel/core@7.28.5(supports-color@10.2.2)) + '@babel/plugin-syntax-optional-chaining': 7.8.3(@babel/core@7.28.5(supports-color@10.2.2)) + '@babel/plugin-syntax-private-property-in-object': 7.14.5(@babel/core@7.28.5(supports-color@10.2.2)) + '@babel/plugin-syntax-top-level-await': 7.14.5(@babel/core@7.28.5(supports-color@10.2.2)) + + babel-preset-jest@29.6.3(@babel/core@7.28.5(supports-color@10.2.2)): + dependencies: + '@babel/core': 7.28.5(supports-color@10.2.2) babel-plugin-jest-hoist: 29.6.3 - babel-preset-current-node-syntax: 1.2.0(@babel/core@7.28.5) + babel-preset-current-node-syntax: 1.2.0(@babel/core@7.28.5(supports-color@10.2.2)) balanced-match@1.0.2: {} + base64-arraybuffer@1.0.2: + optional: true + baseline-browser-mapping@2.8.31: {} basic-ftp@5.0.5: {} @@ -6513,6 +6679,18 @@ snapshots: caniuse-lite@1.0.30001757: {} + canvg@3.0.11: + dependencies: + '@babel/runtime': 7.29.13 + '@types/raf': 3.4.3 + core-js: 3.51.0 + raf: 3.4.1 + regenerator-runtime: 0.13.11 + rgbcolor: 1.0.1 + stackblur-canvas: 2.7.0 + svg-pathdata: 6.0.3 + optional: true + chai@4.5.0: dependencies: assertion-error: 1.1.0 @@ -6534,6 +6712,14 @@ snapshots: chardet@2.1.1: {} + chart.js@4.6.1: + dependencies: + '@kurkle/color': 0.3.4 + + chartjs-chart-matrix@3.1.0(chart.js@4.6.1): + dependencies: + chart.js: 4.6.1 + check-error@1.0.3: dependencies: get-func-name: 2.0.2 @@ -6762,15 +6948,18 @@ snapshots: cookie@1.1.1: {} + core-js@3.51.0: + optional: true + core-util-is@1.0.3: {} - create-jest@29.7.0(@types/node@16.18.126): + create-jest@29.7.0(@types/node@16.18.126)(supports-color@10.2.2): dependencies: '@jest/types': 29.6.3 chalk: 4.1.2 exit: 0.1.2 graceful-fs: 4.2.11 - jest-config: 29.7.0(@types/node@16.18.126) + jest-config: 29.7.0(@types/node@16.18.126)(supports-color@10.2.2) jest-util: 29.7.0 prompts: 2.4.2 transitivePeerDependencies: @@ -6791,6 +6980,11 @@ snapshots: shebang-command: 2.0.0 which: 2.0.2 + css-line-break@2.1.0: + dependencies: + utrie: 1.0.2 + optional: true + css-select@5.2.2: dependencies: boolbase: 1.0.0 @@ -6806,6 +7000,8 @@ snapshots: css-what@6.2.2: {} + cssesc@3.0.0: {} + cssom@0.3.8: {} cssom@0.5.0: {} @@ -6838,9 +7034,11 @@ snapshots: de-indent@1.0.2: {} - debug@4.4.3: + debug@4.4.3(supports-color@10.2.2): dependencies: ms: 2.1.3 + optionalDependencies: + supports-color: 10.2.2 decimal.js@10.6.0: {} @@ -6907,6 +7105,11 @@ snapshots: dependencies: domelementtype: 2.3.0 + dompurify@3.4.17: + optionalDependencies: + '@types/trusted-types': 2.0.7 + optional: true + domutils@3.2.2: dependencies: dom-serializer: 2.0.0 @@ -7070,20 +7273,20 @@ snapshots: eslint-visitor-keys@3.4.3: {} - eslint@8.57.1: + eslint@8.57.1(supports-color@10.2.2): dependencies: - '@eslint-community/eslint-utils': 4.9.0(eslint@8.57.1) + '@eslint-community/eslint-utils': 4.9.0(eslint@8.57.1(supports-color@10.2.2)) '@eslint-community/regexpp': 4.12.2 - '@eslint/eslintrc': 2.1.4 + '@eslint/eslintrc': 2.1.4(supports-color@10.2.2) '@eslint/js': 8.57.1 - '@humanwhocodes/config-array': 0.13.0 + '@humanwhocodes/config-array': 0.13.0(supports-color@10.2.2) '@humanwhocodes/module-importer': 1.0.1 '@nodelib/fs.walk': 1.2.8 '@ungap/structured-clone': 1.3.0 ajv: 6.12.6 chalk: 4.1.2 cross-spawn: 7.0.6 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) doctrine: 3.0.0 escape-string-regexp: 4.0.0 eslint-scope: 7.2.2 @@ -7197,6 +7400,12 @@ snapshots: fast-levenshtein@2.0.6: {} + fast-png@6.4.0: + dependencies: + '@types/pako': 2.0.4 + iobuffer: 5.4.0 + pako: 2.2.0 + fastq@1.19.1: dependencies: reusify: 1.1.0 @@ -7302,11 +7511,11 @@ snapshots: get-stream@8.0.1: {} - get-uri@6.0.5: + get-uri@6.0.5(supports-color@10.2.2): dependencies: basic-ftp: 5.0.5 data-uri-to-buffer: 6.0.2 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) transitivePeerDependencies: - supports-color @@ -7432,6 +7641,12 @@ snapshots: html-escaper@2.0.2: {} + html2canvas@1.4.1: + dependencies: + css-line-break: 2.1.0 + text-segmentation: 1.0.3 + optional: true + htmlparser2@10.0.0: dependencies: domelementtype: 2.3.0 @@ -7439,32 +7654,32 @@ snapshots: domutils: 3.2.2 entities: 6.0.1 - http-proxy-agent@5.0.0: + http-proxy-agent@5.0.0(supports-color@10.2.2): dependencies: '@tootallnate/once': 2.0.0 - agent-base: 6.0.2 - debug: 4.4.3 + agent-base: 6.0.2(supports-color@10.2.2) + debug: 4.4.3(supports-color@10.2.2) transitivePeerDependencies: - supports-color - http-proxy-agent@7.0.2: + http-proxy-agent@7.0.2(supports-color@10.2.2): dependencies: agent-base: 7.1.4 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) transitivePeerDependencies: - supports-color - https-proxy-agent@5.0.1: + https-proxy-agent@5.0.1(supports-color@10.2.2): dependencies: - agent-base: 6.0.2 - debug: 4.4.3 + agent-base: 6.0.2(supports-color@10.2.2) + debug: 4.4.3(supports-color@10.2.2) transitivePeerDependencies: - supports-color - https-proxy-agent@7.0.6: + https-proxy-agent@7.0.6(supports-color@10.2.2): dependencies: agent-base: 7.1.4 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) transitivePeerDependencies: - supports-color @@ -7537,6 +7752,8 @@ snapshots: optionalDependencies: '@types/node': 20.19.25 + iobuffer@5.4.0: {} + ip-address@10.1.0: {} is-arrayish@0.2.1: {} @@ -7601,9 +7818,9 @@ snapshots: istanbul-lib-coverage@3.2.2: {} - istanbul-lib-instrument@5.2.1: + istanbul-lib-instrument@5.2.1(supports-color@10.2.2): dependencies: - '@babel/core': 7.28.5 + '@babel/core': 7.28.5(supports-color@10.2.2) '@babel/parser': 7.28.5 '@istanbuljs/schema': 0.1.3 istanbul-lib-coverage: 3.2.2 @@ -7611,9 +7828,9 @@ snapshots: transitivePeerDependencies: - supports-color - istanbul-lib-instrument@6.0.3: + istanbul-lib-instrument@6.0.3(supports-color@10.2.2): dependencies: - '@babel/core': 7.28.5 + '@babel/core': 7.28.5(supports-color@10.2.2) '@babel/parser': 7.28.5 '@istanbuljs/schema': 0.1.3 istanbul-lib-coverage: 3.2.2 @@ -7627,18 +7844,18 @@ snapshots: make-dir: 4.0.0 supports-color: 7.2.0 - istanbul-lib-source-maps@4.0.1: + istanbul-lib-source-maps@4.0.1(supports-color@10.2.2): dependencies: - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) istanbul-lib-coverage: 3.2.2 source-map: 0.6.1 transitivePeerDependencies: - supports-color - istanbul-lib-source-maps@5.0.6: + istanbul-lib-source-maps@5.0.6(supports-color@10.2.2): dependencies: '@jridgewell/trace-mapping': 0.3.31 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) istanbul-lib-coverage: 3.2.2 transitivePeerDependencies: - supports-color @@ -7654,10 +7871,10 @@ snapshots: jest-util: 29.7.0 p-limit: 3.1.0 - jest-circus@29.7.0: + jest-circus@29.7.0(supports-color@10.2.2): dependencies: '@jest/environment': 29.7.0 - '@jest/expect': 29.7.0 + '@jest/expect': 29.7.0(supports-color@10.2.2) '@jest/test-result': 29.7.0 '@jest/types': 29.6.3 '@types/node': 16.18.126 @@ -7668,8 +7885,8 @@ snapshots: jest-each: 29.7.0 jest-matcher-utils: 29.7.0 jest-message-util: 29.7.0 - jest-runtime: 29.7.0 - jest-snapshot: 29.7.0 + jest-runtime: 29.7.0(supports-color@10.2.2) + jest-snapshot: 29.7.0(supports-color@10.2.2) jest-util: 29.7.0 p-limit: 3.1.0 pretty-format: 29.7.0 @@ -7680,16 +7897,16 @@ snapshots: - babel-plugin-macros - supports-color - jest-cli@29.7.0(@types/node@16.18.126): + jest-cli@29.7.0(@types/node@16.18.126)(supports-color@10.2.2): dependencies: - '@jest/core': 29.7.0 + '@jest/core': 29.7.0(supports-color@10.2.2) '@jest/test-result': 29.7.0 '@jest/types': 29.6.3 chalk: 4.1.2 - create-jest: 29.7.0(@types/node@16.18.126) + create-jest: 29.7.0(@types/node@16.18.126)(supports-color@10.2.2) exit: 0.1.2 import-local: 3.2.0 - jest-config: 29.7.0(@types/node@16.18.126) + jest-config: 29.7.0(@types/node@16.18.126)(supports-color@10.2.2) jest-util: 29.7.0 jest-validate: 29.7.0 yargs: 17.7.2 @@ -7699,23 +7916,23 @@ snapshots: - supports-color - ts-node - jest-config@29.7.0(@types/node@16.18.126): + jest-config@29.7.0(@types/node@16.18.126)(supports-color@10.2.2): dependencies: - '@babel/core': 7.28.5 + '@babel/core': 7.28.5(supports-color@10.2.2) '@jest/test-sequencer': 29.7.0 '@jest/types': 29.6.3 - babel-jest: 29.7.0(@babel/core@7.28.5) + babel-jest: 29.7.0(@babel/core@7.28.5(supports-color@10.2.2))(supports-color@10.2.2) chalk: 4.1.2 ci-info: 3.9.0 deepmerge: 4.3.1 glob: 7.2.3 graceful-fs: 4.2.11 - jest-circus: 29.7.0 + jest-circus: 29.7.0(supports-color@10.2.2) jest-environment-node: 29.7.0 jest-get-type: 29.6.3 jest-regex-util: 29.6.3 jest-resolve: 29.7.0 - jest-runner: 29.7.0 + jest-runner: 29.7.0(supports-color@10.2.2) jest-util: 29.7.0 jest-validate: 29.7.0 micromatch: 4.0.8 @@ -7748,7 +7965,7 @@ snapshots: jest-util: 29.7.0 pretty-format: 29.7.0 - jest-environment-jsdom@29.7.0: + jest-environment-jsdom@29.7.0(supports-color@10.2.2): dependencies: '@jest/environment': 29.7.0 '@jest/fake-timers': 29.7.0 @@ -7757,7 +7974,7 @@ snapshots: '@types/node': 16.18.126 jest-mock: 29.7.0 jest-util: 29.7.0 - jsdom: 20.0.3 + jsdom: 20.0.3(supports-color@10.2.2) transitivePeerDependencies: - bufferutil - supports-color @@ -7778,7 +7995,7 @@ snapshots: dependencies: '@jest/types': 29.6.3 '@types/graceful-fs': 4.1.9 - '@types/node': 16.18.126 + '@types/node': 24.10.1 anymatch: 3.1.3 fb-watchman: 2.0.2 graceful-fs: 4.2.11 @@ -7826,10 +8043,10 @@ snapshots: jest-regex-util@29.6.3: {} - jest-resolve-dependencies@29.7.0: + jest-resolve-dependencies@29.7.0(supports-color@10.2.2): dependencies: jest-regex-util: 29.6.3 - jest-snapshot: 29.7.0 + jest-snapshot: 29.7.0(supports-color@10.2.2) transitivePeerDependencies: - supports-color @@ -7845,12 +8062,12 @@ snapshots: resolve.exports: 2.0.3 slash: 3.0.0 - jest-runner@29.7.0: + jest-runner@29.7.0(supports-color@10.2.2): dependencies: '@jest/console': 29.7.0 '@jest/environment': 29.7.0 '@jest/test-result': 29.7.0 - '@jest/transform': 29.7.0 + '@jest/transform': 29.7.0(supports-color@10.2.2) '@jest/types': 29.6.3 '@types/node': 16.18.126 chalk: 4.1.2 @@ -7862,7 +8079,7 @@ snapshots: jest-leak-detector: 29.7.0 jest-message-util: 29.7.0 jest-resolve: 29.7.0 - jest-runtime: 29.7.0 + jest-runtime: 29.7.0(supports-color@10.2.2) jest-util: 29.7.0 jest-watcher: 29.7.0 jest-worker: 29.7.0 @@ -7871,14 +8088,14 @@ snapshots: transitivePeerDependencies: - supports-color - jest-runtime@29.7.0: + jest-runtime@29.7.0(supports-color@10.2.2): dependencies: '@jest/environment': 29.7.0 '@jest/fake-timers': 29.7.0 - '@jest/globals': 29.7.0 + '@jest/globals': 29.7.0(supports-color@10.2.2) '@jest/source-map': 29.6.3 '@jest/test-result': 29.7.0 - '@jest/transform': 29.7.0 + '@jest/transform': 29.7.0(supports-color@10.2.2) '@jest/types': 29.6.3 '@types/node': 16.18.126 chalk: 4.1.2 @@ -7891,24 +8108,24 @@ snapshots: jest-mock: 29.7.0 jest-regex-util: 29.6.3 jest-resolve: 29.7.0 - jest-snapshot: 29.7.0 + jest-snapshot: 29.7.0(supports-color@10.2.2) jest-util: 29.7.0 slash: 3.0.0 strip-bom: 4.0.0 transitivePeerDependencies: - supports-color - jest-snapshot@29.7.0: + jest-snapshot@29.7.0(supports-color@10.2.2): dependencies: - '@babel/core': 7.28.5 + '@babel/core': 7.28.5(supports-color@10.2.2) '@babel/generator': 7.28.5 - '@babel/plugin-syntax-jsx': 7.27.1(@babel/core@7.28.5) - '@babel/plugin-syntax-typescript': 7.27.1(@babel/core@7.28.5) + '@babel/plugin-syntax-jsx': 7.27.1(@babel/core@7.28.5(supports-color@10.2.2)) + '@babel/plugin-syntax-typescript': 7.27.1(@babel/core@7.28.5(supports-color@10.2.2)) '@babel/types': 7.28.5 '@jest/expect-utils': 29.7.0 - '@jest/transform': 29.7.0 + '@jest/transform': 29.7.0(supports-color@10.2.2) '@jest/types': 29.6.3 - babel-preset-current-node-syntax: 1.2.0(@babel/core@7.28.5) + babel-preset-current-node-syntax: 1.2.0(@babel/core@7.28.5(supports-color@10.2.2)) chalk: 4.1.2 expect: 29.7.0 graceful-fs: 4.2.11 @@ -7926,7 +8143,7 @@ snapshots: jest-util@29.7.0: dependencies: '@jest/types': 29.6.3 - '@types/node': 16.18.126 + '@types/node': 24.10.1 chalk: 4.1.2 ci-info: 3.9.0 graceful-fs: 4.2.11 @@ -7954,17 +8171,17 @@ snapshots: jest-worker@29.7.0: dependencies: - '@types/node': 16.18.126 + '@types/node': 24.10.1 jest-util: 29.7.0 merge-stream: 2.0.0 supports-color: 8.1.1 - jest@29.7.0(@types/node@16.18.126): + jest@29.7.0(@types/node@16.18.126)(supports-color@10.2.2): dependencies: - '@jest/core': 29.7.0 + '@jest/core': 29.7.0(supports-color@10.2.2) '@jest/types': 29.6.3 import-local: 3.2.0 - jest-cli: 29.7.0(@types/node@16.18.126) + jest-cli: 29.7.0(@types/node@16.18.126)(supports-color@10.2.2) transitivePeerDependencies: - '@types/node' - babel-plugin-macros @@ -7988,7 +8205,7 @@ snapshots: dependencies: argparse: 2.0.1 - jsdom@20.0.3: + jsdom@20.0.3(supports-color@10.2.2): dependencies: abab: 2.0.6 acorn: 8.15.0 @@ -8001,8 +8218,8 @@ snapshots: escodegen: 2.1.0 form-data: 4.0.5 html-encoding-sniffer: 3.0.0 - http-proxy-agent: 5.0.0 - https-proxy-agent: 5.0.1 + http-proxy-agent: 5.0.0(supports-color@10.2.2) + https-proxy-agent: 5.0.1(supports-color@10.2.2) is-potential-custom-element-name: 1.0.1 nwsapi: 2.2.22 parse5: 7.3.0 @@ -8021,7 +8238,7 @@ snapshots: - supports-color - utf-8-validate - jsdom@23.2.0: + jsdom@23.2.0(supports-color@10.2.2): dependencies: '@asamuzakjp/dom-selector': 2.0.2 cssstyle: 4.6.0 @@ -8029,8 +8246,8 @@ snapshots: decimal.js: 10.6.0 form-data: 4.0.5 html-encoding-sniffer: 4.0.0 - http-proxy-agent: 7.0.2 - https-proxy-agent: 7.0.6 + http-proxy-agent: 7.0.2(supports-color@10.2.2) + https-proxy-agent: 7.0.6(supports-color@10.2.2) is-potential-custom-element-name: 1.0.1 parse5: 7.3.0 rrweb-cssom: 0.6.0 @@ -8067,6 +8284,17 @@ snapshots: optionalDependencies: graceful-fs: 4.2.11 + jspdf@4.2.1: + dependencies: + '@babel/runtime': 7.29.13 + fast-png: 6.4.0 + fflate: 0.8.2 + optionalDependencies: + canvg: 3.0.11 + core-js: 3.51.0 + dompurify: 3.4.17 + html2canvas: 1.4.1 + jszip@3.10.1: dependencies: lie: 3.3.0 @@ -8335,7 +8563,7 @@ snapshots: obsidian-daily-notes-interface@0.9.4(@codemirror/state@6.5.2)(@codemirror/view@6.38.8): dependencies: - obsidian: https://codeload.github.com/obsidianmd/obsidian-api/tar.gz/53cf3bd402cec654bcf1d963b43cb01d05a6efdf(@codemirror/state@6.5.2)(@codemirror/view@6.38.8) + obsidian: 1.10.3(@codemirror/state@6.5.2)(@codemirror/view@6.38.8) tslib: 2.1.0 transitivePeerDependencies: - '@codemirror/state' @@ -8348,13 +8576,6 @@ snapshots: '@types/codemirror': 5.60.8 moment: 2.29.4 - obsidian@https://codeload.github.com/obsidianmd/obsidian-api/tar.gz/53cf3bd402cec654bcf1d963b43cb01d05a6efdf(@codemirror/state@6.5.2)(@codemirror/view@6.38.8): - dependencies: - '@codemirror/state': 6.5.2 - '@codemirror/view': 6.38.8 - '@types/codemirror': 5.60.8 - moment: 2.29.4 - ohash@2.0.11: {} once@1.4.0: @@ -8428,16 +8649,16 @@ snapshots: p-try@2.2.0: {} - pac-proxy-agent@7.2.0: + pac-proxy-agent@7.2.0(supports-color@10.2.2): dependencies: '@tootallnate/quickjs-emscripten': 0.23.0 agent-base: 7.1.4 - debug: 4.4.3 - get-uri: 6.0.5 - http-proxy-agent: 7.0.2 - https-proxy-agent: 7.0.6 + debug: 4.4.3(supports-color@10.2.2) + get-uri: 6.0.5(supports-color@10.2.2) + http-proxy-agent: 7.0.2(supports-color@10.2.2) + https-proxy-agent: 7.0.6(supports-color@10.2.2) pac-resolver: 7.0.1 - socks-proxy-agent: 8.0.5 + socks-proxy-agent: 8.0.5(supports-color@10.2.2) transitivePeerDependencies: - supports-color @@ -8448,6 +8669,8 @@ snapshots: pako@1.0.11: {} + pako@2.2.0: {} + parent-module@1.0.1: dependencies: callsites: 3.1.0 @@ -8513,6 +8736,9 @@ snapshots: perfect-debounce@2.0.0: {} + performance-now@2.1.0: + optional: true + picocolors@1.1.1: {} picomatch@2.3.1: {} @@ -8537,6 +8763,11 @@ snapshots: exsolve: 1.0.8 pathe: 2.0.3 + postcss-selector-parser@7.1.7: + dependencies: + cssesc: 3.0.0 + util-deprecate: 1.0.2 + postcss@8.5.6: dependencies: nanoid: 3.3.11 @@ -8560,16 +8791,16 @@ snapshots: protocols@2.0.2: {} - proxy-agent@6.5.0: + proxy-agent@6.5.0(supports-color@10.2.2): dependencies: agent-base: 7.1.4 - debug: 4.4.3 - http-proxy-agent: 7.0.2 - https-proxy-agent: 7.0.6 + debug: 4.4.3(supports-color@10.2.2) + http-proxy-agent: 7.0.2(supports-color@10.2.2) + https-proxy-agent: 7.0.6(supports-color@10.2.2) lru-cache: 7.18.3 - pac-proxy-agent: 7.2.0 + pac-proxy-agent: 7.2.0(supports-color@10.2.2) proxy-from-env: 1.1.0 - socks-proxy-agent: 8.0.5 + socks-proxy-agent: 8.0.5(supports-color@10.2.2) transitivePeerDependencies: - supports-color @@ -8587,6 +8818,11 @@ snapshots: queue-microtask@1.2.3: {} + raf@3.4.1: + dependencies: + performance-now: 2.1.0 + optional: true + rc9@2.1.2: dependencies: defu: 6.1.4 @@ -8626,13 +8862,16 @@ snapshots: readdirp@4.1.2: {} + regenerator-runtime@0.13.11: + optional: true + regexp-match-indices@1.0.2: dependencies: regexp-tree: 0.1.27 regexp-tree@0.1.27: {} - release-it@19.0.6(@types/node@16.18.126)(magicast@0.3.5): + release-it@19.0.6(@types/node@16.18.126)(magicast@0.3.5)(supports-color@10.2.2): dependencies: '@nodeutils/defaults-deep': 1.1.0 '@octokit/rest': 22.0.0 @@ -8650,7 +8889,7 @@ snapshots: open: 10.2.0 ora: 9.0.0 os-name: 6.1.0 - proxy-agent: 6.5.0 + proxy-agent: 6.5.0(supports-color@10.2.2) semver: 7.7.2 tinyglobby: 0.2.15 undici: 6.21.3 @@ -8662,7 +8901,7 @@ snapshots: - magicast - supports-color - release-it@19.0.6(@types/node@20.19.25)(magicast@0.3.5): + release-it@19.0.6(@types/node@20.19.25)(magicast@0.3.5)(supports-color@10.2.2): dependencies: '@nodeutils/defaults-deep': 1.1.0 '@octokit/rest': 22.0.0 @@ -8680,7 +8919,7 @@ snapshots: open: 10.2.0 ora: 9.0.0 os-name: 6.1.0 - proxy-agent: 6.5.0 + proxy-agent: 6.5.0(supports-color@10.2.2) semver: 7.7.2 tinyglobby: 0.2.15 undici: 6.21.3 @@ -8728,6 +8967,9 @@ snapshots: reusify@1.1.0: {} + rgbcolor@1.0.1: + optional: true + rimraf@3.0.2: dependencies: glob: 7.2.3 @@ -8865,10 +9107,10 @@ snapshots: smart-buffer@4.2.0: {} - socks-proxy-agent@8.0.5: + socks-proxy-agent@8.0.5(supports-color@10.2.2): dependencies: agent-base: 7.1.4 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) socks: 2.8.7 transitivePeerDependencies: - supports-color @@ -8916,6 +9158,9 @@ snapshots: stackback@0.0.2: {} + stackblur-canvas@2.7.0: + optional: true + std-env@3.10.0: {} stdin-discarder@0.2.2: {} @@ -8982,6 +9227,9 @@ snapshots: supports-preserve-symlinks-flag@1.0.0: {} + svg-pathdata@6.0.3: + optional: true + symbol-tree@3.2.4: {} temp-dir@3.0.0: {} @@ -9003,6 +9251,11 @@ snapshots: glob: 7.2.3 minimatch: 3.1.2 + text-segmentation@1.0.3: + dependencies: + utrie: 1.0.2 + optional: true + text-table@0.2.0: {} tinybench@2.9.0: {} @@ -9041,12 +9294,12 @@ snapshots: dependencies: punycode: 2.3.1 - ts-jest@29.4.5(@babel/core@7.28.5)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.28.5))(esbuild@0.25.9)(jest-util@29.7.0)(jest@29.7.0(@types/node@16.18.126))(typescript@4.7.3): + ts-jest@29.4.5(@babel/core@7.28.5(supports-color@10.2.2))(@jest/transform@29.7.0(supports-color@10.2.2))(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.28.5(supports-color@10.2.2))(supports-color@10.2.2))(esbuild@0.25.9)(jest-util@29.7.0)(jest@29.7.0(@types/node@16.18.126)(supports-color@10.2.2))(typescript@4.7.3): dependencies: bs-logger: 0.2.6 fast-json-stable-stringify: 2.1.0 handlebars: 4.7.8 - jest: 29.7.0(@types/node@16.18.126) + jest: 29.7.0(@types/node@16.18.126)(supports-color@10.2.2) json5: 2.2.3 lodash.memoize: 4.1.2 make-error: 1.3.6 @@ -9055,10 +9308,10 @@ snapshots: typescript: 4.7.3 yargs-parser: 21.1.1 optionalDependencies: - '@babel/core': 7.28.5 - '@jest/transform': 29.7.0 + '@babel/core': 7.28.5(supports-color@10.2.2) + '@jest/transform': 29.7.0(supports-color@10.2.2) '@jest/types': 29.6.3 - babel-jest: 29.7.0(@babel/core@7.28.5) + babel-jest: 29.7.0(@babel/core@7.28.5(supports-color@10.2.2))(supports-color@10.2.2) esbuild: 0.25.9 jest-util: 29.7.0 @@ -9158,6 +9411,11 @@ snapshots: util-deprecate@1.0.2: {} + utrie@1.0.2: + dependencies: + base64-arraybuffer: 1.0.2 + optional: true + v8-to-istanbul@9.3.0: dependencies: '@jridgewell/trace-mapping': 0.3.31 @@ -9171,10 +9429,10 @@ snapshots: validator@13.15.23: {} - vite-node@1.6.1(@types/node@20.19.25)(terser@5.44.1): + vite-node@1.6.1(@types/node@20.19.25)(supports-color@10.2.2)(terser@5.44.1): dependencies: cac: 6.7.14 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) pathe: 1.1.2 picocolors: 1.1.1 vite: 5.4.21(@types/node@20.19.25)(terser@5.44.1) @@ -9189,12 +9447,12 @@ snapshots: - supports-color - terser - vite-plugin-dts@3.9.1(@types/node@20.19.25)(rollup@4.53.3)(typescript@5.9.3)(vite@5.4.21(@types/node@20.19.25)(terser@5.44.1)): + vite-plugin-dts@3.9.1(@types/node@20.19.25)(rollup@4.53.3)(supports-color@10.2.2)(typescript@5.9.3)(vite@5.4.21(@types/node@20.19.25)(terser@5.44.1)): dependencies: '@microsoft/api-extractor': 7.43.0(@types/node@20.19.25) '@rollup/pluginutils': 5.3.0(rollup@4.53.3) '@vue/language-core': 1.8.27(typescript@5.9.3) - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) kolorist: 1.8.0 magic-string: 0.30.21 typescript: 5.9.3 @@ -9216,7 +9474,7 @@ snapshots: fsevents: 2.3.3 terser: 5.44.1 - vitest@1.6.1(@types/node@20.19.25)(@vitest/ui@1.6.1)(jsdom@23.2.0)(terser@5.44.1): + vitest@1.6.1(@types/node@20.19.25)(@vitest/ui@1.6.1)(jsdom@23.2.0(supports-color@10.2.2))(supports-color@10.2.2)(terser@5.44.1): dependencies: '@vitest/expect': 1.6.1 '@vitest/runner': 1.6.1 @@ -9225,7 +9483,7 @@ snapshots: '@vitest/utils': 1.6.1 acorn-walk: 8.3.4 chai: 4.5.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@10.2.2) execa: 8.0.1 local-pkg: 0.5.1 magic-string: 0.30.21 @@ -9236,12 +9494,12 @@ snapshots: tinybench: 2.9.0 tinypool: 0.8.4 vite: 5.4.21(@types/node@20.19.25)(terser@5.44.1) - vite-node: 1.6.1(@types/node@20.19.25)(terser@5.44.1) + vite-node: 1.6.1(@types/node@20.19.25)(supports-color@10.2.2)(terser@5.44.1) why-is-node-running: 2.3.0 optionalDependencies: '@types/node': 20.19.25 '@vitest/ui': 1.6.1(vitest@1.6.1) - jsdom: 23.2.0 + jsdom: 23.2.0(supports-color@10.2.2) transitivePeerDependencies: - less - lightningcss @@ -9263,7 +9521,7 @@ snapshots: vue-tsc@1.8.27(typescript@5.9.3): dependencies: - '@volar/typescript': 1.11.1 + '@volar/typescript': 1.11.1(typescript@5.9.3) '@vue/language-core': 1.8.27(typescript@5.9.3) semver: 7.7.3 typescript: 5.9.3 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 082815b94..07337c94f 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -3,3 +3,7 @@ packages: onlyBuiltDependencies: - esbuild + +overrides: + 'obsidian-daily-notes-interface>obsidian': '1.10.3' + dompurify: '^3.4.16' diff --git a/scripts/audit-native-points.cjs b/scripts/audit-native-points.cjs new file mode 100644 index 000000000..d5013cff9 --- /dev/null +++ b/scripts/audit-native-points.cjs @@ -0,0 +1,46 @@ +const fs = require("fs"); +const path = require("path"); +const vm = require("vm"); +const crypto = require("crypto"); +const esbuild = require("esbuild"); +const vault = process.argv[2]; +if (!vault) throw new Error("Usage: node scripts/audit-native-points.cjs [report.json]"); +const yamlDirectory = fs.readdirSync("node_modules/.pnpm").find(name => name.startsWith("js-yaml@4")) || fs.readdirSync("node_modules/.pnpm").find(name => name.startsWith("js-yaml@")); +const yaml = require(path.resolve("node_modules/.pnpm", yamlDirectory, "node_modules/js-yaml")); +function readData(file) { + const match = fs.readFileSync(file, "utf8").match(/^---\r?\n([\s\S]*?)\r?\n---/); + return match ? yaml.load(match[1]) || {} : {}; +} +const dataPath = "99_System/01_Data/积分系统数据.md"; +const panelPath = "99_System/00_Panel/CHECK - 每日打卡.md"; +const data = readData(path.join(vault, dataPath)); +const files = fs.readdirSync(path.join(vault, "Habits")).filter(name => name.endsWith(".md")).map(name => `Habits/${name}`); +const inputs = files.map(file => ({ name: path.basename(file, ".md"), path: file, frontmatter: readData(path.join(vault, file)) })).filter(item => item.frontmatter.habit); +const panel = fs.readFileSync(path.join(vault, panelPath), "utf8"); +const helpers = panel.slice(panel.indexOf(" const toText"), panel.indexOf(" const collectHabitData")); +const builder = panel.slice(panel.indexOf(" const buildHabitSummaries"), panel.indexOf(" const { parseYaml, getFrontMatterInfo }")); +const collect = `const collectHabitData = async () => rawHabits.map(item => ({ name:item.name, path:item.path, + type:toText(item.frontmatter.type), frequency:toText(item.frontmatter.frequency,'daily'), target:Math.max(0,toNumber(item.frontmatter.target)), + pointRate:Object.prototype.hasOwnProperty.call(item.frontmatter,'bravoPoints')?toNumber(item.frontmatter.bravoPoints):null, + entries:parseRecordEntries(item.frontmatter.records) }));`; +(async () => { + const today = new Date(); + const todayKey = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, "0")}-${String(today.getDate()).padStart(2, "0")}`; + const old = await vm.runInNewContext(`(async()=>{${helpers}${collect}${builder};return await buildHabitSummaries(frontmatter,todayKey);})()`, { rawHabits: inputs, frontmatter: data, todayKey, Date, Map, Math, Number }); + const module = { exports: {} }; + vm.runInNewContext(esbuild.transformSync(fs.readFileSync("src/managers/daily-points.ts", "utf8"), { loader: "ts", format: "cjs", target: "es2020" }).code, { module, exports: module.exports, Date, Map, Set }); + const native = module.exports.calculateDailyHabitPoints(inputs, data, todayKey); + const mismatches = native.filter(item => { + const prior = old.find(value => value.habit === item.name); + return !prior || prior.points !== item.points || prior.todayPoints !== item.todayPoints; + }); + const sourceHashes = Object.fromEntries([dataPath, panelPath, ...files].map(file => [file, crypto.createHash("sha256").update(fs.readFileSync(path.join(vault, file))).digest("hex")])); + const report = { habits: inputs.length, habitRecords: inputs.reduce((sum, item) => sum + Object.keys(item.frontmatter.records || {}).length, 0), + manualRecords: (data.manualPointRecords || []).length, bonusActions: (data.examplePropertyLeft || []).length, rewardWishes: (data.examplePropertyRight || []).length, + oldHabitPoints: old.reduce((sum, item) => sum + item.points, 0), nativeHabitPoints: native.reduce((sum, item) => sum + item.points, 0), + manualPoints: (data.manualPointRecords || []).reduce((sum, item) => sum + Number(item.points), 0), mismatches, sourceHashes }; + if (process.argv[3]) fs.writeFileSync(process.argv[3], JSON.stringify(report, null, 2)); + const { sourceHashes: _, ...summary } = report; + console.log(JSON.stringify(summary)); + if (mismatches.length) process.exitCode = 1; +})().catch(error => { console.error(error); process.exitCode = 1; }); diff --git a/scripts/audit-source-map.cjs b/scripts/audit-source-map.cjs new file mode 100644 index 000000000..79f146ea9 --- /dev/null +++ b/scripts/audit-source-map.cjs @@ -0,0 +1,33 @@ +const fs = require('node:fs'); +const path = require('node:path'); +const roots = ['src', 'packages/calendar/src', 'scripts', 'tests', '.github/workflows']; +const signals = { + timer: /\b(?:setTimeout|setInterval|requestAnimationFrame)\s*\(/g, + directDomListener: /\.addEventListener\s*\(/g, + htmlAssignment: /\.innerHTML\s*=/g, + dynamicEvaluation: /\b(?:eval\s*\(|new\s+Function\s*\()/g, + directNoteWrite: /(?:this\.)?vault\.modify\s*\(/g, + weakRandom: /Math\.random\s*\(/g, +}; +const files=[]; +function visit(directory) { + for (const entry of fs.readdirSync(directory, {withFileTypes:true})) { + const file=path.join(directory, entry.name); + if(entry.isDirectory())visit(file); + else if(/\.(?:ts|tsx|js|mjs|cjs|css|yml|yaml)$/.test(file)) { + const text=fs.readFileSync(file,'utf8'); + const counts=Object.fromEntries(Object.entries(signals).map(([name,pattern])=>[name,[...text.matchAll(pattern)].length]).filter(([,count])=>count)); + files.push({path:file.replace(/\\/g,'/'),lines:text.split(/\r?\n/).length,bytes:Buffer.byteLength(text),test:/__tests__|\.test\./.test(file),signals:counts}); + } + } +} +roots.forEach(visit); +files.sort((a,b)=>a.path.localeCompare(b.path)); +const report={ + purpose:'Repository-wide static review inventory. Signals are review prompts, not confirmed bugs.', + roots, + totals:{files:files.length,lines:files.reduce((sum,file)=>sum+file.lines,0),testFiles:files.filter(file=>file.test).length,typescriptFiles:files.filter(file=>/\.tsx?$/.test(file.path)).length}, + files, +}; +fs.writeFileSync('docs/audit-2026-11-08-inventory.json',JSON.stringify(report,null,2)+'\n'); +console.log(JSON.stringify(report.totals)); diff --git a/scripts/calendar-layout-fixture.mjs b/scripts/calendar-layout-fixture.mjs new file mode 100644 index 000000000..1400569e9 --- /dev/null +++ b/scripts/calendar-layout-fixture.mjs @@ -0,0 +1,30 @@ +// Independent layout fixture: uses the calendar source and the planner's exported real DOM. +import {build} from 'esbuild'; +import fs from 'node:fs'; +import path from 'node:path'; +const output=path.resolve('output/playwright');fs.mkdirSync(output,{recursive:true}); +await build({stdin:{resolveDir:process.cwd(),loader:'ts',contents:` +import {Calendar,DateFnsAdapter} from './packages/calendar/src'; +import * as dateFns from 'date-fns'; +const day=new Date();day.setHours(0,0,0,0); +const date=(hour,minute=0)=>{const result=new Date(day);result.setHours(hour,minute);return result.toISOString();}; +const calendar=new Calendar(document.querySelector('#engine'),{dateAdapter:new DateFnsAdapter(dateFns),view:{type:'week',firstDayOfWeek:1},events:[ +{id:'a',title:'Exercise',start:date(8),end:date(11)}, +{id:'b',title:'Write',start:date(8,30),end:date(10)}, +{id:'c',title:'Research',start:date(9),end:date(12)} +],theme:{cellHeight:60},onRenderEvent:ctx=>{ctx.defaultRender();const check=document.createElement('input');check.type='checkbox';check.className='task-list-item-checkbox';ctx.el.prepend(check);}}); +calendar.goToDate(day); +window.layoutCalendar=calendar; +window.layoutDay=()=>calendar.setView('day'); +window.layoutWorking=()=>{calendar.config.view.timeFilter=hour=>hour>=6&&hour<21;calendar.setView('day');calendar.refresh();}; +`},bundle:true,format:'iife',platform:'browser',outfile:path.join(output,'calendar.js'),logLevel:'silent'}); +const css=['packages/calendar/dist/styles.css','src/styles/taskgenius-calendar.css','src/styles/task-planner.css','src/styles/points-dashboard.css'].map(file=>fs.readFileSync(file,'utf8')).join('\n'); +const planner=fs.readFileSync(path.join(output,'planner.html'),'utf8');const points=fs.existsSync(path.join(output,'points.html'))?fs.readFileSync(path.join(output,'points.html'),'utf8'):''; +const html=`Task Genius layout verification

Calendar week / day

Task scheduler with 100 unplanned tasks

${planner}

Points and rewards

${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 ` diff --git a/src/index.ts b/src/index.ts index 47bb748e9..c05ea2cb9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,3 +1,5 @@ +import { snapshotViewSettings } from "./services/view-settings-signature"; +import { TaskGeniusHabits } from "./integrations/habits/task-genius-host"; import { addIcon, Editor, @@ -78,6 +80,7 @@ import "./styles/task-status.css"; import "./styles/task-selection.css"; import "./styles/quadrant/quadrant.css"; import "./styles/onboarding.css"; +import "./styles/points-dashboard.css"; import "./styles/universal-suggest.css"; import "./styles/noise.css"; import "./styles/changelog.css"; @@ -97,6 +100,7 @@ import { TaskGeniusIconManager } from "./managers/icon-manager"; import { monitorTaskCompletedExtension } from "./editor-extensions/task-operations/completion-monitor"; import { sortTasksInDocument } from "./commands/sortTaskCommands"; import { taskGutterExtension } from "./editor-extensions/task-operations/gutter-marker"; +import { MarkdownStatusSync } from "./services/markdown-status-sync"; import { autoDateManagerExtension } from "./editor-extensions/date-time/date-manager"; import { taskMarkCleanupExtension } from "./editor-extensions/task-operations/mark-cleanup"; import { IcsManager } from "./managers/ics-manager"; @@ -156,6 +160,26 @@ export default class TaskProgressBarPlugin extends Plugin { rewardManager: RewardManager; habitManager: HabitManager; + habitsIntegration?: TaskGeniusHabits; + private viewSettingsSignature = ""; + async ensureHabitsIntegration(): Promise { + if (this.settings.habit.enableHabits && !this.habitManager) { + this.habitManager = this.addChild(new HabitManager(this)); + } + if (!this.habitsIntegration) { + this.habitsIntegration = new TaskGeniusHabits(this); + this.addChild(this.habitsIntegration); + } + const integration = this.habitsIntegration; + try { await integration.ready; return integration; } + catch (error) { + if (this.habitsIntegration === integration) { + this.removeChild(integration); + this.habitsIntegration = undefined; + } + throw error; + } + } // Task timer manager and exporter taskTimerManager: TaskTimerManager; @@ -222,6 +246,7 @@ export default class TaskProgressBarPlugin extends Plugin { async onload() { console.time("[Task Genius] onload"); await this.loadSettings(); + this.addChild(new MarkdownStatusSync(this)); // Initialize version manager first this.versionManager = new VersionManager(this.app, this); @@ -405,8 +430,7 @@ export default class TaskProgressBarPlugin extends Plugin { }); if (this.settings.habit.enableHabits) { - this.habitManager = new HabitManager(this); - this.addChild(this.habitManager); + await this.ensureHabitsIntegration(); } // Initialize ICS manager if sources are configured @@ -490,9 +514,9 @@ export default class TaskProgressBarPlugin extends Plugin { this.initializeWriteAPI(); this.initializeOnCompletionManager(); - if (this.settings.rewards.enableRewards) { - this.initializeRewardManager(); - } + // Points are part of the built-in dashboard even when random rewards are + // disabled. RewardManager owns both point awards and optional rewards. + this.initializeRewardManager(); this.scheduleExtendedCommands(); @@ -1891,6 +1915,9 @@ export default class TaskProgressBarPlugin extends Plugin { async loadSettings() { const savedData = await this.loadData(); this.settings = Object.assign({}, DEFAULT_SETTINGS, savedData); + this.settings.rewards = { ...DEFAULT_SETTINGS.rewards, ...savedData?.rewards, + rewardItems: savedData?.rewards?.rewardItems || DEFAULT_SETTINGS.rewards.rewardItems.map(item => ({ ...item })), + pointsLedger: savedData?.rewards?.pointsLedger || [] }; this.settings.changelog = Object.assign( { enabled: true, @@ -1911,6 +1938,25 @@ export default class TaskProgressBarPlugin extends Plugin { // Migrate settings to new formats migrateSettings(this.settings); + this.settings.enableIndexer = true; + if (this.settings.fileFilter?.scopeControls) this.settings.fileFilter.scopeControls.inlineTasksEnabled = true; + if ((this.settings.interfaceRevision || 0) < 9134) { + for (const view of this.settings.viewConfiguration || []) { + if (view.specificConfig?.viewType !== "table") continue; + const widths = view.specificConfig.columnWidths; + if (!widths) continue; + if (widths.status === 80) widths.status = 64; + if (widths.content === 300) widths.content = 420; + if (widths.priority === 100) widths.priority = 72; + } + this.settings.interfaceRevision = 9134; + } + this.settings.viewConfiguration = this.settings.viewConfiguration.filter(view => view.id !== "rewards"); + for (const view of this.settings.viewConfiguration || []) { + if (view.id === "review") view.visible = false; + if (view.id === "points" && ["Points", "积分", "Points and rewards", "积分与奖励"].includes(view.name)) view.name = t("Points and rewards"); + if (view.id === "gantt" && ["计划", "Gantt", "Gantt Chart", "Planning", "Project plans", "项目计划"].includes(view.name)) view.name = t("Project Gantt"); + } // Repair and validate status cycles if (this.settings.statusCycles) { @@ -1921,6 +1967,7 @@ export default class TaskProgressBarPlugin extends Plugin { // Migrate old inheritance settings to new structure this.migrateInheritanceSettings(savedData); + this.viewSettingsSignature = snapshotViewSettings(this.settings); } private migrateInheritanceSettings(savedData: any) { @@ -1961,6 +2008,11 @@ export default class TaskProgressBarPlugin extends Plugin { ); } catch {} await this.saveData(this.settings); + const viewSignature = snapshotViewSettings(this.settings); + if (viewSignature !== this.viewSettingsSignature) { + this.viewSettingsSignature = viewSignature; + this.app.workspace.trigger("task-genius:view-config-changed", {reason:"settings-saved"}); + } } async loadViews() { @@ -2093,6 +2145,11 @@ export default class TaskProgressBarPlugin extends Plugin { } } } + for (const leaf of this.app.workspace.getLeavesOfType("fluent-task-genius-view")) { + const view = leaf.view as any; + if (typeof view.refreshSettings === "function") await view.refreshSettings(); + else { view.layoutManager?.sidebar?.render(); await view.dataManager?.loadTasks(false); } + } } /** diff --git a/src/integrations/habits/LICENSE b/src/integrations/habits/LICENSE new file mode 100644 index 000000000..e3808aeab --- /dev/null +++ b/src/integrations/habits/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 James Clifford Spratt + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/src/integrations/habits/UPSTREAM.md b/src/integrations/habits/UPSTREAM.md new file mode 100644 index 000000000..23e4f00ac --- /dev/null +++ b/src/integrations/habits/UPSTREAM.md @@ -0,0 +1,9 @@ +# Habits integration + +Ported from [JamesCliffordSpratt/obsidian-habits](https://github.com/JamesCliffordSpratt/obsidian-habits), version 1.12.1, commit `38c44bc4d329455701045ca0858109b5a1708c56`. + +Copyright (c) 2025 James Clifford Spratt. The vendored implementation is MIT licensed; see LICENSE in this directory. Task Genius's existing license is unchanged. The MIT notice is also included in distributed JavaScript. + +Task Genius changes: host settings adapter, namespaced views/commands/code blocks, embedded dashboard/settings, scoped theme styling, legacy-record compatibility, configurable data location, optional completion-based intervals, and integration regression tests. No source from zm4341/taskgenius-plugin is used. + +`upstream.css` is preserved as input; regenerate `scoped.css` with `node scripts/scope-habits-css.mjs` when changing upstream styling. diff --git a/src/integrations/habits/ai-summary.ts b/src/integrations/habits/ai-summary.ts new file mode 100644 index 000000000..4d48672f8 --- /dev/null +++ b/src/integrations/habits/ai-summary.ts @@ -0,0 +1,275 @@ +import { moment, requestUrl } from "obsidian"; +import type { AiSummarySettings } from "./settings"; +import type { HabitDefinition } from "./types"; +import { + getStatsRange, + habitStats, + perfectDays, + rangeLength, + trackingStartKey, + type DateRange, + type StatsPeriod, + type StatsRangeMode, +} from "./stats"; +import { formatValue, toDateKey } from "./utils"; + +/** + * Most habits ever included in a digest. Keeps the prompt (and its cost) + * bounded for users tracking an unusually large number of habits. + */ +const MAX_HABITS = 40; + +/** Most cached summaries kept in memory before the oldest are dropped. */ +const CACHE_LIMIT = 20; + +/** + * Completed summaries keyed by everything that influenced them (model, + * period, mode and the digest itself). Because the digest is built from the + * logged records, any change to the underlying data produces a new key — + * so a cached summary is never stale, and switching tabs back and forth + * never repeats an API call. + */ +const cache = new Map(); + +function cacheKey( + settings: AiSummarySettings, + period: StatsPeriod, + mode: StatsRangeMode, + digest: string, +): string { + return `${settings.baseUrl.trim().replace(/\/+$/, "")}|${settings.model}|${period}|${mode}|${digest}`; +} + +/** A cached summary for this exact data, or null when none exists yet. */ +export function getCachedSummary( + settings: AiSummarySettings, + period: StatsPeriod, + mode: StatsRangeMode, + digest: string, +): string | null { + return cache.get(cacheKey(settings, period, mode, digest)) ?? null; +} + +/** + * Build a compact plain-text digest of the stats the user is looking at. + * This is the only data ever sent to the AI service — habit names and + * aggregate numbers, never per-day records or comments. + */ +export function buildStatsDigest( + habits: HabitDefinition[], + period: StatsPeriod, + mode: StatsRangeMode, + today: Date, + /** The user-picked range; only used when `period` is `custom`. */ + customRange?: DateRange, +): string { + const range = getStatsRange(today, period, mode, customRange); + const length = rangeLength(range); + const all = habits.map((habit) => habitStats(habit, range, today)); + + const totalDays = all.reduce((sum, s) => sum + s.days, 0); + const totalCompleted = all.reduce((sum, s) => sum + s.completed, 0); + const overallRate = + totalDays > 0 ? Math.round((totalCompleted / totalDays) * 100) : 0; + const perfect = perfectDays(habits, range, today); + + const periodLine = + period === "custom" + ? `Period: custom date range of ${length} days, ${toDateKey(range.start)} to ${toDateKey(range.end)}.` + : `Period: ${period === "weekly" ? "week" : "month"} (${ + mode === "rolling" + ? `rolling last ${length} days` + : "calendar" + }), ${toDateKey(range.start)} to ${toDateKey(range.end)}.`; + const lines: string[] = [ + periodLine, + `Overall completion: ${overallRate}%. Perfect days (every habit done): ${perfect}.`, + `Habits (${habits.length}):`, + ]; + + habits.slice(0, MAX_HABITS).forEach((habit, i) => { + const s = all[i]; + const parts: string[] = []; + if (habit.goalDirection === "max") { + parts.push( + habit.type === "binary" + ? "avoiding entirely" + : `limit of ${formatValue(habit.target)}${habit.unit ? ` ${habit.unit}` : ""} per day`, + ); + parts.push(`${s.completed}/${s.days} days within limit`); + if (habit.type !== "binary") { + parts.push( + `${formatValue(s.total)}${habit.unit ? ` ${habit.unit}` : ""} consumed in period`, + ); + } + } else { + const period = + habit.frequency === "flexibleWeekly" + ? "per week, any day" + : habit.frequency === "flexibleMonthly" + ? "per month, any day" + : "per day"; + if (habit.type === "repetition") { + parts.push( + `target ${formatValue(habit.target)}${habit.unit ? ` ${habit.unit}` : ""} ${period}`, + ); + } else if (habit.type === "timed") { + parts.push(`target ${habit.target} min ${period}`); + } else if (habit.frequency === "flexibleWeekly") { + parts.push(`target ${habit.target}x per week, any day`); + } else if (habit.frequency === "flexibleMonthly") { + parts.push(`target ${habit.target}x per month, any day`); + } + parts.push(`${s.completed}/${s.days} due days completed`); + if (habit.type !== "binary") { + parts.push( + `${formatValue(s.total)}${habit.unit ? ` ${habit.unit}` : habit.type === "timed" ? " min" : ""} total`, + ); + } + } + if (habit.frequency === "interval") { + parts.push(`due every ${habit.intervalDays} days`); + } else if ( + habit.frequency === "flexibleWeekly" || + habit.frequency === "flexibleMonthly" + ) { + // Already covered by the target line above. + } else if (habit.frequency !== "daily") { + parts.push(`due ${habit.frequency}`); + } + if (habit.times.length > 0) { + parts.push(`planned at ${habit.times.join(", ")}`); + } + parts.push(`${Math.round(s.rate * 100)}% rate`); + parts.push(`current streak ${s.current}, best ${s.best}`); + // Weekly/monthly goals don't apply to an arbitrary custom range. + if (period !== "custom") { + const goal = + period === "weekly" + ? habit.weeklyTarget + : habit.monthlyTarget; + const isPerfect = + period === "weekly" + ? habit.weeklyPerfect + : habit.monthlyPerfect; + if (isPerfect) { + parts.push(`aiming for a perfect ${period.replace("ly", "")}`); + } else if (goal > 0) { + parts.push(`${period} goal ${s.completed}/${goal} days`); + } + } + if (habit.paused) { + parts.push("currently paused"); + } + const startKey = trackingStartKey(habit, today); + if (startKey > toDateKey(range.start)) { + // Partially tracked period: stats above already exclude earlier + // days, but the model should know the window is shorter. + parts.push(`only tracked since ${startKey}`); + } + lines.push(`- ${habit.name}: ${parts.join(", ")}`); + }); + if (habits.length > MAX_HABITS) { + lines.push(`(and ${habits.length - MAX_HABITS} more habits omitted)`); + } + return lines.join("\n"); +} + +function systemPrompt(period: StatsPeriod): string { + const periodLabel = + period === "weekly" + ? "current week" + : period === "monthly" + ? "current month" + : "date range they selected"; + return [ + "You are a supportive, practical habit coach inside a habit-tracking app.", + `You are given a user's habit statistics for the ${periodLabel}.`, + "Write a short summary of 4 to 6 sentences in plain prose — no markdown, no headings, no bullet points.", + "Briefly acknowledge what is going well, point out the habit or two that most needs attention, and give one or two specific, actionable suggestions for improvement.", + "Habits marked as limits are ones the user wants to stay under, so low totals there are good.", + "Be encouraging but honest; never invent numbers that are not in the data.", + `Respond in the language with locale code "${moment.locale()}".`, + ].join(" "); +} + +/** + * Request a summary from the configured OpenAI-compatible endpoint. + * Results are cached (see {@link getCachedSummary}); the API key is sent + * only as an Authorization header and may be blank for local endpoints + * such as Ollama or LM Studio. + */ +export async function generateSummary( + settings: AiSummarySettings, + period: StatsPeriod, + mode: StatsRangeMode, + digest: string, + /** Skip the cache and request a fresh summary (the Regenerate button). */ + force = false, +): Promise { + const key = cacheKey(settings, period, mode, digest); + const cached = cache.get(key); + if (cached && !force) { + return cached; + } + + const base = settings.baseUrl.trim().replace(/\/+$/, ""); + const headers: Record = { + "Content-Type": "application/json", + }; + if (settings.apiKey.trim() !== "") { + headers.Authorization = `Bearer ${settings.apiKey.trim()}`; + } + const response = await requestUrl({ + url: `${base}/chat/completions`, + method: "POST", + headers, + body: JSON.stringify({ + model: settings.model, + messages: [ + { role: "system", content: systemPrompt(period) }, + { role: "user", content: digest }, + ], + // Generous cap: on reasoning models (e.g. Gemini 2.5) internal + // "thinking" tokens count against this limit, so a tight cap + // truncates the visible summary mid-sentence. The prompt already + // keeps the actual reply short. + max_tokens: 4000, + temperature: 0.7, + }), + throw: false, + }); + + if (response.status >= 400) { + let detail = `HTTP ${response.status}`; + try { + const err = ( + response.json as { error?: { message?: string } } | null + )?.error?.message; + if (err) { + detail = err; + } + } catch { + // Non-JSON error body; keep the status code. + } + throw new Error(detail); + } + + const text = ( + response.json as { + choices?: { message?: { content?: string } }[]; + } | null + )?.choices?.[0]?.message?.content?.trim(); + if (!text) { + throw new Error("The AI service returned an empty response."); + } + + if (cache.size >= CACHE_LIMIT) { + const oldest = cache.keys().next().value; + if (oldest !== undefined) { + cache.delete(oldest); + } + } + cache.set(key, text); + return text; +} diff --git a/src/integrations/habits/comment-log.ts b/src/integrations/habits/comment-log.ts new file mode 100644 index 000000000..9180ce9e1 --- /dev/null +++ b/src/integrations/habits/comment-log.ts @@ -0,0 +1,157 @@ +/** + * Day comments stored as a list in the note body. + * + * Frontmatter cannot carry tags or links that Obsidian will index — it + * only reads tags from the `tags` property and from the body — so the + * comments live in a marked-off section of the note instead: + * + * ```markdown + * %%habits-log%% + * - **2026-08-05** — Ran 5k #fitness with [[Marathon Plan]] + * - **2026-08-04** — Rest day #recovery + * %%/habits-log%% + * ``` + * + * The markers are Obsidian comments, so they vanish in reading view + * while the list itself renders, stays editable by hand, and is indexed + * like any other note content. + */ + +/** Opening marker for the managed section. */ +export const LOG_START = "%%habits-log%%"; +/** Closing marker for the managed section. */ +export const LOG_END = "%%/habits-log%%"; + +/** + * One log entry. + * + * Parsing is deliberately forgiving so an entry the user has reformatted + * by hand still round-trips: the bullet may be `-` or `*`, the date may + * be bold and/or a `[[wiki link]]`, and the separator may be any dash or + * a colon. Writing always uses the canonical form. + */ +const ENTRY_RE = + /^[ \t]*[-*][ \t]+(?:\*\*)?(?:\[\[)?(\d{4}-\d{2}-\d{2})(?:\]\])?(?:\*\*)?[ \t]*(?:[—–:-][ \t]*)?(.*)$/; + +/** Canonical rendering of a single entry, including any extra lines. */ +function formatEntry(dateKey: string, text: string): string { + const [first = "", ...rest] = text.split("\n"); + // Continuation lines are indented so Markdown keeps them in the item. + const tail = rest.map((line) => ` ${line}`); + return [`- **${dateKey}** — ${first}`, ...tail].join("\n"); +} + +/** Locate the managed section, if the note has one. */ +function findSection( + lines: string[], +): { start: number; end: number } | null { + const start = lines.findIndex((line) => line.trim() === LOG_START); + if (start === -1) { + return null; + } + const end = lines.findIndex( + (line, index) => index > start && line.trim() === LOG_END, + ); + return end === -1 ? null : { start, end }; +} + +/** Read the day comments out of a note's raw contents. */ +export function parseCommentLog(content: string): Record { + const lines = content.split("\n"); + const section = findSection(lines); + if (!section) { + return {}; + } + + const comments: Record = {}; + let current: string | null = null; + for (let i = section.start + 1; i < section.end; i++) { + const line = lines[i]; + const match = ENTRY_RE.exec(line); + if (match) { + current = match[1]; + comments[current] = match[2].trim(); + continue; + } + // An indented line continues the entry above it; anything else + // (including a blank line) ends it. + if (current && /^[ \t]+\S/.test(line)) { + comments[current] = `${comments[current]}\n${line.trim()}`.trim(); + continue; + } + current = null; + } + + // Entries left empty by a hand edit are treated as absent. + for (const [key, value] of Object.entries(comments)) { + if (value === "") { + delete comments[key]; + } + } + return comments; +} + +/** True when the note already carries a managed section. */ +export function hasCommentLog(content: string): boolean { + return findSection(content.split("\n")) !== null; +} + +/** + * Return `content` with its managed section replaced by `comments`, + * newest day first. An empty map removes the section entirely. + * + * If the note opens a frontmatter block that is never closed the content + * is returned untouched, rather than risk appending inside it. + */ +export function applyCommentLog( + content: string, + comments: Record, +): string { + const lines = content.split("\n"); + const section = findSection(lines); + + const entries = Object.keys(comments) + .filter((key) => comments[key].trim() !== "") + .sort((a, b) => b.localeCompare(a)) + .map((key) => formatEntry(key, comments[key].trim())); + + if (section) { + if (entries.length === 0) { + // Drop the section and the blank line that padded it. + const before = lines.slice(0, section.start); + const after = lines.slice(section.end + 1); + while (before.length > 0 && before[before.length - 1] === "") { + before.pop(); + } + while (after.length > 0 && after[0] === "") { + after.shift(); + } + const body = [...before, ...(after.length > 0 ? [""] : []), ...after]; + return `${body.join("\n").replace(/\n+$/, "")}\n`; + } + return [ + ...lines.slice(0, section.start + 1), + ...entries, + ...lines.slice(section.end), + ].join("\n"); + } + + if (entries.length === 0) { + return content; + } + if (!frontmatterIsClosed(lines)) { + return content; + } + + const body = content.replace(/\s+$/, ""); + const block = [LOG_START, ...entries, LOG_END].join("\n"); + return body === "" ? `${block}\n` : `${body}\n\n${block}\n`; +} + +/** False only when the note starts a `---` block it never closes. */ +function frontmatterIsClosed(lines: string[]): boolean { + if (lines[0]?.trim() !== "---") { + return true; + } + return lines.slice(1).some((line) => line.trim() === "---"); +} diff --git a/src/integrations/habits/comment-text.ts b/src/integrations/habits/comment-text.ts new file mode 100644 index 000000000..abc6bfd4d --- /dev/null +++ b/src/integrations/habits/comment-text.ts @@ -0,0 +1,204 @@ +import { App, Component } from "obsidian"; + +/** + * Parsing and rendering for the rich bits of a day comment: Obsidian + * tags (`#tag`) and internal links (`[[Note]]` / `[[Note|alias]]`). + * + * Comments live inside frontmatter, so they are stored as plain strings + * and only interpreted when we render them on a card. + */ + +/** One piece of a parsed comment. */ +export type CommentToken = + | { kind: "text"; text: string } + | { kind: "tag"; text: string; tag: string } + | { kind: "link"; text: string; target: string; alias: string }; + +/** + * Matches a tag or a wiki link. + * + * Tags follow Obsidian's rules: they start with `#`, must contain at + * least one non-numeric character, and may nest with `/`. A tag only + * counts when it is not glued to the end of a preceding word, which the + * caller checks via the character before the match. + */ +const TOKEN_RE = /\[\[([^\][|]+)(?:\|([^\][]*))?\]\]|#([\w/\-_À-￿]+)/gu; + +/** True when `raw` (without `#`) is a usable Obsidian tag. */ +function isTagBody(raw: string): boolean { + // Purely numeric tags are not valid in Obsidian, and a trailing or + // leading slash makes for an empty nesting level. + if (raw === "" || /^[\d/]+$/.test(raw)) { + return false; + } + return !raw.startsWith("/") && !raw.endsWith("/"); +} + +/** Split comment text into plain runs, tags and links. */ +export function parseComment(text: string): CommentToken[] { + const tokens: CommentToken[] = []; + let last = 0; + TOKEN_RE.lastIndex = 0; + + const pushText = (upto: number): void => { + if (upto > last) { + tokens.push({ kind: "text", text: text.slice(last, upto) }); + } + }; + + let match: RegExpExecArray | null; + while ((match = TOKEN_RE.exec(text)) !== null) { + const [whole, linkTarget, linkAlias, tagBody] = match; + if (tagBody !== undefined) { + const before = match.index > 0 ? text[match.index - 1] : " "; + if (!/\s|^$/.test(before) || !isTagBody(tagBody)) { + continue; + } + pushText(match.index); + tokens.push({ kind: "tag", text: whole, tag: tagBody }); + } else { + const target = linkTarget.trim(); + if (target === "") { + continue; + } + pushText(match.index); + tokens.push({ + kind: "link", + text: whole, + target, + alias: (linkAlias ?? "").trim() || target, + }); + } + last = match.index + whole.length; + } + pushText(text.length); + return tokens; +} + +/** Every distinct tag (without the leading `#`) used in a comment. */ +export function tagsInComment(text: string): string[] { + const seen = new Set(); + for (const token of parseComment(text)) { + if (token.kind === "tag") { + seen.add(token.tag); + } + } + return [...seen]; +} + +/** Every distinct tag used across a whole `comments` map. */ +export function tagsInComments(comments: Record): Set { + const all = new Set(); + for (const text of Object.values(comments)) { + for (const tag of tagsInComment(text)) { + all.add(tag); + } + } + return all; +} + +/** True when the comment holds at least one tag or link. */ +export function hasRichTokens(text: string): boolean { + return parseComment(text).some((token) => token.kind !== "text"); +} + +/** Options for {@link renderComment}. */ +export interface RenderCommentOptions { + /** Note path the links are resolved relative to. */ + sourcePath: string; + /** Component the hover-preview listeners are tied to. */ + component: Component; +} + +/** + * Render a comment into `el` with clickable tag chips and internal + * links. Links open the target note and support Obsidian's hover + * preview; tags open the search pane filtered to that tag. + */ +export function renderComment( + app: App, + el: HTMLElement, + text: string, + options: RenderCommentOptions, +): void { + el.empty(); + for (const token of parseComment(text)) { + if (token.kind === "text") { + el.appendText(token.text); + continue; + } + + if (token.kind === "tag") { + const chip = el.createEl("a", { + cls: "habits-comment-tag", + text: `#${token.tag}`, + href: `#${token.tag}`, + }); + chip.addEventListener("click", (event) => { + event.preventDefault(); + event.stopPropagation(); + openTagSearch(app, token.tag); + }); + continue; + } + + const link = el.createEl("a", { + cls: "habits-comment-link internal-link", + text: token.alias, + href: token.target, + }); + link.dataset.href = token.target; + const resolved = app.metadataCache.getFirstLinkpathDest( + token.target, + options.sourcePath, + ); + if (!resolved) { + link.addClass("is-unresolved"); + } + link.addEventListener("click", (event) => { + event.preventDefault(); + event.stopPropagation(); + void app.workspace.openLinkText( + token.target, + options.sourcePath, + event.ctrlKey || event.metaKey, + ); + }); + options.component.registerDomEvent(link, "mouseover", (event) => { + (app.workspace as unknown as {trigger(name: string, event: unknown): void}).trigger("hover-link", { + event, + source: "tg-habits", + hoverParent: options.component, + targetEl: link, + linktext: token.target, + sourcePath: options.sourcePath, + }); + }); + } +} + +/** Open the search pane filtered to a tag, mirroring the tag pane. */ +function openTagSearch(app: App, tag: string): void { + const search = app.workspace.getLeavesOfType("search")[0]; + const query = `tag:#${tag}`; + if (search) { + const view = search.view as unknown as { + setQuery?: (value: string) => void; + }; + if (typeof view.setQuery === "function") { + void app.workspace.revealLeaf(search); + view.setQuery(query); + return; + } + } + const globalSearch = ( + app as unknown as { + internalPlugins?: { + getPluginById?: (id: string) => { + instance?: { openGlobalSearch?: (q: string) => void }; + } | null; + }; + } + ).internalPlugins?.getPluginById?.("global-search"); + globalSearch?.instance?.openGlobalSearch?.(query); +} diff --git a/src/integrations/habits/compat.d.ts b/src/integrations/habits/compat.d.ts new file mode 100644 index 000000000..a69cf2c03 --- /dev/null +++ b/src/integrations/habits/compat.d.ts @@ -0,0 +1,4 @@ +/** Modern optional DOM API; callers keep their runtime feature checks. */ +interface HTMLInputElement { + showPicker?: () => void; +} diff --git a/src/integrations/habits/habit-store.ts b/src/integrations/habits/habit-store.ts new file mode 100644 index 000000000..115d5f38d --- /dev/null +++ b/src/integrations/habits/habit-store.ts @@ -0,0 +1,1474 @@ +import { isDue, isComplete, isRescheduleTargetOpen, isRescheduleEligible, isPausedOn, isFailedOn } from "./stats"; +import { App, normalizePath, Notice, TFile, TFolder } from "obsidian"; +import { + DEFAULT_FRONTMATTER_KEYS, + type FrontmatterKeys, + type HabitsPluginSettings, +} from "./settings"; +import type { + GroupStyle, + HabitDefinition, + HabitFrequency, + HabitPause, + HabitReschedule, + HabitType, + NewHabitOptions, + NoteChecklistRequirement, + NoteCompletionMode, +} from "./types"; +import { + addDays, + fromDateKey, + isFlexibleFrequency, + roundValue, + sanitizeFileName, + toDateKey, +} from "./utils"; +import { tagsInComments } from "./comment-text"; +import { applyCommentLog, parseCommentLog } from "./comment-log"; +import { t } from "./i18n"; +import { DEFAULT_NOTE_FILENAME_FORMAT } from "./note-habit"; + +const HABIT_TYPES: readonly HabitType[] = [ + "binary", + "repetition", + "timed", + "note", +]; +const HABIT_FREQUENCIES: readonly HabitFrequency[] = [ + "daily", + "weekly", + "monthly", + "interval", + "flexibleWeekly", + "flexibleMonthly", +]; +const NOTE_COMPLETION_MODES: readonly NoteCompletionMode[] = [ + "chars", + "checklist", + "both", +]; +const NOTE_CHECKLIST_REQUIREMENTS: readonly NoteChecklistRequirement[] = [ + "all", + "count", +]; + +function isHabitType(value: unknown): value is HabitType { + return ( + typeof value === "string" && + (HABIT_TYPES as readonly string[]).includes(value) + ); +} + +function isNoteCompletionMode(value: unknown): value is NoteCompletionMode { + return ( + typeof value === "string" && + (NOTE_COMPLETION_MODES as readonly string[]).includes(value) + ); +} + +function isNoteChecklistRequirement( + value: unknown, +): value is NoteChecklistRequirement { + return ( + typeof value === "string" && + (NOTE_CHECKLIST_REQUIREMENTS as readonly string[]).includes(value) + ); +} + +function isHabitFrequency(value: unknown): value is HabitFrequency { + return ( + typeof value === "string" && + (HABIT_FREQUENCIES as readonly string[]).includes(value) + ); +} + +/** Shallow equality for a day-keyed comment map. */ +function sameComments( + a: Record, + b: Record, +): boolean { + const keys = Object.keys(a); + return ( + keys.length === Object.keys(b).length && + keys.every((key) => a[key] === b[key]) + ); +} + +/** + * Reads and writes habit notes in the configured folder. + * + * Each habit is a single note whose frontmatter defines it and whose `records` + * map stores the value logged for each day. + */ +export class HabitStore { + /** + * Day comments read from each note's body, keyed by note path. + * + * The body can only be read asynchronously, but `getHabits` is + * synchronous and called on every render, so the text is cached here + * and refreshed whenever a habit note changes on disk. + */ + private commentCache = new Map>(); + + constructor( + private app: App, + private getSettings: () => HabitsPluginSettings, + private saveSettings: () => Promise, + ) {} + + /** True when the path lives inside the configured habits folder. */ + isHabitFile(path: string): boolean { + const folder = this.folderPath; + return path === folder || path.startsWith(`${folder}/`); + } + + /** + * Read every habit note's comment section into the cache. Returns true + * when anything changed, so the caller can refresh open views. + */ + async primeComments(): Promise { + let changed = false; + for (const file of this.habitFiles()) { + changed = (await this.refreshComments(file)) || changed; + } + return changed; + } + + /** Re-read one note's comment section. Returns true when it changed. */ + async refreshComments(file: TFile): Promise { + const content = await this.app.vault.cachedRead(file); + return this.putComments(file.path, parseCommentLog(content)); + } + + /** Drop a note from the cache, e.g. after a delete or rename. */ + forgetComments(path: string): void { + this.commentCache.delete(path); + } + + /** Store parsed comments, reporting whether they differ from the cache. */ + private putComments( + path: string, + comments: Record, + ): boolean { + const previous = this.commentCache.get(path); + if (previous && sameComments(previous, comments)) { + return false; + } + if (Object.keys(comments).length === 0) { + this.commentCache.delete(path); + return previous !== undefined; + } + this.commentCache.set(path, comments); + return true; + } + + private get folderPath(): string { + return normalizePath(this.getSettings().habitsFolder); + } + + /** The configured frontmatter property name for each stored field. */ + private keys(): FrontmatterKeys { + return this.getSettings().frontmatterKeys; + } + + /** Shared styling (colour, icon) for a group, if any is stored. */ + getGroupStyle(name: string): GroupStyle | undefined { + return this.getSettings().groups[name.trim()]; + } + + /** + * Store or clear a group's shared styling. Passing a style with no + * colour and no icon (or `null`) removes the entry. + */ + async setGroupStyle( + name: string, + style: GroupStyle | null, + ): Promise { + const key = name.trim(); + if (!key) { + return; + } + const groups = this.getSettings().groups; + const existing = groups[key]; + if (style && (style.color || style.icon)) { + if ( + existing && + existing.color === style.color && + existing.icon === style.icon + ) { + return; + } + groups[key] = { color: style.color, icon: style.icon }; + } else { + if (!existing) { + return; + } + delete groups[key]; + } + await this.saveSettings(); + } + + /** Create the habits folder if it does not already exist. */ + async ensureFolderExists(): Promise { + const existing = this.app.vault.getAbstractFileByPath(this.folderPath); + if (existing instanceof TFolder) { + return; + } + await this.app.vault.createFolder(this.folderPath); + } + + /** Return every habit defined in the folder, sorted by name. */ + getHabits(): HabitDefinition[] { + const habits: HabitDefinition[] = []; + for (const file of this.habitFiles()) { + const habit = this.parseFile(file); + if (habit) { + habits.push(habit); + } + } + + habits.sort((a, b) => a.name.localeCompare(b.name)); + return habits; + } + + private parseFile(file: TFile, currentFrontmatter?: Record): HabitDefinition | null { + const cache = this.app.metadataCache.getFileCache(file); + const fm = currentFrontmatter || cache?.frontmatter; + const k = this.keys(); + if (!fm || !isHabitType(fm[k.type])) { + return null; + } + + const pauses = this.readPauses(fm[k.pauses]); + return { + path: file.path, + name: file.basename, + type: fm[k.type] as HabitType, + goalDirection: fm[k.goalDirection] === "max" ? "max" : "min", + frequency: isHabitFrequency(fm[k.frequency]) + ? (fm[k.frequency] as HabitFrequency) + : "daily", + weekdays: this.readWeekdays(fm[`${k.weekday}s`], fm[k.weekday]), + monthDay: this.clampInt(this.readNumber(fm[k.monthDay], 1), 1, 31), + intervalDays: this.clampInt( + this.readNumber(fm[k.intervalDays], 2), + 2, + 365, + ), + intervalMode: fm[k.intervalMode] === "cycle" ? "cycle" : fm[k.intervalMode] === "completion" ? "completion" : "fixed", + cycleActiveDays: this.clampInt(this.readNumber(fm.cycleActiveDays, 1), 1, this.readNumber(fm[k.intervalDays], 2)), + cycleRestarts: this.readDateList(fm.cycleRestarts), + dailyTarget: Math.max(0, this.readNumber(fm.dailyTarget, 0)), + intervalWindowDays: this.clampInt(this.readNumber(fm[k.intervalWindowDays], 1), 1, this.readNumber(fm[k.intervalDays], 2)), + times: this.readTimes(fm[`${k.time}s`], fm[k.time]), + target: this.readNumber(fm[k.target], 1), + unit: typeof fm[k.unit] === "string" ? (fm[k.unit] as string) : "", + step: this.readStep(fm[k.step]), + weeklyTarget: this.readNumber(fm[k.weeklyTarget], 0), + monthlyTarget: this.readNumber(fm[k.monthlyTarget], 0), + weeklyPerfect: fm[k.weeklyPerfect] === true, + monthlyPerfect: fm[k.monthlyPerfect] === true, + icon: typeof fm[k.icon] === "string" ? (fm[k.icon] as string) : "", + color: + typeof fm[k.color] === "string" ? (fm[k.color] as string) : "", + group: + typeof fm[k.group] === "string" ? (fm[k.group] as string) : "", + useGroupColor: fm[k.useGroupColor] === true, + tags: this.readTagProperty(fm.tags), + startDate: this.readDateString(fm[k.startDate]), + paused: pauses.some((pause) => pause.end === ""), + pauses, + reschedules: this.readReschedules(fm[k.reschedules]), + failed: this.readDateList(fm[k.failed]), + skipped: this.readDateList(fm[k.skipped]), + ignoredMisses: this.readDateList(fm.ignoredMisses), + ignoredMissesBefore: this.readDateString(fm.ignoredMissesBefore), + stopped: fm[k.stopped] === true, + stopDate: this.readDateString(fm[k.stopDate]), + records: this.readRecords(fm[k.records]), + // Notes written before comments moved into the body still keep + // them in frontmatter; the body wins where both exist. + comments: { + ...this.readComments(fm[k.comments]), + ...(this.commentCache.get(file.path) ?? {}), + }, + noteFolder: + typeof fm[k.noteFolder] === "string" + ? (fm[k.noteFolder] as string) + : "", + noteFilenameFormat: + typeof fm[k.noteFilenameFormat] === "string" + ? (fm[k.noteFilenameFormat] as string) + : "", + templatePath: + typeof fm[k.templatePath] === "string" + ? (fm[k.templatePath] as string) + : "", + noteCompletionMode: isNoteCompletionMode(fm[k.noteCompletionMode]) + ? (fm[k.noteCompletionMode] as NoteCompletionMode) + : "chars", + noteChecklistRequirement: isNoteChecklistRequirement( + fm[k.noteChecklistRequirement], + ) + ? (fm[k.noteChecklistRequirement] as NoteChecklistRequirement) + : "all", + noteChecklistMin: this.clampInt( + this.readNumber(fm[k.noteChecklistMin], 1), + 1, + 999, + ), + noteFailKeyword: + typeof fm[k.noteFailKeyword] === "string" + ? (fm[k.noteFailKeyword] as string) + : "", + }; + } + + /** + * Read a `YYYY-MM-DD` scalar, tolerating a native `Date`. + * + * Obsidian's own frontmatter writer (used by `processFrontMatter`) + * re-serializes a note's *entire* frontmatter on every edit, and drops + * the quotes around a plain string that happens to look like a date. + * Once unquoted, that value reads back as a YAML timestamp rather than + * text, so Obsidian hands it to us as a `Date` object instead of a + * string on the next read — for any note that's ever been touched by + * `processFrontMatter`, not just ones written by this plugin. Recovered + * via UTC fields, since YAML resolves a bare date as UTC midnight + * regardless of the reader's own timezone. + */ + private readDateString(value: unknown): string { + if (typeof value === "string") { + return value.trim(); + } + if (value instanceof Date && !Number.isNaN(value.getTime())) { + const year = value.getUTCFullYear(); + const month = String(value.getUTCMonth() + 1).padStart(2, "0"); + const day = String(value.getUTCDate()).padStart(2, "0"); + return `${year}-${month}-${day}`; + } + return ""; + } + + /** + * Parse a frontmatter list of `YYYY-MM-DD` dates (the `failed` and + * `skipped` days), dropping anything that isn't a date. A single scalar + * date is accepted too, for hand-written notes. + */ + private readDateList(raw: unknown): string[] { + const values = Array.isArray(raw) ? raw : raw === undefined ? [] : [raw]; + const dates = new Set(); + for (const value of values) { + const key = this.readDateString(value); + if (/^\d{4}-\d{2}-\d{2}$/.test(key)) { + dates.add(key); + } + } + return [...dates].sort(); + } + + private readNumber(value: unknown, fallback: number): number { + if (typeof value === "number" && Number.isFinite(value)) { + return value; + } + if (typeof value === "string") { + const parsed = Number(value); + if (Number.isFinite(parsed)) { + return parsed; + } + } + return fallback; + } + + /** A counted habit's +/− step size; anything missing or not above 0 is 1. */ + private readStep(value: unknown): number { + const step = roundValue(this.readNumber(value, 1)); + return step > 0 ? step : 1; + } + + /** Round to a whole number and constrain it to an inclusive range. */ + private clampInt(value: number, min: number, max: number): number { + return Math.min(max, Math.max(min, Math.round(value))); + } + + /** + * Parse a weekly habit's due days: the `weekdays` list when present, + * otherwise the original scalar `weekday`. Values are clamped to `0`–`6`, + * deduplicated and sorted; with nothing usable the result falls back to + * `[1]` (Monday), matching the old scalar default. + */ + private readWeekdays(list: unknown, single: unknown): number[] { + const raw = Array.isArray(list) ? list : [single]; + const days = new Set(); + for (const value of raw) { + const parsed = this.readNumber(value, NaN); + if (Number.isFinite(parsed)) { + days.add(this.clampInt(parsed, 0, 6)); + } + } + if (days.size === 0) { + days.add(1); + } + return [...days].sort((a, b) => a - b); + } + + /** + * Parse a single time of day. Anything that isn't a valid `H:mm` or + * `HH:mm` string is treated as "no time" rather than an error, and the + * hour is zero-padded so times sort and compare as plain strings. + */ + private readTime(value: unknown): string { + if (typeof value !== "string") { + return ""; + } + const match = /^([01]?\d|2[0-3]):([0-5]\d)$/.exec(value.trim()); + if (!match) { + return ""; + } + return `${match[1].padStart(2, "0")}:${match[2]}`; + } + + /** + * Parse a habit's planned times: the `times` list when present, + * otherwise the scalar `time`. Invalid entries are dropped, the rest + * deduplicated and sorted chronologically. + */ + private readTimes(list: unknown, single: unknown): string[] { + const raw = Array.isArray(list) ? list : [single]; + const times = new Set(); + for (const value of raw) { + const parsed = this.readTime(value); + if (parsed) { + times.add(parsed); + } + } + return [...times].sort(); + } + + /** Validate, deduplicate and sort a planned-times list. */ + private normalizeTimes(values: string[]): string[] { + return this.readTimes(values, undefined); + } + + /** Clamp, deduplicate and sort a weekday list, defaulting to Monday. */ + private normalizeWeekdays(values: number[]): number[] { + const days = [ + ...new Set(values.map((value) => this.clampInt(value, 0, 6))), + ].sort((a, b) => a - b); + return days.length > 0 ? days : [1]; + } + + /** + * Parse the completion field in either of the two shapes it may be + * stored in: this plugin's own day → value map, or a bare list of + * done dates (the shape TaskNotes uses for `complete_instances`) — + * each listed date is read as a completed day with value `1`. Both + * shapes are always accepted on read, so a note already carrying + * either one (e.g. authored by another plugin) is picked up without + * configuration — see {@link setRecord} for which shape gets written. + */ + private readRecords(raw: unknown): Record { + const records: Record = {}; + if (Array.isArray(raw)) { + for (const value of raw) { + const dateKey = this.readDateString(value); + if (dateKey) { + records[dateKey] = 1; + } + } + return records; + } + if (raw && typeof raw === "object") { + for (const [key, value] of Object.entries( + raw as Record, + )) { + if (typeof value === "number") { + records[key] = value; + } else if (typeof value === "boolean") { + records[key] = value ? 1 : 0; + } else if (typeof value === "string" && value.trim() !== "") { + const parsed = Number(value); + if (Number.isFinite(parsed)) { + records[key] = parsed; + } + } + } + } + return records; + } + + /** Parse the frontmatter `comments` map, dropping empty entries. */ + private readComments(raw: unknown): Record { + const comments: Record = {}; + if (raw && typeof raw === "object") { + for (const [key, value] of Object.entries( + raw as Record, + )) { + if (typeof value === "string" && value.trim() !== "") { + comments[key] = value; + } + } + } + return comments; + } + + /** Parse the frontmatter `pauses` array, dropping malformed entries. */ + private readPauses(raw: unknown): HabitPause[] { + if (!Array.isArray(raw)) { + return []; + } + const pauses: HabitPause[] = []; + for (const item of raw) { + if (!item || typeof item !== "object") { + continue; + } + const entry = item as Record; + const start = this.readDateString(entry.start); + if (start === "") { + continue; + } + pauses.push({ start, end: this.readDateString(entry.end) }); + } + return pauses; + } + + /** Close any open pause as of yesterday; drop it if it covered no days. */ + private closeOpenPause(pauses: HabitPause[]): HabitPause[] { + const yesterday = toDateKey(addDays(new Date(), -1)); + const closed: HabitPause[] = []; + for (const pause of pauses) { + if (pause.end !== "") { + closed.push(pause); + } else if (pause.start <= yesterday) { + closed.push({ start: pause.start, end: yesterday }); + } + // An open pause that started today covered no full day; drop it. + } + return closed; + } + + /** Frontmatter form of pauses: open pauses omit the `end` key. */ + private serializePauses( + pauses: HabitPause[], + ): { start: string; end?: string }[] { + return pauses.map((pause) => + pause.end === "" + ? { start: pause.start } + : { start: pause.start, end: pause.end }, + ); + } + + /** Parse the frontmatter `reschedules` array, dropping malformed entries. */ + private readReschedules(raw: unknown): HabitReschedule[] { + if (!Array.isArray(raw)) { + return []; + } + const reschedules: HabitReschedule[] = []; + for (const item of raw) { + if (!item || typeof item !== "object") { + continue; + } + const entry = item as Record; + const from = this.readDateString(entry.from); + const to = this.readDateString(entry.to); + if (from === "" || to === "") { + continue; + } + reschedules.push({ from, to }); + } + return reschedules; + } + + private serializeReschedules( + reschedules: HabitReschedule[], + ): { from: string; to: string }[] { + return reschedules.map((r) => ({ from: r.from, to: r.to })); + } + + /** + * Write the frequency fields to frontmatter, keeping it tidy: daily habits + * store nothing (it is the default), and only the fields relevant to the + * chosen frequency are kept so stale keys never linger after a change. + * A weekly habit due on a single day keeps the original scalar `weekday` + * form, so notes from before multi-day support are rewritten unchanged. + */ + private writeFrequency( + fm: Record, + options: NewHabitOptions, + ): void { + const k = this.keys(); + delete fm[k.weekday]; + delete fm[`${k.weekday}s`]; + delete fm[k.monthDay]; + delete fm[k.intervalDays]; + delete fm[k.intervalWindowDays]; + delete fm[k.intervalMode]; + delete fm.cycleActiveDays; + delete fm.dailyTarget; + if (options.frequency === "weekly") { + fm[k.frequency] = "weekly"; + const days = this.normalizeWeekdays(options.weekdays); + if (days.length === 1) { + fm[k.weekday] = days[0]; + } else { + fm[`${k.weekday}s`] = days; + } + } else if (options.frequency === "monthly") { + fm[k.frequency] = "monthly"; + fm[k.monthDay] = this.clampInt(options.monthDay, 1, 31); + } else if (options.frequency === "interval") { + fm[k.frequency] = "interval"; + fm[k.intervalDays] = this.clampInt(options.intervalDays, 2, 365); + if ((options.intervalWindowDays ?? 1) > 1) fm[k.intervalWindowDays] = this.clampInt(options.intervalWindowDays ?? 1, 1, options.intervalDays ?? 2); + if (options.intervalMode === "completion") fm[k.intervalMode] = "completion"; + if (options.intervalMode === "cycle") { + fm[k.intervalMode] = "cycle"; + fm.cycleActiveDays = this.clampInt(options.cycleActiveDays ?? 1, 1, options.intervalDays); + delete fm[k.intervalWindowDays]; + } + } else if ( + options.frequency === "flexibleWeekly" || + options.frequency === "flexibleMonthly" + ) { + fm[k.frequency] = options.frequency; + if ((options.dailyTarget ?? 0) > 0) fm.dailyTarget = options.dailyTarget; + } else { + delete fm[k.frequency]; + } + } + + /** + * Write the planned times to frontmatter, mirroring the weekday + * convention: a single time keeps the scalar `time` form, several use + * the `times` list, and none removes both keys. + */ + private writeTimes( + fm: Record, + options: NewHabitOptions, + ): void { + const k = this.keys(); + delete fm[k.time]; + delete fm[`${k.time}s`]; + const times = this.normalizeTimes(options.times); + if (times.length === 1) { + fm[k.time] = times[0]; + } else if (times.length > 1) { + fm[`${k.time}s`] = times; + } + } + + /** + * Write a `note` habit's folder/filename-format/template/completion-mode + * fields, keeping frontmatter tidy: values equal to the default are + * omitted, and every field is dropped for other habit types. A blank + * folder defaults to a dedicated subfolder of the habits folder, named + * after the habit, so every note habit gets a collision-free home + * without the user having to think about it. + */ + private writeNoteFields( + fm: Record, + options: NewHabitOptions, + cleanName: string, + ): void { + const k = this.keys(); + delete fm[k.noteFolder]; + delete fm[k.noteFilenameFormat]; + delete fm[k.templatePath]; + delete fm[k.noteCompletionMode]; + delete fm[k.noteChecklistRequirement]; + delete fm[k.noteChecklistMin]; + delete fm[k.noteFailKeyword]; + if (options.type !== "note") { + return; + } + fm[k.noteFolder] = + options.noteFolder.trim() || `${this.folderPath}/${cleanName}`; + const format = options.noteFilenameFormat.trim(); + if (format && format !== DEFAULT_NOTE_FILENAME_FORMAT) { + fm[k.noteFilenameFormat] = format; + } + if (options.templatePath.trim()) { + fm[k.templatePath] = options.templatePath.trim(); + } + if (options.noteCompletionMode !== "chars") { + fm[k.noteCompletionMode] = options.noteCompletionMode; + } + const usesChecklist = + options.noteCompletionMode === "checklist" || + options.noteCompletionMode === "both"; + if (usesChecklist && options.noteChecklistRequirement === "count") { + fm[k.noteChecklistRequirement] = "count"; + fm[k.noteChecklistMin] = this.clampInt( + options.noteChecklistMin, + 1, + 999, + ); + } + if (options.noteFailKeyword.trim()) { + fm[k.noteFailKeyword] = options.noteFailKeyword.trim(); + } + } + + private fileForHabit(habit: HabitDefinition): TFile | null { + const file = this.app.vault.getAbstractFileByPath(habit.path); + return file instanceof TFile ? file : null; + } + + /** + * Record `value` for `habit` on the day identified by `dateKey`. + * + * A value of zero or less removes the entry to keep the frontmatter tidy. + * + * Writes as a plain day → value map, unless both of these hold: the + * habit is binary (its logged value is always exactly `1`, so a value + * map and a bare date carry the same information) and the completion + * key has been renamed away from its default `records` — the signal + * that this note is meant to interoperate with something else, such as + * TaskNotes' `complete_instances`. In that case it's written as a bare, + * sorted list of completed dates instead (dropping any non-positive + * entries). Repetition/timed habits always use the value map, since + * only it can hold their logged count or duration. + */ + async setRecord( + habit: HabitDefinition, + dateKey: string, + value: number, + expectedValue?: number, + ): Promise { + const file = this.fileForHabit(habit); + if (!file) { + if (expectedValue !== undefined) throw new Error(t("This habit changed. Reopen the habit and try again.")); + new Notice( + t('Could not find the note for "{name}".', { + name: habit.name, + }), + ); + return; + } + + const k = this.keys(); + const useDateList = + habit.type === "binary" && + k.records !== DEFAULT_FRONTMATTER_KEYS.records; + // Repeated +0.1 presses would otherwise store 0.30000000000000004. + value = roundValue(value); + await this.app.fileManager.processFrontMatter(file, (frontmatter) => { + const fm = frontmatter as Record; + const records = this.readRecords(fm[k.records]); + if (expectedValue !== undefined && (fm[k.stopped] === true || (records[dateKey] || 0) !== expectedValue)) { + throw new Error(t("This habit changed. Reopen the habit and try again.")); + } + if (value > 0) { + records[dateKey] = value; + } else { + delete records[dateKey]; + } + fm[k.records] = useDateList + ? Object.entries(records) + .filter(([, recorded]) => recorded > 0) + .map(([day]) => day) + .sort() + : records; + }); + } + + /** + * Save (or clear) the comment for a habit on the given day. + * + * Comments are written to the note body so that Obsidian indexes the + * `#tags` and `[[links]]` inside them against the day they belong to. + * A note still holding comments in frontmatter is migrated on the same + * pass, so no separate upgrade step is needed. + */ + async setComment( + habit: HabitDefinition, + dateKey: string, + text: string, + ): Promise { + const file = this.fileForHabit(habit); + if (!file) { + new Notice( + t('Could not find the note for "{name}".', { + name: habit.name, + }), + ); + return; + } + + const legacy = this.legacyComments(file); + let written: Record = {}; + await this.app.vault.process(file, (content) => { + const comments = { ...legacy, ...parseCommentLog(content) }; + if (text) { + comments[dateKey] = text; + } else { + delete comments[dateKey]; + } + written = comments; + return applyCommentLog(content, comments); + }); + this.putComments(file.path, written); + + if (Object.keys(legacy).length > 0) { + await this.clearLegacyComments(file, legacy); + } + } + + /** Day comments still stored in a note's frontmatter, if any. */ + private legacyComments(file: TFile): Record { + const fm = this.app.metadataCache.getFileCache(file)?.frontmatter; + return this.readComments(fm?.[this.keys().comments]); + } + + /** True when any habit note still keeps its comments in frontmatter. */ + hasLegacyComments(): boolean { + return this.habitFiles().some( + (file) => Object.keys(this.legacyComments(file)).length > 0, + ); + } + + /** + * Move every note's frontmatter comments into its body. Returns how + * many notes were changed. + */ + async migrateComments(): Promise { + let migrated = 0; + for (const file of this.habitFiles()) { + const legacy = this.legacyComments(file); + if (Object.keys(legacy).length === 0) { + continue; + } + let written: Record = {}; + await this.app.vault.process(file, (content) => { + written = { ...legacy, ...parseCommentLog(content) }; + return applyCommentLog(content, written); + }); + this.putComments(file.path, written); + await this.clearLegacyComments(file, legacy); + migrated++; + } + return migrated; + } + + /** + * Move each rename's value onto its new frontmatter key, across every + * habit note, one `processFrontMatter` pass per file (not one pass per + * key). A value is only ever moved, never overwritten: a rename is + * skipped for a given note if its new key is already in use there, so + * existing data can't be clobbered. Returns how many notes were changed. + */ + async renameFrontmatterKeys( + renames: { old: string; new: string }[], + ): Promise { + let changed = 0; + for (const file of this.habitFiles()) { + let fileChanged = false; + await this.app.fileManager.processFrontMatter( + file, + (frontmatter) => { + const fm = frontmatter as Record; + for (const { old: oldKey, new: newKey } of renames) { + if ( + oldKey !== newKey && + fm[oldKey] !== undefined && + fm[newKey] === undefined + ) { + fm[newKey] = fm[oldKey]; + delete fm[oldKey]; + fileChanged = true; + } + } + }, + ); + if (fileChanged) { + changed++; + } + } + return changed; + } + + /** + * Drop the frontmatter `comments` key once its contents live in the + * body, along with any tags an earlier version mirrored into `tags` — + * the body now supplies those to Obsidian's index directly. + */ + private async clearLegacyComments( + file: TFile, + legacy: Record, + ): Promise { + const mirrored = tagsInComments(legacy); + const k = this.keys(); + await this.app.fileManager.processFrontMatter(file, (frontmatter) => { + const fm = frontmatter as Record; + delete fm[k.comments]; + if (mirrored.size === 0 || !("tags" in fm)) { + return; + } + const kept = this.readTagProperty(fm.tags).filter( + (tag) => !mirrored.has(tag), + ); + if (kept.length > 0) { + fm.tags = kept; + } else { + delete fm.tags; + } + }); + } + + /** Read `tags` in any of the shapes Obsidian accepts, minus the `#`. */ + private readTagProperty(raw: unknown): string[] { + const values = Array.isArray(raw) + ? raw + : typeof raw === "string" + ? raw.split(/[,\s]+/) + : []; + const out: string[] = []; + for (const value of values) { + if (typeof value !== "string") { + continue; + } + const tag = value.trim().replace(/^#/, ""); + if (tag !== "" && !out.includes(tag)) { + out.push(tag); + } + } + return out; + } + + /** Every markdown file in the habits folder. */ + private habitFiles(): TFile[] { + const folder = this.app.vault.getAbstractFileByPath(this.folderPath); + if (!(folder instanceof TFolder)) { + return []; + } + return folder.children.filter( + (child): child is TFile => + child instanceof TFile && child.extension === "md", + ); + } + + /** Pause a habit from today. Paused days are skipped by streaks/stats. */ + async pauseHabit(habit: HabitDefinition): Promise { + const file = this.fileForHabit(habit); + if (!file) { + new Notice( + t('Could not find the note for "{name}".', { + name: habit.name, + }), + ); + return; + } + const k = this.keys(); + await this.app.fileManager.processFrontMatter(file, (frontmatter) => { + const fm = frontmatter as Record; + const pauses = this.readPauses(fm[k.pauses]); + if (pauses.some((pause) => pause.end === "")) { + return; + } + pauses.push({ start: toDateKey(new Date()), end: "" }); + fm[k.pauses] = this.serializePauses(pauses); + }); + new Notice(t('Paused "{name}".', { name: habit.name })); + } + + /** + * Close a day as failed or skipped, or reopen it (`null`). A day holds at + * most one of the two, so setting one clears the other; empty lists are + * removed from the frontmatter rather than left as `[]`. + */ + async setDayStatus( + habit: HabitDefinition, + dateKey: string, + status: "failed" | "skipped" | null, + ): Promise { + const file = this.fileForHabit(habit); + if (!file) { + new Notice( + t('Could not find the note for "{name}".', { + name: habit.name, + }), + ); + return; + } + const k = this.keys(); + await this.app.fileManager.processFrontMatter(file, (frontmatter) => { + const fm = frontmatter as Record; + for (const kind of ["failed", "skipped"] as const) { + const key = k[kind]; + const dates = this.readDateList(fm[key]).filter( + (date) => date !== dateKey, + ); + if (kind === status) { + dates.push(dateKey); + dates.sort(); + } + if (dates.length > 0) { + fm[key] = dates; + } else { + delete fm[key]; + } + } + }); + // Mirror the write so a view repainting before the metadata cache + // catches up already sees the change. + habit.failed = habit.failed.filter((date) => date !== dateKey); + habit.skipped = habit.skipped.filter((date) => date !== dateKey); + if (status) { + habit[status].push(dateKey); + } + } + + /** When the habit's snooze ends (epoch ms), or null if it isn't snoozed. */ + snoozedUntil(habit: HabitDefinition, now = Date.now()): number | null { + const until = this.getSettings().snoozes[habit.path]; + return typeof until === "number" && until > now ? until : null; + } + + /** Hide a habit from today's lists until `until` (epoch ms). */ + async snoozeHabit(habit: HabitDefinition, until: number): Promise { + await this.writeSnoozes((snoozes) => { + snoozes[habit.path] = until; + }); + } + + /** End a habit's snooze early. */ + async clearSnooze(habit: HabitDefinition): Promise { + await this.writeSnoozes((snoozes) => { + delete snoozes[habit.path]; + }); + } + + /** Apply a change to the snoozes, pruning any that have already ended. */ + private async writeSnoozes( + change: (snoozes: Record) => void, + ): Promise { + const now = Date.now(); + const snoozes: Record = {}; + for (const [path, until] of Object.entries(this.getSettings().snoozes)) { + if (until > now) { + snoozes[path] = until; + } + } + change(snoozes); + this.getSettings().snoozes = snoozes; + await this.saveSettings(); + } + + /** Resume a paused habit; the pause period stays excluded from stats. */ + async resumeHabit(habit: HabitDefinition): Promise { + const file = this.fileForHabit(habit); + if (!file) { + new Notice( + t('Could not find the note for "{name}".', { + name: habit.name, + }), + ); + return; + } + const k = this.keys(); + await this.app.fileManager.processFrontMatter(file, (frontmatter) => { + const fm = frontmatter as Record; + const pauses = this.closeOpenPause(this.readPauses(fm[k.pauses])); + if (pauses.length > 0) { + fm[k.pauses] = this.serializePauses(pauses); + } else { + delete fm[k.pauses]; + } + }); + new Notice(t('Resumed "{name}".', { name: habit.name })); + } + + /** Move a missed due day, checking the latest data before committing. */ + async rescheduleHabit(habit: HabitDefinition, from: string, to: string): Promise { + const file = this.fileForHabit(habit); + const date = fromDateKey(from); + if (!file || !date) throw new Error(t("This habit changed. Reopen the habit and try again.")); + const k = this.keys(); + let reschedules: HabitReschedule[] = []; + await this.app.fileManager.processFrontMatter(file, (frontmatter) => { + const fm = frontmatter as Record; + const current = this.parseFile(file, fm); + if (!current || !isRescheduleEligible(current) || from >= toDateKey(new Date()) + || !isDue(current, date) || isComplete(current, from) || isPausedOn(current, from) + || isFailedOn(current, from) || current.ignoredMisses?.includes(from) + || (current.ignoredMissesBefore && from < current.ignoredMissesBefore) + || !isRescheduleTargetOpen(current, to)) { + throw new Error(t("That day is already due or has a record. Choose another day.")); + } + // Move the original instance again if a previous destination was missed. + const origin = current.reschedules.find(entry => entry.to === from)?.from ?? from; + reschedules = current.reschedules.filter(entry => entry.from !== origin); + reschedules.push({ from: origin, to }); + fm[k.reschedules] = this.serializeReschedules(reschedules); + }); + new Notice(t('Rescheduled "{name}" to {date}.', { name: habit.name, date: to })); + return reschedules; + } + + /** Dismiss old reminders without changing any records, scores or future due days. */ + async ignoreAllPastMisses(today = toDateKey(new Date())): Promise { + let count = 0; + for (const habit of this.getHabits()) { + const file = this.fileForHabit(habit); if (!file) continue; + await this.app.fileManager.processFrontMatter(file, fm => { + const previous = this.readDateString(fm.ignoredMissesBefore); + fm.ignoredMissesBefore = previous > today ? previous : today; + }); + count++; + } + return count; + } + + async ignoreMissedDay(habit: HabitDefinition, dateKey: string): Promise { + const file = this.fileForHabit(habit); + if (!file) throw new Error(t("Habit note not found.")); + await this.app.fileManager.processFrontMatter(file, fm => { + fm.ignoredMisses = [...new Set([...this.readDateList(fm.ignoredMisses), dateKey])].sort(); + }); + } + + /** Undo a reschedule: the original day goes back to being due. */ + async cancelReschedule(habit: HabitDefinition, from: string): Promise { + const file = this.fileForHabit(habit); + if (!file) { + new Notice( + t('Could not find the note for "{name}".', { + name: habit.name, + }), + ); + return; + } + const k = this.keys(); + await this.app.fileManager.processFrontMatter(file, (frontmatter) => { + const fm = frontmatter as Record; + const reschedules = this.readReschedules(fm[k.reschedules]).filter( + (r) => r.from !== from, + ); + if (reschedules.length > 0) { + fm[k.reschedules] = this.serializeReschedules(reschedules); + } else { + delete fm[k.reschedules]; + } + }); + } + + /** Stop tracking a habit. The note and every record are kept. */ + async stopHabit(habit: HabitDefinition): Promise { + const file = this.fileForHabit(habit); + if (!file) { + new Notice( + t('Could not find the note for "{name}".', { + name: habit.name, + }), + ); + return; + } + const k = this.keys(); + await this.app.fileManager.processFrontMatter(file, (frontmatter) => { + const fm = frontmatter as Record; + fm[k.stopped] = true; + fm[k.stopDate] = toDateKey(new Date()); + const pauses = this.closeOpenPause(this.readPauses(fm[k.pauses])); + if (pauses.length > 0) { + fm[k.pauses] = this.serializePauses(pauses); + } else { + delete fm[k.pauses]; + } + }); + new Notice( + t('Stopped tracking "{name}". Its history is kept in the note.', { + name: habit.name, + }), + ); + } + + /** Resume tracking a previously stopped habit. */ + async restartHabit(habit: HabitDefinition): Promise { + const file = this.fileForHabit(habit); + if (!file) { + new Notice( + t('Could not find the note for "{name}".', { + name: habit.name, + }), + ); + return; + } + const k = this.keys(); + await this.app.fileManager.processFrontMatter(file, (frontmatter) => { + const fm = frontmatter as Record; + delete fm[k.stopped]; + delete fm[k.stopDate]; + }); + new Notice(t('Resumed tracking "{name}".', { name: habit.name })); + } + + /** Create a new habit note and return the created file. */ + async createHabit(options: NewHabitOptions): Promise { + const cleanName = sanitizeFileName(options.name); + if (!cleanName) { + new Notice(t("Please enter a valid habit name.")); + return null; + } + + await this.ensureFolderExists(); + const path = normalizePath(`${this.folderPath}/${cleanName}.md`); + if (this.app.vault.getAbstractFileByPath(path)) { + new Notice( + t('A habit called "{name}" already exists.', { + name: cleanName, + }), + ); + return null; + } + + const body = [ + `# ${cleanName}`, + "", + t("This note is managed by Task Genius."), + "", + "## Metrics", + "", + "```tg-habit-metrics", + "```", + "", + ].join("\n"); + const file = await this.app.vault.create(path, body); + + const k = this.keys(); + await this.app.fileManager.processFrontMatter(file, (frontmatter) => { + const fm = frontmatter as Record; + fm.habit = true; + fm[k.type] = options.type; + // Only limit habits store the field; its absence means "min", so + // notes created before the field existed keep their meaning. + if (options.goalDirection === "max") { + fm[k.goalDirection] = "max"; + } + this.writeFrequency(fm, options); + this.writeTimes(fm, options); + this.writeNoteFields(fm, options, cleanName); + if ( + options.type !== "binary" || + isFlexibleFrequency(options.frequency) + ) { + // A limit of 0 is meaningful ("none at all"), so max habits + // always write the field even when it is zero. A note + // habit's target is its character goal, or 100 for a + // checklist habit's checked percentage. A flexible habit's + // target is its "times per period" goal, which a binary + // habit needs written too (unlike the normal binary case, + // where it is meaningless and left out). + fm[k.target] = options.target; + } + if (options.unit) { + fm[k.unit] = options.unit; + } + // Only written when it differs from the default of 1. + if (options.type === "repetition" && options.step !== 1) { + fm[k.step] = options.step; + } + if (options.weeklyPerfect) { + fm[k.weeklyPerfect] = true; + } else if (options.weeklyTarget > 0) { + fm[k.weeklyTarget] = options.weeklyTarget; + } + if (options.monthlyPerfect) { + fm[k.monthlyPerfect] = true; + } else if (options.monthlyTarget > 0) { + fm[k.monthlyTarget] = options.monthlyTarget; + } + if (options.icon) { + fm[k.icon] = options.icon; + } + if (options.color) { + fm[k.color] = options.color; + } + if (options.group) { + fm[k.group] = options.group; + } + if (options.useGroupColor) { + fm[k.useGroupColor] = true; + } + if (options.tags.length > 0) { + fm.tags = options.tags; + } + fm[k.startDate] = toDateKey(new Date()); + fm[k.records] = {}; + }); + + new Notice(t('Created habit "{name}".', { name: cleanName })); + return file; + } + + /** Update an existing habit's definition, renaming its note if needed. */ + async updateHabit( + habit: HabitDefinition, + options: NewHabitOptions, + ): Promise { + let file = this.fileForHabit(habit); + if (!file) { + new Notice( + t('Could not find the note for "{name}".', { + name: habit.name, + }), + ); + return null; + } + + const cleanName = sanitizeFileName(options.name); + if (!cleanName) { + new Notice(t("Please enter a valid habit name.")); + return null; + } + + if (cleanName !== habit.name) { + const newPath = normalizePath(`${this.folderPath}/${cleanName}.md`); + if (this.app.vault.getAbstractFileByPath(newPath)) { + new Notice( + t('A habit called "{name}" already exists.', { + name: cleanName, + }), + ); + return null; + } + await this.app.fileManager.renameFile(file, newPath); + const renamed = this.app.vault.getAbstractFileByPath(newPath); + if (renamed instanceof TFile) { + file = renamed; + } + } + + const k = this.keys(); + await this.app.fileManager.processFrontMatter(file, (frontmatter) => { + const fm = frontmatter as Record; + fm.habit = true; + fm[k.type] = options.type; + if (options.goalDirection === "max") { + fm[k.goalDirection] = "max"; + } else { + delete fm[k.goalDirection]; + } + this.writeFrequency(fm, options); + if (options.frequency === "interval" && (options.restartIntervalCycle || options.restartCycleDate)) { + const day = options.restartCycleDate || toDateKey(new Date()); + if (/^\d{4}-\d{2}-\d{2}$/.test(day)) fm.cycleRestarts = [...new Set([...this.readDateList(fm.cycleRestarts), day])].sort(); + } + this.writeTimes(fm, options); + this.writeNoteFields(fm, options, cleanName); + if ( + options.type === "binary" && + !isFlexibleFrequency(options.frequency) + ) { + delete fm[k.target]; + } else { + fm[k.target] = options.target; + } + if (options.unit) { + fm[k.unit] = options.unit; + } else { + delete fm[k.unit]; + } + if (options.type === "repetition" && options.step !== 1) { + fm[k.step] = options.step; + } else { + delete fm[k.step]; + } + if (options.weeklyPerfect) { + fm[k.weeklyPerfect] = true; + delete fm[k.weeklyTarget]; + } else { + delete fm[k.weeklyPerfect]; + if (options.weeklyTarget > 0) { + fm[k.weeklyTarget] = options.weeklyTarget; + } else { + delete fm[k.weeklyTarget]; + } + } + if (options.monthlyPerfect) { + fm[k.monthlyPerfect] = true; + delete fm[k.monthlyTarget]; + } else { + delete fm[k.monthlyPerfect]; + if (options.monthlyTarget > 0) { + fm[k.monthlyTarget] = options.monthlyTarget; + } else { + delete fm[k.monthlyTarget]; + } + } + if (options.icon) { + fm[k.icon] = options.icon; + } else { + delete fm[k.icon]; + } + if (options.color) { + fm[k.color] = options.color; + } else { + delete fm[k.color]; + } + if (options.group) { + fm[k.group] = options.group; + } else { + delete fm[k.group]; + } + if (options.useGroupColor) { + fm[k.useGroupColor] = true; + } else { + delete fm[k.useGroupColor]; + } + if (options.tags.length > 0) { + fm.tags = options.tags; + } else { + delete fm.tags; + } + }); + + new Notice(t('Updated "{name}".', { name: cleanName })); + return file; + } + + /** + * Reassign a habit to a group (or ungroup it with ""), writing the + * note's frontmatter. Leaving a group also clears the group-colour + * override, which would otherwise silently point at the old group. + */ + async setHabitGroup( + habit: HabitDefinition, + group: string, + ): Promise { + const file = this.fileForHabit(habit); + if (!file) { + return; + } + const cleaned = group.trim(); + const k = this.keys(); + await this.app.fileManager.processFrontMatter(file, (frontmatter) => { + const fm = frontmatter as Record; + if (cleaned) { + fm[k.group] = cleaned; + } else { + delete fm[k.group]; + delete fm[k.useGroupColor]; + } + }); + habit.group = cleaned; + if (!cleaned) { + habit.useGroupColor = false; + } + } + + /** Move a habit's note to the trash (respecting the user's settings). */ + async deleteHabit(habit: HabitDefinition): Promise { + const file = this.fileForHabit(habit); + if (!file) { + new Notice( + t('Could not find the note for "{name}".', { + name: habit.name, + }), + ); + return; + } + await this.app.fileManager.trashFile(file); + new Notice(t('Removed "{name}".', { name: habit.name })); + } +} diff --git a/src/integrations/habits/i18n/de.ts b/src/integrations/habits/i18n/de.ts new file mode 100644 index 000000000..69530e701 --- /dev/null +++ b/src/integrations/habits/i18n/de.ts @@ -0,0 +1,657 @@ +/** German translations, keyed by the English source string. */ +export const de: Record = { + // Commands and ribbon + "Create habit": "Gewohnheit erstellen", + "Insert dashboard": "Dashboard einfügen", + "Insert habit metrics": "Gewohnheits-Metriken einfügen", + "Insert habits table": "Gewohnheitstabelle einfügen", + "Open panel": "Seitenleiste öffnen", + "Open habits panel": "Gewohnheiten-Seitenleiste öffnen", + Habits: "Gewohnheiten", + + // Settings + "Habits folder": "Gewohnheiten-Ordner", + "Folder where each habit is stored as its own note. It is created automatically if it does not exist.": + "Ordner, in dem jede Gewohnheit als eigene Notiz gespeichert wird. Er wird automatisch erstellt, falls er nicht existiert.", + "Follow daily note date": "Datum der täglichen Notiz übernehmen", + "When a dashboard is embedded in a daily note (a note whose name contains a date like 2026-07-01), open it on that note's date instead of today.": + "Wenn ein Dashboard in eine tägliche Notiz eingebettet ist (eine Notiz, deren Name ein Datum wie 2026-07-01 enthält), öffnet es sich mit dem Datum dieser Notiz statt mit heute.", + "Daily note date format": "Datumsformat der täglichen Notiz", + "Moment.js format used to read the date from a daily note's name, such as YYYY-MM-DD or YYYYMMDD.": + "Moment.js-Format, mit dem das Datum aus dem Namen einer täglichen Notiz gelesen wird, zum Beispiel YYYY-MM-DD oder YYYYMMDD.", + + // Sorting + "Sort habits by": "Gewohnheiten sortieren nach", + "The base order of habit cards in the dashboard and side panel.": + "Die Grundreihenfolge der Gewohnheitskarten im Dashboard und im Seitenpanel.", + "Name (A–Z)": "Name (A–Z)", + Color: "Farbe", + "Last logged": "Zuletzt protokolliert", + "Planned time": "Geplante Uhrzeit", + Manual: "Manuell", + "Manual order": "Manuelle Reihenfolge", + "Drag the cards into the order you want. New habits join the end of the list.": + "Ziehe die Karten in die gewünschte Reihenfolge. Neue Gewohnheiten werden am Ende der Liste eingefügt.", + "Move completed cards to the end": + "Erledigte Karten ans Ende verschieben", + "Completed habits drift to the end of the queue and paused ones park behind them. Turn this off to keep every card in its sorted position.": + "Erledigte Gewohnheiten wandern ans Ende der Warteschlange, pausierte dahinter. Deaktiviere dies, damit jede Karte an ihrer sortierten Position bleibt.", + Group: "Gruppe", + Ungrouped: "Ohne Gruppe", + "Optional group used to build dashboard sections — for example an area of responsibility.": + "Optionale Gruppe für Abschnitte im Dashboard — zum Beispiel ein Verantwortungsbereich.", + "e.g. Health": "z. B. Gesundheit", + "Group color": "Gruppenfarbe", + "Optional color shared by every habit in this group.": + "Optionale Farbe, die alle Gewohnheiten dieser Gruppe teilen.", + "Group icon": "Gruppensymbol", + "Shown in the group lip on cards and in section headers.": + "Wird in der Gruppenleiste auf Karten und in Abschnittsüberschriften angezeigt.", + "Use group color for this card": "Gruppenfarbe für diese Karte verwenden", + "Show this card in the group color instead of its own.": + "Zeigt diese Karte in der Gruppenfarbe statt in ihrer eigenen.", + General: "Allgemein", + Sorting: "Sortierung", + Groups: "Gruppen", + "How to move through your habit cards: a paged carousel with arrows, a grid that wraps onto new rows, or a fixed-height grid that scrolls vertically. The stats page follows the same choice.": + "Wie du durch deine Gewohnheitskarten navigierst: ein seitenweises Karussell mit Pfeilen, ein Raster, das in neue Zeilen umbricht, oder ein Raster mit fester Höhe, das vertikal scrollt. Die Statistikseite folgt derselben Auswahl.", + "Enable groups": "Gruppen aktivieren", + "Show habits in sections by their group, with a group lip on each card.": + "Zeigt Gewohnheiten in Abschnitten nach Gruppe, mit einer Gruppenleiste auf jeder Karte.", + "Group order": "Gruppenreihenfolge", + "Drag the groups into the order you want. Sections follow the same order.": + "Ziehe die Gruppen in die gewünschte Reihenfolge. Abschnitte folgen derselben Reihenfolge.", + "Completion animations": "Abschluss-Animationen", + "Play the check swoosh, card departure, and perfect-day confetti when habits are completed. Turn off for instant, quiet updates.": + "Spielt beim Abschließen von Gewohnheiten das Häkchen-Swoosh, den Kartenabgang und das Perfekter-Tag-Konfetti ab. Ausschalten für sofortige, ruhige Aktualisierungen.", + "Reminders": "Erinnerungen", + "Write reminders for due habits": + "Erinnerungen für fällige Gewohnheiten schreiben", + "Each day, write one reminder checklist line per planned time of every habit due that day, in the format the Reminder plugin picks up. The lines live in a marked block and refresh as you log habits.": + "Schreibt jeden Tag eine Erinnerungs-Checklistenzeile pro geplanter Uhrzeit für jede an dem Tag fällige Gewohnheit, im Format, das das Reminder-Plugin erkennt. Die Zeilen stehen in einem markierten Block und werden beim Protokollieren aktualisiert.", + "Where to write reminders": "Wohin Erinnerungen geschrieben werden", + "The daily note follows the Daily notes core plugin's folder and date format; the block is added once the note exists. A fixed note is created automatically.": + "Die tägliche Notiz folgt Ordner und Datumsformat des Kern-Plugins „Tägliche Notizen“; der Block wird eingefügt, sobald die Notiz existiert. Eine feste Notiz wird automatisch erstellt.", + "Today's daily note": "Heutige tägliche Notiz", + "A fixed note": "Eine feste Notiz", + "Reminder note path": "Pfad der Erinnerungsnotiz", + "Vault path of the note that holds the reminder block.": + "Vault-Pfad der Notiz, die den Erinnerungsblock enthält.", + "Manage groups": "Gruppen verwalten", + "See every habit by group and drag cards between groups.": + "Zeigt alle Gewohnheiten nach Gruppe und erlaubt das Ziehen von Karten zwischen Gruppen.", + Open: "Öffnen", + "New group": "Neue Gruppe", + Add: "Hinzufügen", + "Drag habits between groups to reassign them, or within a group to reorder them.": + "Ziehe Gewohnheiten zwischen Gruppen, um sie neu zuzuordnen, oder innerhalb einer Gruppe, um sie zu sortieren.", + "No habits": "Keine Gewohnheiten", + "Edit group style": "Gruppenstil bearbeiten", + "Delete group": "Gruppe löschen", + 'Delete "{name}"? Its habits are kept and become ungrouped.': + 'Gruppe "{name}" löschen? Ihre Gewohnheiten bleiben erhalten und werden gruppenlos.', + Delete: "Löschen", + "Dashboard layout": "Dashboard-Layout", + Carousel: "Karussell", + Grid: "Raster", + "Vertical scroll": "Vertikales Scrollen", + "Cards per view": "Karten pro Ansicht", + "How many habit cards fit side by side on wider screens.": + "Wie viele Gewohnheitskarten auf breiten Bildschirmen nebeneinander passen.", + "Cards per view on mobile": "Karten pro Ansicht auf dem Handy", + "How many habit cards fit side by side on phone-sized screens.": + "Wie viele Gewohnheitskarten auf Handy-Bildschirmen nebeneinander passen.", + + // Confirm dialog defaults + Cancel: "Abbrechen", + Confirm: "Bestätigen", + + // Store notices + 'Could not find the note for "{name}".': + 'Die Notiz für „{name}" wurde nicht gefunden.', + "Please enter a valid habit name.": + "Bitte gib einen gültigen Namen für die Gewohnheit ein.", + 'A habit called "{name}" already exists.': + 'Eine Gewohnheit namens „{name}" existiert bereits.', + 'Created habit "{name}".': 'Gewohnheit „{name}" erstellt.', + 'Updated "{name}".': '„{name}" aktualisiert.', + 'Paused "{name}".': '„{name}" pausiert.', + 'Resumed "{name}".': '„{name}" fortgesetzt.', + 'Stopped tracking "{name}". Its history is kept in the note.': + '„{name}" wird nicht mehr verfolgt. Der Verlauf bleibt in der Notiz erhalten.', + 'Resumed tracking "{name}".': '„{name}" wird wieder verfolgt.', + 'Removed "{name}".': '„{name}" entfernt.', + "Habit added to the dashboard.": + "Gewohnheit zum Dashboard hinzugefügt.", + + // Dashboard + "Back to habits": "Zurück zu den Gewohnheiten", + "View stats": "Statistiken anzeigen", + "Export stats": "Statistiken exportieren", + Weekly: "Wöchentlich", + Monthly: "Monatlich", + "Previous day": "Vorheriger Tag", + "Next day": "Nächster Tag", + "Choose a date": "Datum wählen", + "Add habit": "Gewohnheit hinzufügen", + "No habits yet. Create your first habit to get started.": + "Noch keine Gewohnheiten. Erstelle deine erste Gewohnheit, um loszulegen.", + Previous: "Zurück", + Next: "Weiter", + "Go to position {n}": "Zu Position {n} springen", + "Right-click or long-press for more options": + "Rechtsklick oder langes Drücken für weitere Optionen", + "Open habit note": "Notiz der Gewohnheit öffnen", + "Open the note for {name}": "Notiz für {name} öffnen", + Paused: "Pausiert", + Stopped: "Beendet", + "Failed": "Fehlgeschlagen", + "Skipped": "Übersprungen", + "Snoozed": "Schlummert", + "Snoozed until {time}": "Schlummert bis {time}", + "Undo fail": "Fehlschlag rückgängig", + "Undo skip": "Überspringen rückgängig", + "End snooze": "Schlummern beenden", + "Fail for today": "Für heute als fehlgeschlagen markieren", + "Fail this day": "Diesen Tag als fehlgeschlagen markieren", + "Marked \"{name}\" as failed.": "„{name}“ als fehlgeschlagen markiert.", + "Skip for today": "Für heute überspringen", + "Skip this day": "Diesen Tag überspringen", + "Skipped \"{name}\".": "„{name}“ übersprungen.", + "Snooze…": "Schlummern…", + "Snooze \"{name}\"": "„{name}“ schlummern lassen", + "It leaves today's lists and comes back on its own. Snoozing never counts for or against the habit.": "Verschwindet aus den heutigen Listen und kommt von selbst zurück. Schlummern zählt nie für oder gegen die Gewohnheit.", + "Snooze for": "Schlummern für", + "30 minutes": "30 Minuten", + "1 hour": "1 Stunde", + "3 hours": "3 Stunden", + "Snooze until": "Schlummern bis", + "Snooze": "Schlummern", + "Pick a time later today.": "Wähle eine spätere Uhrzeit von heute.", + "Snoozed \"{name}\" until {time}.": "„{name}“ schlummert bis {time}.", + "1 hidden for today": "1 für heute ausgeblendet", + "{count} hidden for today": "{count} für heute ausgeblendet", + "1 hidden for this day": "1 für diesen Tag ausgeblendet", + "{count} hidden for this day": "{count} für diesen Tag ausgeblendet", + "Undo": "Rückgängig", + "Click to undo": "Klicken zum Rückgängigmachen", + "Nothing left on this day's list.": "Für diesen Tag ist nichts mehr offen.", + "Nothing left on today's list.": "Für heute ist nichts mehr offen.", + "At least: reach a target for habits you are building, like drinking 1.5 litres of water. At most: stay within a limit for habits you are cutting down, like no more than 2 coffees.": "Mindestens: Erreiche ein Ziel bei Gewohnheiten, die du aufbaust, etwa 1,5 Liter Wasser trinken. Höchstens: Bleib innerhalb eines Limits bei Gewohnheiten, die du reduzierst, etwa nicht mehr als 2 Kaffee.", + "At least (reach a target)": "Mindestens (Ziel erreichen)", + "At most (stay within a limit)": "Höchstens (im Limit bleiben)", + "Step size": "Schrittweite", + "How much each + and − press adds or removes. Use a decimal such as 0.25 for amounts like litres.": "Wie viel jeder Druck auf + und − hinzufügt oder abzieht. Nutze eine Dezimalzahl wie 0.25 für Mengen wie Liter.", + "Decrease by {n}": "Um {n} verringern", + "4 weeks": "4 Wochen", + "12 weeks": "12 Wochen", + "6 months": "6 Monate", + "1 year": "1 Jahr", + "Completion rate": "Erfüllungsquote", + "Monthly completion rate": "Monatliche Erfüllungsquote", + "Daily activity": "Tägliche Aktivität", + "Week of {date}": "Woche vom {date}", + "Since {date} · right-click to resume": + "Seit {date} · Rechtsklick zum Fortsetzen", + "Paused on this day": "An diesem Tag pausiert", + "Mark as done": "Als erledigt markieren", + "Mark as not done": "Als nicht erledigt markieren", + Done: "Erledigt", + "Not done": "Offen", + "Edit value": "Wert bearbeiten", + Value: "Wert", + "Decrease by 1": "Um 1 verringern", + "Increase by 1": "Um 1 erhöhen", + "Increase by {n}": "Um {n} erhöhen", + "Edit habit": "Gewohnheit bearbeiten", + "Pause habit": "Gewohnheit pausieren", + "Resume habit": "Gewohnheit fortsetzen", + "Stop tracking": "Nicht mehr verfolgen", + "Remove habit": "Gewohnheit entfernen", + 'Stop tracking "{name}"? It leaves the dashboard and stats, but its note and full history are kept. You can resume tracking any time from the note\'s metrics view.': + '„{name}" nicht mehr verfolgen? Sie verschwindet aus dem Dashboard und den Statistiken, aber ihre Notiz und ihr gesamter Verlauf bleiben erhalten. Du kannst die Verfolgung jederzeit über die Metrik-Ansicht der Notiz fortsetzen.', + 'Remove "{name}"? Its note will be moved to the trash.': + '„{name}" entfernen? Ihre Notiz wird in den Papierkorb verschoben.', + Remove: "Entfernen", + "Perfect!": "Perfekt!", + Today: "Heute", + Yesterday: "Gestern", + Tomorrow: "Morgen", + "Last 7 days": "Letzte 7 Tage", + "Last 30 days": "Letzte 30 Tage", + "This week": "Diese Woche", + "This month": "Dieser Monat", + + // Sidebar panel + "Habits completed today": "Heute erledigte Gewohnheiten", + "No habits yet.": "Noch keine Gewohnheiten.", + "Click to type a value": "Klicken, um einen Wert einzugeben", + "Open note": "Notiz öffnen", + + // Stats view + "No habits to show stats for yet.": + "Noch keine Gewohnheiten für Statistiken vorhanden.", + Completion: "Erfüllung", + "Best streak": "Beste Serie", + "Perfect days": "Perfekte Tage", + Completions: "Erledigungen", + "Goals met": "Ziele erreicht", + "{completed}/{days} days": "{completed}/{days} Tage", + "{total} total": "{total} insgesamt", + best: "Rekord", + "perfect week": "perfekte Woche", + "perfect month": "perfekter Monat", + "weekly goal": "Wochenziel", + "monthly goal": "Monatsziel", + "{progress}/{goal} days · {label} · {pct}%": + "{progress}/{goal} Tage · {label} · {pct} %", + + // Habit metrics block + 'Place this block inside a habit note, or point it at one with "habit: ".': + 'Platziere diesen Block in einer Gewohnheitsnotiz oder verweise mit „habit: " auf eine.', + 'No habit called "{name}" was found.': + 'Keine Gewohnheit namens „{name}" gefunden.', + "No longer tracked since {date}. All history is kept.": + "Seit {date} nicht mehr verfolgt. Der gesamte Verlauf bleibt erhalten.", + "No longer tracked. All history is kept.": + "Nicht mehr verfolgt. Der gesamte Verlauf bleibt erhalten.", + "Resume tracking": "Verfolgung fortsetzen", + "Paused since {date}. Paused days don't count against streaks or stats.": + "Pausiert seit {date}. Pausierte Tage zählen weder gegen Serien noch gegen Statistiken.", + "Paused. Paused days don't count against streaks or stats.": + "Pausiert. Pausierte Tage zählen weder gegen Serien noch gegen Statistiken.", + "Current streak": "Aktuelle Serie", + "Days completed": "Erledigte Tage", + "30-day rate": "30-Tage-Quote", + "Weekly completion rate": "Wöchentliche Erfüllungsquote", + Logged: "Erfasst", + Target: "Ziel", + + // Export modal + Title: "Titel", + "Habits report": "Gewohnheiten-Bericht", + "Date range": "Zeitraum", + "Custom range": "Benutzerdefinierter Zeitraum", + From: "Von", + To: "Bis", + "Up to {n} days.": "Bis zu {n} Tage.", + Content: "Inhalt", + "Summary tiles": "Zusammenfassungs-Kacheln", + "Completion trend chart": "Trend-Diagramm der Erfüllung", + "Daily grids": "Tagesraster", + "Goal progress": "Zielfortschritt", + Layout: "Layout", + Orientation: "Ausrichtung", + Portrait: "Hochformat", + Landscape: "Querformat", + Density: "Dichte", + Comfortable: "Komfortabel", + Compact: "Kompakt", + Monochrome: "Monochrom", + "Ink-friendly greys instead of accent colours.": + "Tintensparende Grautöne statt Akzentfarben.", + "Export PDF": "PDF exportieren", + "No habits to export yet.": + "Noch keine Gewohnheiten zum Exportieren.", + 'Exported to "{path}" in your vault.': + 'Nach „{path}" in deinem Vault exportiert.', + + // Habit modal + "New habit": "Neue Gewohnheit", + Name: "Name", + Type: "Typ", + "Binary is done or not done. Repetition counts towards a target. Timed tracks minutes.": + "Binär ist erledigt oder nicht erledigt. Wiederholung zählt auf ein Ziel hin. Zeitbasiert erfasst Minuten.", + Binary: "Binär", + Repetition: "Wiederholung", + Timed: "Zeitbasiert", + "Daily target (minutes)": "Tagesziel (Minuten)", + "Daily target": "Tagesziel", + Unit: "Einheit", + "Optional label shown next to the count.": + "Optionale Beschriftung neben dem Zähler.", + Icon: "Symbol", + "Choose a Lucide icon or an emoji to represent this habit.": + "Wähle ein Lucide-Symbol oder ein Emoji für diese Gewohnheit.", + Emoji: "Emoji", + "Choose an emoji": "Emoji wählen", + "Clear icon": "Symbol entfernen", + "Choose icon": "Symbol wählen", + "Save changes": "Änderungen speichern", + "Targets (optional)": "Ziele (optional)", + "Set an optional weekly or monthly goal for how many days you complete this habit. For example, hitting your daily goal on all 7 days is a weekly target of 7. Turn on a perfect toggle to aim for every day of the period automatically, whatever its length.": + "Lege optional ein Wochen- oder Monatsziel fest, an wie vielen Tagen du diese Gewohnheit erfüllst. Wer sein Tagesziel z. B. an allen 7 Tagen erreicht, hat ein Wochenziel von 7. Aktiviere einen Perfekt-Schalter, um automatisch jeden Tag des Zeitraums anzustreben, egal wie lang er ist.", + "Perfect week": "Perfekte Woche", + "Aim to complete this habit every day of the week.": + "Strebe an, diese Gewohnheit an jedem Tag der Woche zu erfüllen.", + "Weekly target": "Wochenziel", + "Optional. Days to complete per week (max 7).": + "Optional. Zu erfüllende Tage pro Woche (max. 7).", + None: "Keins", + "Perfect month": "Perfekter Monat", + "Aim to complete this habit every day of the month.": + "Strebe an, diese Gewohnheit an jedem Tag des Monats zu erfüllen.", + "Monthly target": "Monatsziel", + "Optional. Days to complete per month.": + "Optional. Zu erfüllende Tage pro Monat.", + Colour: "Farbe", + "Pick a colour from your theme, or choose a custom one.": + "Wähle eine Farbe aus deinem Theme oder eine eigene.", + "Your habit": "Deine Gewohnheit", + + // Icon and colour pickers + "Search icons…": "Symbole suchen…", + "Search emojis…": "Emojis suchen…", + + // Comments + "Comments on cards": "Kommentare auf Karten", + "Show a comment flap on dashboard cards for jotting a note about any day.": + "Zeigt eine Kommentarlasche auf den Dashboard-Karten, um Notizen zu einzelnen Tagen festzuhalten.", + "Add comment": "Kommentar hinzufügen", + "Flip back": "Zurückdrehen", + "Edit comment": "Kommentar bearbeiten", + "Move day comments into note bodies": + "Tageskommentare in Notiztexte verschieben", + "No comments left to move.": + "Keine Kommentare mehr zu verschieben.", + "Moved comments in 1 note.": "Kommentare in 1 Notiz verschoben.", + "Moved comments in {n} notes.": + "Kommentare in {n} Notizen verschoben.", + "Add a comment for this day…": "Füge einen Kommentar für diesen Tag hinzu…", + Comments: "Kommentare", + + // Limit habits (experimental) + Experimental: "Experimentell", + "These features are still being tested and may change before they become permanent. Turning one off only hides it from menus — anything you created with it keeps working.": + "Diese Funktionen werden noch getestet und können sich ändern, bevor sie dauerhaft werden. Das Ausschalten blendet sie nur aus den Menüs aus — alles, was du damit erstellt hast, funktioniert weiter.", + "Break bad habits": "Schlechte Gewohnheiten ablegen", + "Track habits you want to reduce or avoid by staying under a daily limit — for example at most 2 hours of gaming, or no smoking at all.": + "Verfolge Gewohnheiten, die du reduzieren oder vermeiden möchtest, indem du unter einem Tageslimit bleibst — zum Beispiel höchstens 2 Stunden Gaming oder gar nicht rauchen.", + Goal: "Ziel", + "Reach a target for habits you are building. Stay under a limit for habits you are cutting down or giving up.": + "Erreiche ein Ziel bei Gewohnheiten, die du aufbaust. Bleibe unter einem Limit bei Gewohnheiten, die du reduzierst oder aufgibst.", + "Reach a target": "Ein Ziel erreichen", + "Stay under a limit": "Unter einem Limit bleiben", + "Binary means avoiding it entirely. Repetition counts against a daily limit. Timed tracks minutes against a daily limit.": + "Binär bedeutet, es ganz zu vermeiden. Wiederholung zählt gegen ein Tageslimit. Zeit misst Minuten gegen ein Tageslimit.", + "Daily limit": "Tageslimit", + "Daily limit (minutes)": "Tageslimit (Minuten)", + "0 means none at all.": "0 bedeutet gar nicht.", + "Set an optional weekly or monthly goal for how many days you stay within your limit. Turn on a perfect toggle to aim for every day of the period automatically, whatever its length.": + "Lege ein optionales Wochen- oder Monatsziel fest, an wie vielen Tagen du innerhalb deines Limits bleibst. Aktiviere einen Perfekt-Schalter, um automatisch jeden Tag des Zeitraums anzustreben, egal wie lang er ist.", + Clean: "Sauber", + Slipped: "Ausgerutscht", + "Mark as clean": "Als sauber markieren", + "Mark as slipped": "Als ausgerutscht markieren", + "Days within limit": "Tage im Limit", + Limit: "Limit", + + // Frequencies and per-note metrics + Frequency: "Häufigkeit", + Daily: "Täglich", + "Days of week": "Wochentage", + Habit: "Gewohnheit", + Schedule: "Zeitplan", + "Time of day": "Uhrzeit", + "Optional times this habit is planned for — once or several times a day. Shown on the habit's card.": + "Optionale Uhrzeiten, zu denen diese Gewohnheit geplant ist — einmal oder mehrmals täglich. Werden auf der Karte der Gewohnheit angezeigt.", + "Add time": "Uhrzeit hinzufügen", + "Remove time": "Uhrzeit entfernen", + "Every N days": "Alle N Tage", + "Repeat every": "Wiederholen alle", + "Day of month": "Tag des Monats", + "The weekdays this habit is due on. Pick as many as you need.": + "Die Wochentage, an denen diese Gewohnheit fällig ist. Wähle so viele wie nötig.", + "Number of days between due dates, counted from the habit's start date. Use 2 for an alternate-day schedule.": + "Anzahl der Tage zwischen den Fälligkeiten, gezählt ab dem Startdatum der Gewohnheit. 2 ergibt einen Rhythmus von jedem zweiten Tag.", + "The day of the month this habit is due. In shorter months it falls due on the last day, so 31 always lands on the final day of the month.": + "Der Tag des Monats, an dem diese Gewohnheit fällig ist. In kürzeren Monaten fällt sie auf den letzten Tag, sodass 31 immer auf den letzten Tag des Monats fällt.", + "Every {day}": "Jeden {day}", + "Monthly · day {day}": "Monatlich · Tag {day}", + "Every other day": "Jeden zweiten Tag", + "Every {n} days": "Alle {n} Tage", + "No habits are due on this day.": + "An diesem Tag sind keine Gewohnheiten fällig.", + "Nothing due today.": "Heute ist nichts fällig.", + "Weekly activity": "Wöchentliche Aktivität", + "Monthly activity": "Monatliche Aktivität", + "Activity on due days": "Aktivität an Fälligkeitstagen", + "Completion rate over {n} due days": + "Erfolgsquote über {n} Fälligkeitstage", + "Weeks completed": "Abgeschlossene Wochen", + "Months completed": "Abgeschlossene Monate", + "Recent rate": "Aktuelle Quote", + "{n}-week completion rate": "Erfüllungsquote über {n} Wochen", + "{n}-month completion rate": "Erfüllungsquote über {n} Monate", + + // AI summaries + "AI summaries": "KI-Zusammenfassungen", + "AI summary": "KI-Zusammenfassung", + "Show an AI-generated summary with feedback and advice on the stats page tabs. Uses an OpenAI-compatible service you configure below; your habit stats are sent to it only when you press the generate button.": + "Zeigt eine KI-generierte Zusammenfassung mit Feedback und Tipps auf den Tabs der Statistik-Seite. Verwendet einen OpenAI-kompatiblen Dienst, den du unten konfigurierst; deine Gewohnheits-Statistiken werden erst gesendet, wenn du den Erstellen-Button drückst.", + "AI base URL": "KI-Basis-URL", + "Base URL of an OpenAI-compatible API. Works with OpenAI, OpenRouter, or local servers like Ollama (http://localhost:11434/v1).": + "Basis-URL einer OpenAI-kompatiblen API. Funktioniert mit OpenAI, OpenRouter oder lokalen Servern wie Ollama (http://localhost:11434/v1).", + "AI API key": "KI-API-Schlüssel", + "Stored locally in this vault's plugin data. Leave blank for local servers that need no key.": + "Wird lokal in den Plugin-Daten dieses Vaults gespeichert. Für lokale Server ohne Schlüssel leer lassen.", + "AI model": "KI-Modell", + "Model name the service should use.": + "Name des Modells, das der Dienst verwenden soll.", + "Generate summary": "Zusammenfassung erstellen", + Regenerate: "Neu erstellen", + "Get feedback and advice on your habits for this period. Your stats are sent to the AI service you configured only when you press the button.": + "Erhalte Feedback und Tipps zu deinen Gewohnheiten in diesem Zeitraum. Deine Statistiken werden erst an den konfigurierten KI-Dienst gesendet, wenn du den Button drückst.", + "Thinking…": "Denkt nach …", + "Could not generate a summary: {message}": + "Zusammenfassung konnte nicht erstellt werden: {message}", + "Adds an AI-generated overview with feedback and advice. Your habit stats are sent to your configured AI service.": + "Fügt einen KI-generierten Überblick mit Feedback und Tipps hinzu. Deine Gewohnheits-Statistiken werden an den konfigurierten KI-Dienst gesendet.", + "Generating AI summary…": "KI-Zusammenfassung wird erstellt …", + "The AI summary will be generated when you export.": + "Die KI-Zusammenfassung wird beim Exportieren erstellt.", + + // Custom stats range + Custom: "Benutzerdefiniert", + "Start date": "Startdatum", + "End date": "Enddatum", + + // Heatmap start markers + "not tracked yet": "noch nicht erfasst", + "started tracking on {date}": "Erfassung ab {date}", + + // Stats carousel + "Stats rows per page": "Statistik-Zeilen pro Seite", + "How many habits each stats page shows.": + "Wie viele Gewohnheiten jede Statistik-Seite anzeigt.", + // Note habits + '"{name}" uses Templater syntax, but the Templater plugin is not installed — the template was copied as plain text.': + '„{name}" verwendet Templater-Syntax, aber das Templater-Plugin ist nicht installiert — die Vorlage wurde als reiner Text kopiert.', + "Binary is done or not done. Repetition counts towards a target. Timed tracks minutes. Note is completed by writing in a per-day note.": + "Binär ist erledigt oder nicht erledigt. Wiederholung zählt auf ein Ziel hin. Zeitbasiert erfasst Minuten. Notiz wird durch Schreiben in eine Tagesnotiz abgeschlossen.", + "Character count is reached": "Eine Zeichenzahl wird erreicht", + "Character goal": "Zeichenziel", + "Completed when": "Abgeschlossen, wenn", + "Every task is checked": "Alle Aufgaben sind abgehakt", + "Filename format": "Dateinamenformat", + "Folder each day's note is created in. Leave blank for a dedicated subfolder named after this habit.": + "Ordner, in dem die Notiz jedes Tages erstellt wird. Leer lassen für einen eigenen Unterordner mit dem Namen dieser Gewohnheit.", + "Moment.js format used to name each day's note, e.g. {example}. May include / for date-based subfolders.": + "Moment.js-Format zur Benennung der Notiz jedes Tages, z. B. {example}. Kann / für datumsbasierte Unterordner enthalten.", + Note: "Notiz", + "Note habits": "Notiz-Gewohnheiten", + "Notes folder": "Notizordner", + "Open this day's note": "Notiz dieses Tages öffnen", + "Open today's note": "Heutige Notiz öffnen", + "Optional template note used when a day's note is created. Expanded through the Templater plugin when it is installed, otherwise copied as plain text.": + "Optionale Vorlagennotiz, die beim Erstellen der Notiz eines Tages verwendet wird. Wird über das Templater-Plugin erweitert, wenn es installiert ist, andernfalls als reiner Text kopiert.", + Template: "Vorlage", + "Track a habit by writing in a per-day note instead of logging a value by hand. A day is complete once the note reaches a character count or every task in it is checked. Works with the Templater plugin to create each day's note from a template.": + "Verfolge eine Gewohnheit, indem du in eine Tagesnotiz schreibst, statt von Hand einen Wert einzutragen. Ein Tag ist abgeschlossen, sobald die Notiz eine Zeichenzahl erreicht oder alle ihre Aufgaben abgehakt sind. Funktioniert mit dem Templater-Plugin, um die Notiz jedes Tages aus einer Vorlage zu erstellen.", + Write: "Schreiben", + "Write this day's note": "Notiz dieses Tages schreiben", + "Write today's note": "Heutige Notiz schreiben", + "e.g. Journal": "z. B. Journal", + "e.g. Templates/Journal.md": "z. B. Templates/Journal.md", + + // Flexible frequency (any day) + "How many times (or, for counted and timed habits, how much in total) this needs to happen somewhere in the period.": + "Wie oft (oder, bei gezählten oder zeitbasierten Gewohnheiten, wie viel insgesamt) dies irgendwann im Zeitraum geschehen muss.", + 'How often this habit is due. Weekly and monthly habits only appear on their due date; the "any day" options appear every day until their quota is met.': + 'Wie oft diese Gewohnheit fällig ist. Wöchentliche und monatliche Gewohnheiten erscheinen nur an ihrem Fälligkeitstag; die Optionen „an beliebigem Tag" erscheinen jeden Tag, bis das Kontingent erreicht ist.', + "Monthly (any day)": "Monatlich (beliebiger Tag)", + "Times per month": "Mal pro Monat", + "Times per week": "Mal pro Woche", + "Weekly (any day)": "Wöchentlich (beliebiger Tag)", + "this month": "diesen Monat", + "this week": "diese Woche", + "{completed}/{days} months": "{completed}/{days} Monate", + "{completed}/{days} weeks": "{completed}/{days} Wochen", + "{n}× a month · any day": "{n}× im Monat · beliebiger Tag", + "{n}× a week · any day": "{n}× in der Woche · beliebiger Tag", + + // Commands + "Insert habits heatmap": "Gewohnheiten-Heatmap einfügen", + + // Habit metrics: heatmap tabs + Charts: "Diagramme", + Month: "Monat", + History: "Verlauf", + "{month} heatmap": "Heatmap für {month}", + "Last {n} weeks": "Letzte {n} Wochen", + + // Heatmap cell states and tooltips + Upcoming: "Bevorstehend", + "Not tracked yet": "Noch nicht erfasst", + "Not due": "Nicht fällig", + "Outside this month": "Außerhalb dieses Monats", + Complete: "Abgeschlossen", + "Over limit": "Über dem Limit", + "Not logged": "Nicht erfasst", + + // Whole-vault heatmap block + "Add a habit to see its heatmap here.": + "Füge eine Gewohnheit hinzu, um hier ihre Heatmap zu sehen.", + "No habits in the \"{group}\" group.": + 'Keine Gewohnheiten in der Gruppe „{group}".', + "No habits due": "Keine Gewohnheiten fällig", + "Perfect day": "Perfekter Tag", + "{completed}/{considered} habits · {pct}%": + "{completed}/{considered} Gewohnheiten · {pct} %", + "This year": "Dieses Jahr", + "Past 6 months": "Letzte 6 Monate", + "{year} heatmap": "Heatmap für {year}", + + // Note habits: checklist requirement and fail keyword + "Both are true": "Beide zutreffend", + "Checklist requirement is met": "Checklisten-Anforderung ist erfüllt", + "Checklist requirement": "Checklisten-Anforderung", + "Require every task to be checked, or just some — useful for a list of alternatives where doing any one of them counts (e.g. \"Cardio\" / \"Weights\" / \"Rest day\").": + 'Verlange, dass alle Aufgaben abgehakt werden, oder nur einige – nützlich für eine Liste von Alternativen, bei der irgendeine davon zählt (z. B. „Cardio" / „Krafttraining" / „Ruhetag").', + "At least this many are checked": "Mindestens so viele sind abgehakt", + "Tasks required": "Erforderliche Aufgaben", + "Fail keyword": "Fehlschlag-Schlüsselwort", + "Optional. Checking a task whose text contains this word forces the day to fail, whatever else is checked — e.g. \"Slipped\" as one of several checklist options. Leave blank to turn this off.": + 'Optional. Wird eine Aufgabe abgehakt, deren Text dieses Wort enthält, gilt der Tag als gescheitert, egal was sonst abgehakt ist — zum Beispiel „Ausgerutscht" als eine von mehreren Checklisten-Optionen. Leer lassen, um dies auszuschalten.', + "e.g. Slipped": "z. B. Ausgerutscht", + "Reach a character count, meet a checklist requirement, or require both.": + "Erreiche eine Zeichenanzahl, erfülle eine Checklisten-Anforderung oder verlange beides.", + + // Tags (cross-plugin compatibility) + Tags: "Tags", + "e.g. task": "z. B. task", + "Optional Obsidian tags for this note, separated by commas or spaces. Useful for making this habit recognisable to another plugin's own tag-based rules — for example TaskNotes' task tag.": + 'Optionale Obsidian-Tags für diese Notiz, getrennt durch Kommas oder Leerzeichen. Nützlich, damit diese Gewohnheit von den eigenen Tag-Regeln eines anderen Plugins erkannt wird — zum Beispiel dem „task"-Tag von TaskNotes.', + + // Advanced settings: frontmatter key remapping + Advanced: "Erweitert", + Apply: "Anwenden", + "Apply key changes": "Schlüsseländerungen anwenden", + "Rename the frontmatter properties habit notes use. Useful for avoiding collisions with another plugin's own properties in the same note (for example TaskNotes).": + "Benenne die Frontmatter-Eigenschaften um, die Gewohnheitsnotizen verwenden. Nützlich, um Kollisionen mit den eigenen Eigenschaften eines anderen Plugins in derselben Notiz zu vermeiden (zum Beispiel TaskNotes).", + "\"{a}\" and \"{b}\" can't use the same property key (\"{value}\").": + '„{a}" und „{b}" können nicht denselben Eigenschaftsschlüssel verwenden („{value}").', + "Property keys can't be empty.": + "Eigenschaftsschlüssel dürfen nicht leer sein.", + "This renames {summary} in every note in your habits folder ({count} habit(s) currently). Existing values are moved, not discarded. Continue?": + "Dies benennt {summary} in jeder Notiz in deinem Gewohnheitsordner um (aktuell {count} Gewohnheit(en)). Vorhandene Werte werden verschoben, nicht verworfen. Fortfahren?", + "Updated the frontmatter keys in {count} note(s).": + "Frontmatter-Schlüssel in {count} Notiz(en) aktualisiert.", + "Renaming this away from the default also changes how binary habits log a day: instead of {\"2026-08-25\": 1}, a completed day becomes a bare date, like [\"2026-08-25\"] — the shape TaskNotes uses for complete_instances. Repetition and timed habits are unaffected either way; they always need a value, never just a date.": + 'Wird dieser Schlüssel vom Standard abweichend umbenannt, ändert sich auch, wie binäre Gewohnheiten einen Tag protokollieren: Statt {"2026-08-25": 1} wird ein abgeschlossener Tag zu einem reinen Datum wie ["2026-08-25"] — dem Format, das TaskNotes für complete_instances verwendet. Wiederholungs- und Zeit-Gewohnheiten sind davon unabhängig nicht betroffen; sie benötigen immer einen Wert, nie nur ein Datum.', + Identity: "Identität", + Legacy: "Altlasten", + Lifecycle: "Lebenszyklus", + Presentation: "Darstellung", + "Note habit": "Notiz-Gewohnheit", + "Habit type key": "Gewohnheitstyp-Schlüssel", + "Completion records key": "Aufzeichnungsschlüssel", + "Frequency key": "Häufigkeitsschlüssel", + "Weekday key": "Wochentagsschlüssel", + "Month day key": "Monatstagsschlüssel", + "Interval days key": "Intervalltage-Schlüssel", + "Planned time key": "Schlüssel für die geplante Uhrzeit", + "Goal direction key": "Zielrichtungsschlüssel", + "Target key": "Zielschlüssel", + "Unit key": "Einheitenschlüssel", + "Step size key": "Schlüssel für die Schrittweite", + "Weekly target key": "Wochenzielschlüssel", + "Monthly target key": "Monatszielschlüssel", + "Weekly perfect key": "Schlüssel für die perfekte Woche", + "Monthly perfect key": "Schlüssel für den perfekten Monat", + "Start date key": "Startdatumsschlüssel", + "Pauses key": "Pausenschlüssel", + "Stopped key": "Schlüssel für den Stopp-Status", + "Stop date key": "Stoppdatumsschlüssel", + "Icon key": "Symbolschlüssel", + "Color key": "Farbschlüssel", + "Group key": "Gruppenschlüssel", + "Use group color key": 'Schlüssel für „Gruppenfarbe verwenden"', + "Note folder key": "Notizordnerschlüssel", + "Note filename format key": "Schlüssel für das Dateinamenformat der Notiz", + "Template path key": "Vorlagenpfadschlüssel", + "Note completion mode key": "Schlüssel für den Abschlussmodus der Notiz", + "Note checklist requirement key": "Schlüssel für die Checklisten-Anforderung", + "Note checklist minimum key": "Schlüssel für die Checklisten-Mindestanzahl", + "Note fail keyword key": "Schlüssel für das Fehlschlag-Schlüsselwort", + "Legacy comments key": "Schlüssel für alte Kommentare", + + // PDF export (read via docT() in export-modal.ts, which falls back to English for zh — jsPDF's built-in fonts can't render CJK) + "Completion trend": "Erfüllungstrend", + "(paused)": "(pausiert)", + "{rate}% · {total} · streak {current} (best {best})": + "{rate} % · {total} · Serie {current} (Rekord {best})", + "Goal: {completed}/{goal} days met": + "Ziel: {completed}/{goal} Tage erreicht", + "{range} · exported {date}": "{range} · exportiert am {date}", + "+{n} more": "+{n} weitere", + + // Back-dating a missed day + Back: "Zurück", + + // Rescheduling missed habits (experimental) + "1 missed habit": "1 verpasste Gewohnheit", + "Add a notification button to the dashboard and sidebar panel when a habit's been missed, opening a review of missed days you can move onto a different one (never a day that habit is already due, so nothing doubles up).": + "Fügt dem Dashboard und dem Seitenpanel eine Benachrichtigungsschaltfläche hinzu, sobald eine Gewohnheit verpasst wurde. Sie öffnet eine Übersicht der verpassten Tage, die du auf einen anderen Tag verschieben kannst (nie auf einen Tag, an dem die Gewohnheit ohnehin schon fällig ist, damit nichts doppelt gezählt wird).", + "Missed habits": "Verpasste Gewohnheiten", + "Move this missed day onto a different one": + "Diesen verpassten Tag auf einen anderen verschieben", + "Move to": "Verschieben auf", + "Nothing missed right now.": "Gerade nichts verpasst.", + "Pick a habit to move it onto a different day.": + "Wähle eine Gewohnheit, um sie auf einen anderen Tag zu verschieben.", + Reschedule: "Verschieben", + "Reschedule missed habits": "Verpasste Gewohnheiten verschieben", + "Rescheduled \"{name}\" to {date}.": '„{name}" wurde auf {date} verschoben.', + "Rescheduled from {date}": "Verschoben von {date}", + "Reschedules key": "Schlüssel für Verschiebungen", + "Failed days key": "Schlüssel für fehlgeschlagene Tage", + "Skipped days key": "Schlüssel für übersprungene Tage", + "Rescheduling \"{name}\" — missed {date}.": + '„{name}" verschieben — verpasst am {date}.', + "That day no longer works — pick another.": + "Dieser Tag funktioniert nicht mehr — wähle einen anderen.", + "That day won't work — it's either already due for this habit or already claimed by another reschedule.": + "Dieser Tag geht nicht — entweder ist die Gewohnheit an diesem Tag bereits fällig, oder er ist schon durch eine andere Verschiebung belegt.", + "{count} missed habits": "{count} verpasste Gewohnheiten", +}; diff --git a/src/integrations/habits/i18n/es.ts b/src/integrations/habits/i18n/es.ts new file mode 100644 index 000000000..46fabc298 --- /dev/null +++ b/src/integrations/habits/i18n/es.ts @@ -0,0 +1,652 @@ +/** Spanish translations, keyed by the English source string. */ +export const es: Record = { + // Commands and ribbon + "Create habit": "Crear hábito", + "Insert dashboard": "Insertar panel de hábitos", + "Insert habit metrics": "Insertar métricas de hábito", + "Insert habits table": "Insertar tabla de hábitos", + "Open panel": "Abrir panel", + "Open habits panel": "Abrir el panel de hábitos", + Habits: "Hábitos", + + // Settings + "Habits folder": "Carpeta de hábitos", + "Folder where each habit is stored as its own note. It is created automatically if it does not exist.": + "Carpeta donde cada hábito se guarda como una nota propia. Se crea automáticamente si no existe.", + "Follow daily note date": "Seguir la fecha de la nota diaria", + "When a dashboard is embedded in a daily note (a note whose name contains a date like 2026-07-01), open it on that note's date instead of today.": + "Cuando un panel está insertado en una nota diaria (una nota cuyo nombre contiene una fecha como 2026-07-01), se abre en la fecha de esa nota en lugar de hoy.", + "Daily note date format": "Formato de fecha de la nota diaria", + "Moment.js format used to read the date from a daily note's name, such as YYYY-MM-DD or YYYYMMDD.": + "Formato de Moment.js usado para leer la fecha del nombre de una nota diaria, por ejemplo YYYY-MM-DD o YYYYMMDD.", + + // Sorting + "Sort habits by": "Ordenar hábitos por", + "The base order of habit cards in the dashboard and side panel.": + "El orden base de las tarjetas de hábitos en el panel principal y el panel lateral.", + "Name (A–Z)": "Nombre (A–Z)", + Color: "Color", + "Last logged": "Último registro", + "Planned time": "Hora prevista", + Manual: "Manual", + "Manual order": "Orden manual", + "Drag the cards into the order you want. New habits join the end of the list.": + "Arrastra las tarjetas en el orden que quieras. Los hábitos nuevos se añaden al final de la lista.", + "Move completed cards to the end": + "Mover las tarjetas completadas al final", + "Completed habits drift to the end of the queue and paused ones park behind them. Turn this off to keep every card in its sorted position.": + "Los hábitos completados se desplazan al final de la cola y los pausados quedan detrás. Desactívalo para que cada tarjeta mantenga su posición ordenada.", + Group: "Grupo", + Ungrouped: "Sin grupo", + "Optional group used to build dashboard sections — for example an area of responsibility.": + "Grupo opcional para crear secciones en el panel — por ejemplo, un área de responsabilidad.", + "e.g. Health": "p. ej. Salud", + "Group color": "Color del grupo", + "Optional color shared by every habit in this group.": + "Color opcional compartido por todos los hábitos de este grupo.", + "Group icon": "Icono del grupo", + "Shown in the group lip on cards and in section headers.": + "Se muestra en la pestaña de grupo de las tarjetas y en los encabezados de sección.", + "Use group color for this card": + "Usar el color del grupo para esta tarjeta", + "Show this card in the group color instead of its own.": + "Muestra esta tarjeta con el color del grupo en lugar del suyo.", + General: "General", + Sorting: "Ordenación", + Groups: "Grupos", + "How to move through your habit cards: a paged carousel with arrows, a grid that wraps onto new rows, or a fixed-height grid that scrolls vertically. The stats page follows the same choice.": + "Cómo navegar por tus tarjetas de hábitos: un carrusel paginado con flechas, una cuadrícula que salta a nuevas filas o una cuadrícula de altura fija con desplazamiento vertical. La página de estadísticas sigue la misma elección.", + "Enable groups": "Activar grupos", + "Show habits in sections by their group, with a group lip on each card.": + "Muestra los hábitos en secciones según su grupo, con una pestaña de grupo en cada tarjeta.", + "Group order": "Orden de los grupos", + "Drag the groups into the order you want. Sections follow the same order.": + "Arrastra los grupos en el orden que quieras. Las secciones siguen el mismo orden.", + "Completion animations": "Animaciones de finalización", + "Play the check swoosh, card departure, and perfect-day confetti when habits are completed. Turn off for instant, quiet updates.": + "Reproduce el swoosh de la marca, la salida de la tarjeta y el confeti del día perfecto al completar hábitos. Desactívalo para actualizaciones instantáneas y silenciosas.", + "Reminders": "Recordatorios", + "Write reminders for due habits": + "Escribir recordatorios para hábitos pendientes", + "Each day, write one reminder checklist line per planned time of every habit due that day, in the format the Reminder plugin picks up. The lines live in a marked block and refresh as you log habits.": + "Cada día escribe una línea de recordatorio por cada hora prevista de cada hábito que toque ese día, en el formato que reconoce el plugin Reminder. Las líneas viven en un bloque marcado y se actualizan al registrar hábitos.", + "Where to write reminders": "Dónde escribir los recordatorios", + "The daily note follows the Daily notes core plugin's folder and date format; the block is added once the note exists. A fixed note is created automatically.": + "La nota diaria sigue la carpeta y el formato de fecha del plugin básico de notas diarias; el bloque se añade cuando la nota existe. Una nota fija se crea automáticamente.", + "Today's daily note": "Nota diaria de hoy", + "A fixed note": "Una nota fija", + "Reminder note path": "Ruta de la nota de recordatorios", + "Vault path of the note that holds the reminder block.": + "Ruta en el vault de la nota que contiene el bloque de recordatorios.", + "Manage groups": "Gestionar grupos", + "See every habit by group and drag cards between groups.": + "Ve todos los hábitos por grupo y arrastra tarjetas entre grupos.", + Open: "Abrir", + "New group": "Nuevo grupo", + Add: "Añadir", + "Drag habits between groups to reassign them, or within a group to reorder them.": + "Arrastra hábitos entre grupos para reasignarlos, o dentro de un grupo para reordenarlos.", + "No habits": "Sin hábitos", + "Edit group style": "Editar estilo del grupo", + "Delete group": "Eliminar grupo", + 'Delete "{name}"? Its habits are kept and become ungrouped.': + '¿Eliminar "{name}"? Sus hábitos se conservan y quedan sin grupo.', + Delete: "Eliminar", + "Dashboard layout": "Diseño del panel", + Carousel: "Carrusel", + Grid: "Cuadrícula", + "Vertical scroll": "Desplazamiento vertical", + "Cards per view": "Tarjetas por vista", + "How many habit cards fit side by side on wider screens.": + "Cuántas tarjetas de hábitos caben una junto a otra en pantallas anchas.", + "Cards per view on mobile": "Tarjetas por vista en el móvil", + "How many habit cards fit side by side on phone-sized screens.": + "Cuántas tarjetas de hábitos caben una junto a otra en pantallas de móvil.", + + // Confirm dialog defaults + Cancel: "Cancelar", + Confirm: "Confirmar", + + // Store notices + 'Could not find the note for "{name}".': + 'No se encontró la nota de "{name}".', + "Please enter a valid habit name.": + "Introduce un nombre de hábito válido.", + 'A habit called "{name}" already exists.': + 'Ya existe un hábito llamado "{name}".', + 'Created habit "{name}".': 'Hábito "{name}" creado.', + 'Updated "{name}".': '"{name}" actualizado.', + 'Paused "{name}".': '"{name}" pausado.', + 'Resumed "{name}".': '"{name}" reanudado.', + 'Stopped tracking "{name}". Its history is kept in the note.': + 'Se dejó de seguir "{name}". Su historial se conserva en la nota.', + 'Resumed tracking "{name}".': 'Se reanudó el seguimiento de "{name}".', + 'Removed "{name}".': '"{name}" eliminado.', + "Habit added to the dashboard.": "Hábito añadido al panel.", + + // Dashboard + "Back to habits": "Volver a los hábitos", + "View stats": "Ver estadísticas", + "Export stats": "Exportar estadísticas", + Weekly: "Semanal", + Monthly: "Mensual", + "Previous day": "Día anterior", + "Next day": "Día siguiente", + "Choose a date": "Elegir una fecha", + "Add habit": "Añadir hábito", + "No habits yet. Create your first habit to get started.": + "Aún no hay hábitos. Crea tu primer hábito para empezar.", + Previous: "Anterior", + Next: "Siguiente", + "Go to position {n}": "Ir a la posición {n}", + "Right-click or long-press for more options": + "Clic derecho o pulsación larga para más opciones", + "Open habit note": "Abrir la nota del hábito", + "Open the note for {name}": "Abrir la nota de {name}", + Paused: "Pausado", + Stopped: "Detenido", + "Failed": "Fallado", + "Skipped": "Omitido", + "Snoozed": "Pospuesto", + "Snoozed until {time}": "Pospuesto hasta las {time}", + "Undo fail": "Deshacer fallo", + "Undo skip": "Deshacer omisión", + "End snooze": "Terminar posposición", + "Fail for today": "Fallar por hoy", + "Fail this day": "Fallar este día", + "Marked \"{name}\" as failed.": "«{name}» marcado como fallado.", + "Skip for today": "Omitir por hoy", + "Skip this day": "Omitir este día", + "Skipped \"{name}\".": "«{name}» omitido.", + "Snooze…": "Posponer…", + "Snooze \"{name}\"": "Posponer «{name}»", + "It leaves today's lists and comes back on its own. Snoozing never counts for or against the habit.": "Sale de las listas de hoy y vuelve por sí solo. Posponer nunca cuenta a favor ni en contra del hábito.", + "Snooze for": "Posponer durante", + "30 minutes": "30 minutos", + "1 hour": "1 hora", + "3 hours": "3 horas", + "Snooze until": "Posponer hasta", + "Snooze": "Posponer", + "Pick a time later today.": "Elige una hora posterior de hoy.", + "Snoozed \"{name}\" until {time}.": "«{name}» pospuesto hasta las {time}.", + "1 hidden for today": "1 oculto por hoy", + "{count} hidden for today": "{count} ocultos por hoy", + "1 hidden for this day": "1 oculto en este día", + "{count} hidden for this day": "{count} ocultos en este día", + "Undo": "Deshacer", + "Click to undo": "Haz clic para deshacer", + "Nothing left on this day's list.": "No queda nada en la lista de este día.", + "Nothing left on today's list.": "No queda nada en la lista de hoy.", + "At least: reach a target for habits you are building, like drinking 1.5 litres of water. At most: stay within a limit for habits you are cutting down, like no more than 2 coffees.": "Al menos: alcanza una meta en los hábitos que estás creando, como beber 1,5 litros de agua. Como máximo: no superes un límite en los hábitos que estás reduciendo, como no más de 2 cafés.", + "At least (reach a target)": "Al menos (alcanzar una meta)", + "At most (stay within a limit)": "Como máximo (no superar un límite)", + "Step size": "Tamaño del paso", + "How much each + and − press adds or removes. Use a decimal such as 0.25 for amounts like litres.": "Cuánto suma o resta cada pulsación de + y −. Usa un decimal como 0.25 para cantidades como litros.", + "Decrease by {n}": "Reducir en {n}", + "4 weeks": "4 semanas", + "12 weeks": "12 semanas", + "6 months": "6 meses", + "1 year": "1 año", + "Completion rate": "Tasa de cumplimiento", + "Monthly completion rate": "Tasa de cumplimiento mensual", + "Daily activity": "Actividad diaria", + "Week of {date}": "Semana del {date}", + "Since {date} · right-click to resume": + "Desde {date} · clic derecho para reanudar", + "Paused on this day": "Pausado en este día", + "Mark as done": "Marcar como hecho", + "Mark as not done": "Marcar como no hecho", + Done: "Hecho", + "Not done": "Pendiente", + "Edit value": "Editar valor", + Value: "Valor", + "Decrease by 1": "Reducir en 1", + "Increase by 1": "Aumentar en 1", + "Increase by {n}": "Aumentar en {n}", + "Edit habit": "Editar hábito", + "Pause habit": "Pausar hábito", + "Resume habit": "Reanudar hábito", + "Stop tracking": "Dejar de seguir", + "Remove habit": "Eliminar hábito", + 'Stop tracking "{name}"? It leaves the dashboard and stats, but its note and full history are kept. You can resume tracking any time from the note\'s metrics view.': + '¿Dejar de seguir "{name}"? Desaparece del panel y de las estadísticas, pero su nota y todo su historial se conservan. Puedes reanudar el seguimiento en cualquier momento desde la vista de métricas de la nota.', + 'Remove "{name}"? Its note will be moved to the trash.': + '¿Eliminar "{name}"? Su nota se moverá a la papelera.', + Remove: "Eliminar", + "Perfect!": "¡Perfecto!", + Today: "Hoy", + Yesterday: "Ayer", + Tomorrow: "Mañana", + "Last 7 days": "Últimos 7 días", + "Last 30 days": "Últimos 30 días", + "This week": "Esta semana", + "This month": "Este mes", + + // Sidebar panel + "Habits completed today": "Hábitos completados hoy", + "No habits yet.": "Aún no hay hábitos.", + "Click to type a value": "Haz clic para escribir un valor", + "Open note": "Abrir nota", + + // Stats view + "No habits to show stats for yet.": + "Aún no hay hábitos para mostrar estadísticas.", + Completion: "Cumplimiento", + "Best streak": "Mejor racha", + "Perfect days": "Días perfectos", + Completions: "Completados", + "Goals met": "Metas logradas", + "{completed}/{days} days": "{completed}/{days} días", + "{total} total": "{total} en total", + best: "mejor", + "perfect week": "semana perfecta", + "perfect month": "mes perfecto", + "weekly goal": "meta semanal", + "monthly goal": "meta mensual", + "{progress}/{goal} days · {label} · {pct}%": + "{progress}/{goal} días · {label} · {pct}%", + + // Habit metrics block + 'Place this block inside a habit note, or point it at one with "habit: ".': + 'Coloca este bloque dentro de una nota de hábito, o indícale uno con "habit: ".', + 'No habit called "{name}" was found.': + 'No se encontró ningún hábito llamado "{name}".', + "No longer tracked since {date}. All history is kept.": + "Sin seguimiento desde {date}. Todo el historial se conserva.", + "No longer tracked. All history is kept.": + "Sin seguimiento. Todo el historial se conserva.", + "Resume tracking": "Reanudar seguimiento", + "Paused since {date}. Paused days don't count against streaks or stats.": + "Pausado desde {date}. Los días en pausa no afectan a las rachas ni a las estadísticas.", + "Paused. Paused days don't count against streaks or stats.": + "Pausado. Los días en pausa no afectan a las rachas ni a las estadísticas.", + "Current streak": "Racha actual", + "Days completed": "Días completados", + "30-day rate": "Tasa de 30 días", + "Weekly completion rate": "Tasa de cumplimiento semanal", + Logged: "Registrado", + Target: "Objetivo", + + // Export modal + Title: "Título", + "Habits report": "Informe de hábitos", + "Date range": "Rango de fechas", + "Custom range": "Rango personalizado", + From: "Desde", + To: "Hasta", + "Up to {n} days.": "Hasta {n} días.", + Content: "Contenido", + "Summary tiles": "Mosaicos de resumen", + "Completion trend chart": "Gráfico de tendencia de cumplimiento", + "Daily grids": "Cuadrículas diarias", + "Goal progress": "Progreso de metas", + Layout: "Diseño", + Orientation: "Orientación", + Portrait: "Vertical", + Landscape: "Horizontal", + Density: "Densidad", + Comfortable: "Cómodo", + Compact: "Compacto", + Monochrome: "Monocromo", + "Ink-friendly greys instead of accent colours.": + "Grises que ahorran tinta en lugar de colores de acento.", + "Export PDF": "Exportar PDF", + "No habits to export yet.": "Aún no hay hábitos para exportar.", + 'Exported to "{path}" in your vault.': + 'Exportado a "{path}" en tu bóveda.', + + // Habit modal + "New habit": "Nuevo hábito", + Name: "Nombre", + Type: "Tipo", + "Binary is done or not done. Repetition counts towards a target. Timed tracks minutes.": + "Binario es hecho o no hecho. Repetición cuenta hacia un objetivo. Temporizado registra minutos.", + Binary: "Binario", + Repetition: "Repetición", + Timed: "Temporizado", + "Daily target (minutes)": "Objetivo diario (minutos)", + "Daily target": "Objetivo diario", + Unit: "Unidad", + "Optional label shown next to the count.": + "Etiqueta opcional que se muestra junto al recuento.", + Icon: "Icono", + "Choose a Lucide icon or an emoji to represent this habit.": + "Elige un icono de Lucide o un emoji para representar este hábito.", + Emoji: "Emoji", + "Choose an emoji": "Elegir un emoji", + "Clear icon": "Quitar icono", + "Choose icon": "Elegir icono", + "Save changes": "Guardar cambios", + "Targets (optional)": "Metas (opcional)", + "Set an optional weekly or monthly goal for how many days you complete this habit. For example, hitting your daily goal on all 7 days is a weekly target of 7. Turn on a perfect toggle to aim for every day of the period automatically, whatever its length.": + "Establece una meta semanal o mensual opcional de cuántos días completas este hábito. Por ejemplo, lograr tu objetivo diario los 7 días es una meta semanal de 7. Activa un interruptor de perfección para aspirar automáticamente a todos los días del período, sea cual sea su duración.", + "Perfect week": "Semana perfecta", + "Aim to complete this habit every day of the week.": + "Aspira a completar este hábito todos los días de la semana.", + "Weekly target": "Meta semanal", + "Optional. Days to complete per week (max 7).": + "Opcional. Días a completar por semana (máx. 7).", + None: "Ninguno", + "Perfect month": "Mes perfecto", + "Aim to complete this habit every day of the month.": + "Aspira a completar este hábito todos los días del mes.", + "Monthly target": "Meta mensual", + "Optional. Days to complete per month.": + "Opcional. Días a completar por mes.", + Colour: "Color", + "Pick a colour from your theme, or choose a custom one.": + "Elige un color de tu tema o escoge uno personalizado.", + "Your habit": "Tu hábito", + + // Icon and colour pickers + "Search icons…": "Buscar iconos…", + "Search emojis…": "Buscar emojis…", + + // Comments + "Comments on cards": "Comentarios en las tarjetas", + "Show a comment flap on dashboard cards for jotting a note about any day.": + "Muestra una pestaña de comentarios en las tarjetas del panel para anotar cualquier día.", + "Add comment": "Añadir comentario", + "Flip back": "Volver a girar", + "Edit comment": "Editar comentario", + "Move day comments into note bodies": + "Mover los comentarios diarios al cuerpo de las notas", + "No comments left to move.": "No quedan comentarios por mover.", + "Moved comments in 1 note.": "Comentarios movidos en 1 nota.", + "Moved comments in {n} notes.": + "Comentarios movidos en {n} notas.", + "Add a comment for this day…": "Añade un comentario para este día…", + Comments: "Comentarios", + + // Limit habits (experimental) + Experimental: "Experimental", + "These features are still being tested and may change before they become permanent. Turning one off only hides it from menus — anything you created with it keeps working.": + "Estas funciones aún se están probando y pueden cambiar antes de ser permanentes. Desactivarlas solo las oculta de los menús: todo lo que hayas creado con ellas sigue funcionando.", + "Break bad habits": "Romper malos hábitos", + "Track habits you want to reduce or avoid by staying under a daily limit — for example at most 2 hours of gaming, or no smoking at all.": + "Controla hábitos que quieres reducir o evitar manteniéndote por debajo de un límite diario — por ejemplo, como máximo 2 horas de videojuegos, o no fumar en absoluto.", + Goal: "Objetivo", + "Reach a target for habits you are building. Stay under a limit for habits you are cutting down or giving up.": + "Alcanza una meta para hábitos que estás construyendo. Mantente bajo un límite para hábitos que estás reduciendo o dejando.", + "Reach a target": "Alcanzar una meta", + "Stay under a limit": "Mantenerse bajo un límite", + "Binary means avoiding it entirely. Repetition counts against a daily limit. Timed tracks minutes against a daily limit.": + "Binario significa evitarlo por completo. Repetición cuenta contra un límite diario. Cronometrado mide minutos contra un límite diario.", + "Daily limit": "Límite diario", + "Daily limit (minutes)": "Límite diario (minutos)", + "0 means none at all.": "0 significa nada en absoluto.", + "Set an optional weekly or monthly goal for how many days you stay within your limit. Turn on a perfect toggle to aim for every day of the period automatically, whatever its length.": + "Establece una meta semanal o mensual opcional de cuántos días te mantienes dentro de tu límite. Activa un interruptor de perfección para aspirar automáticamente a todos los días del período, sea cual sea su duración.", + Clean: "Limpio", + Slipped: "Recaída", + "Mark as clean": "Marcar como limpio", + "Mark as slipped": "Marcar como recaída", + "Days within limit": "Días dentro del límite", + Limit: "Límite", + + // Frequencies and per-note metrics + Frequency: "Frecuencia", + Daily: "Diario", + "Days of week": "Días de la semana", + Habit: "Hábito", + Schedule: "Programación", + "Time of day": "Hora del día", + "Optional times this habit is planned for — once or several times a day. Shown on the habit's card.": + "Horas opcionales previstas para este hábito — una o varias veces al día. Se muestran en la tarjeta del hábito.", + "Add time": "Añadir hora", + "Remove time": "Quitar hora", + "Every N days": "Cada N días", + "Repeat every": "Repetir cada", + "Day of month": "Día del mes", + "The weekdays this habit is due on. Pick as many as you need.": + "Los días de la semana en que vence este hábito. Elige tantos como necesites.", + "Number of days between due dates, counted from the habit's start date. Use 2 for an alternate-day schedule.": + "Número de días entre vencimientos, contado desde la fecha de inicio del hábito. Usa 2 para un esquema de días alternos.", + "The day of the month this habit is due. In shorter months it falls due on the last day, so 31 always lands on the final day of the month.": + "El día del mes en que vence este hábito. En meses más cortos vence el último día, así que 31 siempre cae en el último día del mes.", + "Every {day}": "Cada {day}", + "Monthly · day {day}": "Mensual · día {day}", + "Every other day": "Cada dos días", + "Every {n} days": "Cada {n} días", + "No habits are due on this day.": "Ningún hábito vence este día.", + "Nothing due today.": "Nada vence hoy.", + "Weekly activity": "Actividad semanal", + "Monthly activity": "Actividad mensual", + "Activity on due days": "Actividad en días de vencimiento", + "Completion rate over {n} due days": + "Tasa de cumplimiento en {n} días de vencimiento", + "Weeks completed": "Semanas completadas", + "Months completed": "Meses completados", + "Recent rate": "Tasa reciente", + "{n}-week completion rate": "Tasa de cumplimiento de {n} semanas", + "{n}-month completion rate": "Tasa de cumplimiento de {n} meses", + + // AI summaries + "AI summaries": "Resúmenes con IA", + "AI summary": "Resumen con IA", + "Show an AI-generated summary with feedback and advice on the stats page tabs. Uses an OpenAI-compatible service you configure below; your habit stats are sent to it only when you press the generate button.": + "Muestra un resumen generado por IA con comentarios y consejos en las pestañas de la página de estadísticas. Usa un servicio compatible con OpenAI que configuras abajo; tus estadísticas de hábitos se le envían solo cuando pulsas el botón de generar.", + "AI base URL": "URL base de IA", + "Base URL of an OpenAI-compatible API. Works with OpenAI, OpenRouter, or local servers like Ollama (http://localhost:11434/v1).": + "URL base de una API compatible con OpenAI. Funciona con OpenAI, OpenRouter o servidores locales como Ollama (http://localhost:11434/v1).", + "AI API key": "Clave de API de IA", + "Stored locally in this vault's plugin data. Leave blank for local servers that need no key.": + "Se guarda localmente en los datos del plugin de este vault. Déjala en blanco para servidores locales que no necesitan clave.", + "AI model": "Modelo de IA", + "Model name the service should use.": + "Nombre del modelo que debe usar el servicio.", + "Generate summary": "Generar resumen", + Regenerate: "Regenerar", + "Get feedback and advice on your habits for this period. Your stats are sent to the AI service you configured only when you press the button.": + "Recibe comentarios y consejos sobre tus hábitos en este período. Tus estadísticas se envían al servicio de IA que configuraste solo cuando pulsas el botón.", + "Thinking…": "Pensando…", + "Could not generate a summary: {message}": + "No se pudo generar el resumen: {message}", + "Adds an AI-generated overview with feedback and advice. Your habit stats are sent to your configured AI service.": + "Añade un resumen generado por IA con comentarios y consejos. Tus estadísticas de hábitos se envían al servicio de IA configurado.", + "Generating AI summary…": "Generando resumen con IA…", + "The AI summary will be generated when you export.": + "El resumen con IA se generará al exportar.", + + // Custom stats range + Custom: "Personalizado", + "Start date": "Fecha de inicio", + "End date": "Fecha de fin", + + // Heatmap start markers + "not tracked yet": "aún sin seguimiento", + "started tracking on {date}": "seguimiento iniciado el {date}", + + // Stats carousel + "Stats rows per page": "Filas de estadísticas por página", + "How many habits each stats page shows.": + "Cuántos hábitos muestra cada página de estadísticas.", + // Note habits + '"{name}" uses Templater syntax, but the Templater plugin is not installed — the template was copied as plain text.': + '"{name}" usa la sintaxis de Templater, pero el plugin Templater no está instalado — la plantilla se copió como texto sin formato.', + "Binary is done or not done. Repetition counts towards a target. Timed tracks minutes. Note is completed by writing in a per-day note.": + "Binario es hecho o no hecho. Repetición cuenta hacia un objetivo. Temporizado registra minutos. Nota se completa escribiendo en una nota diaria.", + "Character count is reached": "Se alcanza un número de caracteres", + "Character goal": "Meta de caracteres", + "Completed when": "Completado cuando", + "Every task is checked": "Se marcan todas las tareas", + "Filename format": "Formato del nombre de archivo", + "Folder each day's note is created in. Leave blank for a dedicated subfolder named after this habit.": + "Carpeta donde se crea la nota de cada día. Déjalo en blanco para usar una subcarpeta dedicada con el nombre de este hábito.", + "Moment.js format used to name each day's note, e.g. {example}. May include / for date-based subfolders.": + "Formato de Moment.js usado para nombrar la nota de cada día, p. ej. {example}. Puede incluir / para subcarpetas basadas en fechas.", + Note: "Nota", + "Note habits": "Hábitos de notas", + "Notes folder": "Carpeta de notas", + "Open this day's note": "Abrir la nota de este día", + "Open today's note": "Abrir la nota de hoy", + "Optional template note used when a day's note is created. Expanded through the Templater plugin when it is installed, otherwise copied as plain text.": + "Nota de plantilla opcional usada al crear la nota de un día. Se expande mediante el plugin Templater cuando está instalado; si no, se copia como texto sin formato.", + Template: "Plantilla", + "Track a habit by writing in a per-day note instead of logging a value by hand. A day is complete once the note reaches a character count or every task in it is checked. Works with the Templater plugin to create each day's note from a template.": + "Sigue un hábito escribiendo en una nota diaria en lugar de registrar un valor a mano. Un día se completa cuando la nota alcanza un número de caracteres o se marcan todas sus tareas. Funciona con el plugin Templater para crear la nota de cada día a partir de una plantilla.", + Write: "Escribir", + "Write this day's note": "Escribir la nota de este día", + "Write today's note": "Escribir la nota de hoy", + "e.g. Journal": "p. ej. Diario", + "e.g. Templates/Journal.md": "p. ej. Templates/Diario.md", + + // Flexible frequency (any day) + "How many times (or, for counted and timed habits, how much in total) this needs to happen somewhere in the period.": + "Cuántas veces (o, en hábitos contados o temporizados, cuánto en total) debe ocurrir esto en algún momento del período.", + 'How often this habit is due. Weekly and monthly habits only appear on their due date; the "any day" options appear every day until their quota is met.': + 'Con qué frecuencia vence este hábito. Los hábitos semanales y mensuales solo aparecen en su día de vencimiento; las opciones "cualquier día" aparecen todos los días hasta alcanzar su cuota.', + "Monthly (any day)": "Mensual (cualquier día)", + "Times per month": "Veces al mes", + "Times per week": "Veces a la semana", + "Weekly (any day)": "Semanal (cualquier día)", + "this month": "este mes", + "this week": "esta semana", + "{completed}/{days} months": "{completed}/{days} meses", + "{completed}/{days} weeks": "{completed}/{days} semanas", + "{n}× a month · any day": "{n}× al mes · cualquier día", + "{n}× a week · any day": "{n}× a la semana · cualquier día", + + // Commands + "Insert habits heatmap": "Insertar mapa de calor de hábitos", + + // Habit metrics: heatmap tabs + Charts: "Gráficos", + Month: "Mes", + History: "Historial", + "{month} heatmap": "Mapa de calor de {month}", + "Last {n} weeks": "Últimas {n} semanas", + + // Heatmap cell states and tooltips + Upcoming: "Próximo", + "Not tracked yet": "Aún sin seguimiento", + "Not due": "No vence", + "Outside this month": "Fuera de este mes", + Complete: "Completado", + "Over limit": "Por encima del límite", + "Not logged": "Sin registrar", + + // Whole-vault heatmap block + "Add a habit to see its heatmap here.": + "Añade un hábito para ver aquí su mapa de calor.", + "No habits in the \"{group}\" group.": 'No hay hábitos en el grupo "{group}".', + "No habits due": "No había hábitos previstos", + "Perfect day": "Día perfecto", + "{completed}/{considered} habits · {pct}%": + "{completed}/{considered} hábitos · {pct}%", + "This year": "Este año", + "Past 6 months": "Últimos 6 meses", + "{year} heatmap": "Mapa de calor de {year}", + + // Note habits: checklist requirement and fail keyword + "Both are true": "Se cumplen ambas", + "Checklist requirement is met": "Se cumple el requisito de la lista de tareas", + "Checklist requirement": "Requisito de la lista de tareas", + "Require every task to be checked, or just some — useful for a list of alternatives where doing any one of them counts (e.g. \"Cardio\" / \"Weights\" / \"Rest day\").": + 'Exige marcar todas las tareas, o solo algunas — útil para una lista de alternativas en la que hacer cualquiera de ellas cuenta (p. ej. "Cardio" / "Pesas" / "Día de descanso").', + "At least this many are checked": "Se marca al menos esta cantidad", + "Tasks required": "Tareas requeridas", + "Fail keyword": "Palabra clave de fallo", + "Optional. Checking a task whose text contains this word forces the day to fail, whatever else is checked — e.g. \"Slipped\" as one of several checklist options. Leave blank to turn this off.": + 'Opcional. Marcar una tarea cuyo texto contenga esta palabra obliga a que el día falle, sea lo que sea lo demás que esté marcado — por ejemplo, "Fallé" como una más de las opciones de la lista. Déjalo en blanco para desactivarlo.', + "e.g. Slipped": "p. ej. Fallé", + "Reach a character count, meet a checklist requirement, or require both.": + "Alcanza un número de caracteres, cumple un requisito de lista de tareas, o exige ambos.", + + // Tags (cross-plugin compatibility) + Tags: "Etiquetas", + "e.g. task": "p. ej. task", + "Optional Obsidian tags for this note, separated by commas or spaces. Useful for making this habit recognisable to another plugin's own tag-based rules — for example TaskNotes' task tag.": + 'Etiquetas opcionales de Obsidian para esta nota, separadas por comas o espacios. Útil para que otro plugin reconozca este hábito mediante sus propias reglas basadas en etiquetas, por ejemplo la etiqueta "task" de TaskNotes.', + + // Advanced settings: frontmatter key remapping + Advanced: "Avanzado", + Apply: "Aplicar", + "Apply key changes": "Aplicar cambios de claves", + "Rename the frontmatter properties habit notes use. Useful for avoiding collisions with another plugin's own properties in the same note (for example TaskNotes).": + "Cambia el nombre de las propiedades de frontmatter que usan las notas de hábito. Útil para evitar colisiones con las propiedades propias de otro plugin en la misma nota (por ejemplo, TaskNotes).", + "\"{a}\" and \"{b}\" can't use the same property key (\"{value}\").": + '"{a}" y "{b}" no pueden usar la misma clave de propiedad ("{value}").', + "Property keys can't be empty.": + "Las claves de propiedad no pueden estar vacías.", + "This renames {summary} in every note in your habits folder ({count} habit(s) currently). Existing values are moved, not discarded. Continue?": + "Esto renombrará {summary} en todas las notas de tu carpeta de hábitos ({count} hábito(s) actualmente). Los valores existentes se trasladan, no se descartan. ¿Continuar?", + "Updated the frontmatter keys in {count} note(s).": + "Se actualizaron las claves de frontmatter en {count} nota(s).", + "Renaming this away from the default also changes how binary habits log a day: instead of {\"2026-08-25\": 1}, a completed day becomes a bare date, like [\"2026-08-25\"] — the shape TaskNotes uses for complete_instances. Repetition and timed habits are unaffected either way; they always need a value, never just a date.": + 'Cambiar esta clave del valor predeterminado también cambia cómo los hábitos binarios registran un día: en lugar de {"2026-08-25": 1}, un día completado se convierte en una fecha simple, como ["2026-08-25"] — la forma que usa TaskNotes para complete_instances. Los hábitos de repetición y de tiempo no se ven afectados de todos modos; siempre necesitan un valor, nunca solo una fecha.', + Identity: "Identidad", + Legacy: "Heredado", + Lifecycle: "Ciclo de vida", + Presentation: "Presentación", + "Note habit": "Hábito de nota", + "Habit type key": "Clave del tipo de hábito", + "Completion records key": "Clave de los registros", + "Frequency key": "Clave de la frecuencia", + "Weekday key": "Clave del día de la semana", + "Month day key": "Clave del día del mes", + "Interval days key": "Clave de los días de intervalo", + "Planned time key": "Clave de la hora prevista", + "Goal direction key": "Clave de la dirección de la meta", + "Target key": "Clave de la meta", + "Unit key": "Clave de la unidad", + "Step size key": "Clave del tamaño del paso", + "Weekly target key": "Clave de la meta semanal", + "Monthly target key": "Clave de la meta mensual", + "Weekly perfect key": "Clave de semana perfecta", + "Monthly perfect key": "Clave de mes perfecto", + "Start date key": "Clave de la fecha de inicio", + "Pauses key": "Clave de las pausas", + "Stopped key": "Clave de detenido", + "Stop date key": "Clave de la fecha de detención", + "Icon key": "Clave del icono", + "Color key": "Clave del color", + "Group key": "Clave del grupo", + "Use group color key": "Clave de «usar color de grupo»", + "Note folder key": "Clave de la carpeta de notas", + "Note filename format key": "Clave del formato de nombre de archivo", + "Template path key": "Clave de la ruta de la plantilla", + "Note completion mode key": "Clave del modo de finalización", + "Note checklist requirement key": "Clave del requisito de la lista de tareas", + "Note checklist minimum key": "Clave del mínimo de la lista de tareas", + "Note fail keyword key": "Clave de la palabra clave de fallo", + "Legacy comments key": "Clave de los comentarios heredados", + + // PDF export (read via docT() in export-modal.ts, which falls back to English for zh — jsPDF's built-in fonts can't render CJK) + "Completion trend": "Tendencia de cumplimiento", + "(paused)": "(pausado)", + "{rate}% · {total} · streak {current} (best {best})": + "{rate}% · {total} · racha {current} (mejor {best})", + "Goal: {completed}/{goal} days met": + "Meta: {completed}/{goal} días logrados", + "{range} · exported {date}": "{range} · exportado el {date}", + "+{n} more": "+{n} más", + + // Back-dating a missed day + Back: "Atrás", + + // Rescheduling missed habits (experimental) + "1 missed habit": "1 hábito omitido", + "Add a notification button to the dashboard and sidebar panel when a habit's been missed, opening a review of missed days you can move onto a different one (never a day that habit is already due, so nothing doubles up).": + "Añade un botón de notificación al panel principal y a la barra lateral cuando se ha omitido un hábito, que abre una revisión de los días omitidos para moverlos a otro día (nunca a un día en el que ese hábito ya venza, para que nada se duplique).", + "Missed habits": "Hábitos omitidos", + "Move this missed day onto a different one": "Mover este día omitido a otro", + "Move to": "Mover a", + "Nothing missed right now.": "No hay nada omitido por ahora.", + "Pick a habit to move it onto a different day.": + "Elige un hábito para moverlo a otro día.", + Reschedule: "Reprogramar", + "Reschedule missed habits": "Reprogramar hábitos omitidos", + "Rescheduled \"{name}\" to {date}.": '"{name}" se reprogramó para {date}.', + "Rescheduled from {date}": "Reprogramado desde {date}", + "Reschedules key": "Clave de reprogramaciones", + "Failed days key": "Clave de días fallados", + "Skipped days key": "Clave de días omitidos", + "Rescheduling \"{name}\" — missed {date}.": + 'Reprogramando "{name}" — se omitió el {date}.', + "That day no longer works — pick another.": + "Ese día ya no funciona — elige otro.", + "That day won't work — it's either already due for this habit or already claimed by another reschedule.": + "Ese día no sirve — o ya vence este hábito ese día, o ya lo ha reclamado otra reprogramación.", + "{count} missed habits": "{count} hábitos omitidos", +}; diff --git a/src/integrations/habits/i18n/fr.ts b/src/integrations/habits/i18n/fr.ts new file mode 100644 index 000000000..dc6e2ea86 --- /dev/null +++ b/src/integrations/habits/i18n/fr.ts @@ -0,0 +1,656 @@ +/** French translations, keyed by the English source string. */ +export const fr: Record = { + // Commands and ribbon + "Create habit": "Créer une habitude", + "Insert dashboard": "Insérer le tableau de bord", + "Insert habit metrics": "Insérer les métriques d'habitude", + "Insert habits table": "Insérer le tableau des habitudes", + "Open panel": "Ouvrir le panneau", + "Open habits panel": "Ouvrir le panneau des habitudes", + Habits: "Habitudes", + + // Settings + "Habits folder": "Dossier des habitudes", + "Folder where each habit is stored as its own note. It is created automatically if it does not exist.": + "Dossier où chaque habitude est enregistrée dans sa propre note. Il est créé automatiquement s'il n'existe pas.", + "Follow daily note date": "Suivre la date de la note quotidienne", + "When a dashboard is embedded in a daily note (a note whose name contains a date like 2026-07-01), open it on that note's date instead of today.": + "Lorsqu'un tableau de bord est intégré dans une note quotidienne (une note dont le nom contient une date comme 2026-07-01), il s'ouvre à la date de cette note plutôt qu'à aujourd'hui.", + "Daily note date format": "Format de date de la note quotidienne", + "Moment.js format used to read the date from a daily note's name, such as YYYY-MM-DD or YYYYMMDD.": + "Format Moment.js utilisé pour lire la date dans le nom d'une note quotidienne, par exemple YYYY-MM-DD ou YYYYMMDD.", + + // Sorting + "Sort habits by": "Trier les habitudes par", + "The base order of habit cards in the dashboard and side panel.": + "L'ordre de base des cartes d'habitudes dans le tableau de bord et le panneau latéral.", + "Name (A–Z)": "Nom (A–Z)", + Color: "Couleur", + "Last logged": "Dernier enregistrement", + "Planned time": "Heure prévue", + Manual: "Manuel", + "Manual order": "Ordre manuel", + "Drag the cards into the order you want. New habits join the end of the list.": + "Faites glisser les cartes dans l'ordre souhaité. Les nouvelles habitudes rejoignent la fin de la liste.", + "Move completed cards to the end": + "Déplacer les cartes terminées à la fin", + "Completed habits drift to the end of the queue and paused ones park behind them. Turn this off to keep every card in its sorted position.": + "Les habitudes terminées glissent en fin de file et celles en pause se rangent derrière. Désactivez pour garder chaque carte à sa position triée.", + Group: "Groupe", + Ungrouped: "Sans groupe", + "Optional group used to build dashboard sections — for example an area of responsibility.": + "Groupe facultatif pour créer des sections dans le tableau de bord — par exemple un domaine de responsabilité.", + "e.g. Health": "p. ex. Santé", + "Group color": "Couleur du groupe", + "Optional color shared by every habit in this group.": + "Couleur facultative partagée par toutes les habitudes de ce groupe.", + "Group icon": "Icône du groupe", + "Shown in the group lip on cards and in section headers.": + "Affichée dans le bandeau de groupe des cartes et dans les en-têtes de section.", + "Use group color for this card": + "Utiliser la couleur du groupe pour cette carte", + "Show this card in the group color instead of its own.": + "Affiche cette carte dans la couleur du groupe plutôt que la sienne.", + General: "Général", + Sorting: "Tri", + Groups: "Groupes", + "How to move through your habit cards: a paged carousel with arrows, a grid that wraps onto new rows, or a fixed-height grid that scrolls vertically. The stats page follows the same choice.": + "Comment parcourir vos cartes d'habitudes : un carrousel paginé avec flèches, une grille qui passe à la ligne, ou une grille à hauteur fixe qui défile verticalement. La page de statistiques suit le même choix.", + "Enable groups": "Activer les groupes", + "Show habits in sections by their group, with a group lip on each card.": + "Affiche les habitudes en sections selon leur groupe, avec un bandeau de groupe sur chaque carte.", + "Group order": "Ordre des groupes", + "Drag the groups into the order you want. Sections follow the same order.": + "Faites glisser les groupes dans l'ordre souhaité. Les sections suivent le même ordre.", + "Completion animations": "Animations de complétion", + "Play the check swoosh, card departure, and perfect-day confetti when habits are completed. Turn off for instant, quiet updates.": + "Joue le swoosh de la coche, le départ de la carte et les confettis du jour parfait quand une habitude est complétée. Désactivez pour des mises à jour instantanées et discrètes.", + "Reminders": "Rappels", + "Write reminders for due habits": "Écrire des rappels pour les habitudes dues", + "Each day, write one reminder checklist line per planned time of every habit due that day, in the format the Reminder plugin picks up. The lines live in a marked block and refresh as you log habits.": + "Chaque jour, écrit une ligne de rappel par heure prévue pour chaque habitude due ce jour-là, au format reconnu par le plugin Reminder. Les lignes vivent dans un bloc balisé et se mettent à jour au fil des enregistrements.", + "Where to write reminders": "Où écrire les rappels", + "The daily note follows the Daily notes core plugin's folder and date format; the block is added once the note exists. A fixed note is created automatically.": + "La note quotidienne suit le dossier et le format de date du plugin de base « Notes quotidiennes » ; le bloc est ajouté dès que la note existe. Une note fixe est créée automatiquement.", + "Today's daily note": "Note quotidienne du jour", + "A fixed note": "Une note fixe", + "Reminder note path": "Chemin de la note de rappels", + "Vault path of the note that holds the reminder block.": + "Chemin dans le coffre de la note qui contient le bloc de rappels.", + "Manage groups": "Gérer les groupes", + "See every habit by group and drag cards between groups.": + "Voyez chaque habitude par groupe et faites glisser les cartes entre les groupes.", + Open: "Ouvrir", + "New group": "Nouveau groupe", + Add: "Ajouter", + "Drag habits between groups to reassign them, or within a group to reorder them.": + "Faites glisser les habitudes entre les groupes pour les réaffecter, ou au sein d'un groupe pour les réordonner.", + "No habits": "Aucune habitude", + "Edit group style": "Modifier le style du groupe", + "Delete group": "Supprimer le groupe", + 'Delete "{name}"? Its habits are kept and become ungrouped.': + "Supprimer « {name} » ? Ses habitudes sont conservées et deviennent sans groupe.", + Delete: "Supprimer", + "Dashboard layout": "Disposition du tableau de bord", + Carousel: "Carrousel", + Grid: "Grille", + "Vertical scroll": "Défilement vertical", + "Cards per view": "Cartes par vue", + "How many habit cards fit side by side on wider screens.": + "Combien de cartes d'habitudes tiennent côte à côte sur les grands écrans.", + "Cards per view on mobile": "Cartes par vue sur mobile", + "How many habit cards fit side by side on phone-sized screens.": + "Combien de cartes d'habitudes tiennent côte à côte sur les écrans de téléphone.", + + // Confirm dialog defaults + Cancel: "Annuler", + Confirm: "Confirmer", + + // Store notices + 'Could not find the note for "{name}".': + 'Impossible de trouver la note de « {name} ».', + "Please enter a valid habit name.": + "Veuillez saisir un nom d'habitude valide.", + 'A habit called "{name}" already exists.': + 'Une habitude nommée « {name} » existe déjà.', + 'Created habit "{name}".': 'Habitude « {name} » créée.', + 'Updated "{name}".': '« {name} » mise à jour.', + 'Paused "{name}".': '« {name} » mise en pause.', + 'Resumed "{name}".': '« {name} » reprise.', + 'Stopped tracking "{name}". Its history is kept in the note.': + 'Suivi de « {name} » arrêté. Son historique est conservé dans la note.', + 'Resumed tracking "{name}".': 'Suivi de « {name} » repris.', + 'Removed "{name}".': '« {name} » supprimée.', + "Habit added to the dashboard.": "Habitude ajoutée au tableau de bord.", + + // Dashboard + "Back to habits": "Retour aux habitudes", + "View stats": "Voir les statistiques", + "Export stats": "Exporter les statistiques", + Weekly: "Hebdomadaire", + Monthly: "Mensuel", + "Previous day": "Jour précédent", + "Next day": "Jour suivant", + "Choose a date": "Choisir une date", + "Add habit": "Ajouter une habitude", + "No habits yet. Create your first habit to get started.": + "Aucune habitude pour l'instant. Créez votre première habitude pour commencer.", + Previous: "Précédent", + Next: "Suivant", + "Go to position {n}": "Aller à la position {n}", + "Right-click or long-press for more options": + "Clic droit ou appui long pour plus d'options", + "Open habit note": "Ouvrir la note de l'habitude", + "Open the note for {name}": "Ouvrir la note de {name}", + Paused: "En pause", + Stopped: "Arrêté", + "Failed": "Échoué", + "Skipped": "Passé", + "Snoozed": "En sommeil", + "Snoozed until {time}": "En sommeil jusqu'à {time}", + "Undo fail": "Annuler l'échec", + "Undo skip": "Annuler le passage", + "End snooze": "Réveiller", + "Fail for today": "Échouer pour aujourd'hui", + "Fail this day": "Échouer ce jour", + "Marked \"{name}\" as failed.": "« {name} » marqué comme échoué.", + "Skip for today": "Passer pour aujourd'hui", + "Skip this day": "Passer ce jour", + "Skipped \"{name}\".": "« {name} » passé.", + "Snooze…": "Mettre en sommeil…", + "Snooze \"{name}\"": "Mettre « {name} » en sommeil", + "It leaves today's lists and comes back on its own. Snoozing never counts for or against the habit.": "L'habitude quitte les listes du jour et revient d'elle-même. La mise en sommeil ne compte jamais pour ou contre l'habitude.", + "Snooze for": "Mettre en sommeil pendant", + "30 minutes": "30 minutes", + "1 hour": "1 heure", + "3 hours": "3 heures", + "Snooze until": "En sommeil jusqu'à", + "Snooze": "Mettre en sommeil", + "Pick a time later today.": "Choisissez une heure plus tard aujourd'hui.", + "Snoozed \"{name}\" until {time}.": "« {name} » en sommeil jusqu'à {time}.", + "1 hidden for today": "1 masquée aujourd'hui", + "{count} hidden for today": "{count} masquées aujourd'hui", + "1 hidden for this day": "1 masquée ce jour", + "{count} hidden for this day": "{count} masquées ce jour", + "Undo": "Annuler", + "Click to undo": "Cliquez pour annuler", + "Nothing left on this day's list.": "Plus rien dans la liste de ce jour.", + "Nothing left on today's list.": "Plus rien dans la liste du jour.", + "At least: reach a target for habits you are building, like drinking 1.5 litres of water. At most: stay within a limit for habits you are cutting down, like no more than 2 coffees.": "Au moins : atteignez un objectif pour les habitudes que vous construisez, comme boire 1,5 litre d'eau. Au plus : restez sous une limite pour les habitudes que vous réduisez, comme pas plus de 2 cafés.", + "At least (reach a target)": "Au moins (atteindre un objectif)", + "At most (stay within a limit)": "Au plus (rester sous une limite)", + "Step size": "Pas", + "How much each + and − press adds or removes. Use a decimal such as 0.25 for amounts like litres.": "Quantité ajoutée ou retirée à chaque appui sur + et −. Utilisez une décimale comme 0.25 pour des quantités comme les litres.", + "Decrease by {n}": "Diminuer de {n}", + "4 weeks": "4 semaines", + "12 weeks": "12 semaines", + "6 months": "6 mois", + "1 year": "1 an", + "Completion rate": "Taux de réussite", + "Monthly completion rate": "Taux de réussite mensuel", + "Daily activity": "Activité quotidienne", + "Week of {date}": "Semaine du {date}", + "Since {date} · right-click to resume": + "Depuis le {date} · clic droit pour reprendre", + "Paused on this day": "En pause ce jour-là", + "Mark as done": "Marquer comme fait", + "Mark as not done": "Marquer comme non fait", + Done: "Fait", + "Not done": "À faire", + "Edit value": "Modifier la valeur", + Value: "Valeur", + "Decrease by 1": "Diminuer de 1", + "Increase by 1": "Augmenter de 1", + "Increase by {n}": "Augmenter de {n}", + "Edit habit": "Modifier l'habitude", + "Pause habit": "Mettre en pause", + "Resume habit": "Reprendre l'habitude", + "Stop tracking": "Arrêter le suivi", + "Remove habit": "Supprimer l'habitude", + 'Stop tracking "{name}"? It leaves the dashboard and stats, but its note and full history are kept. You can resume tracking any time from the note\'s metrics view.': + 'Arrêter le suivi de « {name} » ? Elle quitte le tableau de bord et les statistiques, mais sa note et tout son historique sont conservés. Vous pouvez reprendre le suivi à tout moment depuis la vue des métriques de la note.', + 'Remove "{name}"? Its note will be moved to the trash.': + 'Supprimer « {name} » ? Sa note sera déplacée vers la corbeille.', + Remove: "Supprimer", + "Perfect!": "Parfait !", + Today: "Aujourd'hui", + Yesterday: "Hier", + Tomorrow: "Demain", + "Last 7 days": "7 derniers jours", + "Last 30 days": "30 derniers jours", + "This week": "Cette semaine", + "This month": "Ce mois-ci", + + // Sidebar panel + "Habits completed today": "Habitudes accomplies aujourd'hui", + "No habits yet.": "Aucune habitude pour l'instant.", + "Click to type a value": "Cliquez pour saisir une valeur", + "Open note": "Ouvrir la note", + + // Stats view + "No habits to show stats for yet.": + "Aucune habitude à afficher dans les statistiques pour l'instant.", + Completion: "Réussite", + "Best streak": "Meilleure série", + "Perfect days": "Jours parfaits", + Completions: "Accomplissements", + "Goals met": "Objectifs atteints", + "{completed}/{days} days": "{completed}/{days} jours", + "{total} total": "{total} au total", + best: "record", + "perfect week": "semaine parfaite", + "perfect month": "mois parfait", + "weekly goal": "objectif hebdomadaire", + "monthly goal": "objectif mensuel", + "{progress}/{goal} days · {label} · {pct}%": + "{progress}/{goal} jours · {label} · {pct} %", + + // Habit metrics block + 'Place this block inside a habit note, or point it at one with "habit: ".': + 'Placez ce bloc dans une note d\'habitude, ou désignez-en une avec « habit: ».', + 'No habit called "{name}" was found.': + 'Aucune habitude nommée « {name} » n\'a été trouvée.', + "No longer tracked since {date}. All history is kept.": + "Suivi arrêté depuis le {date}. Tout l'historique est conservé.", + "No longer tracked. All history is kept.": + "Suivi arrêté. Tout l'historique est conservé.", + "Resume tracking": "Reprendre le suivi", + "Paused since {date}. Paused days don't count against streaks or stats.": + "En pause depuis le {date}. Les jours en pause ne comptent ni pour les séries ni pour les statistiques.", + "Paused. Paused days don't count against streaks or stats.": + "En pause. Les jours en pause ne comptent ni pour les séries ni pour les statistiques.", + "Current streak": "Série actuelle", + "Days completed": "Jours accomplis", + "30-day rate": "Taux sur 30 jours", + "Weekly completion rate": "Taux de réussite hebdomadaire", + Logged: "Enregistré", + Target: "Objectif", + + // Export modal + Title: "Titre", + "Habits report": "Rapport d'habitudes", + "Date range": "Plage de dates", + "Custom range": "Plage personnalisée", + From: "Du", + To: "Au", + "Up to {n} days.": "Jusqu'à {n} jours.", + Content: "Contenu", + "Summary tiles": "Tuiles de résumé", + "Completion trend chart": "Graphique de tendance de réussite", + "Daily grids": "Grilles quotidiennes", + "Goal progress": "Progression des objectifs", + Layout: "Mise en page", + Orientation: "Orientation", + Portrait: "Portrait", + Landscape: "Paysage", + Density: "Densité", + Comfortable: "Confortable", + Compact: "Compact", + Monochrome: "Monochrome", + "Ink-friendly greys instead of accent colours.": + "Des gris économes en encre plutôt que des couleurs d'accent.", + "Export PDF": "Exporter le PDF", + "No habits to export yet.": "Aucune habitude à exporter pour l'instant.", + 'Exported to "{path}" in your vault.': + 'Exporté vers « {path} » dans votre coffre.', + + // Habit modal + "New habit": "Nouvelle habitude", + Name: "Nom", + Type: "Type", + "Binary is done or not done. Repetition counts towards a target. Timed tracks minutes.": + "Binaire : fait ou non fait. Répétition : compte vers un objectif. Chronométré : enregistre des minutes.", + Binary: "Binaire", + Repetition: "Répétition", + Timed: "Chronométré", + "Daily target (minutes)": "Objectif quotidien (minutes)", + "Daily target": "Objectif quotidien", + Unit: "Unité", + "Optional label shown next to the count.": + "Étiquette facultative affichée à côté du compteur.", + Icon: "Icône", + "Choose a Lucide icon or an emoji to represent this habit.": + "Choisissez une icône Lucide ou un emoji pour représenter cette habitude.", + Emoji: "Emoji", + "Choose an emoji": "Choisir un emoji", + "Clear icon": "Effacer l'icône", + "Choose icon": "Choisir une icône", + "Save changes": "Enregistrer les modifications", + "Targets (optional)": "Objectifs (facultatif)", + "Set an optional weekly or monthly goal for how many days you complete this habit. For example, hitting your daily goal on all 7 days is a weekly target of 7. Turn on a perfect toggle to aim for every day of the period automatically, whatever its length.": + "Définissez un objectif hebdomadaire ou mensuel facultatif indiquant combien de jours vous accomplissez cette habitude. Par exemple, atteindre votre objectif quotidien les 7 jours équivaut à un objectif hebdomadaire de 7. Activez une option « parfait » pour viser automatiquement chaque jour de la période, quelle que soit sa durée.", + "Perfect week": "Semaine parfaite", + "Aim to complete this habit every day of the week.": + "Visez à accomplir cette habitude chaque jour de la semaine.", + "Weekly target": "Objectif hebdomadaire", + "Optional. Days to complete per week (max 7).": + "Facultatif. Jours à accomplir par semaine (max. 7).", + None: "Aucun", + "Perfect month": "Mois parfait", + "Aim to complete this habit every day of the month.": + "Visez à accomplir cette habitude chaque jour du mois.", + "Monthly target": "Objectif mensuel", + "Optional. Days to complete per month.": + "Facultatif. Jours à accomplir par mois.", + Colour: "Couleur", + "Pick a colour from your theme, or choose a custom one.": + "Choisissez une couleur de votre thème ou une couleur personnalisée.", + "Your habit": "Votre habitude", + + // Icon and colour pickers + "Search icons…": "Rechercher des icônes…", + "Search emojis…": "Rechercher des émojis…", + + // Comments + "Comments on cards": "Commentaires sur les cartes", + "Show a comment flap on dashboard cards for jotting a note about any day.": + "Affiche un volet de commentaire sur les cartes du tableau de bord pour annoter n'importe quel jour.", + "Add comment": "Ajouter un commentaire", + "Flip back": "Retourner la carte", + "Edit comment": "Modifier le commentaire", + "Move day comments into note bodies": + "Déplacer les commentaires quotidiens dans le corps des notes", + "No comments left to move.": + "Plus aucun commentaire à déplacer.", + "Moved comments in 1 note.": + "Commentaires déplacés dans 1 note.", + "Moved comments in {n} notes.": + "Commentaires déplacés dans {n} notes.", + "Add a comment for this day…": "Ajoutez un commentaire pour ce jour…", + Comments: "Commentaires", + + // Limit habits (experimental) + Experimental: "Expérimental", + "These features are still being tested and may change before they become permanent. Turning one off only hides it from menus — anything you created with it keeps working.": + "Ces fonctionnalités sont encore en cours de test et peuvent changer avant de devenir permanentes. Les désactiver ne fait que les masquer des menus — tout ce que vous avez créé avec continue de fonctionner.", + "Break bad habits": "Rompre avec les mauvaises habitudes", + "Track habits you want to reduce or avoid by staying under a daily limit — for example at most 2 hours of gaming, or no smoking at all.": + "Suivez les habitudes que vous voulez réduire ou éviter en restant sous une limite quotidienne — par exemple au plus 2 heures de jeu vidéo, ou ne pas fumer du tout.", + Goal: "Objectif", + "Reach a target for habits you are building. Stay under a limit for habits you are cutting down or giving up.": + "Atteignez un objectif pour les habitudes que vous construisez. Restez sous une limite pour les habitudes que vous réduisez ou abandonnez.", + "Reach a target": "Atteindre un objectif", + "Stay under a limit": "Rester sous une limite", + "Binary means avoiding it entirely. Repetition counts against a daily limit. Timed tracks minutes against a daily limit.": + "Binaire signifie l'éviter complètement. Répétition compte par rapport à une limite quotidienne. Chronométré mesure des minutes par rapport à une limite quotidienne.", + "Daily limit": "Limite quotidienne", + "Daily limit (minutes)": "Limite quotidienne (minutes)", + "0 means none at all.": "0 signifie pas du tout.", + "Set an optional weekly or monthly goal for how many days you stay within your limit. Turn on a perfect toggle to aim for every day of the period automatically, whatever its length.": + "Définissez un objectif hebdomadaire ou mensuel facultatif pour le nombre de jours où vous restez dans votre limite. Activez une bascule parfaite pour viser automatiquement chaque jour de la période, quelle que soit sa durée.", + Clean: "Sans écart", + Slipped: "Écart", + "Mark as clean": "Marquer comme sans écart", + "Mark as slipped": "Marquer comme écart", + "Days within limit": "Jours dans la limite", + Limit: "Limite", + + // Frequencies and per-note metrics + Frequency: "Fréquence", + Daily: "Quotidien", + "Days of week": "Jours de la semaine", + Habit: "Habitude", + Schedule: "Programme", + "Time of day": "Heure de la journée", + "Optional times this habit is planned for — once or several times a day. Shown on the habit's card.": + "Heures facultatives prévues pour cette habitude — une ou plusieurs fois par jour. Affichées sur la carte de l'habitude.", + "Add time": "Ajouter une heure", + "Remove time": "Supprimer l'heure", + "Every N days": "Tous les N jours", + "Repeat every": "Répéter tous les", + "Day of month": "Jour du mois", + "The weekdays this habit is due on. Pick as many as you need.": + "Les jours de la semaine où cette habitude est due. Choisissez-en autant que nécessaire.", + "Number of days between due dates, counted from the habit's start date. Use 2 for an alternate-day schedule.": + "Nombre de jours entre les échéances, compté à partir de la date de début de l'habitude. Utilisez 2 pour un rythme d'un jour sur deux.", + "The day of the month this habit is due. In shorter months it falls due on the last day, so 31 always lands on the final day of the month.": + "Le jour du mois où cette habitude est due. Les mois plus courts la placent le dernier jour, donc 31 tombe toujours en fin de mois.", + "Every {day}": "Chaque {day}", + "Monthly · day {day}": "Mensuel · jour {day}", + "Every other day": "Un jour sur deux", + "Every {n} days": "Tous les {n} jours", + "No habits are due on this day.": + "Aucune habitude n'est due ce jour-là.", + "Nothing due today.": "Rien à faire aujourd'hui.", + "Weekly activity": "Activité hebdomadaire", + "Monthly activity": "Activité mensuelle", + "Activity on due days": "Activité aux jours d'échéance", + "Completion rate over {n} due days": + "Taux de réussite sur {n} jours d'échéance", + "Weeks completed": "Semaines accomplies", + "Months completed": "Mois accomplis", + "Recent rate": "Taux récent", + "{n}-week completion rate": "Taux de réussite sur {n} semaines", + "{n}-month completion rate": "Taux de réussite sur {n} mois", + + // AI summaries + "AI summaries": "Résumés par IA", + "AI summary": "Résumé par IA", + "Show an AI-generated summary with feedback and advice on the stats page tabs. Uses an OpenAI-compatible service you configure below; your habit stats are sent to it only when you press the generate button.": + "Affiche un résumé généré par IA avec retours et conseils dans les onglets de la page de statistiques. Utilise un service compatible OpenAI que vous configurez ci-dessous ; vos statistiques d'habitudes ne lui sont envoyées que lorsque vous appuyez sur le bouton de génération.", + "AI base URL": "URL de base de l'IA", + "Base URL of an OpenAI-compatible API. Works with OpenAI, OpenRouter, or local servers like Ollama (http://localhost:11434/v1).": + "URL de base d'une API compatible OpenAI. Fonctionne avec OpenAI, OpenRouter ou des serveurs locaux comme Ollama (http://localhost:11434/v1).", + "AI API key": "Clé d'API IA", + "Stored locally in this vault's plugin data. Leave blank for local servers that need no key.": + "Stockée localement dans les données du plugin de ce coffre. Laissez vide pour les serveurs locaux sans clé.", + "AI model": "Modèle d'IA", + "Model name the service should use.": + "Nom du modèle que le service doit utiliser.", + "Generate summary": "Générer le résumé", + Regenerate: "Régénérer", + "Get feedback and advice on your habits for this period. Your stats are sent to the AI service you configured only when you press the button.": + "Recevez des retours et des conseils sur vos habitudes pour cette période. Vos statistiques ne sont envoyées au service d'IA configuré que lorsque vous appuyez sur le bouton.", + "Thinking…": "Réflexion…", + "Could not generate a summary: {message}": + "Impossible de générer le résumé : {message}", + "Adds an AI-generated overview with feedback and advice. Your habit stats are sent to your configured AI service.": + "Ajoute un aperçu généré par IA avec retours et conseils. Vos statistiques d'habitudes sont envoyées au service d'IA configuré.", + "Generating AI summary…": "Génération du résumé par IA…", + "The AI summary will be generated when you export.": + "Le résumé par IA sera généré lors de l'export.", + + // Custom stats range + Custom: "Personnalisé", + "Start date": "Date de début", + "End date": "Date de fin", + + // Heatmap start markers + "not tracked yet": "pas encore suivi", + "started tracking on {date}": "suivi commencé le {date}", + + // Stats carousel + "Stats rows per page": "Lignes de statistiques par page", + "How many habits each stats page shows.": + "Combien d'habitudes chaque page de statistiques affiche.", + // Note habits + '"{name}" uses Templater syntax, but the Templater plugin is not installed — the template was copied as plain text.': + "« {name} » utilise la syntaxe Templater, mais le plugin Templater n'est pas installé — le modèle a été copié en texte brut.", + "Binary is done or not done. Repetition counts towards a target. Timed tracks minutes. Note is completed by writing in a per-day note.": + "Binaire : fait ou non fait. Répétition : compte vers un objectif. Chronométré : enregistre des minutes. Note : se complète en écrivant dans une note quotidienne.", + "Character count is reached": "Un nombre de caractères est atteint", + "Character goal": "Objectif de caractères", + "Completed when": "Complété quand", + "Every task is checked": "Toutes les tâches sont cochées", + "Filename format": "Format du nom de fichier", + "Folder each day's note is created in. Leave blank for a dedicated subfolder named after this habit.": + "Dossier où la note de chaque jour est créée. Laissez vide pour un sous-dossier dédié portant le nom de cette habitude.", + "Moment.js format used to name each day's note, e.g. {example}. May include / for date-based subfolders.": + "Format Moment.js utilisé pour nommer la note de chaque jour, p. ex. {example}. Peut inclure / pour des sous-dossiers basés sur la date.", + Note: "Note", + "Note habits": "Habitudes en note", + "Notes folder": "Dossier des notes", + "Open this day's note": "Ouvrir la note de ce jour", + "Open today's note": "Ouvrir la note d'aujourd'hui", + "Optional template note used when a day's note is created. Expanded through the Templater plugin when it is installed, otherwise copied as plain text.": + "Note modèle optionnelle utilisée lors de la création de la note d'un jour. Développée via le plugin Templater lorsqu'il est installé, sinon copiée en texte brut.", + Template: "Modèle", + "Track a habit by writing in a per-day note instead of logging a value by hand. A day is complete once the note reaches a character count or every task in it is checked. Works with the Templater plugin to create each day's note from a template.": + "Suivez une habitude en écrivant dans une note quotidienne plutôt qu'en enregistrant une valeur à la main. Un jour est complet une fois que la note atteint un nombre de caractères ou que toutes ses tâches sont cochées. Fonctionne avec le plugin Templater pour créer la note de chaque jour à partir d'un modèle.", + Write: "Écrire", + "Write this day's note": "Écrire la note de ce jour", + "Write today's note": "Écrire la note d'aujourd'hui", + "e.g. Journal": "p. ex. Journal", + "e.g. Templates/Journal.md": "p. ex. Templates/Journal.md", + + // Flexible frequency (any day) + "How many times (or, for counted and timed habits, how much in total) this needs to happen somewhere in the period.": + "Combien de fois (ou, pour les habitudes comptées ou chronométrées, quelle quantité au total) cela doit se produire dans la période.", + 'How often this habit is due. Weekly and monthly habits only appear on their due date; the "any day" options appear every day until their quota is met.': + "La fréquence à laquelle cette habitude est due. Les habitudes hebdomadaires et mensuelles n'apparaissent qu'à leur date d'échéance ; les options « n'importe quel jour » apparaissent chaque jour jusqu'à ce que le quota soit atteint.", + "Monthly (any day)": "Mensuel (n'importe quel jour)", + "Times per month": "Fois par mois", + "Times per week": "Fois par semaine", + "Weekly (any day)": "Hebdomadaire (n'importe quel jour)", + "this month": "ce mois-ci", + "this week": "cette semaine", + "{completed}/{days} months": "{completed}/{days} mois", + "{completed}/{days} weeks": "{completed}/{days} semaines", + "{n}× a month · any day": "{n}× par mois · n'importe quel jour", + "{n}× a week · any day": "{n}× par semaine · n'importe quel jour", + + // Commands + "Insert habits heatmap": "Insérer la carte de chaleur des habitudes", + + // Habit metrics: heatmap tabs + Charts: "Graphiques", + Month: "Mois", + History: "Historique", + "{month} heatmap": "Carte de chaleur de {month}", + "Last {n} weeks": "{n} dernières semaines", + + // Heatmap cell states and tooltips + Upcoming: "À venir", + "Not tracked yet": "Pas encore suivi", + "Not due": "Non prévu", + "Outside this month": "Hors de ce mois", + Complete: "Terminé", + "Over limit": "Dépassement de limite", + "Not logged": "Non enregistré", + + // Whole-vault heatmap block + "Add a habit to see its heatmap here.": + "Ajoutez une habitude pour voir sa carte de chaleur ici.", + "No habits in the \"{group}\" group.": + "Aucune habitude dans le groupe « {group} ».", + "No habits due": "Aucune habitude prévue", + "Perfect day": "Journée parfaite", + "{completed}/{considered} habits · {pct}%": + "{completed}/{considered} habitudes · {pct} %", + "This year": "Cette année", + "Past 6 months": "6 derniers mois", + "{year} heatmap": "Carte de chaleur de {year}", + + // Note habits: checklist requirement and fail keyword + "Both are true": "Les deux sont vraies", + "Checklist requirement is met": "L'exigence de la liste de tâches est remplie", + "Checklist requirement": "Exigence de la liste de tâches", + "Require every task to be checked, or just some — useful for a list of alternatives where doing any one of them counts (e.g. \"Cardio\" / \"Weights\" / \"Rest day\").": + "Exigez que toutes les tâches soient cochées, ou seulement certaines — utile pour une liste d'alternatives où faire l'une d'elles suffit (par ex. « Cardio » / « Musculation » / « Jour de repos »).", + "At least this many are checked": "Au moins ce nombre est coché", + "Tasks required": "Tâches requises", + "Fail keyword": "Mot-clé d'échec", + "Optional. Checking a task whose text contains this word forces the day to fail, whatever else is checked — e.g. \"Slipped\" as one of several checklist options. Leave blank to turn this off.": + "Facultatif. Cocher une tâche dont le texte contient ce mot force la journée à échouer, quoi que vous ayez coché par ailleurs — par exemple « Raté » comme l'une des options de la liste. Laissez vide pour désactiver.", + "e.g. Slipped": "p. ex. Raté", + "Reach a character count, meet a checklist requirement, or require both.": + "Atteignez un nombre de caractères, remplissez une exigence de liste de tâches, ou exigez les deux.", + + // Tags (cross-plugin compatibility) + Tags: "Étiquettes", + "e.g. task": "p. ex. task", + "Optional Obsidian tags for this note, separated by commas or spaces. Useful for making this habit recognisable to another plugin's own tag-based rules — for example TaskNotes' task tag.": + "Tags Obsidian optionnels pour cette note, séparés par des virgules ou des espaces. Utile pour rendre cette habitude reconnaissable par les règles basées sur les tags d'un autre plugin — par exemple le tag « task » de TaskNotes.", + + // Advanced settings: frontmatter key remapping + Advanced: "Avancé", + Apply: "Appliquer", + "Apply key changes": "Appliquer les changements de clés", + "Rename the frontmatter properties habit notes use. Useful for avoiding collisions with another plugin's own properties in the same note (for example TaskNotes).": + "Renommez les propriétés de frontmatter utilisées par les notes d'habitude. Utile pour éviter les collisions avec les propriétés d'un autre plugin dans la même note (par exemple TaskNotes).", + "\"{a}\" and \"{b}\" can't use the same property key (\"{value}\").": + "« {a} » et « {b} » ne peuvent pas utiliser la même clé de propriété (« {value} »).", + "Property keys can't be empty.": + "Les clés de propriété ne peuvent pas être vides.", + "This renames {summary} in every note in your habits folder ({count} habit(s) currently). Existing values are moved, not discarded. Continue?": + "Cette opération renomme {summary} dans toutes les notes de votre dossier d'habitudes ({count} habitude(s) actuellement). Les valeurs existantes sont déplacées, pas supprimées. Continuer ?", + "Updated the frontmatter keys in {count} note(s).": + "Clés de frontmatter mises à jour dans {count} note(s).", + "Renaming this away from the default also changes how binary habits log a day: instead of {\"2026-08-25\": 1}, a completed day becomes a bare date, like [\"2026-08-25\"] — the shape TaskNotes uses for complete_instances. Repetition and timed habits are unaffected either way; they always need a value, never just a date.": + "Renommer cette clé par rapport à sa valeur par défaut change aussi la façon dont les habitudes binaires enregistrent un jour : au lieu de {\"2026-08-25\": 1}, un jour terminé devient une simple date, comme [\"2026-08-25\"] — le format que TaskNotes utilise pour complete_instances. Les habitudes à répétitions et chronométrées ne sont pas concernées dans tous les cas ; elles ont toujours besoin d'une valeur, jamais d'une simple date.", + Identity: "Identité", + Legacy: "Hérité", + Lifecycle: "Cycle de vie", + Presentation: "Présentation", + "Note habit": "Habitude de note", + "Habit type key": "Clé du type d'habitude", + "Completion records key": "Clé des enregistrements", + "Frequency key": "Clé de fréquence", + "Weekday key": "Clé du jour de la semaine", + "Month day key": "Clé du jour du mois", + "Interval days key": "Clé des jours d'intervalle", + "Planned time key": "Clé de l'heure prévue", + "Goal direction key": "Clé du sens de l'objectif", + "Target key": "Clé de l'objectif", + "Unit key": "Clé de l'unité", + "Step size key": "Clé du pas", + "Weekly target key": "Clé de l'objectif hebdomadaire", + "Monthly target key": "Clé de l'objectif mensuel", + "Weekly perfect key": "Clé de la semaine parfaite", + "Monthly perfect key": "Clé du mois parfait", + "Start date key": "Clé de la date de début", + "Pauses key": "Clé des pauses", + "Stopped key": "Clé de l'arrêt", + "Stop date key": "Clé de la date d'arrêt", + "Icon key": "Clé de l'icône", + "Color key": "Clé de la couleur", + "Group key": "Clé du groupe", + "Use group color key": "Clé « utiliser la couleur du groupe »", + "Note folder key": "Clé du dossier des notes", + "Note filename format key": "Clé du format de nom de fichier", + "Template path key": "Clé du chemin du modèle", + "Note completion mode key": "Clé du mode d'achèvement", + "Note checklist requirement key": "Clé de l'exigence de la liste de tâches", + "Note checklist minimum key": "Clé du minimum de la liste de tâches", + "Note fail keyword key": "Clé du mot-clé d'échec", + "Legacy comments key": "Clé des commentaires hérités", + + // PDF export (read via docT() in export-modal.ts, which falls back to English for zh — jsPDF's built-in fonts can't render CJK) + "Completion trend": "Tendance de réussite", + "(paused)": "(en pause)", + "{rate}% · {total} · streak {current} (best {best})": + "{rate} % · {total} · série {current} (record {best})", + "Goal: {completed}/{goal} days met": + "Objectif : {completed}/{goal} jours atteints", + "{range} · exported {date}": "{range} · exporté le {date}", + "+{n} more": "+{n} de plus", + + // Back-dating a missed day + Back: "Retour", + + // Rescheduling missed habits (experimental) + "1 missed habit": "1 habitude manquée", + "Add a notification button to the dashboard and sidebar panel when a habit's been missed, opening a review of missed days you can move onto a different one (never a day that habit is already due, so nothing doubles up).": + "Ajoute un bouton de notification au tableau de bord et au panneau latéral lorsqu'une habitude a été manquée, ouvrant une revue des jours manqués que vous pouvez déplacer vers un autre jour (jamais un jour où cette habitude est déjà due, pour qu'il n'y ait jamais de doublon).", + "Missed habits": "Habitudes manquées", + "Move this missed day onto a different one": + "Déplacer ce jour manqué vers un autre", + "Move to": "Déplacer vers", + "Nothing missed right now.": "Rien de manqué pour l'instant.", + "Pick a habit to move it onto a different day.": + "Choisissez une habitude à déplacer vers un autre jour.", + Reschedule: "Replanifier", + "Reschedule missed habits": "Replanifier les habitudes manquées", + "Rescheduled \"{name}\" to {date}.": "« {name} » a été replanifiée au {date}.", + "Rescheduled from {date}": "Reporté depuis {date}", + "Reschedules key": "Clé des replanifications", + "Failed days key": "Clé des jours échoués", + "Skipped days key": "Clé des jours passés", + "Rescheduling \"{name}\" — missed {date}.": + "Replanification de « {name} » — manqué le {date}.", + "That day no longer works — pick another.": + "Ce jour ne fonctionne plus — choisissez-en un autre.", + "That day won't work — it's either already due for this habit or already claimed by another reschedule.": + "Ce jour ne convient pas — soit cette habitude y est déjà due, soit un autre déplacement l'a déjà pris.", + "{count} missed habits": "{count} habitudes manquées", +}; diff --git a/src/integrations/habits/i18n/index.ts b/src/integrations/habits/i18n/index.ts new file mode 100644 index 000000000..9e262fe9e --- /dev/null +++ b/src/integrations/habits/i18n/index.ts @@ -0,0 +1,61 @@ +import { moment } from "obsidian"; +import { es } from "./es"; +import { fr } from "./fr"; +import { de } from "./de"; +import { zh } from "./zh"; +import { ja } from "./ja"; +import { ko } from "./ko"; + +const LOCALES: Record> = { + es, + fr, + de, + zh, + ja, + ko, +}; + +/** Resolve the active dictionary from Obsidian's language setting. */ +function dictionary(): Record | null { + const lang = moment.locale(); + if (lang.startsWith("zh")) { + // Only Simplified Chinese is bundled; Traditional falls back to + // English rather than showing Simplified text. + return lang === "zh-tw" ? null : LOCALES.zh; + } + return LOCALES[lang.split("-")[0]] ?? null; +} + +/** + * Translate an English source string, interpolating `{placeholders}`. + * + * The English text itself is the lookup key (i18next-style natural keys), + * so any string missing from a dictionary safely falls back to English. + */ +export function t( + text: string, + vars?: Record, +): string { + return interpolate(dictionary()?.[text] ?? text, vars); +} + +/** Interpolate placeholders without translating (English source text). */ +export function tEn( + text: string, + vars?: Record, +): string { + return interpolate(text, vars); +} + +function interpolate( + text: string, + vars?: Record, +): string { + let out = text; + if (vars) { + for (const [key, value] of Object.entries(vars)) { + out = out.split(`{${key}}`).join(String(value)); + } + } + return out; +} diff --git a/src/integrations/habits/i18n/ja.ts b/src/integrations/habits/i18n/ja.ts new file mode 100644 index 000000000..c792264b7 --- /dev/null +++ b/src/integrations/habits/i18n/ja.ts @@ -0,0 +1,643 @@ +/** Japanese translations, keyed by the English source string. */ +export const ja: Record = { + // Commands and ribbon + "Create habit": "習慣を作成", + "Insert dashboard": "ダッシュボードを挿入", + "Insert habit metrics": "習慣メトリクスを挿入", + "Insert habits table": "習慣テーブルを挿入", + "Open panel": "パネルを開く", + "Open habits panel": "習慣パネルを開く", + Habits: "習慣", + + // Settings + "Habits folder": "習慣フォルダー", + "Folder where each habit is stored as its own note. It is created automatically if it does not exist.": + "各習慣を個別のノートとして保存するフォルダー。存在しない場合は自動的に作成されます。", + "Follow daily note date": "デイリーノートの日付に従う", + "When a dashboard is embedded in a daily note (a note whose name contains a date like 2026-07-01), open it on that note's date instead of today.": + "ダッシュボードがデイリーノート(2026-07-01 のような日付を名前に含むノート)に埋め込まれている場合、今日ではなくそのノートの日付で開きます。", + "Daily note date format": "デイリーノートの日付形式", + "Moment.js format used to read the date from a daily note's name, such as YYYY-MM-DD or YYYYMMDD.": + "デイリーノート名から日付を読み取るための Moment.js 形式。例:YYYY-MM-DD、YYYYMMDD。", + + // Sorting + "Sort habits by": "習慣の並び順", + "The base order of habit cards in the dashboard and side panel.": + "ダッシュボードとサイドパネルでのカードの基本的な並び順。", + "Name (A–Z)": "名前(A–Z)", + Color: "色", + "Last logged": "最終記録", + "Planned time": "予定時刻", + Manual: "手動", + "Manual order": "手動の順序", + "Drag the cards into the order you want. New habits join the end of the list.": + "カードをドラッグして好きな順序に並べます。新しい習慣はリストの最後に追加されます。", + "Move completed cards to the end": "完了したカードを最後に移動", + "Completed habits drift to the end of the queue and paused ones park behind them. Turn this off to keep every card in its sorted position.": + "完了した習慣はキューの最後へ移動し、一時停止中の習慣はその後ろに並びます。オフにすると、すべてのカードが並び順の位置に留まります。", + Group: "グループ", + Ungrouped: "グループなし", + "Optional group used to build dashboard sections — for example an area of responsibility.": + "ダッシュボードのセクションを作るための任意のグループ — 例えば責任範囲など。", + "e.g. Health": "例:健康", + "Group color": "グループの色", + "Optional color shared by every habit in this group.": + "このグループのすべての習慣で共有される任意の色。", + "Group icon": "グループのアイコン", + "Shown in the group lip on cards and in section headers.": + "カードのグループバーとセクション見出しに表示されます。", + "Use group color for this card": "このカードにグループの色を使う", + "Show this card in the group color instead of its own.": + "このカードを自身の色ではなくグループの色で表示します。", + General: "一般", + Sorting: "並べ替え", + Groups: "グループ", + "How to move through your habit cards: a paged carousel with arrows, a grid that wraps onto new rows, or a fixed-height grid that scrolls vertically. The stats page follows the same choice.": + "カードの表示方法:矢印で切り替えるカルーセル、行を折り返すグリッド、または高さ固定で縦にスクロールするグリッド。統計ページも同じ設定に従います。", + "Enable groups": "グループを有効にする", + "Show habits in sections by their group, with a group lip on each card.": + "習慣をグループごとのセクションで表示し、各カードにグループバーを付けます。", + "Group order": "グループの順序", + "Drag the groups into the order you want. Sections follow the same order.": + "グループを好きな順序にドラッグします。セクションも同じ順序に従います。", + "Completion animations": "完了アニメーション", + "Play the check swoosh, card departure, and perfect-day confetti when habits are completed. Turn off for instant, quiet updates.": + "習慣の完了時にチェックのスウッシュ、カードの退場、パーフェクトデーの紙吹雪を再生します。オフにすると即座に静かに更新されます。", + "Reminders": "リマインダー", + "Write reminders for due habits": "当日実施予定の習慣のリマインダーを書き込む", + "Each day, write one reminder checklist line per planned time of every habit due that day, in the format the Reminder plugin picks up. The lines live in a marked block and refresh as you log habits.": + "毎日、その日に実施予定の各習慣の予定時刻ごとにリマインダー行を書き込みます。形式は Reminder プラグインが認識するものです。行はマーカー付きブロック内にあり、記録に応じて更新されます。", + "Where to write reminders": "リマインダーの書き込み先", + "The daily note follows the Daily notes core plugin's folder and date format; the block is added once the note exists. A fixed note is created automatically.": + "デイリーノートはコアプラグイン「デイリーノート」のフォルダーと日付形式に従い、ノートが存在すればブロックが追加されます。固定ノートは自動的に作成されます。", + "Today's daily note": "今日のデイリーノート", + "A fixed note": "固定ノート", + "Reminder note path": "リマインダーノートのパス", + "Vault path of the note that holds the reminder block.": + "リマインダーブロックを保持するノートの保管庫内パス。", + "Manage groups": "グループを管理", + "See every habit by group and drag cards between groups.": + "グループごとに習慣を確認し、カードをグループ間でドラッグできます。", + Open: "開く", + "New group": "新しいグループ", + Add: "追加", + "Drag habits between groups to reassign them, or within a group to reorder them.": + "習慣をグループ間でドラッグして割り当て直すか、グループ内でドラッグして並べ替えます。", + "No habits": "習慣なし", + "Edit group style": "グループのスタイルを編集", + "Delete group": "グループを削除", + 'Delete "{name}"? Its habits are kept and become ungrouped.': + "「{name}」を削除しますか?習慣は保持され、グループなしになります。", + Delete: "削除", + "Dashboard layout": "ダッシュボードのレイアウト", + Carousel: "カルーセル", + Grid: "グリッド", + "Vertical scroll": "縦スクロール", + "Cards per view": "1画面あたりのカード数", + "How many habit cards fit side by side on wider screens.": + "広い画面で横に並べるカードの数。", + "Cards per view on mobile": "モバイルでの1画面あたりのカード数", + "How many habit cards fit side by side on phone-sized screens.": + "スマートフォンの画面で横に並べるカードの数。", + + // Confirm dialog defaults + Cancel: "キャンセル", + Confirm: "確認", + + // Store notices + 'Could not find the note for "{name}".': + "「{name}」のノートが見つかりませんでした。", + "Please enter a valid habit name.": "有効な習慣名を入力してください。", + 'A habit called "{name}" already exists.': + "「{name}」という習慣はすでに存在します。", + 'Created habit "{name}".': "習慣「{name}」を作成しました。", + 'Updated "{name}".': "「{name}」を更新しました。", + 'Paused "{name}".': "「{name}」を一時停止しました。", + 'Resumed "{name}".': "「{name}」を再開しました。", + 'Stopped tracking "{name}". Its history is kept in the note.': + "「{name}」のトラッキングを停止しました。履歴はノートに保存されています。", + 'Resumed tracking "{name}".': "「{name}」のトラッキングを再開しました。", + 'Removed "{name}".': "「{name}」を削除しました。", + "Habit added to the dashboard.": "習慣をダッシュボードに追加しました。", + + // Dashboard + "Back to habits": "習慣に戻る", + "View stats": "統計を表示", + "Export stats": "統計をエクスポート", + Weekly: "週間", + Monthly: "月間", + "Previous day": "前の日", + "Next day": "次の日", + "Choose a date": "日付を選択", + "Add habit": "習慣を追加", + "No habits yet. Create your first habit to get started.": + "まだ習慣がありません。最初の習慣を作成して始めましょう。", + Previous: "前へ", + Next: "次へ", + "Go to position {n}": "位置 {n} へ移動", + "Right-click or long-press for more options": + "右クリックまたは長押しでその他のオプション", + "Open habit note": "習慣のノートを開く", + "Open the note for {name}": "{name} のノートを開く", + Paused: "一時停止中", + Stopped: "記録停止", + "Failed": "失敗", + "Skipped": "スキップ", + "Snoozed": "スヌーズ中", + "Snoozed until {time}": "{time} までスヌーズ中", + "Undo fail": "失敗を取り消す", + "Undo skip": "スキップを取り消す", + "End snooze": "スヌーズを終了", + "Fail for today": "今日は失敗にする", + "Fail this day": "この日を失敗にする", + "Marked \"{name}\" as failed.": "「{name}」を失敗にしました。", + "Skip for today": "今日はスキップ", + "Skip this day": "この日をスキップ", + "Skipped \"{name}\".": "「{name}」をスキップしました。", + "Snooze…": "スヌーズ…", + "Snooze \"{name}\"": "「{name}」をスヌーズ", + "It leaves today's lists and comes back on its own. Snoozing never counts for or against the habit.": "今日のリストから外れ、時間になると戻ってきます。スヌーズは習慣の記録に影響しません。", + "Snooze for": "スヌーズする時間", + "30 minutes": "30分", + "1 hour": "1時間", + "3 hours": "3時間", + "Snooze until": "スヌーズの終了時刻", + "Snooze": "スヌーズ", + "Pick a time later today.": "今日のこれより後の時刻を選んでください。", + "Snoozed \"{name}\" until {time}.": "「{name}」を {time} までスヌーズしました。", + "1 hidden for today": "今日は1件非表示", + "{count} hidden for today": "今日は{count}件非表示", + "1 hidden for this day": "この日は1件非表示", + "{count} hidden for this day": "この日は{count}件非表示", + "Undo": "元に戻す", + "Click to undo": "クリックで元に戻す", + "Nothing left on this day's list.": "この日のリストには何も残っていません。", + "Nothing left on today's list.": "今日のリストには何も残っていません。", + "At least: reach a target for habits you are building, like drinking 1.5 litres of water. At most: stay within a limit for habits you are cutting down, like no more than 2 coffees.": "以上:身につけたい習慣の目標を達成します(例:水を1.5リットル飲む)。以下:減らしたい習慣を上限内に収めます(例:コーヒーは2杯まで)。", + "At least (reach a target)": "以上(目標を達成)", + "At most (stay within a limit)": "以下(上限内に収める)", + "Step size": "増減の単位", + "How much each + and − press adds or removes. Use a decimal such as 0.25 for amounts like litres.": "+ と − を1回押したときに増減する量です。リットルなどの量には 0.25 のような小数を使えます。", + "Decrease by {n}": "{n} 減らす", + "4 weeks": "4週間", + "12 weeks": "12週間", + "6 months": "6か月", + "1 year": "1年", + "Completion rate": "達成率", + "Monthly completion rate": "月間達成率", + "Daily activity": "日別アクティビティ", + "Week of {date}": "{date}の週", + "Since {date} · right-click to resume": + "{date} から · 右クリックで再開", + "Paused on this day": "この日は一時停止中", + "Mark as done": "完了にする", + "Mark as not done": "未完了にする", + Done: "完了", + "Not done": "未完了", + "Edit value": "値を編集", + Value: "値", + "Decrease by 1": "1 減らす", + "Increase by 1": "1 増やす", + "Increase by {n}": "{n} 増やす", + "Edit habit": "習慣を編集", + "Pause habit": "習慣を一時停止", + "Resume habit": "習慣を再開", + "Stop tracking": "トラッキングを停止", + "Remove habit": "習慣を削除", + 'Stop tracking "{name}"? It leaves the dashboard and stats, but its note and full history are kept. You can resume tracking any time from the note\'s metrics view.': + "「{name}」のトラッキングを停止しますか?ダッシュボードと統計から消えますが、ノートと履歴はすべて保存されます。ノートのメトリクス表示からいつでも再開できます。", + 'Remove "{name}"? Its note will be moved to the trash.': + "「{name}」を削除しますか?ノートはゴミ箱に移動されます。", + Remove: "削除", + "Perfect!": "パーフェクト!", + Today: "今日", + Yesterday: "昨日", + Tomorrow: "明日", + "Last 7 days": "過去7日間", + "Last 30 days": "過去30日間", + "This week": "今週", + "This month": "今月", + + // Sidebar panel + "Habits completed today": "今日完了した習慣", + "No habits yet.": "まだ習慣がありません。", + "Click to type a value": "クリックして値を入力", + "Open note": "ノートを開く", + + // Stats view + "No habits to show stats for yet.": + "統計を表示できる習慣がまだありません。", + Completion: "達成率", + "Best streak": "最長ストリーク", + "Perfect days": "パーフェクトな日", + Completions: "達成回数", + "Goals met": "達成した目標", + "{completed}/{days} days": "{completed}/{days} 日", + "{total} total": "合計 {total}", + best: "最高", + "perfect week": "パーフェクトな週", + "perfect month": "パーフェクトな月", + "weekly goal": "週間目標", + "monthly goal": "月間目標", + "{progress}/{goal} days · {label} · {pct}%": + "{progress}/{goal} 日 · {label} · {pct}%", + + // Habit metrics block + 'Place this block inside a habit note, or point it at one with "habit: ".': + "このブロックは習慣ノート内に置くか、「habit: <名前>」で習慣を指定してください。", + 'No habit called "{name}" was found.': + "「{name}」という習慣は見つかりませんでした。", + "No longer tracked since {date}. All history is kept.": + "{date} 以降トラッキングされていません。履歴はすべて保存されています。", + "No longer tracked. All history is kept.": + "トラッキングされていません。履歴はすべて保存されています。", + "Resume tracking": "トラッキングを再開", + "Paused since {date}. Paused days don't count against streaks or stats.": + "{date} から一時停止中。一時停止した日はストリークや統計に影響しません。", + "Paused. Paused days don't count against streaks or stats.": + "一時停止中。一時停止した日はストリークや統計に影響しません。", + "Current streak": "現在のストリーク", + "Days completed": "完了した日数", + "30-day rate": "30日間の達成率", + "Weekly completion rate": "週間達成率", + Logged: "記録", + Target: "目標", + + // Export modal + Title: "タイトル", + "Habits report": "習慣レポート", + "Date range": "期間", + "Custom range": "カスタム期間", + From: "開始", + To: "終了", + "Up to {n} days.": "最大 {n} 日。", + Content: "内容", + "Summary tiles": "サマリータイル", + "Completion trend chart": "達成率トレンドのグラフ", + "Daily grids": "日別グリッド", + "Goal progress": "目標の進捗", + Layout: "レイアウト", + Orientation: "向き", + Portrait: "縦", + Landscape: "横", + Density: "密度", + Comfortable: "ゆったり", + Compact: "コンパクト", + Monochrome: "モノクロ", + "Ink-friendly greys instead of accent colours.": + "アクセントカラーの代わりにインクにやさしいグレーを使います。", + "Export PDF": "PDF をエクスポート", + "No habits to export yet.": + "エクスポートできる習慣がまだありません。", + 'Exported to "{path}" in your vault.': + "ボルト内の「{path}」にエクスポートしました。", + + // Habit modal + "New habit": "新しい習慣", + Name: "名前", + Type: "タイプ", + "Binary is done or not done. Repetition counts towards a target. Timed tracks minutes.": + "バイナリは完了か未完了か。回数は目標に向けてカウント。時間は分を記録します。", + Binary: "バイナリ", + Repetition: "回数", + Timed: "時間", + "Daily target (minutes)": "1日の目標(分)", + "Daily target": "1日の目標", + Unit: "単位", + "Optional label shown next to the count.": + "カウントの横に表示される任意のラベル。", + Icon: "アイコン", + "Choose a Lucide icon or an emoji to represent this habit.": + "この習慣を表す Lucide アイコンか絵文字を選んでください。", + Emoji: "絵文字", + "Choose an emoji": "絵文字を選択", + "Clear icon": "アイコンをクリア", + "Choose icon": "アイコンを選択", + "Save changes": "変更を保存", + "Targets (optional)": "目標(任意)", + "Set an optional weekly or monthly goal for how many days you complete this habit. For example, hitting your daily goal on all 7 days is a weekly target of 7. Turn on a perfect toggle to aim for every day of the period automatically, whatever its length.": + "この習慣を達成する日数について、週間または月間の目標を任意で設定できます。たとえば7日間すべてで1日の目標を達成すると週間目標は7です。パーフェクトのスイッチをオンにすると、期間の長さに関係なく毎日を自動的に目指します。", + "Perfect week": "パーフェクトな週", + "Aim to complete this habit every day of the week.": + "この習慣を週の毎日達成することを目指します。", + "Weekly target": "週間目標", + "Optional. Days to complete per week (max 7).": + "任意。1週間に達成する日数(最大7)。", + None: "なし", + "Perfect month": "パーフェクトな月", + "Aim to complete this habit every day of the month.": + "この習慣を月の毎日達成することを目指します。", + "Monthly target": "月間目標", + "Optional. Days to complete per month.": + "任意。1か月に達成する日数。", + Colour: "カラー", + "Pick a colour from your theme, or choose a custom one.": + "テーマのカラーから選ぶか、カスタムカラーを指定してください。", + "Your habit": "あなたの習慣", + + // Icon and colour pickers + "Search icons…": "アイコンを検索…", + "Search emojis…": "絵文字を検索…", + + // Comments + "Comments on cards": "カードのコメント", + "Show a comment flap on dashboard cards for jotting a note about any day.": + "ダッシュボードのカードにコメント用のフラップを表示し、その日のメモを書き留められます。", + "Add comment": "コメントを追加", + "Flip back": "表に戻す", + "Edit comment": "コメントを編集", + "Move day comments into note bodies": "日別コメントをノート本文へ移動", + "No comments left to move.": "移動するコメントはありません。", + "Moved comments in 1 note.": "1 件のノートのコメントを移動しました。", + "Moved comments in {n} notes.": "{n} 件のノートのコメントを移動しました。", + "Add a comment for this day…": "この日のコメントを追加…", + Comments: "コメント", + + // Limit habits (experimental) + Experimental: "実験的機能", + "These features are still being tested and may change before they become permanent. Turning one off only hides it from menus — anything you created with it keeps working.": + "これらの機能はまだテスト中で、正式版になる前に変更される可能性があります。オフにしてもメニューから隠れるだけで、作成したものはそのまま動き続けます。", + "Break bad habits": "悪い習慣を断つ", + "Track habits you want to reduce or avoid by staying under a daily limit — for example at most 2 hours of gaming, or no smoking at all.": + "1日の上限内に収めることで、減らしたい・やめたい習慣をトラッキングします。たとえばゲームは1日2時間まで、喫煙はゼロなど。", + Goal: "ゴール", + "Reach a target for habits you are building. Stay under a limit for habits you are cutting down or giving up.": + "身につけたい習慣は目標を達成し、減らしたい・やめたい習慣は上限内にとどめます。", + "Reach a target": "目標を達成する", + "Stay under a limit": "上限内にとどめる", + "Binary means avoiding it entirely. Repetition counts against a daily limit. Timed tracks minutes against a daily limit.": + "バイナリは完全に避けること。回数は1日の上限に対してカウント。時間は1日の上限に対して分を記録します。", + "Daily limit": "1日の上限", + "Daily limit (minutes)": "1日の上限(分)", + "0 means none at all.": "0 は一切なしという意味です。", + "Set an optional weekly or monthly goal for how many days you stay within your limit. Turn on a perfect toggle to aim for every day of the period automatically, whatever its length.": + "上限内に収めた日数について、週間または月間の目標を任意で設定できます。パーフェクトのスイッチをオンにすると、期間の長さに関係なく毎日を自動的に目指します。", + Clean: "クリーン", + Slipped: "スリップ", + "Mark as clean": "クリーンにする", + "Mark as slipped": "スリップにする", + "Days within limit": "上限内の日数", + Limit: "上限", + + // Frequencies and per-note metrics + Frequency: "頻度", + Daily: "毎日", + "Days of week": "曜日", + Habit: "習慣", + Schedule: "スケジュール", + "Time of day": "時刻", + "Optional times this habit is planned for — once or several times a day. Shown on the habit's card.": + "この習慣を行う予定時刻(任意)。1日1回または複数回。習慣のカードに表示されます。", + "Add time": "時刻を追加", + "Remove time": "時刻を削除", + "Every N days": "N日ごと", + "Repeat every": "繰り返し間隔", + "Day of month": "日にち", + "The weekdays this habit is due on. Pick as many as you need.": + "この習慣の期日となる曜日。複数選択できます。", + "Number of days between due dates, counted from the habit's start date. Use 2 for an alternate-day schedule.": + "期日と期日の間の日数。習慣の開始日から数えます。2にすると1日おきになります。", + "The day of the month this habit is due. In shorter months it falls due on the last day, so 31 always lands on the final day of the month.": + "この習慣の期日となる日。短い月では月末が期日になるため、31 は常にその月の最終日になります。", + "Every {day}": "毎週 {day}", + "Monthly · day {day}": "毎月 · {day} 日", + "Every other day": "1日おき", + "Every {n} days": "{n}日ごと", + "No habits are due on this day.": + "この日に期日の習慣はありません。", + "Nothing due today.": "今日は期日のものがありません。", + "Weekly activity": "週間アクティビティ", + "Monthly activity": "月間アクティビティ", + "Activity on due days": "期日の活動", + "Completion rate over {n} due days": "直近{n}回の期日の達成率", + "Weeks completed": "完了した週", + "Months completed": "完了した月", + "Recent rate": "最近の達成率", + "{n}-week completion rate": "{n} 週間の達成率", + "{n}-month completion rate": "{n} か月の達成率", + + // AI summaries + "AI summaries": "AI サマリー", + "AI summary": "AI サマリー", + "Show an AI-generated summary with feedback and advice on the stats page tabs. Uses an OpenAI-compatible service you configure below; your habit stats are sent to it only when you press the generate button.": + "統計ページのタブに、フィードバックとアドバイス付きの AI 生成サマリーを表示します。下で設定する OpenAI 互換サービスを使用し、習慣の統計は生成ボタンを押したときにのみ送信されます。", + "AI base URL": "AI ベース URL", + "Base URL of an OpenAI-compatible API. Works with OpenAI, OpenRouter, or local servers like Ollama (http://localhost:11434/v1).": + "OpenAI 互換 API のベース URL。OpenAI、OpenRouter、Ollama(http://localhost:11434/v1)などのローカルサーバーで動作します。", + "AI API key": "AI API キー", + "Stored locally in this vault's plugin data. Leave blank for local servers that need no key.": + "このボルトのプラグインデータにローカル保存されます。キー不要のローカルサーバーでは空欄のままにしてください。", + "AI model": "AI モデル", + "Model name the service should use.": + "サービスが使用するモデル名。", + "Generate summary": "サマリーを生成", + Regenerate: "再生成", + "Get feedback and advice on your habits for this period. Your stats are sent to the AI service you configured only when you press the button.": + "この期間の習慣についてフィードバックとアドバイスを受け取ります。統計は、ボタンを押したときにのみ設定した AI サービスへ送信されます。", + "Thinking…": "考え中…", + "Could not generate a summary: {message}": + "サマリーを生成できませんでした:{message}", + "Adds an AI-generated overview with feedback and advice. Your habit stats are sent to your configured AI service.": + "フィードバックとアドバイス付きの AI 生成概要を追加します。習慣の統計は設定した AI サービスへ送信されます。", + "Generating AI summary…": "AI サマリーを生成中…", + "The AI summary will be generated when you export.": + "AI サマリーはエクスポート時に生成されます。", + + // Custom stats range + Custom: "カスタム", + "Start date": "開始日", + "End date": "終了日", + + // Heatmap start markers + "not tracked yet": "まだ記録なし", + "started tracking on {date}": "{date} にトラッキング開始", + + // Stats carousel + "Stats rows per page": "1ページあたりの統計行数", + "How many habits each stats page shows.": + "各統計ページに表示する習慣の数。", + // Note habits + '"{name}" uses Templater syntax, but the Templater plugin is not installed — the template was copied as plain text.': + "「{name}」はTemplater構文を使用していますが、Templaterプラグインがインストールされていません — テンプレートはプレーンテキストとしてコピーされました。", + "Binary is done or not done. Repetition counts towards a target. Timed tracks minutes. Note is completed by writing in a per-day note.": + "バイナリは完了か未完了か。回数は目標に向けてカウント。時間は分を記録します。ノートは日ごとのノートに書き込むことで完了します。", + "Character count is reached": "文字数に到達する", + "Character goal": "文字数の目標", + "Completed when": "完了の条件", + "Every task is checked": "すべてのタスクにチェックが入る", + "Filename format": "ファイル名の形式", + "Folder each day's note is created in. Leave blank for a dedicated subfolder named after this habit.": + "毎日のノートを作成するフォルダー。空欄のままにすると、この習慣の名前が付いた専用サブフォルダーが使われます。", + "Moment.js format used to name each day's note, e.g. {example}. May include / for date-based subfolders.": + "毎日のノートの名前に使うMoment.js形式。例:{example}。日付ごとのサブフォルダーには / を含めることができます。", + Note: "ノート", + "Note habits": "ノート習慣", + "Notes folder": "ノートのフォルダー", + "Open this day's note": "この日のノートを開く", + "Open today's note": "今日のノートを開く", + "Optional template note used when a day's note is created. Expanded through the Templater plugin when it is installed, otherwise copied as plain text.": + "日ごとのノート作成時に使う任意のテンプレートノート。Templaterプラグインがインストールされていれば展開され、なければプレーンテキストとしてコピーされます。", + Template: "テンプレート", + "Track a habit by writing in a per-day note instead of logging a value by hand. A day is complete once the note reaches a character count or every task in it is checked. Works with the Templater plugin to create each day's note from a template.": + "値を手動で記録する代わりに、日ごとのノートに書き込むことで習慣を記録します。ノートが文字数に到達するか、すべてのタスクにチェックが入ると、その日は完了になります。Templaterプラグインと連携し、テンプレートから毎日のノートを作成できます。", + Write: "書く", + "Write this day's note": "この日のノートを書く", + "Write today's note": "今日のノートを書く", + "e.g. Journal": "例: Journal", + "e.g. Templates/Journal.md": "例: Templates/Journal.md", + + // Flexible frequency (any day) + "How many times (or, for counted and timed habits, how much in total) this needs to happen somewhere in the period.": + "期間内のどこかでこれが何回(カウントや時間の習慣では合計でどれだけ)必要かを指定します。", + 'How often this habit is due. Weekly and monthly habits only appear on their due date; the "any day" options appear every day until their quota is met.': + "この習慣の頻度。週間・月間の習慣は期日にのみ表示されますが、「任意の日」オプションはノルマを達成するまで毎日表示されます。", + "Monthly (any day)": "月間(任意の日)", + "Times per month": "月あたりの回数", + "Times per week": "週あたりの回数", + "Weekly (any day)": "週間(任意の日)", + "this month": "今月", + "this week": "今週", + "{completed}/{days} months": "{completed}/{days} か月", + "{completed}/{days} weeks": "{completed}/{days} 週", + "{n}× a month · any day": "月{n}回 · 任意の日", + "{n}× a week · any day": "週{n}回 · 任意の日", + + // Commands + "Insert habits heatmap": "習慣ヒートマップを挿入", + + // Habit metrics: heatmap tabs + Charts: "グラフ", + Month: "月", + History: "履歴", + "{month} heatmap": "{month}のヒートマップ", + "Last {n} weeks": "直近{n}週間", + + // Heatmap cell states and tooltips + Upcoming: "今後", + "Not tracked yet": "まだ記録なし", + "Not due": "対象外", + "Outside this month": "今月の範囲外", + Complete: "達成", + "Over limit": "上限超過", + "Not logged": "未記録", + + // Whole-vault heatmap block + "Add a habit to see its heatmap here.": "習慣を追加すると、ここにヒートマップが表示されます。", + "No habits in the \"{group}\" group.": "「{group}」グループに習慣がありません。", + "No habits due": "予定されている習慣なし", + "Perfect day": "パーフェクトな日", + "{completed}/{considered} habits · {pct}%": + "{completed}/{considered} 件の習慣 · {pct}%", + "This year": "今年", + "Past 6 months": "過去6か月", + "{year} heatmap": "{year}年のヒートマップ", + + // Note habits: checklist requirement and fail keyword + "Both are true": "両方とも満たす", + "Checklist requirement is met": "チェックリストの条件を満たす", + "Checklist requirement": "チェックリストの条件", + "Require every task to be checked, or just some — useful for a list of alternatives where doing any one of them counts (e.g. \"Cardio\" / \"Weights\" / \"Rest day\").": + "すべてのタスクにチェックを必須にするか、一部だけでもよいことにするか選べます — 「有酸素運動」「筋トレ」「休養日」のように、どれか一つで達成とみなしたい選択肢リストに便利です。", + "At least this many are checked": "少なくともこの数だけチェックが入る", + "Tasks required": "必要なタスク数", + "Fail keyword": "失敗キーワード", + "Optional. Checking a task whose text contains this word forces the day to fail, whatever else is checked — e.g. \"Slipped\" as one of several checklist options. Leave blank to turn this off.": + "任意設定です。テキストにこの単語を含むタスクにチェックを入れると、他に何をチェックしていても、その日は強制的に失敗扱いになります — 例えば「失敗」をチェックリストの選択肢の一つにする、といった使い方です。空欄にするとオフになります。", + "e.g. Slipped": "例: 失敗", + "Reach a character count, meet a checklist requirement, or require both.": + "文字数に到達する、チェックリストの条件を満たす、またはその両方を必須にする、から選べます。", + + // Tags (cross-plugin compatibility) + Tags: "タグ", + "e.g. task": "例: task", + "Optional Obsidian tags for this note, separated by commas or spaces. Useful for making this habit recognisable to another plugin's own tag-based rules — for example TaskNotes' task tag.": + "このノートの任意の Obsidian タグです。カンマまたはスペースで区切ります。別のプラグイン独自のタグルールにこの習慣を認識させるのに便利です — 例えば TaskNotes の task タグなど。", + + // Advanced settings: frontmatter key remapping + Advanced: "詳細設定", + Apply: "適用", + "Apply key changes": "キーの変更を適用", + "Rename the frontmatter properties habit notes use. Useful for avoiding collisions with another plugin's own properties in the same note (for example TaskNotes).": + "習慣ノートが使用するフロントマターのプロパティ名を変更します。同じノート内で別のプラグイン(例: TaskNotes)独自のプロパティと衝突するのを避けるのに便利です。", + "\"{a}\" and \"{b}\" can't use the same property key (\"{value}\").": + "「{a}」と「{b}」に同じプロパティキー(「{value}」)は使用できません。", + "Property keys can't be empty.": "プロパティキーを空にすることはできません。", + "This renames {summary} in every note in your habits folder ({count} habit(s) currently). Existing values are moved, not discarded. Continue?": + "これにより、習慣フォルダー内のすべてのノート(現在 {count} 件の習慣)で {summary} の名前が変更されます。既存の値は破棄されず移動します。続行しますか?", + "Updated the frontmatter keys in {count} note(s).": + "{count} 件のノートでフロントマターのキーを更新しました。", + "Renaming this away from the default also changes how binary habits log a day: instead of {\"2026-08-25\": 1}, a completed day becomes a bare date, like [\"2026-08-25\"] — the shape TaskNotes uses for complete_instances. Repetition and timed habits are unaffected either way; they always need a value, never just a date.": + 'このキーを既定値から変更すると、バイナリ習慣が1日をどう記録するかも変わります。{"2026-08-25": 1} の代わりに、完了した日は ["2026-08-25"] のような単なる日付になります — これは TaskNotes が complete_instances に使う形式です。回数記録・時間記録の習慣はどちらの場合も影響を受けません。常に値が必要で、日付だけになることはありません。', + Identity: "識別情報", + Legacy: "レガシー", + Lifecycle: "ライフサイクル", + Presentation: "表示", + "Note habit": "ノート習慣", + "Habit type key": "習慣タイプキー", + "Completion records key": "完了記録キー", + "Frequency key": "頻度キー", + "Weekday key": "曜日キー", + "Month day key": "月内日キー", + "Interval days key": "間隔日数キー", + "Planned time key": "予定時刻キー", + "Goal direction key": "目標の方向キー", + "Target key": "目標キー", + "Unit key": "単位キー", + "Step size key": "増減単位キー", + "Weekly target key": "週間目標キー", + "Monthly target key": "月間目標キー", + "Weekly perfect key": "パーフェクト週キー", + "Monthly perfect key": "パーフェクト月キー", + "Start date key": "開始日キー", + "Pauses key": "一時停止記録キー", + "Stopped key": "停止状態キー", + "Stop date key": "停止日キー", + "Icon key": "アイコンキー", + "Color key": "色キー", + "Group key": "グループキー", + "Use group color key": "「グループの色を使用」キー", + "Note folder key": "ノートフォルダーキー", + "Note filename format key": "ノートのファイル名形式キー", + "Template path key": "テンプレートパスキー", + "Note completion mode key": "ノート完了モードキー", + "Note checklist requirement key": "チェックリスト条件キー", + "Note checklist minimum key": "チェックリスト最小数キー", + "Note fail keyword key": "失敗ワードのキー", + "Legacy comments key": "旧形式コメントキー", + + // PDF export (read via docT() in export-modal.ts, which falls back to English for zh — jsPDF's built-in fonts can't render CJK) + "Completion trend": "達成率トレンド", + "(paused)": "(一時停止中)", + "{rate}% · {total} · streak {current} (best {best})": + "{rate}% · {total} · ストリーク {current}(最高 {best})", + "Goal: {completed}/{goal} days met": + "目標:{completed}/{goal} 日達成", + "{range} · exported {date}": "{range} · {date} にエクスポート", + "+{n} more": "他 {n} 件", + + // Back-dating a missed day + Back: "戻る", + + // Rescheduling missed habits (experimental) + "1 missed habit": "見逃した習慣が1件", + "Add a notification button to the dashboard and sidebar panel when a habit's been missed, opening a review of missed days you can move onto a different one (never a day that habit is already due, so nothing doubles up).": + "習慣を見逃したときに、ダッシュボードとサイドパネルに通知ボタンを追加します。見逃した日を確認し、別の日に移動できます(その習慣がもともと予定されている日には移動できないため、二重記録にはなりません)。", + "Missed habits": "見逃した習慣", + "Move this missed day onto a different one": "この見逃した日を別の日に移動", + "Move to": "移動先", + "Nothing missed right now.": "現在、見逃したものはありません。", + "Pick a habit to move it onto a different day.": "別の日に移動する習慣を選んでください。", + Reschedule: "リスケジュール", + "Reschedule missed habits": "見逃した習慣をリスケジュール", + "Rescheduled \"{name}\" to {date}.": "「{name}」を{date}にリスケジュールしました。", + "Rescheduled from {date}": "{date}からリスケジュール", + "Reschedules key": "リスケジュールキー", + "Failed days key": "失敗した日のキー", + "Skipped days key": "スキップした日のキー", + "Rescheduling \"{name}\" — missed {date}.": + "「{name}」をリスケジュール中 — {date}に見逃しました。", + "That day no longer works — pick another.": "その日はもう使えません — 別の日を選んでください。", + "That day won't work — it's either already due for this habit or already claimed by another reschedule.": + "その日は使えません — その習慣がもともとその日に予定されているか、すでに別のリスケジュールで使われています。", + "{count} missed habits": "見逃した習慣が{count}件", +}; diff --git a/src/integrations/habits/i18n/ko.ts b/src/integrations/habits/i18n/ko.ts new file mode 100644 index 000000000..b8d767807 --- /dev/null +++ b/src/integrations/habits/i18n/ko.ts @@ -0,0 +1,644 @@ +/** Korean translations, keyed by the English source string. */ +export const ko: Record = { + // Commands and ribbon + "Create habit": "습관 만들기", + "Insert dashboard": "대시보드 삽입", + "Insert habit metrics": "습관 지표 삽입", + "Insert habits table": "습관 표 삽입", + "Open panel": "패널 열기", + "Open habits panel": "습관 패널 열기", + Habits: "습관", + + // Settings + "Habits folder": "습관 폴더", + "Folder where each habit is stored as its own note. It is created automatically if it does not exist.": + "각 습관이 개별 노트로 저장되는 폴더입니다. 없으면 자동으로 생성됩니다.", + "Follow daily note date": "데일리 노트 날짜 따라가기", + "When a dashboard is embedded in a daily note (a note whose name contains a date like 2026-07-01), open it on that note's date instead of today.": + "대시보드가 데일리 노트(이름에 2026-07-01 같은 날짜가 포함된 노트)에 삽입된 경우, 오늘 대신 해당 노트의 날짜로 엽니다.", + "Daily note date format": "데일리 노트 날짜 형식", + "Moment.js format used to read the date from a daily note's name, such as YYYY-MM-DD or YYYYMMDD.": + "데일리 노트 이름에서 날짜를 읽는 데 사용하는 Moment.js 형식입니다. 예: YYYY-MM-DD, YYYYMMDD.", + + // Sorting + "Sort habits by": "습관 정렬 기준", + "The base order of habit cards in the dashboard and side panel.": + "대시보드와 사이드 패널에서 습관 카드의 기본 순서.", + "Name (A–Z)": "이름(A–Z)", + Color: "색상", + "Last logged": "마지막 기록", + "Planned time": "예정 시간", + Manual: "수동", + "Manual order": "수동 순서", + "Drag the cards into the order you want. New habits join the end of the list.": + "카드를 원하는 순서로 드래그하세요. 새 습관은 목록 끝에 추가됩니다.", + "Move completed cards to the end": "완료된 카드를 끝으로 이동", + "Completed habits drift to the end of the queue and paused ones park behind them. Turn this off to keep every card in its sorted position.": + "완료된 습관은 대기열 끝으로 이동하고 일시정지된 습관은 그 뒤에 놓입니다. 끄면 모든 카드가 정렬된 위치를 유지합니다.", + Group: "그룹", + Ungrouped: "그룹 없음", + "Optional group used to build dashboard sections — for example an area of responsibility.": + "대시보드 섹션을 만들기 위한 선택적 그룹 — 예를 들어 책임 영역.", + "e.g. Health": "예: 건강", + "Group color": "그룹 색상", + "Optional color shared by every habit in this group.": + "이 그룹의 모든 습관이 공유하는 선택적 색상.", + "Group icon": "그룹 아이콘", + "Shown in the group lip on cards and in section headers.": + "카드의 그룹 표시줄과 섹션 머리글에 표시됩니다.", + "Use group color for this card": "이 카드에 그룹 색상 사용", + "Show this card in the group color instead of its own.": + "이 카드를 자체 색상 대신 그룹 색상으로 표시합니다.", + General: "일반", + Sorting: "정렬", + Groups: "그룹", + "How to move through your habit cards: a paged carousel with arrows, a grid that wraps onto new rows, or a fixed-height grid that scrolls vertically. The stats page follows the same choice.": + "습관 카드 탐색 방식: 화살표로 넘기는 캐러셀, 새 줄로 이어지는 그리드, 또는 고정 높이에서 세로로 스크롤되는 그리드. 통계 페이지도 같은 설정을 따릅니다.", + "Enable groups": "그룹 사용", + "Show habits in sections by their group, with a group lip on each card.": + "습관을 그룹별 섹션으로 표시하고 각 카드에 그룹 표시줄을 붙입니다.", + "Group order": "그룹 순서", + "Drag the groups into the order you want. Sections follow the same order.": + "그룹을 원하는 순서로 드래그하세요. 섹션도 같은 순서를 따릅니다.", + "Completion animations": "완료 애니메이션", + "Play the check swoosh, card departure, and perfect-day confetti when habits are completed. Turn off for instant, quiet updates.": + "습관을 완료할 때 체크 스우시, 카드 퇴장, 완벽한 하루 색종이를 재생합니다. 끄면 즉시 조용히 갱신됩니다.", + "Reminders": "알림", + "Write reminders for due habits": "오늘 해야 할 습관의 알림 작성", + "Each day, write one reminder checklist line per planned time of every habit due that day, in the format the Reminder plugin picks up. The lines live in a marked block and refresh as you log habits.": + "매일 그날 해야 할 각 습관의 예정 시간마다 알림 체크리스트 한 줄을 Reminder 플러그인이 인식하는 형식으로 작성합니다. 이 줄들은 표시된 블록 안에 있으며 기록에 따라 갱신됩니다.", + "Where to write reminders": "알림을 작성할 위치", + "The daily note follows the Daily notes core plugin's folder and date format; the block is added once the note exists. A fixed note is created automatically.": + "데일리 노트는 코어 데일리 노트 플러그인의 폴더와 날짜 형식을 따르며, 노트가 존재하면 블록이 추가됩니다. 고정 노트는 자동으로 생성됩니다.", + "Today's daily note": "오늘의 데일리 노트", + "A fixed note": "고정 노트", + "Reminder note path": "알림 노트 경로", + "Vault path of the note that holds the reminder block.": + "알림 블록을 담는 노트의 볼트 경로.", + "Manage groups": "그룹 관리", + "See every habit by group and drag cards between groups.": + "그룹별로 습관을 보고 카드를 그룹 간에 드래그하세요.", + Open: "열기", + "New group": "새 그룹", + Add: "추가", + "Drag habits between groups to reassign them, or within a group to reorder them.": + "습관을 그룹 간에 드래그하여 다시 지정하거나, 그룹 안에서 드래그하여 순서를 바꾸세요.", + "No habits": "습관 없음", + "Edit group style": "그룹 스타일 편집", + "Delete group": "그룹 삭제", + 'Delete "{name}"? Its habits are kept and become ungrouped.': + '"{name}"을(를) 삭제할까요? 습관은 유지되며 그룹 없음이 됩니다.', + Delete: "삭제", + "Dashboard layout": "대시보드 레이아웃", + Carousel: "캐러셀", + Grid: "그리드", + "Vertical scroll": "세로 스크롤", + "Cards per view": "한 화면당 카드 수", + "How many habit cards fit side by side on wider screens.": + "넓은 화면에서 나란히 표시할 습관 카드 수.", + "Cards per view on mobile": "모바일 한 화면당 카드 수", + "How many habit cards fit side by side on phone-sized screens.": + "휴대폰 화면에서 나란히 표시할 습관 카드 수.", + + // Confirm dialog defaults + Cancel: "취소", + Confirm: "확인", + + // Store notices + 'Could not find the note for "{name}".': + "“{name}”의 노트를 찾을 수 없습니다.", + "Please enter a valid habit name.": "올바른 습관 이름을 입력하세요.", + 'A habit called "{name}" already exists.': + "“{name}” 습관이 이미 있습니다.", + 'Created habit "{name}".': "습관 “{name}”을(를) 만들었습니다.", + 'Updated "{name}".': "“{name}”을(를) 업데이트했습니다.", + 'Paused "{name}".': "“{name}”을(를) 일시정지했습니다.", + 'Resumed "{name}".': "“{name}”을(를) 재개했습니다.", + 'Stopped tracking "{name}". Its history is kept in the note.': + "“{name}” 추적을 중단했습니다. 기록은 노트에 보관됩니다.", + 'Resumed tracking "{name}".': "“{name}” 추적을 재개했습니다.", + 'Removed "{name}".': "“{name}”을(를) 삭제했습니다.", + "Habit added to the dashboard.": "습관을 대시보드에 추가했습니다.", + + // Dashboard + "Back to habits": "습관으로 돌아가기", + "View stats": "통계 보기", + "Export stats": "통계 내보내기", + Weekly: "주간", + Monthly: "월간", + "Previous day": "이전 날", + "Next day": "다음 날", + "Choose a date": "날짜 선택", + "Add habit": "습관 추가", + "No habits yet. Create your first habit to get started.": + "아직 습관이 없습니다. 첫 습관을 만들어 시작해 보세요.", + Previous: "이전", + Next: "다음", + "Go to position {n}": "{n}번 위치로 이동", + "Right-click or long-press for more options": + "더 많은 옵션은 우클릭 또는 길게 누르기", + "Open habit note": "습관 노트 열기", + "Open the note for {name}": "{name} 노트 열기", + Paused: "일시정지됨", + Stopped: "추적 중지됨", + "Failed": "실패", + "Skipped": "건너뜀", + "Snoozed": "다시 알림 대기", + "Snoozed until {time}": "{time}까지 다시 알림 대기", + "Undo fail": "실패 취소", + "Undo skip": "건너뛰기 취소", + "End snooze": "다시 알림 종료", + "Fail for today": "오늘은 실패로 표시", + "Fail this day": "이 날을 실패로 표시", + "Marked \"{name}\" as failed.": "\"{name}\"을(를) 실패로 표시했습니다.", + "Skip for today": "오늘은 건너뛰기", + "Skip this day": "이 날 건너뛰기", + "Skipped \"{name}\".": "\"{name}\"을(를) 건너뛰었습니다.", + "Snooze…": "다시 알림…", + "Snooze \"{name}\"": "\"{name}\" 다시 알림", + "It leaves today's lists and comes back on its own. Snoozing never counts for or against the habit.": "오늘 목록에서 사라졌다가 저절로 돌아옵니다. 다시 알림은 습관 기록에 영향을 주지 않습니다.", + "Snooze for": "다시 알림 시간", + "30 minutes": "30분", + "1 hour": "1시간", + "3 hours": "3시간", + "Snooze until": "다시 알림 종료 시각", + "Snooze": "다시 알림", + "Pick a time later today.": "오늘 이후의 시각을 선택하세요.", + "Snoozed \"{name}\" until {time}.": "\"{name}\"을(를) {time}까지 다시 알림으로 설정했습니다.", + "1 hidden for today": "오늘 1개 숨김", + "{count} hidden for today": "오늘 {count}개 숨김", + "1 hidden for this day": "이 날 1개 숨김", + "{count} hidden for this day": "이 날 {count}개 숨김", + "Undo": "실행 취소", + "Click to undo": "클릭하여 실행 취소", + "Nothing left on this day's list.": "이 날 목록에 남은 항목이 없습니다.", + "Nothing left on today's list.": "오늘 목록에 남은 항목이 없습니다.", + "At least: reach a target for habits you are building, like drinking 1.5 litres of water. At most: stay within a limit for habits you are cutting down, like no more than 2 coffees.": "이상: 만들고 싶은 습관의 목표를 달성합니다(예: 물 1.5리터 마시기). 이하: 줄이고 싶은 습관을 한도 안에서 유지합니다(예: 커피 2잔 이하).", + "At least (reach a target)": "이상 (목표 달성)", + "At most (stay within a limit)": "이하 (한도 유지)", + "Step size": "증감 단위", + "How much each + and − press adds or removes. Use a decimal such as 0.25 for amounts like litres.": "+ 와 − 를 한 번 누를 때 더하거나 빼는 양입니다. 리터 같은 양에는 0.25 같은 소수를 사용하세요.", + "Decrease by {n}": "{n}만큼 줄이기", + "4 weeks": "4주", + "12 weeks": "12주", + "6 months": "6개월", + "1 year": "1년", + "Completion rate": "달성률", + "Monthly completion rate": "월간 달성률", + "Daily activity": "일별 활동", + "Week of {date}": "{date} 주", + "Since {date} · right-click to resume": + "{date}부터 · 우클릭으로 재개", + "Paused on this day": "이 날은 일시정지됨", + "Mark as done": "완료로 표시", + "Mark as not done": "미완료로 표시", + Done: "완료", + "Not done": "미완료", + "Edit value": "값 편집", + Value: "값", + "Decrease by 1": "1 줄이기", + "Increase by 1": "1 늘리기", + "Increase by {n}": "{n} 늘리기", + "Edit habit": "습관 편집", + "Pause habit": "습관 일시정지", + "Resume habit": "습관 재개", + "Stop tracking": "추적 중단", + "Remove habit": "습관 삭제", + 'Stop tracking "{name}"? It leaves the dashboard and stats, but its note and full history are kept. You can resume tracking any time from the note\'s metrics view.': + "“{name}” 추적을 중단할까요? 대시보드와 통계에서 사라지지만 노트와 전체 기록은 보관됩니다. 노트의 지표 화면에서 언제든지 다시 시작할 수 있습니다.", + 'Remove "{name}"? Its note will be moved to the trash.': + "“{name}”을(를) 삭제할까요? 노트는 휴지통으로 이동합니다.", + Remove: "삭제", + "Perfect!": "퍼펙트!", + Today: "오늘", + Yesterday: "어제", + Tomorrow: "내일", + "Last 7 days": "지난 7일", + "Last 30 days": "지난 30일", + "This week": "이번 주", + "This month": "이번 달", + + // Sidebar panel + "Habits completed today": "오늘 완료한 습관", + "No habits yet.": "아직 습관이 없습니다.", + "Click to type a value": "클릭해서 값 입력", + "Open note": "노트 열기", + + // Stats view + "No habits to show stats for yet.": + "아직 통계를 표시할 습관이 없습니다.", + Completion: "달성률", + "Best streak": "최고 연속 기록", + "Perfect days": "퍼펙트한 날", + Completions: "달성 횟수", + "Goals met": "달성한 목표", + "{completed}/{days} days": "{completed}/{days}일", + "{total} total": "총 {total}", + best: "최고", + "perfect week": "퍼펙트한 주", + "perfect month": "퍼펙트한 달", + "weekly goal": "주간 목표", + "monthly goal": "월간 목표", + "{progress}/{goal} days · {label} · {pct}%": + "{progress}/{goal}일 · {label} · {pct}%", + + // Habit metrics block + 'Place this block inside a habit note, or point it at one with "habit: ".': + "이 블록을 습관 노트 안에 넣거나 “habit: <이름>”으로 습관을 지정하세요.", + 'No habit called "{name}" was found.': + "“{name}” 습관을 찾을 수 없습니다.", + "No longer tracked since {date}. All history is kept.": + "{date}부터 더 이상 추적하지 않습니다. 모든 기록은 보관됩니다.", + "No longer tracked. All history is kept.": + "더 이상 추적하지 않습니다. 모든 기록은 보관됩니다.", + "Resume tracking": "추적 재개", + "Paused since {date}. Paused days don't count against streaks or stats.": + "{date}부터 일시정지됨. 일시정지된 날은 연속 기록이나 통계에 영향을 주지 않습니다.", + "Paused. Paused days don't count against streaks or stats.": + "일시정지됨. 일시정지된 날은 연속 기록이나 통계에 영향을 주지 않습니다.", + "Current streak": "현재 연속 기록", + "Days completed": "완료한 일수", + "30-day rate": "30일 달성률", + "Weekly completion rate": "주간 달성률", + Logged: "기록", + Target: "목표", + + // Export modal + Title: "제목", + "Habits report": "습관 보고서", + "Date range": "기간", + "Custom range": "사용자 지정 기간", + From: "시작", + To: "끝", + "Up to {n} days.": "최대 {n}일.", + Content: "내용", + "Summary tiles": "요약 타일", + "Completion trend chart": "달성률 추이 차트", + "Daily grids": "일별 그리드", + "Goal progress": "목표 진행률", + Layout: "레이아웃", + Orientation: "방향", + Portrait: "세로", + Landscape: "가로", + Density: "밀도", + Comfortable: "여유", + Compact: "간결", + Monochrome: "흑백", + "Ink-friendly greys instead of accent colours.": + "강조 색 대신 잉크를 아끼는 회색을 사용합니다.", + "Export PDF": "PDF 내보내기", + "No habits to export yet.": + "아직 내보낼 습관이 없습니다.", + 'Exported to "{path}" in your vault.': + "보관소의 “{path}”에 내보냈습니다.", + + // Habit modal + "New habit": "새 습관", + Name: "이름", + Type: "유형", + "Binary is done or not done. Repetition counts towards a target. Timed tracks minutes.": + "이진은 완료 여부만 기록합니다. 반복은 목표 횟수를 세고, 시간은 분을 기록합니다.", + Binary: "이진", + Repetition: "반복", + Timed: "시간", + "Daily target (minutes)": "일일 목표(분)", + "Daily target": "일일 목표", + Unit: "단위", + "Optional label shown next to the count.": + "횟수 옆에 표시되는 선택적 라벨입니다.", + Icon: "아이콘", + "Choose a Lucide icon or an emoji to represent this habit.": + "이 습관을 나타낼 Lucide 아이콘이나 이모지를 선택하세요.", + Emoji: "이모지", + "Choose an emoji": "이모지 선택", + "Clear icon": "아이콘 지우기", + "Choose icon": "아이콘 선택", + "Save changes": "변경 사항 저장", + "Targets (optional)": "목표(선택)", + "Set an optional weekly or monthly goal for how many days you complete this habit. For example, hitting your daily goal on all 7 days is a weekly target of 7. Turn on a perfect toggle to aim for every day of the period automatically, whatever its length.": + "이 습관을 달성할 일수에 대한 주간 또는 월간 목표를 선택적으로 설정하세요. 예를 들어 7일 모두 일일 목표를 달성하면 주간 목표는 7입니다. 퍼펙트 토글을 켜면 기간 길이와 관계없이 자동으로 매일을 목표로 합니다.", + "Perfect week": "퍼펙트한 주", + "Aim to complete this habit every day of the week.": + "이 습관을 일주일 내내 달성하는 것을 목표로 합니다.", + "Weekly target": "주간 목표", + "Optional. Days to complete per week (max 7).": + "선택. 일주일에 달성할 일수(최대 7).", + None: "없음", + "Perfect month": "퍼펙트한 달", + "Aim to complete this habit every day of the month.": + "이 습관을 한 달 내내 달성하는 것을 목표로 합니다.", + "Monthly target": "월간 목표", + "Optional. Days to complete per month.": + "선택. 한 달에 달성할 일수.", + Colour: "색상", + "Pick a colour from your theme, or choose a custom one.": + "테마 색상 중에서 고르거나 사용자 지정 색상을 선택하세요.", + "Your habit": "나의 습관", + + // Icon and colour pickers + "Search icons…": "아이콘 검색…", + "Search emojis…": "이모지 검색…", + + // Comments + "Comments on cards": "카드 코멘트", + "Show a comment flap on dashboard cards for jotting a note about any day.": + "대시보드 카드에 코멘트 플랩을 표시해 그날에 대한 메모를 남길 수 있습니다.", + "Add comment": "코멘트 추가", + "Flip back": "앞면으로 돌리기", + "Edit comment": "코멘트 편집", + "Move day comments into note bodies": "일별 코멘트를 노트 본문으로 이동", + "No comments left to move.": "이동할 코멘트가 없습니다.", + "Moved comments in 1 note.": "노트 1개의 코멘트를 이동했습니다.", + "Moved comments in {n} notes.": "노트 {n}개의 코멘트를 이동했습니다.", + "Add a comment for this day…": "이 날에 대한 코멘트 추가…", + Comments: "코멘트", + + // Limit habits (experimental) + Experimental: "실험 기능", + "These features are still being tested and may change before they become permanent. Turning one off only hides it from menus — anything you created with it keeps working.": + "이 기능들은 아직 테스트 중이며 정식 기능이 되기 전에 바뀔 수 있습니다. 끄면 메뉴에서 숨겨질 뿐, 이미 만든 것은 계속 작동합니다.", + "Break bad habits": "나쁜 습관 끊기", + "Track habits you want to reduce or avoid by staying under a daily limit — for example at most 2 hours of gaming, or no smoking at all.": + "하루 한도 안에 머무는 방식으로 줄이거나 피하고 싶은 습관을 추적합니다. 예: 게임 하루 최대 2시간, 금연.", + Goal: "목표", + "Reach a target for habits you are building. Stay under a limit for habits you are cutting down or giving up.": + "만들고 싶은 습관은 목표를 달성하고, 줄이거나 끊고 싶은 습관은 한도 안에 머뭅니다.", + "Reach a target": "목표 달성하기", + "Stay under a limit": "한도 안에 머물기", + "Binary means avoiding it entirely. Repetition counts against a daily limit. Timed tracks minutes against a daily limit.": + "이진은 완전히 피하는 것을 뜻합니다. 반복은 하루 한도에 대해 횟수를 세고, 시간은 하루 한도에 대해 분을 기록합니다.", + "Daily limit": "일일 한도", + "Daily limit (minutes)": "일일 한도(분)", + "0 means none at all.": "0은 전혀 하지 않음을 뜻합니다.", + "Set an optional weekly or monthly goal for how many days you stay within your limit. Turn on a perfect toggle to aim for every day of the period automatically, whatever its length.": + "한도 안에 머문 일수에 대한 주간 또는 월간 목표를 선택적으로 설정하세요. 퍼펙트 토글을 켜면 기간 길이와 관계없이 자동으로 매일을 목표로 합니다.", + Clean: "클린", + Slipped: "실수", + "Mark as clean": "클린으로 표시", + "Mark as slipped": "실수로 표시", + "Days within limit": "한도 내 일수", + Limit: "한도", + + // Frequencies and per-note metrics + Frequency: "주기", + Daily: "매일", + "Days of week": "요일", + Habit: "습관", + Schedule: "일정", + "Time of day": "시간", + "Optional times this habit is planned for — once or several times a day. Shown on the habit's card.": + "이 습관을 실행할 예정 시간(선택) — 하루 한 번 또는 여러 번. 습관 카드에 표시됩니다.", + "Add time": "시간 추가", + "Remove time": "시간 제거", + "Every N days": "N일마다", + "Repeat every": "반복 주기", + "Day of month": "날짜(일)", + "The weekdays this habit is due on. Pick as many as you need.": + "이 습관이 예정된 요일입니다. 여러 개를 선택할 수 있습니다.", + "Number of days between due dates, counted from the habit's start date. Use 2 for an alternate-day schedule.": + "예정일 사이의 일수로, 습관 시작일부터 계산합니다. 격일로 하려면 2를 입력하세요.", + "The day of the month this habit is due. In shorter months it falls due on the last day, so 31 always lands on the final day of the month.": + "이 습관의 예정 일자입니다. 더 짧은 달에는 마지막 날로 넘어가므로 31은 항상 그 달의 마지막 날이 됩니다.", + "Every {day}": "매주 {day}", + "Monthly · day {day}": "매월 {day}일", + "Every other day": "격일", + "Every {n} days": "{n}일마다", + "No habits are due on this day.": + "이 날에 예정된 습관이 없습니다.", + "Nothing due today.": "오늘은 예정된 것이 없습니다.", + "Weekly activity": "주간 활동", + "Monthly activity": "월간 활동", + "Activity on due days": "예정일 활동", + "Completion rate over {n} due days": "최근 예정일 {n}회 완료율", + "Weeks completed": "완료한 주", + "Months completed": "완료한 달", + "Recent rate": "최근 달성률", + "{n}-week completion rate": "{n}주 달성률", + "{n}-month completion rate": "{n}개월 달성률", + + // AI summaries + "AI summaries": "AI 요약", + "AI summary": "AI 요약", + "Show an AI-generated summary with feedback and advice on the stats page tabs. Uses an OpenAI-compatible service you configure below; your habit stats are sent to it only when you press the generate button.": + "통계 페이지 탭에 피드백과 조언이 담긴 AI 생성 요약을 표시합니다. 아래에서 설정한 OpenAI 호환 서비스를 사용하며, 습관 통계는 생성 버튼을 눌렀을 때만 전송됩니다.", + "AI base URL": "AI 기본 URL", + "Base URL of an OpenAI-compatible API. Works with OpenAI, OpenRouter, or local servers like Ollama (http://localhost:11434/v1).": + "OpenAI 호환 API의 기본 URL입니다. OpenAI, OpenRouter 또는 Ollama(http://localhost:11434/v1) 같은 로컬 서버에서 작동합니다.", + "AI API key": "AI API 키", + "Stored locally in this vault's plugin data. Leave blank for local servers that need no key.": + "이 보관소의 플러그인 데이터에 로컬로 저장됩니다. 키가 필요 없는 로컬 서버라면 비워 두세요.", + "AI model": "AI 모델", + "Model name the service should use.": + "서비스가 사용할 모델 이름입니다.", + "Generate summary": "요약 생성", + Regenerate: "다시 생성", + "Get feedback and advice on your habits for this period. Your stats are sent to the AI service you configured only when you press the button.": + "이 기간의 습관에 대한 피드백과 조언을 받습니다. 통계는 버튼을 눌렀을 때만 설정한 AI 서비스로 전송됩니다.", + "Thinking…": "생각 중…", + "Could not generate a summary: {message}": + "요약을 생성하지 못했습니다: {message}", + "Adds an AI-generated overview with feedback and advice. Your habit stats are sent to your configured AI service.": + "피드백과 조언이 담긴 AI 생성 개요를 추가합니다. 습관 통계가 설정한 AI 서비스로 전송됩니다.", + "Generating AI summary…": "AI 요약 생성 중…", + "The AI summary will be generated when you export.": + "AI 요약은 내보낼 때 생성됩니다.", + + // Custom stats range + Custom: "사용자 지정", + "Start date": "시작일", + "End date": "종료일", + + // Heatmap start markers + "not tracked yet": "아직 기록 없음", + "started tracking on {date}": "{date}에 추적 시작", + + // Stats carousel + "Stats rows per page": "페이지당 통계 행 수", + "How many habits each stats page shows.": + "각 통계 페이지에 표시할 습관 수입니다.", + // Note habits + '"{name}" uses Templater syntax, but the Templater plugin is not installed — the template was copied as plain text.': + '"{name}"에는 Templater 문법이 사용되었지만 Templater 플러그인이 설치되어 있지 않아 서식 없는 텍스트로 복사되었습니다.', + "Binary is done or not done. Repetition counts towards a target. Timed tracks minutes. Note is completed by writing in a per-day note.": + "이진은 완료 여부만 기록합니다. 반복은 목표 횟수를 세고, 시간은 분을 기록합니다. 노트는 매일의 노트에 글을 써서 완료합니다.", + "Character count is reached": "글자 수에 도달", + "Character goal": "글자 수 목표", + "Completed when": "완료 조건", + "Every task is checked": "모든 할 일 체크", + "Filename format": "파일명 형식", + "Folder each day's note is created in. Leave blank for a dedicated subfolder named after this habit.": + "매일의 노트가 생성될 폴더입니다. 비워두면 이 습관 이름을 딴 전용 하위 폴더가 사용됩니다.", + "Moment.js format used to name each day's note, e.g. {example}. May include / for date-based subfolders.": + "매일의 노트 이름에 사용할 Moment.js 형식입니다(예: {example}). 날짜별 하위 폴더를 만들려면 /를 포함할 수 있습니다.", + Note: "노트", + "Note habits": "노트 습관", + "Notes folder": "노트 폴더", + "Open this day's note": "이 날의 노트 열기", + "Open today's note": "오늘의 노트 열기", + "Optional template note used when a day's note is created. Expanded through the Templater plugin when it is installed, otherwise copied as plain text.": + "하루의 노트를 만들 때 사용할 선택적 템플릿 노트입니다. Templater 플러그인이 설치되어 있으면 이를 통해 확장되고, 그렇지 않으면 서식 없는 텍스트로 복사됩니다.", + Template: "템플릿", + "Track a habit by writing in a per-day note instead of logging a value by hand. A day is complete once the note reaches a character count or every task in it is checked. Works with the Templater plugin to create each day's note from a template.": + "값을 직접 기록하는 대신 매일의 노트에 글을 써서 습관을 기록합니다. 노트가 글자 수에 도달하거나 모든 할 일에 체크가 되면 그날은 완료로 처리됩니다. Templater 플러그인과 연동해 템플릿으로 매일의 노트를 만들 수 있습니다.", + Write: "쓰기", + "Write this day's note": "이 날의 노트 쓰기", + "Write today's note": "오늘의 노트 쓰기", + "e.g. Journal": "예: Journal", + "e.g. Templates/Journal.md": "예: Templates/Journal.md", + + // Flexible frequency (any day) + "How many times (or, for counted and timed habits, how much in total) this needs to happen somewhere in the period.": + "이 기간 중 언제든 몇 번(횟수·시간 습관의 경우 총량) 발생해야 하는지입니다.", + 'How often this habit is due. Weekly and monthly habits only appear on their due date; the "any day" options appear every day until their quota is met.': + '이 습관의 주기입니다. 주간·월간 습관은 예정일에만 표시되지만, "요일 무관" 옵션은 목표를 채울 때까지 매일 표시됩니다.', + "Monthly (any day)": "월간 (요일 무관)", + "Times per month": "월 횟수", + "Times per week": "주 횟수", + "Weekly (any day)": "주간 (요일 무관)", + "this month": "이번 달", + "this week": "이번 주", + "{completed}/{days} months": "{completed}/{days}개월", + "{completed}/{days} weeks": "{completed}/{days}주", + "{n}× a month · any day": "월 {n}회 · 요일 무관", + "{n}× a week · any day": "주 {n}회 · 요일 무관", + + // Commands + "Insert habits heatmap": "습관 히트맵 삽입", + + // Habit metrics: heatmap tabs + Charts: "차트", + Month: "월", + History: "기록", + "{month} heatmap": "{month} 히트맵", + "Last {n} weeks": "최근 {n}주", + + // Heatmap cell states and tooltips + Upcoming: "예정", + "Not tracked yet": "아직 추적 안 됨", + "Not due": "해당 없음", + "Outside this month": "이번 달 아님", + Complete: "완료", + "Over limit": "한도 초과", + "Not logged": "기록 없음", + + // Whole-vault heatmap block + "Add a habit to see its heatmap here.": "습관을 추가하면 여기에 히트맵이 표시됩니다.", + "No habits in the \"{group}\" group.": '"{group}" 그룹에 습관이 없습니다.', + "No habits due": "예정된 습관 없음", + "Perfect day": "퍼펙트한 날", + "{completed}/{considered} habits · {pct}%": + "습관 {completed}/{considered} · {pct}%", + "This year": "올해", + "Past 6 months": "지난 6개월", + "{year} heatmap": "{year}년 히트맵", + + // Note habits: checklist requirement and fail keyword + "Both are true": "둘 다 충족", + "Checklist requirement is met": "체크리스트 요건 충족", + "Checklist requirement": "체크리스트 요건", + "Require every task to be checked, or just some — useful for a list of alternatives where doing any one of them counts (e.g. \"Cardio\" / \"Weights\" / \"Rest day\").": + '모든 할 일에 체크해야 하는지, 일부만 체크해도 되는지 정할 수 있습니다 — "유산소" / "웨이트" / "휴식일"처럼 그중 하나만 해도 되는 선택지 목록에 유용합니다.', + "At least this many are checked": "최소한 이 개수만큼 체크됨", + "Tasks required": "필요한 할 일 수", + "Fail keyword": "실패 키워드", + "Optional. Checking a task whose text contains this word forces the day to fail, whatever else is checked — e.g. \"Slipped\" as one of several checklist options. Leave blank to turn this off.": + '선택 사항입니다. 텍스트에 이 단어가 포함된 할 일에 체크하면, 다른 항목을 체크했더라도 그날은 강제로 실패 처리됩니다 — 예를 들어 여러 체크리스트 항목 중 하나로 "실패"를 넣어두는 식입니다. 비워 두면 이 기능은 꺼집니다.', + "e.g. Slipped": "예: 실패", + "Reach a character count, meet a checklist requirement, or require both.": + "글자 수 도달, 체크리스트 요건 충족, 또는 둘 다 요구하는 방식 중에서 선택할 수 있습니다.", + + // Tags (cross-plugin compatibility) + Tags: "태그", + "e.g. task": "예: task", + "Optional Obsidian tags for this note, separated by commas or spaces. Useful for making this habit recognisable to another plugin's own tag-based rules — for example TaskNotes' task tag.": + "이 노트에 대한 선택적 Obsidian 태그입니다. 쉼표나 공백으로 구분합니다. 다른 플러그인의 태그 기반 규칙이 이 습관을 인식하게 하는 데 유용합니다 — 예를 들어 TaskNotes의 task 태그입니다.", + + // Advanced settings: frontmatter key remapping + Advanced: "고급", + Apply: "적용", + "Apply key changes": "키 변경 적용", + "Rename the frontmatter properties habit notes use. Useful for avoiding collisions with another plugin's own properties in the same note (for example TaskNotes).": + "습관 노트가 사용하는 프런트매터 속성 이름을 바꿉니다. 같은 노트에서 다른 플러그인(예: TaskNotes) 고유의 속성과 충돌하는 것을 피할 때 유용합니다.", + "\"{a}\" and \"{b}\" can't use the same property key (\"{value}\").": + '"{a}"와 "{b}"는 같은 속성 키("{value}")를 사용할 수 없습니다.', + "Property keys can't be empty.": "속성 키는 비워 둘 수 없습니다.", + "This renames {summary} in every note in your habits folder ({count} habit(s) currently). Existing values are moved, not discarded. Continue?": + "이 작업은 습관 폴더에 있는 모든 노트(현재 {count}개 습관)에서 {summary}의 이름을 바꿉니다. 기존 값은 삭제되지 않고 이동됩니다. 계속할까요?", + "Updated the frontmatter keys in {count} note(s).": + "{count}개 노트에서 프런트매터 키를 업데이트했습니다.", + "Renaming this away from the default also changes how binary habits log a day: instead of {\"2026-08-25\": 1}, a completed day becomes a bare date, like [\"2026-08-25\"] — the shape TaskNotes uses for complete_instances. Repetition and timed habits are unaffected either way; they always need a value, never just a date.": + '이 키를 기본값에서 다른 이름으로 바꾸면 이진 습관이 하루를 기록하는 방식도 달라집니다. {"2026-08-25": 1} 대신, 완료한 날은 ["2026-08-25"]처럼 단순한 날짜가 됩니다 — 이는 TaskNotes가 complete_instances에 사용하는 형식입니다. 반복 및 시간 습관은 어느 경우든 영향을 받지 않습니다. 항상 값이 필요하며, 날짜만으로는 안 됩니다.', + Identity: "식별 정보", + Legacy: "레거시", + Lifecycle: "라이프사이클", + Presentation: "표시", + "Note habit": "노트 습관", + "Habit type key": "습관 유형 키", + "Completion records key": "완료 기록 키", + "Frequency key": "빈도 키", + "Weekday key": "요일 키", + "Month day key": "월중 날짜 키", + "Interval days key": "간격 일수 키", + "Planned time key": "예정 시간 키", + "Goal direction key": "목표 방향 키", + "Target key": "목표 키", + "Unit key": "단위 키", + "Step size key": "증감 단위 키", + "Weekly target key": "주간 목표 키", + "Monthly target key": "월간 목표 키", + "Weekly perfect key": "퍼펙트 주 키", + "Monthly perfect key": "퍼펙트 달 키", + "Start date key": "시작일 키", + "Pauses key": "일시중지 기록 키", + "Stopped key": "중단 상태 키", + "Stop date key": "중단일 키", + "Icon key": "아이콘 키", + "Color key": "색상 키", + "Group key": "그룹 키", + "Use group color key": "그룹 색상 사용 키", + "Note folder key": "노트 폴더 키", + "Note filename format key": "노트 파일명 형식 키", + "Template path key": "템플릿 경로 키", + "Note completion mode key": "노트 완료 모드 키", + "Note checklist requirement key": "노트 체크리스트 요건 키", + "Note checklist minimum key": "노트 체크리스트 최소 개수 키", + "Note fail keyword key": "노트 실패 키워드 키", + "Legacy comments key": "이전 코멘트 키", + + // PDF export (read via docT() in export-modal.ts, which falls back to English for zh — jsPDF's built-in fonts can't render CJK) + "Completion trend": "달성률 추이", + "(paused)": "(일시정지됨)", + "{rate}% · {total} · streak {current} (best {best})": + "{rate}% · {total} · 연속 {current} (최고 {best})", + "Goal: {completed}/{goal} days met": + "목표: {completed}/{goal}일 달성", + "{range} · exported {date}": "{range} · {date} 내보냄", + "+{n} more": "+{n}개 더", + + // Back-dating a missed day + Back: "뒤로", + + // Rescheduling missed habits (experimental) + "1 missed habit": "놓친 습관 1개", + "Add a notification button to the dashboard and sidebar panel when a habit's been missed, opening a review of missed days you can move onto a different one (never a day that habit is already due, so nothing doubles up).": + "습관을 놓쳤을 때 대시보드와 사이드바 패널에 알림 버튼을 추가합니다. 놓친 날을 검토하고 다른 날로 옮길 수 있습니다(그 습관이 원래 예정된 날로는 옮길 수 없어 중복 기록이 생기지 않습니다).", + "Missed habits": "놓친 습관", + "Move this missed day onto a different one": "이 놓친 날을 다른 날로 옮기기", + "Move to": "옮길 날짜", + "Nothing missed right now.": "지금은 놓친 것이 없습니다.", + "Pick a habit to move it onto a different day.": "다른 날로 옮길 습관을 선택하세요.", + Reschedule: "일정 변경", + "Reschedule missed habits": "놓친 습관 일정 변경", + "Rescheduled \"{name}\" to {date}.": '"{name}"의 일정을 {date}(으)로 변경했습니다.', + "Rescheduled from {date}": "{date}에서 일정 변경됨", + "Reschedules key": "일정 변경 키", + "Failed days key": "실패한 날 키", + "Skipped days key": "건너뛴 날 키", + "Rescheduling \"{name}\" — missed {date}.": + '"{name}" 일정 변경 중 — {date}에 놓쳤습니다.', + "That day no longer works — pick another.": + "그 날짜는 더 이상 사용할 수 없습니다 — 다른 날짜를 선택하세요.", + "That day won't work — it's either already due for this habit or already claimed by another reschedule.": + "그 날짜는 안 됩니다 — 이미 그 습관이 그 날짜에 예정되어 있거나, 다른 일정 변경에서 이미 사용 중입니다.", + "{count} missed habits": "놓친 습관 {count}개", +}; diff --git a/src/integrations/habits/i18n/zh.ts b/src/integrations/habits/i18n/zh.ts new file mode 100644 index 000000000..b4c02a8ea --- /dev/null +++ b/src/integrations/habits/i18n/zh.ts @@ -0,0 +1,699 @@ +/** Simplified Chinese translations, keyed by the English source string. */ +export const zh: Record = { + "Check-in window": "签到窗口", + "You can complete this habit on any of these days in each interval. Missed windows do not shift the next fixed cycle.": "每个周期中的任意一天都可完成;错过窗口不会改变下一个固定周期。", + "Restart cycle from today": "从今天重新开始周期", + "Keep past records and start a new interval cycle today.": "保留过去的记录,从今天开始新的间隔周期。", + "Interval window days key": "间隔签到窗口天数属性名", + "Interval schedule key": "间隔排期方式属性名", + "This note is managed by Task Genius.": "此笔记由 Task Genius 管理。", + // Commands and ribbon + "Create habit": "创建习惯", + "Insert dashboard": "插入习惯面板", + "Insert habit metrics": "插入习惯指标", + "Insert habits table": "插入习惯表格", + "Open panel": "打开侧边栏面板", + "Open habits panel": "打开习惯侧边栏", + Habits: "习惯", + + // Settings + "Habits folder": "习惯文件夹", + "Folder where each habit is stored as its own note. It is created automatically if it does not exist.": + "每个习惯都以独立笔记的形式存放在此文件夹中。如果不存在会自动创建。", + "Follow daily note date": "跟随日记日期", + "When a dashboard is embedded in a daily note (a note whose name contains a date like 2026-07-01), open it on that note's date instead of today.": + "当习惯面板嵌入到日记中(笔记名称包含类似 2026-07-01 的日期)时,面板会显示该笔记日期的记录,而不是今天。", + "Daily note date format": "日记日期格式", + "Moment.js format used to read the date from a daily note's name, such as YYYY-MM-DD or YYYYMMDD.": + "用于从日记名称中读取日期的 Moment.js 格式,例如 YYYY-MM-DD 或 YYYYMMDD。", + + // Sorting + "Sort habits by": "习惯排序方式", + "The base order of habit cards in the dashboard and side panel.": + "仪表盘和侧边面板中习惯卡片的基本顺序。", + "Name (A–Z)": "名称(A–Z)", + Color: "颜色", + "Last logged": "最近记录", + "Planned time": "计划时间", + Manual: "手动", + "Manual order": "手动排序", + "Drag the cards into the order you want. New habits join the end of the list.": + "拖动卡片调整顺序。新习惯会添加到列表末尾。", + "Move completed cards to the end": "将已完成的卡片移到末尾", + "Completed habits drift to the end of the queue and paused ones park behind them. Turn this off to keep every card in its sorted position.": + "已完成的习惯会移到队列末尾,暂停的习惯排在其后。关闭后,所有卡片保持排序位置不变。", + Group: "分组", + Ungrouped: "未分组", + "Optional group used to build dashboard sections — for example an area of responsibility.": + "用于在仪表盘中创建分区的可选分组 — 例如某个职责领域。", + "e.g. Health": "例如:健康", + "Group color": "分组颜色", + "Optional color shared by every habit in this group.": "该分组中所有习惯共享的可选颜色。", + "Group icon": "分组图标", + "Shown in the group lip on cards and in section headers.": + "显示在卡片的分组条和分区标题中。", + "Use group color for this card": "此卡片使用分组颜色", + "Show this card in the group color instead of its own.": + "以分组颜色而非自身颜色显示此卡片。", + General: "常规", + Sorting: "排序", + Groups: "分组", + "How to move through your habit cards: a paged carousel with arrows, a grid that wraps onto new rows, or a fixed-height grid that scrolls vertically. The stats page follows the same choice.": + "浏览习惯卡片的方式:带箭头的分页轮播、自动换行的网格,或固定高度、垂直滚动的网格。统计页面遵循相同设置。", + "Enable groups": "启用分组", + "Show habits in sections by their group, with a group lip on each card.": + "按分组分区显示习惯,并在每张卡片上显示分组条。", + "Group order": "分组顺序", + "Drag the groups into the order you want. Sections follow the same order.": + "拖动分组以调整顺序。分区遵循相同顺序。", + "Completion animations": "完成动画", + "Play the check swoosh, card departure, and perfect-day confetti when habits are completed. Turn off for instant, quiet updates.": + "完成习惯时播放对勾划入、卡片退场和完美一天的彩纸动画。关闭后立即静默更新。", + "Reminders": "提醒", + "Write reminders for due habits": "为当日应做的习惯写入提醒", + "Each day, write one reminder checklist line per planned time of every habit due that day, in the format the Reminder plugin picks up. The lines live in a marked block and refresh as you log habits.": + "每天为当日应做的每个习惯的每个计划时间写入一行提醒清单,格式可被 Reminder 插件识别。这些行位于带标记的块中,并随打卡自动刷新。", + "Where to write reminders": "提醒写入位置", + "The daily note follows the Daily notes core plugin's folder and date format; the block is added once the note exists. A fixed note is created automatically.": + "每日笔记遵循核心“每日笔记”插件的文件夹和日期格式;笔记存在后即会添加该块。固定笔记会自动创建。", + "Today's daily note": "今天的每日笔记", + "A fixed note": "固定笔记", + "Reminder note path": "提醒笔记路径", + "Vault path of the note that holds the reminder block.": "存放提醒块的笔记在库中的路径。", + "Manage groups": "管理分组", + "See every habit by group and drag cards between groups.": + "按分组查看所有习惯,并在分组间拖动卡片。", + Open: "打开", + "New group": "新建分组", + Add: "添加", + "Drag habits between groups to reassign them, or within a group to reorder them.": + "在分组之间拖动习惯以重新分配,或在分组内拖动以调整顺序。", + "No habits": "没有习惯", + "Edit group style": "编辑分组样式", + "Delete group": "删除分组", + 'Delete "{name}"? Its habits are kept and become ungrouped.': + "删除“{name}”?其习惯将保留并变为未分组。", + Delete: "删除", + "Dashboard layout": "仪表盘布局", + Carousel: "轮播", + Grid: "网格", + "Vertical scroll": "垂直滚动", + "Cards per view": "每页卡片数", + "How many habit cards fit side by side on wider screens.": + "宽屏上并排显示多少张习惯卡片。", + "Cards per view on mobile": "移动端每页卡片数", + "How many habit cards fit side by side on phone-sized screens.": + "手机屏幕上并排显示多少张习惯卡片。", + + // Confirm dialog defaults + Cancel: "取消", + Confirm: "确认", + + // Store notices + 'Could not find the note for "{name}".': "找不到“{name}”的笔记。", + "Please enter a valid habit name.": "请输入有效的习惯名称。", + 'A habit called "{name}" already exists.': + "名为“{name}”的习惯已存在。", + 'Created habit "{name}".': "已创建习惯“{name}”。", + 'Updated "{name}".': "已更新“{name}”。", + 'Paused "{name}".': "已暂停“{name}”。", + 'Resumed "{name}".': "已恢复“{name}”。", + 'Stopped tracking "{name}". Its history is kept in the note.': + "已停止跟踪“{name}”。其历史记录保留在笔记中。", + 'Resumed tracking "{name}".': "已恢复跟踪“{name}”。", + 'Removed "{name}".': "已删除“{name}”。", + "Habit added to the dashboard.": "习惯已添加到面板。", + + // Dashboard + "Back to habits": "返回习惯", + "View stats": "查看统计", + "Export stats": "导出统计", + Weekly: "每周", + Monthly: "每月", + "Previous day": "前一天", + "Next day": "后一天", + "Choose a date": "选择日期", + "Add habit": "添加习惯", + "No habits yet. Create your first habit to get started.": + "还没有习惯。创建你的第一个习惯开始吧。", + Previous: "上一页", + Next: "下一页", + "Go to position {n}": "跳到第 {n} 页", + "Right-click or long-press for more options": + "右键或长按查看更多选项", + "Open habit note": "打开习惯笔记", + "Open the note for {name}": "打开 {name} 的笔记", + Paused: "已暂停", + Stopped: "已停止追踪", + "Failed": "已失败", + "Skipped": "已跳过", + "Snoozed": "已暂缓", + "Snoozed until {time}": "暂缓至 {time}", + "Undo fail": "撤销失败", + "Undo skip": "撤销跳过", + "End snooze": "结束暂缓", + "Fail for today": "今天标记为失败", + "Fail this day": "将这一天标记为失败", + "Marked \"{name}\" as failed.": "已将“{name}”标记为失败。", + "Skip for today": "今天跳过", + "Skip this day": "跳过这一天", + "Skipped \"{name}\".": "已跳过“{name}”。", + "Snooze…": "暂缓…", + "Snooze \"{name}\"": "暂缓“{name}”", + "It leaves today's lists and comes back on its own. Snoozing never counts for or against the habit.": "它会离开今天的列表并在到时后自动回来。暂缓不会计入习惯的成功或失败。", + "Snooze for": "暂缓时长", + "30 minutes": "30 分钟", + "1 hour": "1 小时", + "3 hours": "3 小时", + "Snooze until": "暂缓至", + "Snooze": "暂缓", + "Pick a time later today.": "请选择今天稍后的时间。", + "Snoozed \"{name}\" until {time}.": "已将“{name}”暂缓至 {time}。", + "1 hidden for today": "今天隐藏了 1 个", + "{count} hidden for today": "今天隐藏了 {count} 个", + "1 hidden for this day": "这一天隐藏了 1 个", + "{count} hidden for this day": "这一天隐藏了 {count} 个", + "Undo": "撤销", + "Click to undo": "点击撤销", + "Nothing left on this day's list.": "这一天的列表已清空。", + "Nothing left on today's list.": "今天的列表已清空。", + "At least: reach a target for habits you are building, like drinking 1.5 litres of water. At most: stay within a limit for habits you are cutting down, like no more than 2 coffees.": "至少:为正在养成的习惯达成目标,例如喝 1.5 升水。至多:为正在减少的习惯保持在限额内,例如不超过 2 杯咖啡。", + "At least (reach a target)": "至少(达成目标)", + "At most (stay within a limit)": "至多(不超过限额)", + "Step size": "步长", + "How much each + and − press adds or removes. Use a decimal such as 0.25 for amounts like litres.": "每次按 + 或 − 增加或减少的数量。对于升等数量,可使用 0.25 这样的小数。", + "Decrease by {n}": "减少 {n}", + "4 weeks": "4 周", + "12 weeks": "12 周", + "6 months": "6 个月", + "1 year": "1 年", + "Completion rate": "完成率", + "Monthly completion rate": "每月完成率", + "Daily activity": "每日活动", + "Week of {date}": "{date} 当周", + "Since {date} · right-click to resume": + "自 {date} 起 · 右键恢复", + "Paused on this day": "当天已暂停", + "Mark as done": "标记为已完成", + "Mark as not done": "标记为未完成", + Done: "已完成", + "Not done": "未完成", + "Edit value": "编辑数值", + Value: "数值", + "Decrease by 1": "减少 1", + "Compact list": "紧凑列表", + "Choose a carousel, grid, vertical scroll, or compact list for your habits dashboard.": "选择轮播、网格、垂直滚动或紧凑列表作为习惯仪表盘样式。", + "Could not save habit record.": "无法保存习惯记录。", + "Increase by 1": "增加 1", + "Increase by {n}": "增加 {n}", + "Edit habit": "编辑习惯", + "Pause habit": "暂停习惯", + "Resume habit": "恢复习惯", + "Stop tracking": "停止跟踪", + "Stop habit": "停止习惯", + "Remove habit": "删除习惯", + 'Stop tracking "{name}"? It leaves the dashboard and stats, but its note and full history are kept. You can resume tracking any time from the note\'s metrics view.': + "停止跟踪“{name}”?它将从面板和统计中移除,但其笔记和全部历史记录会保留。你随时可以在笔记的指标视图中恢复跟踪。", + 'Remove "{name}"? Its note will be moved to the trash.': + "删除“{name}”?其笔记将被移入回收站。", + Remove: "删除", + "Perfect!": "完美!", + Today: "今天", + Yesterday: "昨天", + Tomorrow: "明天", + "Last 7 days": "最近 7 天", + "Last 30 days": "最近 30 天", + "This week": "本周", + "This month": "本月", + + // Sidebar panel + "Habits completed today": "今日已完成的习惯", + "No habits yet.": "还没有习惯。", + "Click to type a value": "点击输入数值", + "Open note": "打开笔记", + + // Stats view + "No habits to show stats for yet.": "还没有可统计的习惯。", + Completion: "完成率", + "Best streak": "最长连击", + "Perfect days": "完美天数", + Completions: "完成次数", + "Goals met": "达成目标", + "{completed}/{days} days": "{completed}/{days} 天", + "{total} total": "共 {total}", + best: "最佳", + "perfect week": "完美一周", + "perfect month": "完美一月", + "weekly goal": "周目标", + "monthly goal": "月目标", + "{progress}/{goal} days · {label} · {pct}%": + "{progress}/{goal} 天 · {label} · {pct}%", + + // Habit metrics block + 'Place this block inside a habit note, or point it at one with "habit: ".': + "请将此代码块放入习惯笔记中,或用“habit: <名称>”指定一个习惯。", + 'No habit called "{name}" was found.': "找不到名为“{name}”的习惯。", + "No longer tracked since {date}. All history is kept.": + "自 {date} 起已停止跟踪。所有历史记录均已保留。", + "No longer tracked. All history is kept.": + "已停止跟踪。所有历史记录均已保留。", + "Resume tracking": "恢复跟踪", + "Paused since {date}. Paused days don't count against streaks or stats.": + "自 {date} 起暂停。暂停的日子不会影响连击或统计。", + "Paused. Paused days don't count against streaks or stats.": + "已暂停。暂停的日子不会影响连击或统计。", + "Current streak": "当前连击", + "Days completed": "完成天数", + "30-day rate": "30 天完成率", + "Weekly completion rate": "每周完成率", + Logged: "已记录", + Target: "目标", + + // Export modal + Title: "标题", + "Habits report": "习惯报告", + "Date range": "日期范围", + "Custom range": "自定义范围", + From: "从", + To: "到", + "Up to {n} days.": "最多 {n} 天。", + Content: "内容", + "Summary tiles": "摘要卡片", + "Completion trend chart": "完成趋势图", + "Daily grids": "每日网格", + "Goal progress": "目标进度", + Layout: "布局", + Orientation: "方向", + Portrait: "纵向", + Landscape: "横向", + Density: "密度", + Comfortable: "宽松", + Compact: "紧凑", + Monochrome: "黑白", + "Ink-friendly greys instead of accent colours.": + "使用省墨的灰色代替强调色。", + "Export PDF": "导出 PDF", + "No habits to export yet.": "还没有可导出的习惯。", + 'Exported to "{path}" in your vault.': + "已导出到仓库中的“{path}”。", + + // Habit modal + "New habit": "新习惯", + Name: "名称", + Type: "类型", + "Binary is done or not done. Repetition counts towards a target. Timed tracks minutes.": + "二元型:完成或未完成。重复型:向目标计数。计时型:记录分钟数。", + Binary: "二元", + Repetition: "重复", + Timed: "计时", + "Daily target (minutes)": "每日目标(分钟)", + "Daily target": "每日目标", + Unit: "单位", + "Optional label shown next to the count.": + "显示在计数旁边的可选标签。", + Icon: "图标", + "Choose a Lucide icon or an emoji to represent this habit.": + "选择一个 Lucide 图标或 emoji 来代表这个习惯。", + Emoji: "表情符号", + "Choose an emoji": "选择表情符号", + "Clear icon": "清除图标", + "Choose icon": "选择图标", + "Save changes": "保存更改", + "Targets (optional)": "目标(可选)", + "Set an optional weekly or monthly goal for how many days you complete this habit. For example, hitting your daily goal on all 7 days is a weekly target of 7. Turn on a perfect toggle to aim for every day of the period automatically, whatever its length.": + "设置可选的每周或每月目标,规定完成该习惯的天数。例如,7 天全部达成每日目标即为周目标 7。开启“完美”开关可自动以该周期的每一天为目标,无论周期多长。", + "Perfect week": "完美一周", + "Aim to complete this habit every day of the week.": + "力争一周中的每一天都完成这个习惯。", + "Weekly target": "周目标", + "Optional. Days to complete per week (max 7).": + "可选。每周需完成的天数(最多 7 天)。", + None: "无", + "Perfect month": "完美一月", + "Aim to complete this habit every day of the month.": + "力争一个月中的每一天都完成这个习惯。", + "Monthly target": "月目标", + "Optional. Days to complete per month.": + "可选。每月需完成的天数。", + Colour: "颜色", + "Pick a colour from your theme, or choose a custom one.": + "从主题中选择颜色,或自定义一个。", + "Your habit": "你的习惯", + + // Icon and colour pickers + "Search icons…": "搜索图标…", + "Search emojis…": "搜索表情符号…", + + // Comments + "Comments on cards": "卡片评论", + "Show a comment flap on dashboard cards for jotting a note about any day.": + "在面板卡片上显示评论翻页,可为任意一天记录备注。", + "Add comment": "添加评论", + "Flip back": "翻回正面", + "Edit comment": "编辑评论", + "Move day comments into note bodies": "将每日评论移入笔记正文", + "No comments left to move.": "没有需要移动的评论。", + "Moved comments in 1 note.": "已移动 1 篇笔记中的评论。", + "Moved comments in {n} notes.": "已移动 {n} 篇笔记中的评论。", + "Add a comment for this day…": "为这一天添加评论…", + Comments: "评论", + + // Limit habits (experimental) + Experimental: "实验性功能", + "These features are still being tested and may change before they become permanent. Turning one off only hides it from menus — anything you created with it keeps working.": + "这些功能仍在测试中,在正式发布前可能会有变化。关闭某项功能只会将其从菜单中隐藏——你用它创建的内容会继续正常工作。", + "Break bad habits": "戒除坏习惯", + "Track habits you want to reduce or avoid by staying under a daily limit — for example at most 2 hours of gaming, or no smoking at all.": + "通过保持在每日限额以下来跟踪你想减少或戒除的习惯——例如每天最多玩 2 小时游戏,或完全不吸烟。", + Goal: "目标", + "Reach a target for habits you are building. Stay under a limit for habits you are cutting down or giving up.": + "要养成的习惯选择达成目标。要减少或戒除的习惯选择保持在限额以下。", + "Reach a target": "达成目标", + "Stay under a limit": "保持在限额以下", + "Binary means avoiding it entirely. Repetition counts against a daily limit. Timed tracks minutes against a daily limit.": + "二元表示完全避免。重复按每日限额计数。计时按每日限额记录分钟数。", + "Daily limit": "每日限额", + "Weekly limit": "每周限额", + "Weekly total limit · any day": "每周累计限额 · 任意日期", + "Monthly total limit · any day": "每月累计限额 · 任意日期", + "Monthly limit": "每月限额", + "Limit per due day": "每个计划日的限额", + "Limit in minutes. 0 means none at all.": "限额以分钟计,0 表示完全不允许。", + "Choose the days this limit applies, or a weekly/monthly total limit that can be logged on any day.": "选择限制适用的日期,或选择可在任意日期记录的每周/每月累计限额。", + "Binary means avoiding it entirely. Repetition counts against a limit. Timed tracks minutes against a limit. Frequency determines when the limit applies.": "二元类型表示完全避免;计数和计时类型分别按次数和分钟判断是否超限。频率决定限制适用的日期或周期。", + "Daily limit (minutes)": "每日限额(分钟)", + "0 means none at all.": "0 表示完全不做。", + "Set an optional weekly or monthly goal for how many days you stay within your limit. Turn on a perfect toggle to aim for every day of the period automatically, whatever its length.": + "设置一个可选的每周或每月目标,即有多少天保持在限额以内。打开完美开关即可自动以该时段的每一天为目标,无论其长短。", + Clean: "未破戒", + Slipped: "破戒", + "Mark as clean": "标记为未破戒", + "Mark as slipped": "标记为破戒", + "Days within limit": "限额内天数", + Limit: "限额", + + // Frequencies and per-note metrics + Frequency: "频率", + Daily: "每天", + "Days of week": "星期几", + Habit: "习惯", + Schedule: "计划", + "Time of day": "时间", + "Optional times this habit is planned for — once or several times a day. Shown on the habit's card.": + "此习惯计划进行的时间(可选)——每天一次或多次。显示在习惯卡片上。", + "Add time": "添加时间", + "Remove time": "移除时间", + "Every N days": "每 N 天", + "Repeat every": "重复间隔", + "Day of month": "每月日期", + "The weekdays this habit is due on. Pick as many as you need.": + "此习惯到期的星期几。可选择多个。", + "Number of days between due dates, counted from the habit's start date. Use 2 for an alternate-day schedule.": + "两次到期之间的天数,从习惯的开始日期算起。填 2 表示隔天一次。", + "The day of the month this habit is due. In shorter months it falls due on the last day, so 31 always lands on the final day of the month.": + "此习惯每月的到期日。在较短的月份中落在最后一天,因此 31 总是落在当月最后一天。", + "Every {day}": "每{day}", + "Monthly · day {day}": "每月 · 第 {day} 天", + "Every other day": "隔天一次", + "Every {n} days": "每 {n} 天", + "No habits are due on this day.": "这一天没有到期的习惯。", + "Nothing due today.": "今天没有到期的习惯。", + "Weekly activity": "每周活动", + "Monthly activity": "每月活动", + "Activity on due days": "到期日活动", + "Completion rate over {n} due days": "最近 {n} 个到期日的完成率", + "Weeks completed": "已完成周数", + "Months completed": "已完成月数", + "Recent rate": "近期完成率", + "{n}-week completion rate": "{n} 周完成率", + "{n}-month completion rate": "{n} 个月完成率", + + // AI summaries + "AI summaries": "AI 摘要", + "AI summary": "AI 摘要", + "Show an AI-generated summary with feedback and advice on the stats page tabs. Uses an OpenAI-compatible service you configure below; your habit stats are sent to it only when you press the generate button.": + "在统计页的标签页中显示由 AI 生成的摘要,包含反馈和建议。使用下方配置的 OpenAI 兼容服务;只有按下生成按钮时,习惯统计数据才会发送给它。", + "AI base URL": "AI 基础 URL", + "Base URL of an OpenAI-compatible API. Works with OpenAI, OpenRouter, or local servers like Ollama (http://localhost:11434/v1).": + "OpenAI 兼容 API 的基础 URL。适用于 OpenAI、OpenRouter 或本地服务器(如 Ollama:http://localhost:11434/v1)。", + "AI API key": "AI API 密钥", + "Stored locally in this vault's plugin data. Leave blank for local servers that need no key.": + "保存在此仓库的插件数据中(仅限本地)。本地服务器无需密钥时可留空。", + "AI model": "AI 模型", + "Model name the service should use.": "服务应使用的模型名称。", + "Generate summary": "生成摘要", + Regenerate: "重新生成", + "Get feedback and advice on your habits for this period. Your stats are sent to the AI service you configured only when you press the button.": + "获取本时段习惯的反馈和建议。只有按下按钮时,统计数据才会发送到所配置的 AI 服务。", + "Thinking…": "思考中…", + "Could not generate a summary: {message}": "无法生成摘要:{message}", + "Adds an AI-generated overview with feedback and advice. Your habit stats are sent to your configured AI service.": + "添加由 AI 生成的概览,包含反馈和建议。习惯统计数据会发送到所配置的 AI 服务。", + "Generating AI summary…": "正在生成 AI 摘要…", + "The AI summary will be generated when you export.": + "导出时将生成 AI 摘要。", + + // Custom stats range + Custom: "自定义", + "Start date": "开始日期", + "End date": "结束日期", + + // Heatmap start markers + "not tracked yet": "尚未跟踪", + "started tracking on {date}": "自 {date} 开始跟踪", + + // Stats carousel + "Stats rows per page": "每页统计行数", + "How many habits each stats page shows.": "每页统计显示多少个习惯。", + // Note habits + '"{name}" uses Templater syntax, but the Templater plugin is not installed — the template was copied as plain text.': + '"{name}" 使用了 Templater 语法,但未安装 Templater 插件——模板已作为纯文本复制。', + "Binary is done or not done. Repetition counts towards a target. Timed tracks minutes. Note is completed by writing in a per-day note.": + "二元型:完成或未完成。重复型:向目标计数。计时型:记录分钟数。笔记型:通过在每日笔记中写作来完成。", + "Character count is reached": "达到字数", + "Character goal": "字数目标", + "Completed when": "完成条件", + "Every task is checked": "勾选所有任务", + "Filename format": "文件名格式", + "Folder each day's note is created in. Leave blank for a dedicated subfolder named after this habit.": + "每日笔记的创建文件夹。留空则使用以此习惯命名的专用子文件夹。", + "Moment.js format used to name each day's note, e.g. {example}. May include / for date-based subfolders.": + "用于命名每日笔记的 Moment.js 格式,例如 {example}。可包含 / 以创建按日期划分的子文件夹。", + Note: "笔记", + "Note habits": "笔记习惯", + "Notes folder": "笔记文件夹", + "Open this day's note": "打开这一天的笔记", + "Open today's note": "打开今天的笔记", + "Optional template note used when a day's note is created. Expanded through the Templater plugin when it is installed, otherwise copied as plain text.": + "创建每日笔记时使用的可选模板笔记。安装 Templater 插件后会展开其语法,否则将作为纯文本复制。", + Template: "模板", + "Track a habit by writing in a per-day note instead of logging a value by hand. A day is complete once the note reaches a character count or every task in it is checked. Works with the Templater plugin to create each day's note from a template.": + "通过在每日笔记中写作来追踪习惯,而不是手动记录数值。当笔记达到字数或其中所有任务都被勾选时,这一天即算完成。可与 Templater 插件配合,从模板创建每日笔记。", + Write: "写作", + "Write this day's note": "写这一天的笔记", + "Write today's note": "写今天的笔记", + "e.g. Journal": "例如:日记", + "e.g. Templates/Journal.md": "例如:Templates/Journal.md", + + // Flexible frequency (any day) + "How many times (or, for counted and timed habits, how much in total) this needs to happen somewhere in the period.": + "需要在该周期内的某个时刻发生多少次(对于计数型或计时型习惯,则是总量)。", + 'How often this habit is due. Weekly and monthly habits only appear on their due date; the "any day" options appear every day until their quota is met.': + '此习惯的到期频率。每周和每月习惯只在到期日显示;"任意日"选项每天都会显示,直到达到配额。', + "Monthly (any day)": "每月(任意日)", + "Times per month": "每月次数", + "Times per week": "每周次数", + "Weekly (any day)": "每周(任意日)", + "this month": "本月", + "this week": "本周", + "{completed}/{days} months": "{completed}/{days} 个月", + "{completed}/{days} weeks": "{completed}/{days} 周", + "{n}× a month · any day": "每月 {n} 次 · 任意日", + "{n}× a week · any day": "每周 {n} 次 · 任意日", + + // Commands + "Insert habits heatmap": "插入习惯热力图", + + // Habit metrics: heatmap tabs + Charts: "图表", + Month: "月", + History: "历史", + "{month} heatmap": "{month}热力图", + "Last {n} weeks": "最近 {n} 周", + + // Heatmap cell states and tooltips + Upcoming: "未到", + "Not tracked yet": "尚未开始记录", + "Not due": "不适用", + "Outside this month": "不在本月内", + Complete: "已完成", + "Over limit": "超出限制", + "Not logged": "未记录", + + // Whole-vault heatmap block + "Add a habit to see its heatmap here.": "添加一个习惯即可在此查看其热力图。", + "No habits in the \"{group}\" group.": "“{group}”分组中没有习惯。", + "No habits due": "当天没有到期习惯", + "Perfect day": "完美的一天", + "{completed}/{considered} habits · {pct}%": + "{completed}/{considered} 个习惯 · {pct}%", + "This year": "今年", + "Past 6 months": "过去 6 个月", + "{year} heatmap": "{year} 年热力图", + + // Note habits: checklist requirement and fail keyword + "Both are true": "两者均满足", + "Checklist requirement is met": "满足清单要求", + "Checklist requirement": "清单要求", + "Require every task to be checked, or just some — useful for a list of alternatives where doing any one of them counts (e.g. \"Cardio\" / \"Weights\" / \"Rest day\").": + "要求勾选所有任务,或只需勾选其中一部分——适用于一组可任选其一即可的备选项(例如“有氧”/“力量训练”/“休息日”)。", + "At least this many are checked": "至少勾选这么多项", + "Tasks required": "所需任务数", + "Fail keyword": "失败关键词", + "Optional. Checking a task whose text contains this word forces the day to fail, whatever else is checked — e.g. \"Slipped\" as one of several checklist options. Leave blank to turn this off.": + "可选。勾选文本中包含该词的任务,会强制当天判定为失败,无论其他项是否勾选——例如把“破功”设为清单中的一个选项。留空可关闭此功能。", + "e.g. Slipped": "例如:破功", + "Reach a character count, meet a checklist requirement, or require both.": + "达到字数目标、满足清单要求,或两者都要求。", + + // Tags (cross-plugin compatibility) + Tags: "标签", + "e.g. task": "例如:task", + "Optional Obsidian tags for this note, separated by commas or spaces. Useful for making this habit recognisable to another plugin's own tag-based rules — for example TaskNotes' task tag.": + "此笔记的可选 Obsidian 标签,用逗号或空格分隔。可用于让其他插件通过自己基于标签的规则识别这个习惯——例如 TaskNotes 的 task 标签。", + + // Advanced settings: frontmatter key remapping + Advanced: "高级", + Apply: "应用", + "Apply key changes": "应用键更改", + "Rename the frontmatter properties habit notes use. Useful for avoiding collisions with another plugin's own properties in the same note (for example TaskNotes).": + "重命名习惯笔记使用的 frontmatter 属性。可用于避免与同一笔记中另一个插件自身属性发生冲突(例如 TaskNotes)。", + "\"{a}\" and \"{b}\" can't use the same property key (\"{value}\").": + "“{a}”和“{b}”不能使用相同的属性键(“{value}”)。", + "Property keys can't be empty.": "属性键不能为空。", + "This renames {summary} in every note in your habits folder ({count} habit(s) currently). Existing values are moved, not discarded. Continue?": + "这将重命名习惯文件夹中每篇笔记的 {summary}(当前共 {count} 个习惯)。已有的值会被迁移,不会丢弃。是否继续?", + "Updated the frontmatter keys in {count} note(s).": + "已在 {count} 篇笔记中更新 frontmatter 键。", + "Renaming this away from the default also changes how binary habits log a day: instead of {\"2026-08-25\": 1}, a completed day becomes a bare date, like [\"2026-08-25\"] — the shape TaskNotes uses for complete_instances. Repetition and timed habits are unaffected either way; they always need a value, never just a date.": + '把这个键改成默认值以外的名称,也会改变二元习惯记录当天的方式:不再是 {"2026-08-25": 1},已完成的一天会变成一个纯日期,如 ["2026-08-25"] —— 这正是 TaskNotes 用于 complete_instances 的格式。计数和计时习惯不受影响,它们始终需要一个数值,而不仅仅是日期。', + Identity: "标识", + Legacy: "遗留", + Lifecycle: "生命周期", + Presentation: "外观", + "Note habit": "笔记习惯", + "Habit type key": "习惯类型键", + "Completion records key": "完成记录键", + "Frequency key": "频率键", + "Weekday key": "星期键", + "Month day key": "月内日期键", + "Interval days key": "间隔天数键", + "Planned time key": "计划时间键", + "Goal direction key": "目标方向键", + "Target key": "目标键", + "Unit key": "单位键", + "Step size key": "步长键", + "Weekly target key": "周目标键", + "Monthly target key": "月目标键", + "Weekly perfect key": "完美一周键", + "Monthly perfect key": "完美一月键", + "Start date key": "开始日期键", + "Pauses key": "暂停记录键", + "Stopped key": "停止状态键", + "Stop date key": "停止日期键", + "Icon key": "图标键", + "Color key": "颜色键", + "Group key": "分组键", + "Use group color key": "使用分组颜色键", + "Note folder key": "笔记文件夹键", + "Note filename format key": "笔记文件名格式键", + "Template path key": "模板路径键", + "Note completion mode key": "笔记完成模式键", + "Note checklist requirement key": "笔记清单要求键", + "Note checklist minimum key": "笔记清单最少数量键", + "Note fail keyword key": "笔记失败关键词键", + "Legacy comments key": "旧版评论键", + + // PDF export (read via docT() in export-modal.ts, which falls back to English for zh — jsPDF's built-in fonts can't render CJK) + "Completion trend": "完成趋势", + "(paused)": "(已暂停)", + "{rate}% · {total} · streak {current} (best {best})": + "{rate}% · {total} · 连击 {current}(最佳 {best})", + "Goal: {completed}/{goal} days met": + "目标:已达成 {completed}/{goal} 天", + "{range} · exported {date}": "{range} · 导出于 {date}", + "+{n} more": "还有 {n} 条", + + // Back-dating a missed day + Back: "返回", + + // Rescheduling missed habits (experimental) + "1 missed habit": "1 个错过的习惯", + "Add a notification button to the dashboard and sidebar panel when a habit's been missed, opening a review of missed days you can move onto a different one (never a day that habit is already due, so nothing doubles up).": + "当习惯被错过时,在仪表盘和侧边栏面板上添加一个通知按钮,点击可查看错过的日子,并将其移到另一天(绝不会是该习惯本来就到期的日子,避免重复记录)。", + "Missed habits": "错过的习惯", + "Move this missed day onto a different one": "将这个错过的日子移到另一天", + "Move to": "移到", + "Nothing missed right now.": "目前没有错过任何内容。", + "Pick a habit to move it onto a different day.": "选择一个习惯,将其移到另一天。", + "Move a missed habit to an open day or record it on its original date.": "可将漏打卡移到空闲日期,或在原日期补记。", + "Backfill": "补记", + "Record on the original date": "在原日期补记", + "This habit changed. Reopen the habit and try again.": "这条习惯记录已变化。请重新打开习惯后再试。", + Reschedule: "改期", + "Reschedule missed habits": "重新安排错过的习惯", + "Rescheduled \"{name}\" to {date}.": '已将"{name}"改期到 {date}。', + "Rescheduled from {date}": "从 {date} 改期而来", + "Reschedules key": "改期记录键", + "Failed days key": "失败日期键", + "Skipped days key": "跳过日期键", + "Rescheduling \"{name}\" — missed {date}.": '正在为"{name}"改期——错过了 {date}。', + "That day no longer works — pick another.": "那一天已经不可用了——请选择另一天。", + "That day won't work — it's either already due for this habit or already claimed by another reschedule.": + "那一天不行——要么这个习惯当天本来就到期,要么已经被另一次改期占用。", + "{count} missed habits": "{count} 个错过的习惯", + "Interval schedule": "间隔排期方式", + "Fixed schedules follow the start date. Completion schedules stay due when missed and restart the interval after you complete the habit. Maximum limits keep a fixed schedule.": "固定排期从开始日期计算。按完成日期排期时,漏做的习惯会一直待办,完成后重新计算间隔。上限目标仍使用固定排期。", + "From start date": "从开始日期计算", + "From actual completion": "从实际完成日期计算", + "Existing Task Genius habits": "原有 Task Genius 习惯", + "Original daily-note records remain available below. Import creates habit notes with a complete source snapshot and never changes the original records.": "下方保留原有日记记录。导入会创建独立习惯笔记,并保存完整来源快照,不修改原始记录。", + "Import existing records": "导入原有记录", + "No records available to import.": "暂无可导入的记录。", + "Create {n} habit notes in {folder}? Existing notes and daily records will be preserved.": "将在 {folder} 中创建 {n} 个习惯笔记。现有笔记和日记记录都会保留,是否继续?", + "Imported {created} habits; skipped {skipped} existing imports.": "已导入 {created} 个习惯,跳过 {skipped} 个已导入习惯。", + "Habit import failed. Existing files have been preserved.": "习惯导入失败。现有文件已保留,可重试以继续导入。", + "Unable to load habits. Check the console for details.": "无法加载习惯,详细信息请查看控制台。", + "Work and rest cycle": "工作与休息循环", + "Active days at the start of each cycle": "每个循环开始时的签到天数", + "For a four-day cycle with three active days, check in separately on days 1, 2, and 3; day 4 is a rest day.": "例如每 4 天一个循环、前 3 天签到:第 1、2、3 天分别打卡,第 4 天休息。", + "Daily completion target": "每日完成目标", + "Finish today's card after this amount; the weekly or monthly quota is tracked separately. Use 0 to track only the period quota.": "当天达到这个数量就算完成;每周或每月总目标单独累计。设为 0 则只判断周期总目标。", + "Restart cycle on": "从指定日期重新开始循环", + "Choose a new cycle start date. Existing records and earlier schedules are preserved.": "选择新循环的开始日期,已有记录和此前的排期都会保留。", + "{active} active days / {days}-day cycle": "每 {days} 天循环,前 {active} 天签到", + "Date": "日期", + "More actions": "更多操作", + "Check in": "签到", + "Decrease": "减少", + "Increase": "增加", + "Period progress": "本周期进度", + "Task Genius habit layout": "习惯页面布局", + "Choose the page layout. Habit goals, schedules and records stay the same.": "只改变页面布局,目标、周期、限额及记录仍按 Habits 设置执行。", + "Task Genius cards": "原生卡片布局", + "No activity": "未记录", + "Below target": "已记录,未达标", + "Target met": "已达标", + "Double target": "达到两倍目标", + "At most": "限额", + "At least": "目标", + "Daily goal": "每日目标", + "Habit columns": "习惯列数", + "Choose a fixed column count or fit cards to the available space.": "选择一至四列,或根据页面宽度自动排列。", + "Automatic": "自适应", + "Ignore": "忽略", + "Habit note not found.": "找不到对应的习惯笔记。", + "That day is already due or has a record. Choose another day.": "这一天已有计划、记录或改期安排,请选择另一天。", + "This habit is already due every day. Ignore this miss or record it on its original day.": "这个习惯每天都有计划。可忽略本次漏记,或在原日期补记。", + "Close": "关闭", +}; diff --git a/src/integrations/habits/legacy-import.ts b/src/integrations/habits/legacy-import.ts new file mode 100644 index 000000000..3d4b44536 --- /dev/null +++ b/src/integrations/habits/legacy-import.ts @@ -0,0 +1,96 @@ +import { normalizePath, parseYaml, stringifyYaml, type App } from "obsidian"; +import type { HabitProps } from "@/types/habit-card"; +import { DEFAULT_FRONTMATTER_KEYS, type HabitsPluginSettings } from "./settings"; +import { sanitizeFileName } from "./utils"; + +export interface LegacyHabitPlan { + identity: string; + name: string; + type: "binary" | "repetition"; + target: number; + unit: string; + records: Record; + source: HabitProps; +} + +/** Pure conversion: retain the complete original record beside numeric statistics. */ +export function planLegacyHabits(habits: HabitProps[]): LegacyHabitPlan[] { + return habits.flatMap(habit => { + const events = habit.type === "scheduled" ? habit.events.map(event => event.name) : [""]; + return events.map(event => { + const records: Record = {}; + for (const [date, value] of Object.entries(habit.completions ?? {})) { + if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) continue; + if (habit.type === "scheduled") { + // A scheduled event is completed by presence, even with an empty detail. + if (value && typeof value === "object" && Object.prototype.hasOwnProperty.call(value, event)) records[date] = 1; + } else if (habit.type === "daily") { + if (value !== null && value !== false && value !== "" && value !== undefined && value !== 0) records[date] = 1; + } else if (typeof value === "number" && Number.isFinite(value)) records[date] = value; + } + return { + identity: JSON.stringify([habit.id, event]), + name: event ? `${habit.name} — ${event}` : habit.name, + type: habit.type === "count" || habit.type === "mapping" ? "repetition" as const : "binary" as const, + target: habit.type === "count" ? Math.max(0, habit.min ?? 1) : 1, + unit: habit.type === "count" ? habit.countUnit ?? "" : "", + records, + source: JSON.parse(JSON.stringify(habit)), + }; + }); + }); +} + +function suffix(identity: string): string { + let hash = 2166136261; + for (let i = 0; i < identity.length; i++) hash = Math.imul(hash ^ identity.charCodeAt(i), 16777619); + return (hash >>> 0).toString(16); +} + +/** Create-only import through Obsidian's vault API; never overwrite any existing file. */ +export async function importLegacyHabits(app: App, settings: HabitsPluginSettings, plans: LegacyHabitPlan[]): Promise<{created: number; skipped: number}> { + const folder = normalizePath(settings.habitsFolder.trim()); + if (!folder || folder === "." || folder.split("/").some(part => part === "..")) throw new Error("Invalid habits folder"); + let path = ""; + for (const part of folder.split("/")) { + path = path ? `${path}/${part}` : part; + if (!app.vault.getAbstractFileByPath(path)) await app.vault.createFolder(path); + } + const k = {...DEFAULT_FRONTMATTER_KEYS, ...settings.frontmatterKeys}; + const imported = new Set(); + // Read actual content so a renamed import remains idempotent, without relying + // on a metadata event arriving before a second import starts. + for (const file of app.vault.getMarkdownFiles()) { + if (!file.path.startsWith(`${folder}/`)) continue; + const text = await app.vault.read(file); + const match = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text); + if (!match) continue; + try { + const identity = parseYaml(match[1])?.taskGeniusLegacy?.identity; + if (typeof identity === "string") imported.add(identity); + } catch { /* Unrelated notes with malformed YAML are not modified. */ } + } + let created = 0, skipped = 0; + for (const plan of plans) { + if (imported.has(plan.identity)) { skipped++; continue; } + const name = sanitizeFileName(plan.name).slice(0, 100) || "Habit"; + const filePath = normalizePath(`${folder}/${name} (TG-${suffix(plan.identity)}).md`); + if (await app.vault.adapter.exists(filePath)) { + const text = await app.vault.adapter.read(filePath); + const match = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text); + if (!match || parseYaml(match[1])?.taskGeniusLegacy?.identity !== plan.identity) throw new Error(`Import conflict: ${filePath}`); + skipped++; + continue; + } + const fm = { + habit: true, [k.type]: plan.type, [k.frequency]: "daily", [k.target]: plan.target, + [k.unit]: plan.unit, [k.icon]: plan.source.icon, [k.records]: plan.records, + [k.startDate]: Object.keys(plan.records).sort()[0] ?? "", + taskGeniusLegacy: {identity: plan.identity, importedAt: new Date().toISOString(), source: plan.source}, + }; + await app.vault.create(filePath, `---\n${stringifyYaml(fm)}---\n\n# ${plan.name.replace(/[\r\n]/g, " ")}\n\n\`\`\`tg-habit-metrics\n\`\`\`\n`); + imported.add(plan.identity); + created++; + } + return {created, skipped}; +} diff --git a/src/integrations/habits/main.ts b/src/integrations/habits/main.ts new file mode 100644 index 000000000..381b5a894 --- /dev/null +++ b/src/integrations/habits/main.ts @@ -0,0 +1,458 @@ +import { + debounce, + Editor, + Events, + Notice, + normalizePath, + Plugin, + TFile, + type TAbstractFile, + type WorkspaceLeaf, +} from "obsidian"; +import { t } from "./i18n"; +import { HabitStore } from "./habit-store"; +import { ReminderSync } from "./reminders"; +import { NoteHabitSync } from "./note-habit"; +import { + DEFAULT_AI_SUMMARY, + DEFAULT_EXPERIMENTAL, + DEFAULT_FRONTMATTER_KEYS, + DEFAULT_REMINDERS, + DEFAULT_SETTINGS, + HabitsSettingTab, + type HabitsPluginSettings, +} from "./settings"; +import { HabitsBlock } from "./ui/habits-block"; +import { HabitMetrics } from "./ui/habit-metrics"; +import { HabitsHeatmap } from "./ui/habits-heatmap"; +import { HabitsTable } from "./ui/habits-table"; +import { HabitModal } from "./ui/habit-modal"; +import { HabitMetricsSuggest } from "./ui/metrics-suggest"; +import { + HABITS_PANEL_VIEW_TYPE, + HabitsPanelView, +} from "./ui/panel-view"; + +export default class HabitsPlugin extends Plugin { + settings: HabitsPluginSettings = DEFAULT_SETTINGS; + /** Plugin-internal event bus (e.g. "settings-changed"). */ + readonly events = new Events(); + /** Public so the settings tab can list habits for the order editor. */ + store!: HabitStore; + + async onload(): Promise { + await this.loadSettings(); + if (!this.integrationActive()) return; + this.store = new HabitStore( + this.app, + () => this.settings, + () => this.saveSettings(), + ); + + this.addSettingTab(new HabitsSettingTab(this.app, this)); + + // Lets Core Plugins → Page preview offer hover previews for the + // [[links]] users write in day comments. + this.registerHoverLinkSource("tg-habits", { + display: t("Habits"), + defaultMod: true, + }); + + this.registerMarkdownCodeBlockProcessor("habits", (_source, el, ctx) => { + const dashboard = new HabitsBlock( + this.app, + this.store, + () => this.settings, + this.events, + ctx.sourcePath, + el, + ); + ctx.addChild(dashboard); + }); + + this.registerMarkdownCodeBlockProcessor( + "habit-metrics", + (source, el, ctx) => { + ctx.addChild( + new HabitMetrics( + this.app, + this.store, + ctx.sourcePath, + source, + el, + ctx, + ), + ); + }, + ); + + this.registerMarkdownCodeBlockProcessor( + "habits-table", + (_source, el, ctx) => { + ctx.addChild( + new HabitsTable( + this.app, + this.store, + () => this.settings, + this.events, + el, + ), + ); + }, + ); + + this.registerMarkdownCodeBlockProcessor( + "habits-heatmap", + (source, el, ctx) => { + ctx.addChild( + new HabitsHeatmap( + this.app, + this.store, + this.events, + ctx.sourcePath, + source, + el, + ctx, + ), + ); + }, + ); + + this.registerEditorSuggest( + new HabitMetricsSuggest(this.app, this.store), + ); + + this.registerView( + HABITS_PANEL_VIEW_TYPE, + (leaf) => + new HabitsPanelView( + leaf, + this.store, + () => this.settings, + this.events, + ), + ); + + this.addRibbonIcon("list-checks", t("Open habits panel"), () => { + void this.activatePanel(); + }); + + this.addCommand({ + id: "open-panel", + name: t("Open panel"), + callback: () => { + void this.activatePanel(); + }, + }); + + this.addCommand({ + id: "create-habit", + name: t("Create habit"), + callback: () => { + new HabitModal( + this.app, + this.store, + () => { + // The dashboard reloads itself when reopened. + }, + null, + this.settings.experimental.noteHabits, + ).open(); + }, + }); + + // Keep the manual sort order pointing at the right notes when a + // habit is renamed or moved. + this.registerEvent( + this.app.vault.on("rename", (file, oldPath) => { + const index = this.settings.manualOrder.indexOf(oldPath); + if (index >= 0) { + this.settings.manualOrder[index] = file.path; + void this.saveData(this.settings); + } + }), + ); + + this.watchComments(); + + this.addCommand({ + id: "migrate-comments", + name: t("Move day comments into note bodies"), + callback: () => { + void this.migrateComments(); + }, + }); + + this.addCommand({ + id: "insert-dashboard", + name: t("Insert dashboard"), + editorCallback: (editor: Editor) => { + editor.replaceSelection("```tg-habits\n```\n"); + }, + }); + + this.addCommand({ + id: "insert-habit-metrics", + name: t("Insert habit metrics"), + editorCallback: (editor: Editor) => { + // Every field is written out so it's clear what can be set: + // `habits:` names one habit, or several (comma-separated) to + // compare them; left empty, the block shows its own note's + // habit. `view:` picks the opening tab (charts/month/history); + // `range:` is the timeframe when comparing several habits. + const start = editor.getCursor("from"); + editor.replaceSelection( + "```tg-habit-metrics\nhabits: \nview: charts\nrange: 12w\n```\n", + ); + editor.setCursor({ line: start.line + 1, ch: "habits: ".length }); + }, + }); + + this.addCommand({ + id: "insert-table", + name: t("Insert habits table"), + editorCallback: (editor: Editor) => { + editor.replaceSelection("```tg-habits-table\n```\n"); + }, + }); + + this.addCommand({ + id: "insert-heatmap", + name: t("Insert habits heatmap"), + editorCallback: (editor: Editor) => { + editor.replaceSelection("```tg-habits-heatmap\n```\n"); + }, + }); + + this.registerReminderSync(); + this.registerNoteHabitSync(); + } + + /** + * Keeps note habits' records in step with their day-notes: primes every + * note habit's folder once the vault is ready, then watches for edits so + * writing (or deleting) a day-note updates its habit's completion live. + */ + protected integrationActive(): boolean { return true; } + protected backgroundSyncAllowed(): boolean { return this.integrationActive(); } + + private registerNoteHabitSync(): void { + const sync = new NoteHabitSync(this.app, this.store); + const prime = () => { if (this.backgroundSyncAllowed()) void sync.primeAll(); }; + this.registerEvent(this.events.on("settings-changed", prime)); + + this.app.workspace.onLayoutReady(() => prime()); + this.registerEvent( + this.app.vault.on("modify", (file) => { + if (file instanceof TFile && this.backgroundSyncAllowed()) { + void sync.syncFile(file); + } + }), + ); + this.registerEvent( + this.app.vault.on("create", (file) => { + if (file instanceof TFile && this.backgroundSyncAllowed()) { + void sync.syncFile(file); + } + }), + ); + this.registerEvent( + this.app.vault.on("delete", (file) => { + if (this.backgroundSyncAllowed()) void sync.handleDelete(file.path); + }), + ); + this.registerEvent( + this.app.vault.on("rename", (file, oldPath) => { + if (this.backgroundSyncAllowed()) void sync.handleDelete(oldPath); + if (file instanceof TFile && this.backgroundSyncAllowed()) { + void sync.syncFile(file); + } + }), + ); + } + + /** + * Keep the reminder block in step with the habits: regenerate it when + * the plugin loads, when a habit note changes, when settings change, + * when the target daily note is created, and when the day rolls over + * (so the new day's note gets its block without a restart). + */ + private registerReminderSync(): void { + const sync = new ReminderSync(this.app, this.store, () => this.settings); + const requestUpdate = debounce(() => { if (this.backgroundSyncAllowed()) void sync.update(); }, 1000, true); + + const isHabitFile = (path: string): boolean => { + const folder = normalizePath(this.settings.habitsFolder); + return path === folder || path.startsWith(`${folder}/`); + }; + + this.app.workspace.onLayoutReady(() => requestUpdate()); + this.registerEvent( + this.app.metadataCache.on("changed", (file) => { + // The target note matters too: ticking a reminder line + // there (by hand or from a notification) logs the habit. + if ( + isHabitFile(file.path) || + file.path === sync.targetPath(new Date()) + ) { + requestUpdate(); + } + }), + ); + this.registerEvent( + this.app.vault.on("create", (file) => { + // A new habit, or the target note appearing (e.g. today's + // daily note being created after the plugin loaded). + if ( + isHabitFile(file.path) || + file.path === sync.targetPath(new Date()) + ) { + requestUpdate(); + } + }), + ); + this.registerEvent( + this.app.vault.on("delete", (file) => { + if (isHabitFile(file.path)) { + requestUpdate(); + } + }), + ); + this.registerEvent( + this.app.vault.on("rename", (file, oldPath) => { + if (isHabitFile(file.path) || isHabitFile(oldPath)) { + requestUpdate(); + } + }), + ); + this.registerEvent( + this.events.on("settings-changed", () => requestUpdate()), + ); + + // Day rollover: a minute-level check is cheap and avoids the drift + // and DST pitfalls of scheduling one long timeout for midnight. + let currentDay = new Date().toDateString(); + this.registerInterval( + window.setInterval(() => { + const day = new Date().toDateString(); + if (day !== currentDay) { + currentDay = day; + requestUpdate(); + } + }, 60_000), + ); + } + + /** + * Day comments live in the note body, which can only be read + * asynchronously, so the store caches them. Prime that cache once the + * vault is ready and keep it in step with edits from any source — + * including the user typing straight into a habit note. + */ + private watchComments(): void { + const notify = debounce( + () => this.events.trigger("comments-changed"), + 150, + true, + ); + const refresh = async (file: TAbstractFile): Promise => { + if (!(file instanceof TFile) || !this.store.isHabitFile(file.path)) { + return; + } + if (await this.store.refreshComments(file)) { + notify(); + } + }; + + this.app.workspace.onLayoutReady(() => { + void this.store.primeComments().then((changed) => { + if (changed) { + notify(); + } + }); + }); + this.registerEvent( + this.app.vault.on("modify", (file) => void refresh(file)), + ); + this.registerEvent( + this.app.vault.on("create", (file) => void refresh(file)), + ); + this.registerEvent( + this.app.vault.on("delete", (file) => { + this.store.forgetComments(file.path); + }), + ); + this.registerEvent( + this.app.vault.on("rename", (file, oldPath) => { + this.store.forgetComments(oldPath); + void refresh(file); + }), + ); + } + + /** Bulk-migrate notes still keeping their comments in frontmatter. */ + private async migrateComments(): Promise { + if (!this.store.hasLegacyComments()) { + new Notice(t("No comments left to move.")); + return; + } + const count = await this.store.migrateComments(); + this.events.trigger("comments-changed"); + new Notice( + count === 1 + ? t("Moved comments in 1 note.") + : t("Moved comments in {n} notes.", { n: count }), + ); + } + + /** Open (or reveal) the habits panel in the right sidebar. */ + private async activatePanel(): Promise { + const existing = this.app.workspace.getLeavesOfType( + HABITS_PANEL_VIEW_TYPE, + ); + let leaf: WorkspaceLeaf | null = existing[0] ?? null; + if (!leaf) { + leaf = this.app.workspace.getRightLeaf(false); + if (!leaf) { + return; + } + await leaf.setViewState({ + type: HABITS_PANEL_VIEW_TYPE, + active: true, + }); + } + await this.app.workspace.revealLeaf(leaf); + } + + async loadSettings(): Promise { + const data = (await this.loadData()) as + | Partial + | null; + this.settings = Object.assign(JSON.parse(JSON.stringify(DEFAULT_SETTINGS)), data ?? {}); + // Merge nested experimental flags so a data.json saved before a new + // flag existed still picks up that flag's default. + this.settings.experimental = { + ...DEFAULT_EXPERIMENTAL, + ...(data?.experimental ?? {}), + }; + this.settings.aiSummary = { + ...DEFAULT_AI_SUMMARY, + ...(data?.aiSummary ?? {}), + }; + this.settings.reminders = { + ...DEFAULT_REMINDERS, + ...(data?.reminders ?? {}), + }; + this.settings.frontmatterKeys = { + ...DEFAULT_FRONTMATTER_KEYS, + ...(data?.frontmatterKeys ?? {}), + }; + this.settings.groups = { ...(data?.groups ?? {}) }; + this.settings.snoozes = { ...(data?.snoozes ?? {}) }; + } + + async saveSettings(): Promise { + await this.saveData(this.settings); + this.events.trigger("settings-changed"); + } +} diff --git a/src/integrations/habits/note-habit.ts b/src/integrations/habits/note-habit.ts new file mode 100644 index 000000000..8b6ddbeb0 --- /dev/null +++ b/src/integrations/habits/note-habit.ts @@ -0,0 +1,375 @@ +import { App, moment, normalizePath, Notice, TFile, TFolder } from "obsidian"; +import type { HabitStore } from "./habit-store"; +import type { HabitDefinition } from "./types"; +import { fromDateKey, parseNoteDate, toDateKey } from "./utils"; +import { t } from "./i18n"; + +/** Default filename format for a note habit's day-notes. */ +export const DEFAULT_NOTE_FILENAME_FORMAT = "YYYY-MM-DD"; + +/** The slice of Moment.js formatting this module needs, typed by hand. */ +interface FormattableMoment { + format(format: string): string; +} +const toMoment = moment as unknown as (input: Date) => FormattableMoment; + +/** The note habit's filename format, defaulting when blank. */ +function filenameFormat(habit: HabitDefinition): string { + return habit.noteFilenameFormat.trim() || DEFAULT_NOTE_FILENAME_FORMAT; +} + +/** + * Vault path of the note a `note` habit's day should live at. May include + * subfolders when the filename format contains `/` (e.g. `YYYY/MM-DD`), + * mirroring how the Daily notes plugin supports year subfolders. + */ +export function notePathForDate( + habit: HabitDefinition, + dateKey: string, +): string { + const date = fromDateKey(dateKey) ?? new Date(); + const relative = toMoment(date).format(filenameFormat(habit)); + const folder = normalizePath(habit.noteFolder.trim()); + return normalizePath( + folder && folder !== "/" ? `${folder}/${relative}.md` : `${relative}.md`, + ); +} + +/** + * Reverse-match a vault path back to the day it belongs to for a note habit + * (folder containment plus a strict Moment parse of the remaining path + * against the habit's filename format). Returns `null` when the path is not + * one of this habit's day-notes. + */ +export function matchNoteDate( + habit: HabitDefinition, + path: string, +): string | null { + if (!path.endsWith(".md")) { + return null; + } + const folder = normalizePath(habit.noteFolder.trim()); + let relative: string; + if (folder === "" || folder === "/") { + relative = path; + } else if (path === folder || !path.startsWith(`${folder}/`)) { + return null; + } else { + relative = path.slice(folder.length + 1); + } + relative = relative.slice(0, -3); // drop ".md" + const date = parseNoteDate(relative, filenameFormat(habit)); + return date ? toDateKey(date) : null; +} + +/** Strip a leading `---`…`---` frontmatter block, if any. */ +export function stripFrontmatter(content: string): string { + const lines = content.split("\n"); + if (lines[0]?.trim() !== "---") { + return content; + } + const end = lines.findIndex( + (line, i) => i > 0 && line.trim() === "---", + ); + if (end === -1) { + return content; + } + return lines.slice(end + 1).join("\n"); +} + +/** Character count of a note's body, frontmatter stripped and trimmed. */ +export function countChars(content: string): number { + return stripFrontmatter(content).trim().length; +} + +/** One task-list item: whether it's checked, and its label text. */ +export interface ChecklistItem { + checked: boolean; + text: string; +} + +/** Every task-list item in a note's body, in document order. */ +export function checklistItems(content: string): ChecklistItem[] { + const body = stripFrontmatter(content); + const items: ChecklistItem[] = []; + for (const match of body.matchAll(/^[ \t]*[-*+] \[(.)\][ \t]?(.*)$/gm)) { + items.push({ + checked: match[1].toLowerCase() === "x", + text: match[2].trim(), + }); + } + return items; +} + +/** Total task-list items in a note's body, and how many are checked. */ +export function checklistProgress(content: string): { + checked: number; + total: number; +} { + const items = checklistItems(content); + return { + total: items.length, + checked: items.filter((item) => item.checked).length, + }; +} + +/** + * True when a checked item's label contains the habit's configured fail + * keyword (case-insensitive), e.g. a "Slipped" item ticked on a day the + * user missed every option on an otherwise flexible checklist. An empty + * keyword disables the feature. + */ +export function hasFailedChecklistItem( + habit: HabitDefinition, + content: string, +): boolean { + const keyword = habit.noteFailKeyword.trim().toLowerCase(); + if (!keyword) { + return false; + } + return checklistItems(content).some( + (item) => item.checked && item.text.toLowerCase().includes(keyword), + ); +} + +/** + * Fraction (0–1) of a habit's checklist requirement satisfied by + * `checked`/`total` items: every item checked in `all` mode, or at least + * `noteChecklistMin` of them (any of them) checked in `count` mode. + */ +function checklistFraction( + habit: HabitDefinition, + checked: number, + total: number, +): number { + if (habit.noteChecklistRequirement === "count") { + return Math.min(1, checked / Math.max(1, habit.noteChecklistMin)); + } + return total > 0 ? checked / total : 0; +} + +/** + * Reduce a day-note's content to the single number stored in `records`, + * keeping the plugin's existing numeric completion, streak, and stats + * machinery unchanged: + * + * - `chars`: the raw character count. + * - `checklist`, `all` requirement: a 0–100 checked percentage (against a + * fixed `target` of 100), since the number of tasks varies day to day. + * - `checklist`, `count` requirement: the raw checked count (against + * `target` = `noteChecklistMin`). + * - `both`: the lower of the char and checklist fractions, scaled to + * `target` (the character goal) — `value >= target` then only holds once + * neither is the bottleneck. + * + * Regardless of mode, a checked item matching `noteFailKeyword` forces the + * value to `0`, an automatic fail that overrides everything else. + */ +export function computeNoteValue( + habit: HabitDefinition, + content: string, +): number { + if (hasFailedChecklistItem(habit, content)) { + return 0; + } + + if (habit.noteCompletionMode === "chars") { + return countChars(content); + } + + // Both scaled fractions below use floor rather than round: on a large + // enough checklist, rounding a not-quite-1 fraction (e.g. 199/200) can + // land exactly on the target and read as complete one tick early. + // Flooring can't overshoot the true threshold, and still lands exactly + // on it — floor(1 * n) === n — when the requirement is genuinely met. + const { checked, total } = checklistProgress(content); + if (habit.noteCompletionMode === "checklist") { + return habit.noteChecklistRequirement === "count" + ? checked + : Math.floor(checklistFraction(habit, checked, total) * 100); + } + + // "both": target doubles as the character goal in this mode (see + // habit-modal.ts), so scaling the combined fraction to it is what makes + // the generic `value >= target` completion check land at "both met". + const charGoal = habit.target > 0 ? habit.target : 1; + const charsFraction = Math.min(1, countChars(content) / charGoal); + const combined = Math.min( + charsFraction, + checklistFraction(habit, checked, total), + ); + return Math.floor(combined * charGoal); +} + +/** The subset of the Templater plugin's API this module calls into. */ +interface TemplaterApi { + create_new_note_from_template( + template: TFile, + folder?: TFolder, + filename?: string, + openNewNote?: boolean, + ): Promise; +} + +/** The Templater plugin's exposed API, if the plugin is installed and enabled. */ +function findTemplater(app: App): TemplaterApi | null { + const plugins = ( + app as unknown as { + plugins?: { plugins?: Record }; + } + ).plugins?.plugins; + const candidate = plugins?.["templater-obsidian"] as + | { templater?: TemplaterApi } + | undefined; + return candidate?.templater ?? null; +} + +/** True once, per template, so the missing-Templater hint isn't repeated. */ +const warnedMissingTemplater = new Set(); + +/** + * Create (or return the existing) day-note for a note habit. With a template + * and Templater installed, the template is expanded through Templater's own + * API; with a template but no Templater, its raw text is copied verbatim + * (and a one-time Notice suggests installing Templater if the text looks + * like it uses Templater syntax); with no template, an empty note is + * created. + */ +export async function createNoteHabitEntry( + app: App, + habit: HabitDefinition, + dateKey: string, +): Promise { + const path = notePathForDate(habit, dateKey); + const existing = app.vault.getAbstractFileByPath(path); + if (existing instanceof TFile) { + return existing; + } + + const slash = path.lastIndexOf("/"); + const folderPath = slash >= 0 ? path.slice(0, slash) : ""; + const filename = (slash >= 0 ? path.slice(slash + 1) : path).replace( + /\.md$/, + "", + ); + if (folderPath) { + const folder = app.vault.getAbstractFileByPath(folderPath); + if (!(folder instanceof TFolder)) { + await app.vault.createFolder(folderPath); + } + } + + const templatePath = normalizePath(habit.templatePath.trim()); + const templateFile = templatePath + ? app.vault.getAbstractFileByPath(templatePath) + : null; + if (templateFile instanceof TFile) { + const templater = findTemplater(app); + if (templater) { + const folder = folderPath + ? app.vault.getAbstractFileByPath(folderPath) + : app.vault.getRoot(); + if (folder instanceof TFolder) { + const created = await templater.create_new_note_from_template( + templateFile, + folder, + filename, + false, + ); + if (created instanceof TFile) { + return created; + } + } + } + const content = await app.vault.cachedRead(templateFile); + const looksLikeTemplater = !templater && content.includes("<%"); + if (looksLikeTemplater && !warnedMissingTemplater.has(templatePath)) { + warnedMissingTemplater.add(templatePath); + new Notice( + t( + '"{name}" uses Templater syntax, but the Templater plugin is not installed — the template was copied as plain text.', + { name: templateFile.basename }, + ), + ); + } + return await app.vault.create(path, content); + } + + return await app.vault.create(path, ""); +} + +/** + * Keeps note habits' `records` in step with their day-notes: watches the + * vault for edits to any file that matches a note habit's folder and + * filename format, and writes the derived character count or checked + * percentage back through {@link HabitStore.setRecord} — the same numeric + * record every other habit type uses, so streaks and stats need no changes + * of their own. + */ +export class NoteHabitSync { + constructor( + private app: App, + private store: HabitStore, + ) {} + + private noteHabits(): HabitDefinition[] { + return this.store + .getHabits() + .filter((habit) => habit.type === "note" && !habit.stopped); + } + + private async syncOne(habit: HabitDefinition, file: TFile): Promise { + const dateKey = matchNoteDate(habit, file.path); + if (!dateKey) { + return; + } + const content = await this.app.vault.cachedRead(file); + const value = computeNoteValue(habit, content); + if ((habit.records[dateKey] ?? 0) !== value) { + await this.store.setRecord(habit, dateKey, value); + } + } + + /** Recompute every note habit whose day-note this file might be. */ + async syncFile(file: TFile): Promise { + if (file.extension !== "md") { + return; + } + for (const habit of this.noteHabits()) { + await this.syncOne(habit, file); + } + } + + /** A day-note was deleted or moved away: clear its record, if any. */ + async handleDelete(path: string): Promise { + for (const habit of this.noteHabits()) { + const dateKey = matchNoteDate(habit, path); + if (dateKey && (habit.records[dateKey] ?? 0) !== 0) { + await this.store.setRecord(habit, dateKey, 0); + } + } + } + + /** + * One-time backfill over every note habit's folder, so day-notes that + * already existed before the plugin loaded (or before a habit's folder + * was pointed at them) are picked up without needing an edit first. + */ + async primeAll(): Promise { + for (const habit of this.noteHabits()) { + const folder = normalizePath(habit.noteFolder.trim()); + const files = this.app.vault + .getMarkdownFiles() + .filter( + (file) => + folder === "" || + folder === "/" || + file.path === folder || + file.path.startsWith(`${folder}/`), + ); + for (const file of files) { + await this.syncOne(habit, file); + } + } + } +} diff --git a/src/integrations/habits/reminders.ts b/src/integrations/habits/reminders.ts new file mode 100644 index 000000000..53bd6d441 --- /dev/null +++ b/src/integrations/habits/reminders.ts @@ -0,0 +1,475 @@ +import { App, TFile, moment, normalizePath } from "obsidian"; +import type { HabitStore } from "./habit-store"; +import type { HabitsPluginSettings } from "./settings"; +import type { HabitDefinition } from "./types"; +import { isDue, isFailedOn, isPausedOn } from "./stats"; +import { toDateKey } from "./utils"; + +/** + * Obsidian's bundled Moment.js, typed by hand — its own type definitions + * are not always resolvable in stricter lint setups, which would otherwise + * make every call through `moment` unsafely typed (mirrors the same cast + * in utils.ts and note-habit.ts). + */ +const formatDate = moment as unknown as ( + input: Date, +) => { format(format: string): string }; + +/** + * Markers around the plugin-managed reminder block. Obsidian `%%` comments, + * so they stay invisible in reading view while the checklist lines between + * them render (and get scanned by the Reminder plugin) normally. + */ +export const REMINDERS_START = "%% habits-reminders start %%"; +export const REMINDERS_END = "%% habits-reminders end %%"; + +/** One reminder checklist line in the Reminder plugin's default format. */ +export function reminderLine( + name: string, + dateKey: string, + time: string, + checked: boolean, +): string { + return `- [${checked ? "x" : " "}] ${name} (@${dateKey} ${time})`; +} + +/** The managed block inside `content`, or null when the markers are absent. */ +function findBlock( + content: string, +): { start: number; end: number; body: string } | null { + const start = content.indexOf(REMINDERS_START); + if (start < 0) { + return null; + } + const bodyStart = start + REMINDERS_START.length; + const end = content.indexOf(REMINDERS_END, bodyStart); + if (end < 0) { + return null; + } + return { + start, + end: end + REMINDERS_END.length, + body: content.slice(bodyStart, end), + }; +} + +/** One parsed checklist line of the managed block. */ +export interface ReminderBlockLine { + checked: boolean; + name: string; + date: string; + time: string; +} + +/** Parse every reminder line inside the managed block. */ +export function parseReminderLines(content: string): ReminderBlockLine[] { + const block = findBlock(content); + if (!block) { + return []; + } + const line = + /^- \[([ xX])\] (.+) \(@(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2})\)$/gm; + return [...block.body.matchAll(line)].map((match) => ({ + checked: match[1] !== " ", + name: match[2], + date: match[3], + time: match[4], + })); +} + +/** + * The `name|time` keys of lines ticked off inside the managed block. + * Regeneration keeps these checked even when the habit's record does not + * account for them — a partially ticked binary habit (one of two times + * done) would otherwise lose its tick on every refresh, since a binary + * record has no way to express half a day. + */ +export function checkedKeys(content: string): Set { + const keys = new Set(); + for (const line of parseReminderLines(content)) { + if (line.checked) { + keys.add(`${line.name}|${line.time}`); + } + } + return keys; +} + +/** + * The day's goal for a counted or timed habit — the target, floored at 1 + * so a habit saved without one still logs something when ticked. + */ +function goalOf(habit: HabitDefinition): number { + return Math.max(habit.target, 1); +} + +/** + * True when the habit's record can express a partly ticked day. + * + * That needs every planned time to own at least one whole unit of the + * goal. A binary record never can — 0 or 1 has no way to say "one session + * of two" — and neither can a goal smaller than its number of times, such + * as a single tablet reminded for twice. Those habits are all-or-nothing, + * and their partial ticks are kept visually instead. + */ +function splitsEvenly(habit: HabitDefinition): boolean { + return habit.type !== "binary" && goalOf(habit) >= habit.times.length; +} + +/** The value that marks a whole day done. */ +function doneValue(habit: HabitDefinition): number { + return habit.type === "binary" ? 1 : goalOf(habit); +} + +/** + * The record value today's tick state calls for. Ticking is logging. + * + * A binary habit is done once *all* its lines are ticked, and un-done + * when one is unticked again. Counted and timed habits log the share of + * the day's goal that the ticked lines represent, so a single tick on a + * habit with one planned time records the whole target: ticking off + * "Meditate" writes its 15 minutes, not a bare 1. With several times the + * goal is split across them — two of four ticks on a 30-minute habit + * records 15. + * + * A larger value logged in the dashboard survives while every line stays + * ticked, so reading for 40 minutes against a 20-minute target is not + * quietly rounded back down by a regeneration. + */ +export function desiredRecord( + habit: HabitDefinition, + checked: number, + total: number, + current: number, +): number { + const goal = goalOf(habit); + if (checked === total && current >= goal && habit.type !== "binary") { + return current; + } + if (!splitsEvenly(habit)) { + return checked === total ? doneValue(habit) : 0; + } + // Rounded *up*, because this has to be the exact inverse of the floor + // in coveredTimes: the smallest value that still reads back as this + // many covered lines. Rounding to nearest instead would let a middle + // tick write a value that regenerates as one tick fewer, and the block + // would undo the tick the user had just made. + return total > 0 ? Math.ceil((goal * checked) / total) : 0; +} + +/** Snapshot key for one line's tick state. */ +function tickKey(line: ReminderBlockLine): string { + return `${line.date}|${line.name}|${line.time}`; +} + +/** + * The habits whose tick state differs from the snapshot taken after our + * last regeneration — the actual user edits. Only these may write records: + * a line can be stale the *other* way round (the record just changed in + * the dashboard and the block has not been regenerated yet), and mirroring + * such a line back would silently revert the fresh record. A line the + * snapshot has never seen counts as an edit only when it is ticked, so + * ticks made while the plugin was not watching are still honoured. + */ +export function changedHabitNames( + lines: ReminderBlockLine[], + snapshot: ReadonlyMap | null, +): Set { + const changed = new Set(); + for (const line of lines) { + const before = snapshot?.get(tickKey(line)); + if (before === undefined ? line.checked : before !== line.checked) { + changed.add(line.name); + } + } + return changed; +} + +/** + * How many of the habit's planned times today's record already covers. + * + * This is the exact inverse of {@link desiredRecord}: a counted or timed + * habit covers a line for each whole share of the goal its value reaches, + * so writing the value a tick asks for and reading it back produces the + * same ticks. The two must agree, or every regeneration would disturb the + * ticks it had just written. Binary values stay all-or-nothing. + */ +function coveredTimes(habit: HabitDefinition, value: number): number { + const total = habit.times.length; + if (!splitsEvenly(habit)) { + return value >= doneValue(habit) ? total : 0; + } + const covered = Math.floor((value * total) / goalOf(habit)); + return Math.max(0, Math.min(total, covered)); +} + +/** + * Today's reminder lines: one per planned time of every habit that is due + * today, in time order. Lines start checked when today's record already + * covers that time or when the user ticked them off in the previous block. + * Habits with no planned times, paused habits, and limit habits (reminding + * to *not* do something is unhelpful) produce no lines. + */ +export function reminderLines( + habits: HabitDefinition[], + today: Date, + previouslyChecked: Set, +): string[] { + const dateKey = toDateKey(today); + const entries: { time: string; line: string }[] = []; + for (const habit of habits) { + if ( + habit.stopped || + habit.goalDirection === "max" || + habit.times.length === 0 || + isPausedOn(habit, dateKey) || + isFailedOn(habit, dateKey) || + !isDue(habit, today) + ) { + continue; + } + const covered = coveredTimes(habit, habit.records[dateKey] ?? 0); + habit.times.forEach((time, index) => { + // Habits whose record can express a partial day mirror it + // exactly — ticking is logging, so the record is the whole + // truth. The all-or-nothing ones need their ticks remembered + // instead, or a partial tick would be lost on every refresh. + const checked = + index < covered || + (!splitsEvenly(habit) && + previouslyChecked.has(`${habit.name}|${time}`)); + entries.push({ + time, + line: reminderLine(habit.name, dateKey, time, checked), + }); + }); + } + entries.sort((a, b) => a.time.localeCompare(b.time)); + return entries.map((entry) => entry.line); +} + +/** + * Return `content` with the managed block replaced by `lines`. With lines + * to write, a missing block is appended at the end of the note; with none, + * an existing block is emptied but its markers stay — they may have been + * planted by a daily-note template to pick the block's position, and + * keeping them means the next refill lands in that same spot. A note + * without markers is left untouched on an empty day. + */ +export function applyReminderLines( + content: string, + lines: string[], +): string { + const existing = findBlock(content); + if (lines.length === 0 && !existing) { + return content; + } + const body = lines.length > 0 ? `${lines.join("\n")}\n` : ""; + const block = `${REMINDERS_START}\n${body}${REMINDERS_END}`; + if (existing) { + return ( + content.slice(0, existing.start) + + block + + content.slice(existing.end) + ); + } + const separator = content.endsWith("\n\n") + ? "" + : content.endsWith("\n") + ? "\n" + : "\n\n"; + return content + separator + block + "\n"; +} + +/** The subset of the core Daily notes plugin's options we read. */ +interface DailyNotesOptions { + folder?: string; + format?: string; +} + +/** Folder and name format configured in the core Daily notes plugin. */ +function dailyNoteOptions(app: App): DailyNotesOptions { + const withInternals = app as unknown as { + internalPlugins?: { + getPluginById?: (id: string) => { + instance?: { options?: DailyNotesOptions }; + } | null; + }; + }; + return ( + withInternals.internalPlugins?.getPluginById?.("daily-notes")?.instance + ?.options ?? {} + ); +} + +/** + * Keeps a managed block of reminder lines in sync with today's due habits, + * in the checklist format the Reminder plugin scans — the bridge that turns + * habit schedules into actual notifications. Writing markdown is the whole + * integration: the Reminder plugin has no API, its input surface is notes. + */ +export class ReminderSync { + /** + * Tick state of the block as of our last regeneration (or first read), + * keyed per line. Diffing against it separates user edits from lines + * that are merely stale because a record changed elsewhere first. + */ + private lastTicks: Map | null = null; + + constructor( + private app: App, + private store: HabitStore, + private getSettings: () => HabitsPluginSettings, + ) {} + + /** Refresh the tick snapshot from the note content just written/read. */ + private rememberTicks(content: string): void { + this.lastTicks = new Map( + parseReminderLines(content).map((line) => [ + tickKey(line), + line.checked, + ]), + ); + } + + /** Vault path the block should live in today, or null when unknown. */ + targetPath(today: Date): string | null { + const settings = this.getSettings().reminders; + if (settings.target === "fixed-note") { + const path = settings.notePath.trim(); + return path ? normalizePath(path) : null; + } + const options = dailyNoteOptions(this.app); + const name = formatDate(today).format(options.format || "YYYY-MM-DD"); + const folder = options.folder?.trim() ?? ""; + return normalizePath(folder ? `${folder}/${name}.md` : `${name}.md`); + } + + /** + * Regenerate the block for `today`. The daily note is never created by + * the plugin — the block is added once the note exists (the caller + * re-runs on file creation); a fixed note is created on demand. The + * file is only written when the block actually changed. + */ + async update(today = new Date()): Promise { + const settings = this.getSettings().reminders; + if (!settings.enabled) { + return; + } + const path = this.targetPath(today); + if (!path) { + return; + } + const file = this.app.vault.getAbstractFileByPath(path); + if (!(file instanceof TFile)) { + if (file || settings.target !== "fixed-note") { + return; + } + const lines = reminderLines( + this.store.getHabits(), + today, + new Set(), + ); + if (lines.length > 0) { + await this.ensureParentFolder(path); + const created = applyReminderLines("", lines); + await this.app.vault.create(path, created); + this.rememberTicks(created); + } + return; + } + const content = await this.app.vault.cachedRead(file); + await this.syncRecords(content, today); + const next = applyReminderLines( + content, + reminderLines( + this.store.getHabits(), + today, + checkedKeys(content), + ), + ); + if (next === content) { + this.rememberTicks(content); + return; + } + let written = next; + await this.app.vault.process(file, (current) => { + written = applyReminderLines( + current, + reminderLines( + this.store.getHabits(), + today, + checkedKeys(current), + ), + ); + return written; + }); + this.rememberTicks(written); + } + + /** + * Ticking is logging: carry the block's *edited* tick state into the + * habit records (per {@link desiredRecord}) before the block is + * regenerated from those records. Only habits whose ticks changed + * since our last regeneration count as edited — a record logged in + * the dashboard a moment ago leaves the block momentarily stale, and + * mirroring those untouched lines back would revert the fresh record. + * Changed records are mirrored into the in-memory habit immediately, + * so the regeneration that follows sees them before the note write + * round-trips through the cache. + */ + private async syncRecords(content: string, today: Date): Promise { + const dateKey = toDateKey(today); + const todayLines = parseReminderLines(content).filter( + (line) => line.date === dateKey, + ); + const edited = changedHabitNames(todayLines, this.lastTicks); + if (edited.size === 0) { + return; + } + const ticks = new Map(); + for (const line of todayLines) { + const tally = ticks.get(line.name) ?? { checked: 0, total: 0 }; + tally.total += 1; + tally.checked += line.checked ? 1 : 0; + ticks.set(line.name, tally); + } + for (const habit of this.store.getHabits()) { + const tally = ticks.get(habit.name); + if ( + !tally || + !edited.has(habit.name) || + habit.stopped || + habit.goalDirection === "max" || + isPausedOn(habit, dateKey) || + isFailedOn(habit, dateKey) || + !isDue(habit, today) + ) { + continue; + } + const current = habit.records[dateKey] ?? 0; + const desired = desiredRecord( + habit, + tally.checked, + tally.total, + current, + ); + if (desired === current) { + continue; + } + if (desired > 0) { + habit.records[dateKey] = desired; + } else { + delete habit.records[dateKey]; + } + await this.store.setRecord(habit, dateKey, desired); + } + } + + /** Create the folders leading up to `path` when they are missing. */ + private async ensureParentFolder(path: string): Promise { + const parent = path.split("/").slice(0, -1).join("/"); + if (parent && !this.app.vault.getAbstractFileByPath(parent)) { + await this.app.vault.createFolder(parent); + } + } +} diff --git a/src/integrations/habits/scoped.css b/src/integrations/habits/scoped.css new file mode 100644 index 000000000..b3bcfe6c7 --- /dev/null +++ b/src/integrations/habits/scoped.css @@ -0,0 +1,3226 @@ +/* Generated by scripts/scope-habits-css.mjs; upstream MIT licensed. */ +/* Habits plugin — dashboard styles. + Colours use Obsidian theme variables so the plugin adapts to light/dark and + custom themes. Each card exposes an optional --habits-accent override. */ + +.habits-dashboard:where(.tg-habits-surface, .tg-habits-surface *) { + --habits-accent: var(--interactive-accent); + position: relative; + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-m); + padding: 0.75rem; + background: var(--background-secondary); +} + +.habits-header:where(.tg-habits-surface, .tg-habits-surface *) { + display: grid; + grid-template-columns: 1fr auto 1fr; + align-items: center; + gap: 0.5rem; + margin-bottom: 0.75rem; +} + +.habits-date-nav:where(.tg-habits-surface, .tg-habits-surface *) { + grid-column: 2; + justify-self: center; +} + +.habits-header-left:where(.tg-habits-surface, .tg-habits-surface *) { + grid-column: 1; + justify-self: start; +} + +.habits-header-right:where(.tg-habits-surface, .tg-habits-surface *) { + grid-column: 3; + justify-self: end; +} + +.habits-stats-tabs:where(.tg-habits-surface, .tg-habits-surface *) { + grid-column: 2; + justify-self: center; + display: flex; + gap: 0.25rem; +} + +.habits-date-nav:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: center; + gap: 0.5rem; +} + +.habits-date-display:where(.tg-habits-surface, .tg-habits-surface *) { + position: relative; + display: inline-flex; +} + +.habits-dashboard .habits-date-label:where(.tg-habits-surface, .tg-habits-surface *) { + display: inline-flex; + align-items: center; + justify-content: center; + padding: 0.25rem 0.6rem; + font-weight: var(--font-semibold); + color: var(--text-normal); + background: transparent; + border: none; + border-radius: var(--radius-s); + cursor: pointer; + box-shadow: none; +} + +.habits-dashboard .habits-date-label:hover:where(.tg-habits-surface, .tg-habits-surface *) { + background: var(--background-modifier-hover); +} + +.habits-dashboard .habits-date-input:where(.tg-habits-surface, .tg-habits-surface *) { + position: absolute; + left: 0; + bottom: 0; + width: 1px; + height: 1px; + margin: 0; + padding: 0; + border: 0; + opacity: 0; + pointer-events: none; +} + +.habits-icon-button:where(.tg-habits-surface, .tg-habits-surface *) { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 0.25rem; + padding: 0.35rem; + border-radius: var(--radius-s); + background: transparent; + color: var(--text-normal); + cursor: pointer; + box-shadow: none; +} + +.habits-icon-button:hover:where(.tg-habits-surface, .tg-habits-surface *) { + background: var(--background-modifier-hover); +} + +.habits-empty:where(.tg-habits-surface, .tg-habits-surface *) { + text-align: center; + padding: 1.5rem 0.5rem; + color: var(--text-muted); +} + +/* Vertical slack (padding + negative margin) so hovered cards can lift + and cast a shadow without being clipped by the carousel. */ +.habits-carousel-viewport:where(.tg-habits-surface, .tg-habits-surface *) { + overflow: hidden; + padding: 8px 0; + margin: -8px 0; +} + +.habits-carousel-track:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + transform: translateX(var(--habits-translate, 0)); + transition: transform 0.25s ease; +} + +/* Grid and vertical-scroll layouts: rows of cards instead of a paged + track, gathered into one or more sections (one per group when + grouping is on). The slack padding + negative margin mirror the + carousel viewport so hovered cards can lift without being clipped. */ +.habits-grid-wrap:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + flex-direction: column; + gap: 0.75rem; + padding: 8px 4px; + margin: -8px -4px; +} + +.habits-grid:where(.tg-habits-surface, .tg-habits-surface *) { + display: grid; + grid-template-columns: repeat(var(--habits-per-row, 4), minmax(0, 1fr)); + gap: 0.6rem; +} + +/* The vertical variant caps its height (set from JS at about a row and + a half, so a partial row peeks out below as the "there is more" cue) + and scrolls the cards inside the widget. Wheel and touch-drag both + work natively; `overscroll-behavior` keeps the note from scrolling + along once the cards run out, and proximity snapping settles rows + cleanly after a flick without fighting free scrolling. */ +.habits-grid-wrap.is-vertical:where(.tg-habits-surface, .tg-habits-surface *) { + /* The fallback cap keeps vertical mode scrollable even before the + exact height (1.55 card heights) has been measured. */ + max-height: var(--habits-vertical-max, min(60vh, 480px)); + overflow-y: auto; + overflow-x: hidden; + overscroll-behavior: contain; + scroll-snap-type: y proximity; + -webkit-overflow-scrolling: touch; +} + +.habits-grid-wrap.is-vertical .habits-card:where(.tg-habits-surface, .tg-habits-surface *) { + scroll-snap-align: start; + scroll-margin-top: 8px; +} + +/* Section headers shown when grouping is on: a small muted label, with + a colour swatch in colour mode. */ +.habits-group-header:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: center; + gap: 0.4rem; + margin-bottom: -0.35rem; + font-size: var(--font-ui-small); + font-weight: 600; + color: var(--text-muted); +} + +.habits-group-swatch:where(.tg-habits-surface, .tg-habits-surface *) { + width: 10px; + height: 10px; + border-radius: 3px; + flex-shrink: 0; + background: var(--habits-accent); +} + +.habits-group-swatch.is-none:where(.tg-habits-surface, .tg-habits-surface *) { + background: var(--background-modifier-border); +} + +.habits-group-icon:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: center; + color: var(--habits-accent, var(--text-muted)); + flex-shrink: 0; +} + +.habits-group-icon svg:where(.tg-habits-surface, .tg-habits-surface *) { + width: 14px; + height: 14px; +} + +/* Lip along the top edge of a card naming its group, tinted with the + group colour when one is set. Sits flush against the card edges by + cancelling the card's padding. */ +.habits-card-group-lip:where(.tg-habits-surface, .tg-habits-surface *) { + align-self: stretch; + display: flex; + align-items: center; + justify-content: center; + gap: 0.3rem; + margin: -1.1rem -0.65rem 0; + padding: 0.3rem 0.6rem; + border-radius: var(--radius-m) var(--radius-m) 0 0; + background: color-mix( + in srgb, + var(--habits-group-color, var(--habits-accent, var(--text-muted))) + 14%, + transparent + ); + color: var(--text-muted); + font-size: var(--font-ui-smaller); + font-weight: 600; + min-width: 0; +} + +.habits-card-group-lip .habits-card-group-icon:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: center; + color: var(--habits-group-color, var(--habits-accent, var(--text-muted))); + flex-shrink: 0; +} + +.habits-card-group-lip .habits-card-group-icon svg:where(.tg-habits-surface, .tg-habits-surface *) { + width: 13px; + height: 13px; +} + +.habits-card-group-name:where(.tg-habits-surface, .tg-habits-surface *) { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +/* Group lip on stats rows: the card lip re-margined to sit flush with + the stats row's own padding. */ +.habits-stats-group-lip:where(.tg-habits-surface, .tg-habits-surface *) { + margin: -0.7rem -0.8rem 0; +} + +/* Vertical layout: the stats list caps its height and scrolls in + place — shorter than the dashboard's cap, so the stats block stays + compact inside a note. */ +.habits-stats-list.is-scrollable:where(.tg-habits-surface, .tg-habits-surface *) { + max-height: min(45vh, 340px); + overflow-y: auto; + overflow-x: hidden; + overscroll-behavior: contain; + padding-right: 4px; +} + +/* Groups manager modal: one dashed container per group, habits as + draggable chips. The container under the pointer highlights while a + chip is being dragged. */ +.habits-groups-hint:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--text-muted); + font-size: var(--font-ui-small); + margin: 0 0 0.5rem; +} + +.habits-groups-board:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + flex-direction: column; + gap: 0.6rem; + margin-top: 0.75rem; +} + +.habits-groups-section:where(.tg-habits-surface, .tg-habits-surface *) { + border: 1px dashed var(--background-modifier-border); + border-radius: var(--radius-m); + padding: 0.6rem; +} + +.habits-groups-section.is-drop-target:where(.tg-habits-surface, .tg-habits-surface *) { + border-color: var(--interactive-accent); + background: color-mix( + in srgb, + var(--interactive-accent) 8%, + transparent + ); +} + +.habits-groups-actions:where(.tg-habits-surface, .tg-habits-surface *) { + margin-left: auto; + display: flex; + gap: 2px; +} + +.habits-groups-actions .habits-icon-button.is-active:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--interactive-accent); +} + +/* Inline group style editor (colour + icon) inside a section. */ +.habits-groups-style:where(.tg-habits-surface, .tg-habits-surface *) { + margin-top: 0.4rem; + border-top: 1px solid var(--background-modifier-border); +} + +.habits-groups-style .setting-item:where(.tg-habits-surface, .tg-habits-surface *) { + border: none; + padding: 0.45rem 0; +} + +.habits-groups-chips:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + flex-wrap: wrap; + gap: 0.4rem; + margin-top: 0.45rem; +} + +.habits-groups-chip:where(.tg-habits-surface, .tg-habits-surface *) { + display: inline-flex; + align-items: center; + gap: 0.35rem; + padding: 0.25rem 0.6rem; + background: var(--background-primary); + border: 1px solid var(--background-modifier-border); + border-left: 3px solid + var(--habits-accent, var(--background-modifier-border)); + border-radius: var(--radius-s); + cursor: grab; + touch-action: none; + -webkit-user-select: none; + user-select: none; +} + +.habits-groups-chip.is-dragging:where(.tg-habits-surface, .tg-habits-surface *) { + opacity: 0.6; + cursor: grabbing; +} + +.habits-groups-chip-icon:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: center; +} + +.habits-groups-empty:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--text-faint); + font-size: var(--font-ui-smaller); +} + +.habits-panel-group:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: center; + gap: 0.4rem; + margin: 0.6rem 0 0.15rem; + font-size: var(--font-ui-smaller); + font-weight: 600; + color: var(--text-muted); +} + +.habits-panel-group:first-child:where(.tg-habits-surface, .tg-habits-surface *) { + margin-top: 0; +} + +/* Manual sort order editor in settings: one slim draggable row per + habit, mirroring the card's accent stripe and icon. `touch-action: + none` lets pointer events drive the drag on touchscreens too. */ +.habits-order-setting:where(.tg-habits-surface, .tg-habits-surface *) { + display: block; +} + +.habits-order-list:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + flex-direction: column; + gap: 4px; + margin-top: 0.75rem; +} + +.habits-order-row:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: center; + gap: 0.5rem; + padding: 6px 10px; + background: var(--background-primary); + border: 1px solid var(--background-modifier-border); + border-left: 3px solid + var(--habits-accent, var(--background-modifier-border)); + border-radius: var(--radius-s); + cursor: grab; + touch-action: none; + -webkit-user-select: none; + user-select: none; +} + +.habits-order-row.is-dragging:where(.tg-habits-surface, .tg-habits-surface *) { + opacity: 0.85; + cursor: grabbing; + box-shadow: var(--shadow-s); + z-index: 2; + position: relative; +} + +.habits-order-grip:where(.tg-habits-surface, .tg-habits-surface *), +.habits-order-icon:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: center; + color: var(--text-muted); +} + +.habits-order-name:where(.tg-habits-surface, .tg-habits-surface *) { + flex: 1; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.habits-card:where(.tg-habits-surface, .tg-habits-surface *) { + position: relative; + overflow: hidden; + min-width: 0; + perspective: 1000px; + -webkit-user-select: none; + user-select: none; + -webkit-touch-callout: none; + flex: 0 0 calc(100% / var(--habits-per-view, 1)); + box-sizing: border-box; + display: flex; + flex-direction: column; + align-items: center; + gap: 0.85rem; + padding: 1.1rem 0.65rem; + background: var(--background-primary); + border: 1px solid var(--background-modifier-border); + border-left: 3px solid var(--habits-accent); + border-radius: var(--radius-m); + box-shadow: var(--shadow-s); +} + +/* Comment flip: the card body lives in a 3D inner wrapper with a front + and back face; the lip along the bottom edge flips between them. */ + +.habits-card-inner:where(.tg-habits-surface, .tg-habits-surface *) { + position: relative; + width: 100%; + flex: 1 1 auto; + transform-style: preserve-3d; + transition: transform 0.45s cubic-bezier(0.4, 0.2, 0.2, 1); +} + +.habits-card.is-flipped .habits-card-inner:where(.tg-habits-surface, .tg-habits-surface *) { + transform: rotateY(180deg); +} + +.habits-card-front:where(.tg-habits-surface, .tg-habits-surface *), +.habits-card-back:where(.tg-habits-surface, .tg-habits-surface *) { + -webkit-backface-visibility: hidden; + backface-visibility: hidden; +} + +.habits-card-front:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + flex-direction: column; + align-items: center; + gap: 0.85rem; +} + +.habits-card-back:where(.tg-habits-surface, .tg-habits-surface *) { + position: absolute; + inset: 0; + display: flex; + flex-direction: column; + gap: 0.4rem; + transform: rotateY(180deg); +} + +.habits-card-back-title:where(.tg-habits-surface, .tg-habits-surface *) { + text-align: center; + font-size: var(--font-ui-smaller); + font-weight: var(--font-semibold); + color: var(--text-muted); +} + +/* Holds the two faces of the comment area: the rendered read view and + the textarea that replaces it while editing. */ +.habits-comment-stage:where(.tg-habits-surface, .tg-habits-surface *) { + position: relative; + flex: 1; + min-height: 0; + display: flex; +} + +.habits-card .habits-comment-input:where(.tg-habits-surface, .tg-habits-surface *) { + flex: 1; + width: 100%; + min-height: 0; + resize: none; + padding: 0.4rem 0.5rem; + font-size: var(--font-ui-small); + font-family: inherit; + color: var(--text-normal); + background: var(--background-modifier-form-field); + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-s); + -webkit-user-select: text; + user-select: text; +} + +/* Only one face is shown at a time. */ +.habits-comment-stage:not(.is-editing) .habits-comment-input:where(.tg-habits-surface, .tg-habits-surface *), +.habits-comment-stage.is-editing .habits-comment-read:where(.tg-habits-surface, .tg-habits-surface *) { + display: none; +} + +.habits-comment-read:where(.tg-habits-surface, .tg-habits-surface *) { + flex: 1; + min-height: 0; + overflow-y: auto; + padding: 0.4rem 0.5rem; + font-size: var(--font-ui-small); + line-height: 1.45; + white-space: pre-wrap; + overflow-wrap: anywhere; + color: var(--text-normal); + background: var(--background-modifier-form-field); + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-s); + cursor: text; + -webkit-user-select: text; + user-select: text; +} + +.habits-comment-read:focus-visible:where(.tg-habits-surface, .tg-habits-surface *) { + outline: 2px solid var(--background-modifier-border-focus); + outline-offset: -2px; +} + +/* Placeholder styling when the day has no comment yet. */ +.habits-comment-read.is-empty:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--text-faint); + font-style: italic; +} + +/* Tags render as compact accent-tinted chips. */ +.habits-comment-read a.habits-comment-tag:where(.tg-habits-surface, .tg-habits-surface *) { + display: inline; + padding: 0.05em 0.35em; + margin: 0 0.05em; + font-size: 0.85em; + font-weight: var(--font-medium); + line-height: 1.4; + text-decoration: none; + color: var(--habits-accent); + background: color-mix(in srgb, var(--habits-accent) 14%, transparent); + border-radius: var(--radius-s); + cursor: pointer; +} + +.habits-comment-read a.habits-comment-tag:hover:where(.tg-habits-surface, .tg-habits-surface *) { + background: color-mix(in srgb, var(--habits-accent) 26%, transparent); +} + +.habits-comment-read a.habits-comment-link:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--link-color); + text-decoration: none; + cursor: pointer; +} + +.habits-comment-read a.habits-comment-link:hover:where(.tg-habits-surface, .tg-habits-surface *) { + text-decoration: underline; +} + +/* Links whose target note does not exist yet, matching Obsidian. */ +.habits-comment-read a.habits-comment-link.is-unresolved:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--link-unresolved-color, var(--text-accent)); + opacity: var(--link-unresolved-opacity, 0.7); +} + +/* Autocomplete popup for # and [[ inside the comment textarea. It is + appended to the body so the card's 3D transform cannot clip it. */ +.habits-comment-suggest:where(.tg-habits-surface, .tg-habits-surface *) { + position: fixed; + z-index: var(--layer-menu); + top: var(--habits-suggest-top); + left: var(--habits-suggest-left); + width: var(--habits-suggest-width); + max-height: 15rem; + overflow-y: auto; + padding: 0.25rem; + background: var(--background-secondary); + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-m); + box-shadow: var(--shadow-s); +} + +.habits-comment-suggest-item:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: center; + gap: 0.5rem; + padding: 0.3rem 0.45rem; + border-radius: var(--radius-s); + cursor: pointer; +} + +.habits-comment-suggest-item.is-selected:where(.tg-habits-surface, .tg-habits-surface *) { + background: var(--background-modifier-hover); +} + +.habits-comment-suggest-icon:where(.tg-habits-surface, .tg-habits-surface *) { + display: inline-flex; + flex: 0 0 auto; + color: var(--text-muted); +} + +.habits-comment-suggest-icon .svg-icon:where(.tg-habits-surface, .tg-habits-surface *) { + width: 0.9rem; + height: 0.9rem; +} + +.habits-comment-suggest-body:where(.tg-habits-surface, .tg-habits-surface *) { + min-width: 0; +} + +.habits-comment-suggest-title:where(.tg-habits-surface, .tg-habits-surface *) { + font-size: var(--font-ui-small); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.habits-comment-suggest-detail:where(.tg-habits-surface, .tg-habits-surface *) { + font-size: var(--font-ui-smaller); + color: var(--text-faint); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +/* The comment lip along the bottom edge of the card. */ +.habits-dashboard button.habits-card-lip:where(.tg-habits-surface, .tg-habits-surface *) { + width: 100%; + margin-top: auto; + display: flex; + align-items: center; + justify-content: center; + padding: 0.2rem 0; + background: transparent; + border: none; + border-top: 1px solid var(--background-modifier-border); + border-radius: 0; + box-shadow: none; + color: var(--text-faint); + cursor: pointer; +} + +.habits-dashboard button.habits-card-lip:hover:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--habits-accent); + background: var(--background-modifier-hover); +} + +/* Days with a comment: accent-tinted, lightly filled speech bubble. */ +.habits-dashboard button.habits-card-lip.has-comment:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--habits-accent); +} + +.habits-dashboard button.habits-card-lip.has-comment .svg-icon:where(.tg-habits-surface, .tg-habits-surface *) { + fill: color-mix(in srgb, var(--habits-accent) 30%, transparent); +} + +.habits-card-lip-icon:where(.tg-habits-surface, .tg-habits-surface *) { + display: inline-flex; +} + +.habits-card-lip-icon .svg-icon:where(.tg-habits-surface, .tg-habits-surface *) { + width: 0.95rem; + height: 0.95rem; +} + +/* Hover: a gentle lift with a deeper shadow and an accent-tinted border. + Departing cards are excluded so the exit animation owns the transform. */ +.habits-card:not(.is-departing):where(.tg-habits-surface, .tg-habits-surface *) { + transition: + transform 0.18s ease, + box-shadow 0.18s ease, + border-color 0.18s ease; +} + +/* Only lift on devices with a real pointer, so the effect can't get + "stuck" after a tap on touchscreens. */ +@media (hover: hover) { + .habits-card:not(.is-departing):hover:where(.tg-habits-surface, .tg-habits-surface *) { + transform: translateY(-3px) scale(1.015); + box-shadow: 0 6px 16px rgba(0, 0, 0, 0.22); + border-color: var(--habits-accent); + z-index: 2; + } +} + +.habits-card-title:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: center; + justify-content: center; + gap: 0.3rem; + width: 100%; + min-width: 0; + font-size: calc(var(--font-ui-medium) + 2px); + font-weight: var(--font-semibold); + text-align: center; +} + +.habits-card-icon:where(.tg-habits-surface, .tg-habits-surface *) { + display: inline-flex; + color: var(--habits-accent); +} + +/* The card name is a button that opens the habit's note. Names stay on + a single line and ellipsize when the card runs out of room; the + tooltip always shows the full name. */ +.habits-dashboard button.habits-card-name:where(.tg-habits-surface, .tg-habits-surface *) { + max-width: 100%; + min-width: 0; + padding: 0; + font-size: inherit; + font-weight: inherit; + line-height: 1.3; + color: var(--text-normal); + background: transparent; + border: none; + border-radius: var(--radius-s); + cursor: pointer; + box-shadow: none; + white-space: normal; + text-align: center; +} + +.habits-card-name-text:where(.tg-habits-surface, .tg-habits-surface *) { + display: block; + max-width: 100%; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.habits-dashboard button.habits-card-name:hover:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--habits-accent); + text-decoration: underline; +} + +/* "Every Monday" / "Monthly · day 15" caption on weekly and monthly cards. */ +.habits-card-frequency:where(.tg-habits-surface, .tg-habits-surface *) { + width: 100%; + margin-top: 0.15rem; + color: var(--text-muted); + font-size: var(--font-ui-small); + font-weight: var(--font-normal); + text-align: center; +} + +.habits-card-body:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + flex-direction: column; + align-items: center; + gap: 0.75rem; +} + +.habits-binary-toggle:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + flex-direction: column; + align-items: center; + gap: 0.35rem; + padding: 1rem 1.5rem; + border-radius: var(--radius-m); + background: var(--background-primary); + color: var(--text-muted); + cursor: pointer; +} + +.habits-binary-toggle.is-done:where(.tg-habits-surface, .tg-habits-surface *) { + background: var(--habits-accent); + color: var(--text-on-accent); +} + +.habits-binary-label:where(.tg-habits-surface, .tg-habits-surface *) { + font-weight: var(--font-semibold); +} + +.habits-readout:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: baseline; + gap: 0.35rem; +} + +.habits-dashboard button.habits-value:where(.tg-habits-surface, .tg-habits-surface *) { + padding: 0 0.15rem; + font-size: 1.8rem; + font-weight: var(--font-bold); + line-height: 1; + color: var(--habits-accent); + background: transparent; + border: none; + border-radius: var(--radius-s); + cursor: pointer; + box-shadow: none; +} + +.habits-dashboard button.habits-value:hover:where(.tg-habits-surface, .tg-habits-surface *) { + background: var(--background-modifier-hover); +} + +.habits-dashboard .habits-value-input:where(.tg-habits-surface, .tg-habits-surface *) { + width: 4rem; + padding: 0 0.25rem; + font-size: 1.8rem; + font-weight: var(--font-bold); + line-height: 1; + text-align: center; + color: var(--habits-accent); + background: var(--background-modifier-form-field); + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-s); +} + +.habits-target:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--text-muted); +} + +.habits-progress:where(.tg-habits-surface, .tg-habits-surface *) { + width: 100%; + height: 0.4rem; + border-radius: var(--radius-s); + background: var(--background-modifier-border); + overflow: hidden; +} + +.habits-progress-fill:where(.tg-habits-surface, .tg-habits-surface *) { + width: var(--habits-progress, 0%); + height: 100%; + background: var(--habits-accent); + transition: width 0.2s ease; +} + +.habits-progress.is-complete .habits-progress-fill:where(.tg-habits-surface, .tg-habits-surface *) { + background: var(--color-green, var(--habits-accent)); +} + +/* A big, read-only derived number — a note habit's char/checklist count, + or a flexible habit's running total for the period. */ +.habits-readout-value:where(.tg-habits-surface, .tg-habits-surface *) { + padding: 0 0.15rem; + font-size: 1.8rem; + font-weight: var(--font-bold); + line-height: 1; + color: var(--habits-accent); + font-variant-numeric: tabular-nums; +} + +.habits-note-action:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: center; + gap: 0.4rem; + padding: 0.5rem 1.25rem; + border-radius: var(--radius-m); + background: var(--interactive-accent); + color: var(--text-on-accent); + font-weight: var(--font-semibold); + border: none; + cursor: pointer; +} + +.habits-note-action:hover:where(.tg-habits-surface, .tg-habits-surface *) { + background: var(--interactive-accent-hover); +} + +.habits-counter-buttons:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: center; + gap: 1.5rem; +} + +.habits-counter-buttons .habits-icon-button:where(.tg-habits-surface, .tg-habits-surface *) { + padding: 0.5rem; + border: 1px solid var(--background-modifier-border); +} + +/* Timed habits show +1/+5/+10 chips: spread them across the card. */ +.habits-counter-buttons.is-compact:where(.tg-habits-surface, .tg-habits-surface *) { + width: 100%; + gap: 0.4rem; + justify-content: center; +} + +.habits-counter-buttons.is-compact .habits-icon-button:where(.tg-habits-surface, .tg-habits-surface *) { + flex: 1 1 0; + min-width: 0; + max-width: 4.5rem; + padding: 0.45rem 0.3rem; +} + +.habits-dashboard .habits-step-button:where(.tg-habits-surface, .tg-habits-surface *) { + padding: 0.45rem 0.55rem; + font-size: var(--font-ui-small); + font-weight: var(--font-semibold); + font-variant-numeric: tabular-nums; + line-height: 1; +} + +.habits-carousel-controls:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: center; + justify-content: center; + gap: 0.75rem; + margin-top: 0.75rem; +} + +.habits-dots:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: center; + gap: 0.35rem; +} + +.habits-dot:where(.tg-habits-surface, .tg-habits-surface *) { + width: 0.5rem; + height: 0.5rem; + padding: 0; + border-radius: 50%; + background: var(--background-modifier-border); + cursor: pointer; + box-shadow: none; +} + +.habits-dot.is-active:where(.tg-habits-surface, .tg-habits-surface *) { + background: var(--habits-accent); +} + +/* Completion animation: a green circle-check swooshes in with a springy + spin while a ring pulses outward behind it, then the card is re-queued to + the end of the carousel. Colour comes from the theme palette. */ + +.habits-complete-overlay:where(.tg-habits-surface, .tg-habits-surface *) { + position: absolute; + inset: 0; + z-index: 1; + display: flex; + align-items: center; + justify-content: center; + background: var(--background-primary); + border-radius: inherit; + opacity: 1; + transition: opacity 0.2s ease; + animation: habits-complete-fade-in 0.15s ease-out; +} + +.habits-complete-overlay.is-leaving:where(.tg-habits-surface, .tg-habits-surface *) { + opacity: 0; +} + +.habits-complete-icon:where(.tg-habits-surface, .tg-habits-surface *) { + display: inline-flex; + color: var(--color-green, var(--text-success)); + animation: habits-complete-swoosh 0.55s cubic-bezier(0.34, 1.56, 0.64, 1) forwards; +} + +.habits-complete-icon .svg-icon:where(.tg-habits-surface, .tg-habits-surface *) { + width: 3rem; + height: 3rem; +} + +/* Soft ring that pulses outward just as the check lands. */ +.habits-complete-ring:where(.tg-habits-surface, .tg-habits-surface *) { + position: absolute; + inset: 0; + margin: auto; + width: 3.4rem; + height: 3.4rem; + border-radius: 50%; + border: 2px solid var(--color-green, var(--text-success)); + opacity: 0; + animation: habits-complete-ring 0.6s ease-out 0.3s forwards; +} + +@keyframes habits-complete-fade-in { + from { + opacity: 0; + } + to { + opacity: 1; + } +} + +@keyframes habits-complete-swoosh { + 0% { + transform: rotate(-180deg) scale(0.2); + opacity: 0; + } + 50% { + opacity: 1; + } + 100% { + transform: rotate(0deg) scale(1); + opacity: 1; + } +} + +@keyframes habits-complete-ring { + 0% { + transform: scale(0.8); + opacity: 0.65; + } + 100% { + transform: scale(2); + opacity: 0; + } +} + +/* Departure: the completed card swooshes off to the right and its slot + collapses, so the rest of the queue slides in to close the gap. + + The slot collapsing to zero width reflows the card's own contents into + a very tall, very narrow column. Both the carousel track and the grid + stretch their items to the tallest one, so without the height clamp + below that momentary column drags every sibling card taller for the + length of the animation. The card is already fully transparent by the + time the collapse starts (opacity finishes at 0.25s, which is exactly + when flex-basis begins), so its height is pinned to zero at that same + moment — invisible, and no longer able to set the row's height. */ +.habits-card.is-departing:where(.tg-habits-surface, .tg-habits-surface *) { + opacity: 0; + transform: translateX(45%) scale(0.9); + flex-basis: 0; + max-height: 0; + padding-left: 0; + padding-right: 0; + border-left-width: 0; + border-right-width: 0; + transition: + opacity 0.25s ease-in, + transform 0.3s ease-in, + flex-basis 0.3s ease-in-out 0.25s, + padding 0.3s ease-in-out 0.25s, + border-width 0.3s ease-in-out 0.25s, + max-height 0s linear 0.25s; +} + +/* Perfect day: glow, confetti and "Perfect!" spanning the dashboard when + every habit for the selected day is complete. Pointer-transparent. */ + +.habits-perfect-overlay:where(.tg-habits-surface, .tg-habits-surface *) { + position: absolute; + inset: 0; + z-index: 10; + display: flex; + align-items: center; + justify-content: center; + overflow: hidden; + pointer-events: none; + border-radius: var(--radius-m); + opacity: 1; + transition: opacity 0.25s ease; +} + +.habits-perfect-overlay.is-leaving:where(.tg-habits-surface, .tg-habits-surface *) { + opacity: 0; +} + +.habits-perfect-glow:where(.tg-habits-surface, .tg-habits-surface *) { + position: absolute; + inset: 0; + background: radial-gradient( + ellipse at center, + color-mix( + in srgb, + var(--color-green, var(--interactive-accent)) 22%, + transparent + ), + transparent 70% + ); + animation: habits-perfect-glow 1.85s ease-out forwards; +} + +@keyframes habits-perfect-glow { + 0% { + opacity: 0; + } + 25% { + opacity: 1; + } + 100% { + opacity: 0.5; + } +} + +.habits-perfect-text:where(.tg-habits-surface, .tg-habits-surface *) { + position: relative; + font-size: clamp(2rem, 8vw, 3.2rem); + font-weight: 800; + letter-spacing: 0.02em; + line-height: 1; + background: linear-gradient( + 120deg, + var(--color-green, var(--text-success)), + var(--interactive-accent) + ); + -webkit-background-clip: text; + background-clip: text; + -webkit-text-fill-color: transparent; + animation: habits-perfect-pop 0.6s cubic-bezier(0.34, 1.56, 0.64, 1) forwards; +} + +@keyframes habits-perfect-pop { + 0% { + transform: scale(0.3) rotate(-6deg); + opacity: 0; + } + 60% { + opacity: 1; + } + 100% { + transform: scale(1) rotate(0deg); + opacity: 1; + } +} + +.habits-perfect-confetti:where(.tg-habits-surface, .tg-habits-surface *) { + position: absolute; + inset: 0; + display: flex; + align-items: center; + justify-content: center; +} + +.habits-perfect-piece:where(.tg-habits-surface, .tg-habits-surface *) { + position: absolute; + width: 7px; + height: 11px; + border-radius: 1px; + background: var(--hc-color, var(--interactive-accent)); + opacity: 0; + animation: habits-perfect-confetti 1.4s ease-out var(--hc-delay, 0ms) + forwards; +} + +@keyframes habits-perfect-confetti { + 0% { + transform: translate(0, 0) rotate(0deg); + opacity: 1; + } + 30% { + transform: translate(calc(var(--hc-x) * 0.5), var(--hc-my)) + rotate(calc(var(--hc-r) * 0.5)); + opacity: 1; + } + 100% { + transform: translate(var(--hc-x), var(--hc-y)) + rotate(var(--hc-r)); + opacity: 0; + } +} + +/* New-habit modal: live preview and icon picker */ + +.habits-modal-preview:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: center; + gap: 0.75rem; + padding: 0.75rem 0; + margin-bottom: 0.25rem; + border-bottom: 1px solid var(--background-modifier-border); +} + +.habits-modal-preview-icon:where(.tg-habits-surface, .tg-habits-surface *) { + --habits-accent: var(--interactive-accent); + display: flex; + align-items: center; + justify-content: center; + width: 3rem; + height: 3rem; + border-radius: 50%; + color: var(--text-on-accent); + background: var(--habits-accent); + flex: 0 0 auto; +} + +.habits-modal-preview-icon .svg-icon:where(.tg-habits-surface, .tg-habits-surface *) { + width: 1.6rem; + height: 1.6rem; +} + +.habits-modal-preview-name:where(.tg-habits-surface, .tg-habits-surface *) { + font-size: var(--font-ui-large); + font-weight: var(--font-semibold); + color: var(--text-normal); +} + +.habits-button-icon:where(.tg-habits-surface, .tg-habits-surface *) { + display: inline-flex; + align-items: center; + margin-right: 0.4rem; + vertical-align: middle; +} + +.habits-button-icon .svg-icon:where(.tg-habits-surface, .tg-habits-surface *) { + width: 1em; + height: 1em; +} + +.habits-icon-suggestion:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: center; + gap: 0.6rem; +} + +.habits-icon-suggestion-glyph:where(.tg-habits-surface, .tg-habits-surface *) { + display: inline-flex; + color: var(--text-muted); +} + +.habits-icon-suggestion-glyph .svg-icon:where(.tg-habits-surface, .tg-habits-surface *) { + width: 1.1rem; + height: 1.1rem; +} + +/* Theme colour swatches */ + +.habits-swatches:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + flex-wrap: wrap; + gap: 0.35rem; + margin-right: 0.5rem; +} + +.habits-swatches button.habits-swatch:where(.tg-habits-surface, .tg-habits-surface *) { + width: 1.5rem; + height: 1.5rem; + min-width: 0; + padding: 0; + border-radius: 50%; + background-color: var(--habits-swatch); + background-image: none; + border: 2px solid transparent; + cursor: pointer; + box-shadow: none; +} + +.habits-swatches button.habits-swatch:hover:where(.tg-habits-surface, .tg-habits-surface *) { + border-color: var(--background-modifier-border-hover); +} + +.habits-swatches button.habits-swatch.is-selected:where(.tg-habits-surface, .tg-habits-surface *) { + border-color: var(--text-normal); +} + +/* Emoji icons */ + +.habits-modal-preview-icon:where(.tg-habits-surface, .tg-habits-surface *) { + font-size: 1.5rem; + line-height: 1; +} + +.habits-card-icon:where(.tg-habits-surface, .tg-habits-surface *) { + font-size: 1.1rem; + line-height: 1; +} + +.habits-emoji-suggestion:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: center; + gap: 0.6rem; +} + +.habits-emoji-suggestion-glyph:where(.tg-habits-surface, .tg-habits-surface *) { + font-size: 1.2rem; + line-height: 1; +} + +/* Carousel arrow disabled state and position counter */ + +.habits-carousel-prev.is-disabled:where(.tg-habits-surface, .tg-habits-surface *), +.habits-carousel-next.is-disabled:where(.tg-habits-surface, .tg-habits-surface *) { + opacity: 0.3; + pointer-events: none; +} + +.habits-carousel-count:where(.tg-habits-surface, .tg-habits-surface *) { + min-width: 3rem; + text-align: center; + color: var(--text-muted); + font-size: var(--font-ui-small); +} + +/* Stats view */ + +.habits-dashboard .habits-stats-tab:where(.tg-habits-surface, .tg-habits-surface *) { + padding: 0.25rem 0.7rem; + font-weight: var(--font-semibold); + color: var(--text-muted); + background: transparent; + border: none; + border-radius: var(--radius-s); + cursor: pointer; + box-shadow: none; +} + +.habits-dashboard .habits-stats-tab.is-active:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--text-on-accent); + background: var(--interactive-accent); +} + +.habits-stats-range:where(.tg-habits-surface, .tg-habits-surface *) { + margin-bottom: 0.75rem; + text-align: center; + color: var(--text-muted); + font-size: var(--font-ui-small); +} + +/* From/to pickers on the custom stats tab. */ +.habits-custom-range:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: center; + justify-content: center; + gap: 0.4rem; +} + +.habits-dashboard input.habits-custom-date:where(.tg-habits-surface, .tg-habits-surface *) { + font-size: var(--font-ui-small); + padding: 0.15rem 0.45rem; + background: var(--background-primary); + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-s); + color: var(--text-normal); +} + +.habits-custom-range-sep:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--text-muted); +} + +.habits-stats-summary:where(.tg-habits-surface, .tg-habits-surface *) { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(4.5rem, 1fr)); + gap: 0.5rem; + margin-bottom: 0.85rem; +} + +.habits-stat-tile:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + flex-direction: column; + align-items: center; + gap: 0.15rem; + padding: 0.6rem 0.3rem; + background: var(--background-primary); + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-m); +} + +.habits-stat-value:where(.tg-habits-surface, .tg-habits-surface *) { + font-size: 1.4rem; + font-weight: var(--font-bold); + color: var(--interactive-accent); + line-height: 1; +} + +.habits-stat-label:where(.tg-habits-surface, .tg-habits-surface *) { + text-align: center; + color: var(--text-muted); + font-size: var(--font-ui-smaller); +} + +.habits-ai-summary:where(.tg-habits-surface, .tg-habits-surface *) { + margin-bottom: 0.85rem; + padding: 0.7rem 0.8rem; + background: var(--background-primary); + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-m); +} + +.habits-ai-summary-header:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: center; + justify-content: space-between; + gap: 0.5rem; + margin-bottom: 0.4rem; +} + +.habits-ai-summary-title:where(.tg-habits-surface, .tg-habits-surface *) { + display: inline-flex; + align-items: center; + gap: 0.35rem; + font-weight: var(--font-semibold); + font-size: var(--font-ui-small); +} + +.habits-ai-summary-icon:where(.tg-habits-surface, .tg-habits-surface *) { + display: inline-flex; + color: var(--interactive-accent); +} + +.habits-ai-summary-icon svg:where(.tg-habits-surface, .tg-habits-surface *) { + width: 1em; + height: 1em; +} + +.habits-ai-summary-button:where(.tg-habits-surface, .tg-habits-surface *) { + font-size: var(--font-ui-smaller); + padding: 0.25rem 0.7rem; + border-radius: var(--radius-s); + cursor: pointer; +} + +.habits-ai-summary-button:disabled:where(.tg-habits-surface, .tg-habits-surface *) { + opacity: 0.6; + cursor: default; +} + +.habits-ai-summary-body p:where(.tg-habits-surface, .tg-habits-surface *) { + margin: 0 0 0.5rem; + font-size: var(--font-ui-small); + line-height: 1.45; +} + +.habits-ai-summary-body p:last-child:where(.tg-habits-surface, .tg-habits-surface *) { + margin-bottom: 0; +} + +.habits-ai-summary-body.is-muted p:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--text-muted); +} + +.habits-ai-summary.is-loading .habits-ai-summary-body p:where(.tg-habits-surface, .tg-habits-surface *) { + animation: habits-ai-pulse 1.2s ease-in-out infinite; +} + +@keyframes habits-ai-pulse { + 0%, + 100% { + opacity: 1; + } + 50% { + opacity: 0.45; + } +} + +.habits-stats-list:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + flex-direction: column; + gap: 0.6rem; +} + +/* Stats carousel: pages of habit rows sliding horizontally. */ +.habits-stats-carousel-viewport:where(.tg-habits-surface, .tg-habits-surface *) { + overflow: hidden; +} + +.habits-stats-carousel-track:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: flex-start; + transform: translateX(var(--habits-stats-translate, 0%)); + transition: transform 0.3s ease; +} + +.habits-stats-page:where(.tg-habits-surface, .tg-habits-surface *) { + flex: 0 0 100%; + min-width: 0; +} + +.habits-stats-carousel-controls:where(.tg-habits-surface, .tg-habits-surface *) { + margin-top: 0.6rem; +} + +.habits-stats-row:where(.tg-habits-surface, .tg-habits-surface *) { + --habits-accent: var(--interactive-accent); + display: flex; + flex-direction: column; + gap: 0.45rem; + padding: 0.7rem 0.8rem; + background: var(--background-primary); + border: 1px solid var(--background-modifier-border); + border-left: 3px solid var(--habits-accent); + border-radius: var(--radius-m); +} + +.habits-stats-row-top:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: center; + justify-content: space-between; + gap: 0.5rem; +} + +.habits-stats-name:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: center; + gap: 0.4rem; + font-weight: var(--font-semibold); +} + +.habits-stats-streak:where(.tg-habits-surface, .tg-habits-surface *) { + display: inline-flex; + align-items: center; + gap: 0.2rem; + font-weight: var(--font-semibold); + white-space: nowrap; +} + +/* Lucide flame used for streaks, tinted with the habit's accent. */ +.habits-stats-flame:where(.tg-habits-surface, .tg-habits-surface *) { + display: inline-flex; + align-items: center; + vertical-align: text-bottom; + color: var(--habits-accent); +} + +.habits-stats-flame .svg-icon:where(.tg-habits-surface, .tg-habits-surface *) { + width: 1em; + height: 1em; +} + +.habits-stats-heatmap:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + flex-wrap: wrap; + gap: 3px; +} + +.habits-stats-cell:where(.tg-habits-surface, .tg-habits-surface *) { + width: 0.85rem; + height: 0.85rem; + border-radius: 3px; + background: var(--background-modifier-border); +} + +.habits-stats-cell.is-partial:where(.tg-habits-surface, .tg-habits-surface *) { + background: var(--habits-accent); + opacity: 0.45; +} + +.habits-stats-cell.is-complete:where(.tg-habits-surface, .tg-habits-surface *) { + background: var(--habits-accent); +} + +.habits-stats-meta:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--text-muted); + font-size: var(--font-ui-small); +} + +/* Stats range toggle (rolling vs calendar) */ + +.habits-range-toggle:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + justify-content: center; + gap: 0.25rem; + margin-bottom: 0.75rem; + padding: 0.2rem; + background: var(--background-primary); + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-m); +} + +.habits-dashboard .habits-range-btn:where(.tg-habits-surface, .tg-habits-surface *) { + flex: 1; + max-width: 12rem; + padding: 0.3rem 0.6rem; + font-size: var(--font-ui-small); + font-weight: var(--font-semibold); + color: var(--text-muted); + background: transparent; + border: none; + border-radius: var(--radius-s); + cursor: pointer; + box-shadow: none; +} + +.habits-dashboard .habits-range-btn.is-active:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--text-normal); + background: var(--background-modifier-hover); +} + +.habits-stats-cell.is-future:where(.tg-habits-surface, .tg-habits-surface *) { + background: transparent; + border: 1px dashed var(--background-modifier-border); +} + +.habits-stats-cell.is-paused:where(.tg-habits-surface, .tg-habits-surface *) { + background: transparent; + border: 1px solid var(--background-modifier-border); + opacity: 0.6; +} + +/* Days a weekly/monthly habit is not due: faint, so due days stand out. */ +.habits-stats-cell.is-notdue:where(.tg-habits-surface, .tg-habits-surface *) { + background: transparent; + opacity: 0.25; +} + +.habits-stats-cell.is-prestart:where(.tg-habits-surface, .tg-habits-surface *) { + background: transparent; + border: 1px dotted var(--background-modifier-border); + opacity: 0.35; +} + +.habits-stats-cell.is-start:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: center; + justify-content: center; +} + +/* Filled play icon marking the first tracked day. Accent-coloured on + neutral cells; flipped to the on-accent text colour when the cell + itself is filled with the accent (start day already complete). */ +.habits-stats-cell.is-start svg:where(.tg-habits-surface, .tg-habits-surface *) { + width: 72%; + height: 72%; + color: var(--habits-accent); + fill: currentcolor; +} + +.habits-stats-cell.is-start.is-complete svg:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--text-on-accent); +} + +/* A partial start cell would fade the icon along with the whole-cell + opacity; keep the icon solid and fade only the background instead. */ +.habits-stats-cell.is-start.is-partial:where(.tg-habits-surface, .tg-habits-surface *) { + opacity: 1; + background: color-mix(in srgb, var(--habits-accent) 45%, transparent); +} + +.habits-stats-cell.is-start.is-partial svg:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--text-on-accent); +} + +/* Stats per-habit goal progress */ + +.habits-goal-bar:where(.tg-habits-surface, .tg-habits-surface *) { + width: 100%; + height: 0.4rem; + margin-top: 0.15rem; + border-radius: var(--radius-s); + background: var(--background-modifier-border); + overflow: hidden; +} + +.habits-goal-fill:where(.tg-habits-surface, .tg-habits-surface *) { + width: var(--habits-progress, 0%); + height: 100%; + background: var(--habits-accent); + transition: width 0.2s ease; +} + +.habits-goal-bar.is-complete .habits-goal-fill:where(.tg-habits-surface, .tg-habits-surface *) { + background: var(--color-green, var(--habits-accent)); +} + +.habits-stats-goal-label:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--text-muted); + font-size: var(--font-ui-smaller); +} + +/* Collapsible targets section in the habit modal */ + +.habits-targets:where(.tg-habits-surface, .tg-habits-surface *) { + margin: 0.25rem 0 0.5rem; + padding: 0.4rem 0.6rem; + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-m); + background: var(--background-secondary); +} + +.habits-targets-summary:where(.tg-habits-surface, .tg-habits-surface *) { + cursor: pointer; + font-weight: var(--font-semibold); + color: var(--text-normal); + list-style: none; + display: flex; + align-items: center; + gap: 0.4rem; + padding: 0.15rem 0; +} + +.habits-targets-summary:where(.tg-habits-surface, .tg-habits-surface *)::-webkit-details-marker { + display: none; +} + +.habits-targets-summary:where(.tg-habits-surface, .tg-habits-surface *)::before { + content: "▸"; + color: var(--text-muted); + transition: transform 0.15s ease; +} + +.habits-targets[open] .habits-targets-summary:where(.tg-habits-surface, .tg-habits-surface *)::before { + transform: rotate(90deg); +} + +.habits-targets-intro:where(.tg-habits-surface, .tg-habits-surface *) { + margin: 0.25rem 0 0.5rem; + color: var(--text-muted); + font-size: var(--font-ui-small); +} + +/* Missed-habits review modal (experimental rescheduling) */ + +.habits-missed-intro:where(.tg-habits-surface, .tg-habits-surface *) { + margin: 0.25rem 0 0.5rem; + color: var(--text-muted); + font-size: var(--font-ui-small); +} + +.habits-missed-empty:where(.tg-habits-surface, .tg-habits-surface *) { + margin: 0.5rem 0 0; + color: var(--text-muted); +} + +.habits-missed-error:where(.tg-habits-surface, .tg-habits-surface *) { + min-height: 1.2em; + margin: 0.25rem 0; + color: var(--color-red, var(--text-error)); + font-size: var(--font-ui-small); +} + +.habits-missed-list:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + flex-direction: column; + gap: 0.4rem; + max-height: 60vh; + overflow-y: auto; +} + +.habits-missed-card:where(.tg-habits-surface, .tg-habits-surface *) { + --habits-accent: var(--interactive-accent); + display: flex; + align-items: center; + gap: 0.6rem; + padding: 0.5rem 0.6rem; + border: 1px solid var(--background-modifier-border); + border-left: 3px solid var(--habits-accent); + border-radius: var(--radius-m); + background: var(--background-primary); +} + +.habits-missed-icon:where(.tg-habits-surface, .tg-habits-surface *) { + display: inline-flex; + align-items: center; + justify-content: center; + width: 1.6rem; + height: 1.6rem; + flex-shrink: 0; + color: var(--habits-accent); +} + +.habits-missed-info:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + flex-direction: column; + min-width: 0; + flex: 1; +} + +.habits-missed-name:where(.tg-habits-surface, .tg-habits-surface *) { + font-weight: var(--font-semibold); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.habits-missed-date:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--text-muted); + font-size: var(--font-ui-small); +} + +.habits-missed-reschedule:where(.tg-habits-surface, .tg-habits-surface *) { + flex-shrink: 0; + padding: 0.3rem 0.7rem; + font-size: var(--font-ui-small); + font-weight: var(--font-semibold); +} + +/* Dashboard/panel: notification button and rescheduled-card indicators */ + +/* Same size and shape as the other header icon buttons (habits-header-left/ + -right) — .habits-icon-button already supplies that; this just anchors it + to the corner and adds the pulse. */ +.habits-missed-button:where(.tg-habits-surface, .tg-habits-surface *) { + position: absolute; + right: 0.75rem; + bottom: 0.75rem; + z-index: 2; + animation: habits-missed-pulse 2.2s ease-in-out infinite; +} + +.habits-missed-badge:where(.tg-habits-surface, .tg-habits-surface *) { + position: absolute; + top: -0.3rem; + right: -0.3rem; + display: inline-flex; + align-items: center; + justify-content: center; + min-width: 1.1rem; + height: 1.1rem; + padding: 0 0.25rem; + border-radius: 1rem; + background: var(--color-red, var(--text-error)); + color: var(--text-on-accent); + font-size: 0.65rem; + font-weight: var(--font-semibold); + line-height: 1; +} + +@keyframes habits-missed-pulse { + 0%, + 100% { + box-shadow: 0 0 0 0 rgba(var(--color-red-rgb, 224, 93, 93), 0.4); + } + 50% { + box-shadow: 0 0 0 6px rgba(var(--color-red-rgb, 224, 93, 93), 0); + } +} + +.habits-panel-missed:where(.tg-habits-surface, .tg-habits-surface *) { + position: relative; +} + +.habits-card-rescheduled:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: center; + gap: 0.3rem; + margin-top: 0.1rem; + color: var(--text-muted); + font-size: var(--font-ui-smaller); +} + +.habits-card-rescheduled-icon:where(.tg-habits-surface, .tg-habits-surface *) { + display: inline-flex; +} + +.habits-card-rescheduled-icon .svg-icon:where(.tg-habits-surface, .tg-habits-surface *) { + width: 0.85em; + height: 0.85em; +} + +.habits-panel-rescheduled:where(.tg-habits-surface, .tg-habits-surface *) { + display: inline-flex; + align-items: center; + color: var(--text-muted); + flex-shrink: 0; +} + +.habits-panel-rescheduled .svg-icon:where(.tg-habits-surface, .tg-habits-surface *) { + width: 0.85em; + height: 0.85em; +} + +/* Trim the last setting's bottom border inside the section */ +.habits-targets .setting-item:last-child:where(.tg-habits-surface, .tg-habits-surface *) { + border-bottom: none; + padding-bottom: 0; +} + +/* Mobile: tighter cards and controls, stacked export modal. */ +@media (max-width: 768px) { + .habits-dashboard:where(.tg-habits-surface, .tg-habits-surface *) { + padding: 0.5rem; + } + + .habits-card:where(.tg-habits-surface, .tg-habits-surface *) { + padding: 0.75rem 0.6rem; + gap: 0.6rem; + } + + /* Match the tighter card padding so the lip stays flush. */ + .habits-card-group-lip:where(.tg-habits-surface, .tg-habits-surface *) { + margin: -0.75rem -0.6rem 0; + } + + .habits-card-title:where(.tg-habits-surface, .tg-habits-surface *) { + font-size: var(--font-ui-medium); + } + + .habits-dashboard button.habits-value:where(.tg-habits-surface, .tg-habits-surface *) { + font-size: 1.5rem; + } + + .habits-dashboard .habits-value-input:where(.tg-habits-surface, .tg-habits-surface *) { + font-size: 1.5rem; + width: 3.4rem; + } + + .habits-counter-buttons:where(.tg-habits-surface, .tg-habits-surface *) { + gap: 0.75rem; + } + + .habits-counter-buttons.is-compact:where(.tg-habits-surface, .tg-habits-surface *) { + flex-wrap: wrap; + gap: 0.3rem; + } + + .habits-counter-buttons.is-compact .habits-icon-button:where(.tg-habits-surface, .tg-habits-surface *) { + padding: 0.35rem 0.25rem; + } + + .habits-binary-toggle:where(.tg-habits-surface, .tg-habits-surface *) { + padding: 0.75rem 1.1rem; + } + + .habits-stats-cell:where(.tg-habits-surface, .tg-habits-surface *) { + width: 0.7rem; + height: 0.7rem; + } + + .habits-export-body:where(.tg-habits-surface, .tg-habits-surface *) { + flex-direction: column; + max-height: none; + } + + .habits-export-controls:where(.tg-habits-surface, .tg-habits-surface *) { + flex: none; + width: 100%; + max-height: none; + padding-right: 0; + } + + .habits-export-preview:where(.tg-habits-surface, .tg-habits-surface *) { + width: 100%; + max-height: 50vh; + } +} + +/* Habit metrics (rendered by the habit-metrics code block) */ + +.habits-metrics:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + flex-direction: column; + gap: 0.85rem; + padding: 0.75rem; + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-m); + background: var(--background-secondary); +} + +.habits-metrics-empty:where(.tg-habits-surface, .tg-habits-surface *) { + margin: 0; + text-align: center; + color: var(--text-muted); +} + +.habits-metrics-section:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + flex-direction: column; + gap: 0.4rem; +} + +.habits-metrics-title:where(.tg-habits-surface, .tg-habits-surface *) { + font-weight: var(--font-semibold); + font-size: var(--font-ui-small); + color: var(--text-muted); +} + +.habits-metrics-canvas:where(.tg-habits-surface, .tg-habits-surface *) { + position: relative; + height: var(--habits-metrics-height, 220px); +} + +/* Comparison view: a habit-metrics block listing several habits */ + +.habits-metrics-range:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.5rem 0.75rem; +} + +.habits-metrics-range .habits-metrics-tabs:where(.tg-habits-surface, .tg-habits-surface *) { + flex-wrap: wrap; + margin-bottom: 0; +} + +.habits-metrics-range-label:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--text-muted); + font-size: var(--font-ui-small); +} + +.habits-metrics input.habits-custom-date:where(.tg-habits-surface, .tg-habits-surface *) { + font-size: var(--font-ui-small); + padding: 0.15rem 0.45rem; + background: var(--background-primary); + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-s); + color: var(--text-normal); +} + +.habits-metrics-compare:where(.tg-habits-surface, .tg-habits-surface *) { + overflow-x: auto; +} + +.habits-metrics-compare-table:where(.tg-habits-surface, .tg-habits-surface *) { + width: 100%; + border-collapse: collapse; + font-size: var(--font-ui-small); +} + +.habits-metrics-compare-table th:where(.tg-habits-surface, .tg-habits-surface *), +.habits-metrics-compare-table td:where(.tg-habits-surface, .tg-habits-surface *) { + padding: 0.35rem 0.5rem; + text-align: right; + border-bottom: 1px solid var(--background-modifier-border); + font-variant-numeric: tabular-nums; +} + +.habits-metrics-compare-table th:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--text-muted); + font-weight: var(--font-semibold); +} + +.habits-metrics-compare-table th:first-child:where(.tg-habits-surface, .tg-habits-surface *), +.habits-metrics-compare-table td:first-child:where(.tg-habits-surface, .tg-habits-surface *) { + text-align: left; +} + +.habits-metrics-compare-table tr:last-child td:where(.tg-habits-surface, .tg-habits-surface *) { + border-bottom: none; +} + +.habits-metrics-compare-swatch:where(.tg-habits-surface, .tg-habits-surface *) { + display: inline-block; + width: 0.7rem; + height: 0.7rem; + margin-right: 0.45rem; + border-radius: 50%; + background: var(--habits-compare-color); + vertical-align: middle; +} + +.habits-metrics-compare-badge:where(.tg-habits-surface, .tg-habits-surface *) { + margin-left: 0.45rem; + padding: 0 0.35rem; + border-radius: var(--radius-s); + background: var(--background-modifier-hover); + color: var(--text-muted); + font-size: var(--font-ui-smaller); +} + +/* Charts/Heatmap tab bar in a habit-metrics block */ + +.habits-metrics-tabs:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + gap: 0.25rem; + width: fit-content; + margin-bottom: 0.75rem; + padding: 0.2rem; + background: var(--background-primary); + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-m); +} + +.habits-metrics-tab:where(.tg-habits-surface, .tg-habits-surface *) { + padding: 0.3rem 0.75rem; + font-size: var(--font-ui-small); + font-weight: var(--font-semibold); + color: var(--text-muted); + background: transparent; + border: none; + border-radius: var(--radius-s); + cursor: pointer; + box-shadow: none; +} + +.habits-metrics-tab.is-active:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--text-normal); + background: var(--background-modifier-hover); +} + +/* Paused and stopped habit states */ + +.habits-card.is-paused:where(.tg-habits-surface, .tg-habits-surface *) { + opacity: 0.75; + border-left-style: dashed; +} + +.habits-paused-badge:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: center; + gap: 0.4rem; + padding: 0.5rem 1rem; + border-radius: var(--radius-m); + background: var(--background-modifier-hover); + color: var(--text-muted); + font-weight: var(--font-semibold); +} + +.habits-paused-icon:where(.tg-habits-surface, .tg-habits-surface *) { + display: inline-flex; +} + +/* Overlay icon shown while a freshly paused card departs the queue. */ +.habits-paused-overlay-icon:where(.tg-habits-surface, .tg-habits-surface *) { + display: inline-flex; + color: var(--text-muted); + animation: habits-complete-swoosh 0.45s cubic-bezier(0.34, 1.56, 0.64, 1) forwards; +} + +.habits-paused-overlay-icon .svg-icon:where(.tg-habits-surface, .tg-habits-surface *) { + width: 3rem; + height: 3rem; +} + +.habits-paused-note:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--text-faint); + font-size: var(--font-ui-smaller); + text-align: center; +} + +.habits-metrics-banner:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: center; + gap: 0.6rem; + padding: 0.5rem 0.75rem; + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-m); + background: var(--background-primary); + color: var(--text-muted); +} + +.habits-metrics-banner-icon:where(.tg-habits-surface, .tg-habits-surface *) { + display: inline-flex; +} + +.habits-metrics-banner-text:where(.tg-habits-surface, .tg-habits-surface *) { + flex: 1; + font-size: var(--font-ui-small); +} + +/* Sidebar quick-log panel */ + +.habits-panel:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + flex-direction: column; + gap: 0.5rem; + padding: 0.5rem; +} + +.habits-panel-header:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: center; + gap: 0.5rem; +} + +.habits-panel-title:where(.tg-habits-surface, .tg-habits-surface *) { + flex: 1; + display: flex; + align-items: baseline; + gap: 0.4rem; + min-width: 0; + font-weight: var(--font-semibold); +} + +.habits-panel-date:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--text-muted); + font-size: var(--font-ui-smaller); + font-weight: var(--font-normal); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.habits-panel-count:where(.tg-habits-surface, .tg-habits-surface *) { + padding: 0.1rem 0.5rem; + border-radius: 1rem; + background: var(--background-modifier-hover); + color: var(--text-muted); + font-size: var(--font-ui-smaller); + font-weight: var(--font-semibold); + white-space: nowrap; +} + +.habits-panel-count.is-all-done:where(.tg-habits-surface, .tg-habits-surface *) { + background: var(--color-green, var(--text-success)); + color: var(--text-on-accent); +} + +.habits-panel-empty:where(.tg-habits-surface, .tg-habits-surface *) { + text-align: center; + padding: 1rem 0.5rem; + color: var(--text-muted); +} + +.habits-panel-list:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + flex-direction: column; + gap: 0.35rem; +} + +.habits-panel-row:where(.tg-habits-surface, .tg-habits-surface *) { + --habits-accent: var(--interactive-accent); + position: relative; + overflow: hidden; + -webkit-user-select: none; + user-select: none; + -webkit-touch-callout: none; + display: flex; + flex-direction: column; + gap: 0.3rem; + padding: 0.4rem 0.55rem; + background: var(--background-primary); + border: 1px solid var(--background-modifier-border); + border-left: 2px solid var(--habits-accent); + border-radius: var(--radius-s); +} + +.habits-panel-row.is-done:where(.tg-habits-surface, .tg-habits-surface *) { + opacity: 0.75; +} + +.habits-panel-row.is-paused:where(.tg-habits-surface, .tg-habits-surface *) { + opacity: 0.6; + border-left-style: dashed; +} + +.habits-panel-row-main:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: center; + gap: 0.4rem; + min-width: 0; +} + +.habits-panel-icon:where(.tg-habits-surface, .tg-habits-surface *) { + display: inline-flex; + flex: 0 0 auto; + color: var(--habits-accent); + font-size: 1rem; + line-height: 1; +} + +.habits-panel-icon .svg-icon:where(.tg-habits-surface, .tg-habits-surface *) { + width: 1rem; + height: 1rem; +} + +.habits-panel .habits-panel-name:where(.tg-habits-surface, .tg-habits-surface *) { + display: block; + flex: 1 1 auto; + min-width: 0; + width: auto; + margin: 0; + padding: 0; + justify-content: flex-start; + text-align: left; + font-size: var(--font-ui-small); + font-weight: var(--font-semibold); + color: var(--text-normal); + background: transparent; + border: none; + box-shadow: none; + cursor: pointer; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.habits-panel .habits-panel-name:hover:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--habits-accent); + text-decoration: underline; +} + +.habits-panel-time:where(.tg-habits-surface, .tg-habits-surface *) { + flex: 0 0 auto; + color: var(--text-muted); + font-size: var(--font-ui-smaller); + font-variant-numeric: tabular-nums; + white-space: nowrap; +} + +.habits-panel .habits-panel-value:where(.tg-habits-surface, .tg-habits-surface *) { + flex: 0 0 auto; + margin: 0; + padding: 0 0.15rem; + background: transparent; + border: none; + border-radius: var(--radius-s); + box-shadow: none; + cursor: pointer; + color: var(--text-muted); + font-size: var(--font-ui-smaller); + font-variant-numeric: tabular-nums; + white-space: nowrap; +} + +.habits-panel .habits-panel-value:hover:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--text-normal); + background: var(--background-modifier-hover); +} + +.habits-panel .habits-panel-value-input:where(.tg-habits-surface, .tg-habits-surface *) { + flex: 0 0 auto; + width: 3rem; + padding: 0 0.2rem; + font-size: var(--font-ui-smaller); + text-align: center; + color: var(--text-normal); + background: var(--background-modifier-form-field); + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-s); +} + +/* Note and flexible habits: the readout is machine-derived (a note's + char/checklist count, or a flexible habit's period total), so it is + plain text rather than the click-to-edit button other types use. */ +.habits-panel .habits-panel-readout-value:where(.tg-habits-surface, .tg-habits-surface *) { + cursor: default; +} + +.habits-panel .habits-panel-readout-value:hover:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--text-muted); + background: transparent; +} + +.habits-panel .habits-panel-mini:where(.tg-habits-surface, .tg-habits-surface *) { + flex: 0 0 auto; + padding: 0.2rem; + border: 1px solid var(--background-modifier-border); +} + +.habits-panel .habits-panel-mini .svg-icon:where(.tg-habits-surface, .tg-habits-surface *) { + width: 0.85rem; + height: 0.85rem; +} + +.habits-panel .habits-panel-step:where(.tg-habits-surface, .tg-habits-surface *) { + padding: 0.2rem 0.3rem; + font-size: var(--font-ui-smaller); + font-weight: var(--font-semibold); + font-variant-numeric: tabular-nums; + line-height: 1; +} + +.habits-panel .habits-panel-toggle:where(.tg-habits-surface, .tg-habits-surface *) { + flex: 0 0 auto; + display: inline-flex; + align-items: center; + justify-content: center; + padding: 0.25rem; + border-radius: 50%; + background: transparent; + color: var(--text-muted); + cursor: pointer; + box-shadow: none; +} + +.habits-panel .habits-panel-toggle:hover:where(.tg-habits-surface, .tg-habits-surface *) { + background: var(--background-modifier-hover); +} + +.habits-panel-row.is-done .habits-panel-toggle:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--color-green, var(--text-success)); +} + +.habits-panel-progress:where(.tg-habits-surface, .tg-habits-surface *) { + width: 100%; + height: 3px; + border-radius: var(--radius-s); + background: var(--background-modifier-border); + overflow: hidden; +} + +.habits-panel-progress-fill:where(.tg-habits-surface, .tg-habits-surface *) { + width: var(--habits-progress, 0%); + height: 100%; + background: var(--habits-accent); + transition: width 0.2s ease; +} + +.habits-panel-progress.is-complete .habits-panel-progress-fill:where(.tg-habits-surface, .tg-habits-surface *) { + background: var(--color-green, var(--habits-accent)); +} + +/* Brief celebration when a row is completed from the panel. */ +.habits-panel-flash:where(.tg-habits-surface, .tg-habits-surface *) { + position: absolute; + inset: 0; + display: flex; + align-items: center; + justify-content: center; + background: var(--background-primary); + border-radius: inherit; + animation: habits-complete-fade-in 0.15s ease-out; +} + +.habits-panel-flash-icon:where(.tg-habits-surface, .tg-habits-surface *) { + display: inline-flex; + color: var(--color-green, var(--text-success)); + animation: habits-complete-swoosh 0.45s cubic-bezier(0.34, 1.56, 0.64, 1) forwards; +} + +.habits-panel-flash-icon .svg-icon:where(.tg-habits-surface, .tg-habits-surface *) { + width: 1.4rem; + height: 1.4rem; +} + +/* Export modal: options left, live A4 preview right. */ + +.modal.habits-export-modal:where(.tg-habits-surface, .tg-habits-surface *) { + width: 1020px; + max-width: 96vw; +} + +.habits-export-body:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + gap: 1rem; + align-items: flex-start; + max-height: 80vh; +} + +.habits-export-controls:where(.tg-habits-surface, .tg-habits-surface *) { + flex: 0 0 320px; + max-height: 80vh; + overflow-y: auto; + padding-right: 0.5rem; +} + +.habits-export-controls .setting-item:where(.tg-habits-surface, .tg-habits-surface *) { + padding: 0.45rem 0; + border-top: none; +} + +.habits-export-hidden:where(.tg-habits-surface, .tg-habits-surface *) { + display: none; +} + +.habits-export-preview:where(.tg-habits-surface, .tg-habits-surface *) { + flex: 1; + max-height: 80vh; + overflow-y: auto; + overflow-x: hidden; + padding: 0.75rem; + background: var(--background-secondary-alt, var(--background-secondary)); + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-m); +} + +.habits-export-pages:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + flex-direction: column; + align-items: center; + gap: 0.75rem; +} + +.habits-export-empty:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--text-muted); + padding: 1.5rem; + text-align: center; +} + +/* Scaled wrapper: reserves the on-screen footprint of the scaled page. */ +.habits-export-page-outer:where(.tg-habits-surface, .tg-habits-surface *) { + position: relative; + flex: 0 0 auto; + width: var(--hx-outer-w); + height: var(--hx-outer-h); + overflow: hidden; +} + +.habits-export-page-outer.is-zoomable:where(.tg-habits-surface, .tg-habits-surface *) { + cursor: zoom-in; +} + +/* Magnifying-glass badge shown while hovering a preview page. */ +.habits-export-zoom-hint:where(.tg-habits-surface, .tg-habits-surface *) { + position: absolute; + top: 6px; + right: 6px; + z-index: 2; + display: flex; + align-items: center; + justify-content: center; + width: 26px; + height: 26px; + border-radius: 50%; + background: rgba(0, 0, 0, 0.55); + color: #ffffff; + opacity: 0; + transition: opacity 0.15s ease; + pointer-events: none; +} + +.habits-export-zoom-hint .svg-icon:where(.tg-habits-surface, .tg-habits-surface *) { + width: 14px; + height: 14px; +} + +.habits-export-page-outer.is-zoomable:hover .habits-export-zoom-hint:where(.tg-habits-surface, .tg-habits-surface *) { + opacity: 1; +} + +/* Full-size lightbox overlaying the whole window. */ +.habits-export-lightbox:where(.tg-habits-surface, .tg-habits-surface *) { + position: absolute; + inset: 0; + z-index: 100; + display: flex; + flex-direction: column; + align-items: center; + overflow-y: auto; + padding: 1.5rem; + background: rgba(0, 0, 0, 0.7); + cursor: zoom-out; +} + +.habits-export-lightbox-pages:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + flex-direction: column; + align-items: center; + gap: 1rem; + margin: auto; +} + +.habits-export-lightbox-close:where(.tg-habits-surface, .tg-habits-surface *) { + position: sticky; + top: 0; + z-index: 2; + align-self: flex-end; + display: flex; + align-items: center; + justify-content: center; + width: 2rem; + height: 2rem; + padding: 0; + border-radius: 50%; + background: rgba(0, 0, 0, 0.6); + color: #ffffff; + border: 1px solid rgba(255, 255, 255, 0.25); + cursor: pointer; + box-shadow: none; +} + +/* The preview page is always paper-white regardless of theme. */ +.habits-export-page:where(.tg-habits-surface, .tg-habits-surface *) { + transform: scale(var(--hx-scale, 1)); + transform-origin: top left; +} + +.habits-export-page:where(.tg-habits-surface, .tg-habits-surface *) { + position: relative; + flex: 0 0 auto; + box-sizing: border-box; + overflow: hidden; + width: var(--hx-page-w); + height: var(--hx-page-h); + padding: var(--hx-page-pad); + background: #ffffff; + color: #222222; + box-shadow: var(--shadow-s); + border-radius: 2px; +} + +.habits-export-block:where(.tg-habits-surface, .tg-habits-surface *) { + height: var(--hx-block-h); + margin-bottom: var(--hx-block-gap); +} + +.habits-export-text:where(.tg-habits-surface, .tg-habits-surface *) { + font-size: var(--hx-font); +} + +.habits-export-page-number:where(.tg-habits-surface, .tg-habits-surface *) { + position: absolute; + bottom: 4px; + left: 0; + right: 0; + text-align: center; + font-size: 6px; + color: #6e6e6e; +} + +.habits-export-block:where(.tg-habits-surface, .tg-habits-surface *) { + overflow: hidden; +} + +.habits-export-title:where(.tg-habits-surface, .tg-habits-surface *) { + font-weight: 700; + color: #222222; + line-height: 1.3; +} + +.habits-export-subtitle:where(.tg-habits-surface, .tg-habits-surface *) { + color: #6e6e6e; + line-height: 1.4; +} + +.habits-export-summary:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + gap: 9px; +} + +.habits-export-tile:where(.tg-habits-surface, .tg-habits-surface *) { + flex: 1; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 2px; + background: #f6f6f6; + border: 1px solid #cdcdcd; + border-radius: 3px; +} + +.habits-export-tile-value:where(.tg-habits-surface, .tg-habits-surface *) { + font-weight: 700; + color: #222222; + line-height: 1; +} + +.habits-export-tile-label:where(.tg-habits-surface, .tg-habits-surface *) { + color: #6e6e6e; + line-height: 1; +} + +.habits-export-section:where(.tg-habits-surface, .tg-habits-surface *) { + font-weight: 700; + color: #222222; + margin-bottom: 2px; +} + +.habits-export-chart:where(.tg-habits-surface, .tg-habits-surface *) { + display: block; + width: 100%; + height: auto; +} + +.habits-export-habit:where(.tg-habits-surface, .tg-habits-surface *) { + border-left: 3px solid var(--hx-accent, #888888); + padding-left: 8px; +} + +.habits-export-habit-name:where(.tg-habits-surface, .tg-habits-surface *) { + font-weight: 700; + color: #222222; + line-height: 1.4; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.habits-export-habit-meta:where(.tg-habits-surface, .tg-habits-surface *) { + color: #6e6e6e; + line-height: 1.4; + margin-bottom: 3px; +} + +.habits-export-grid:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + flex-wrap: wrap; + gap: var(--hx-cell-gap, 2px); +} + +.habits-export-cell:where(.tg-habits-surface, .tg-habits-surface *) { + box-sizing: border-box; + width: var(--hx-cell, 8px); + height: var(--hx-cell, 8px); + background: var(--hx-fill, #ffffff); + border: 1px solid var(--hx-border, transparent); + border-radius: 1px; +} + +.habits-export-goal:where(.tg-habits-surface, .tg-habits-surface *) { + color: #6e6e6e; + margin-top: 3px; +} + +.habits-export-comment:where(.tg-habits-surface, .tg-habits-surface *) { + height: var(--hx-line-h, 10px); + line-height: var(--hx-line-h, 10px); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + color: #555555; +} + +/* == Limit habits (experimental) ================================== */ + +/* Clean / Slipped boxes on binary limit-habit cards. The two boxes act + like radio buttons; Clean is highlighted by default because an + unlogged day already counts as clean. */ +.habits-limit-boxes:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + /* If both labels don't fit side by side, the boxes stack vertically + instead of truncating or breaking the text. */ + flex-wrap: wrap; + gap: 6px; + width: 100%; +} + +.habits-limit-box:where(.tg-habits-surface, .tg-habits-surface *) { + flex: 1 1 0; + /* Never smaller than the label, so the text always shows in full. */ + min-width: fit-content; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 3px; + /* Obsidian buttons have a fixed height (--input-height); this box + stacks an icon over a label, so it must size to its content. */ + height: auto; + min-height: 0; + padding: 8px 4px; + border-radius: 8px; + border: 1px solid var(--background-modifier-border); + background: var(--background-secondary); + color: var(--text-muted); + cursor: pointer; + box-sizing: border-box; + box-shadow: none; + line-height: 1.2; + transition: + background-color 0.15s ease, + border-color 0.15s ease, + color 0.15s ease; +} + +.habits-limit-box-icon:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: center; + justify-content: center; +} + +.habits-limit-box-icon svg:where(.tg-habits-surface, .tg-habits-surface *) { + width: 16px; + height: 16px; +} + +.habits-limit-box-label:where(.tg-habits-surface, .tg-habits-surface *) { + font-size: var(--font-ui-smaller); + line-height: 1.2; + text-align: center; + white-space: nowrap; +} + +.habits-limit-box.habits-limit-clean.is-active:where(.tg-habits-surface, .tg-habits-surface *) { + border-color: var(--color-green, var(--text-success)); + background: rgba(var(--color-green-rgb, 76, 175, 80), 0.12); + color: var(--color-green, var(--text-success)); +} + +.habits-limit-box.habits-limit-slipped.is-active:where(.tg-habits-surface, .tg-habits-surface *) { + border-color: var(--color-red, var(--text-error)); + background: rgba(var(--color-red-rgb, 224, 93, 93), 0.12); + color: var(--color-red, var(--text-error)); +} + +/* Counter/timed limit habits: the bar turns red once over the limit. */ +.habits-progress.is-over .habits-progress-fill:where(.tg-habits-surface, .tg-habits-surface *), +.habits-panel-progress.is-over .habits-panel-progress-fill:where(.tg-habits-surface, .tg-habits-surface *) { + background: var(--color-red, var(--text-error)); +} + +/* Stats heatmap: a day over the limit. */ +.habits-stats-cell.is-over:where(.tg-habits-surface, .tg-habits-surface *) { + background: var(--color-red, var(--text-error)); + opacity: 0.75; +} + +/* Panel row for a slipped/over-limit day: tint the toggle red. */ +.habits-panel-row.is-slipped .habits-panel-slip-toggle:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--color-red, var(--text-error)); +} + +/* Note shown at the top of the experimental settings section. */ +.habits-experimental-note:where(.tg-habits-surface, .tg-habits-surface *) { + margin: 0 0 12px; + color: var(--text-muted); + font-size: var(--font-ui-small); +} + +.habits-advanced-note:where(.tg-habits-surface, .tg-habits-surface *) { + margin: 0 0 12px; + color: var(--text-muted); + font-size: var(--font-ui-small); +} + +/* Hand-rolled top tab bar for the settings tab (General/Experimental/ + Advanced) — Obsidian has no native tab component. */ +.habits-settings-tabs:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + gap: 4px; + margin-bottom: 12px; + border-bottom: 1px solid var(--background-modifier-border); +} + +.habits-settings-tab:where(.tg-habits-surface, .tg-habits-surface *) { + padding: 6px 14px; + background: transparent; + border: none; + border-bottom: 2px solid transparent; + border-radius: 0; + box-shadow: none; + color: var(--text-muted); + font-size: var(--font-ui-medium); + cursor: pointer; +} + +.habits-settings-tab:hover:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--text-normal); + background: transparent; +} + +.habits-settings-tab.is-active:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--text-normal); + border-bottom-color: var(--interactive-accent); + font-weight: var(--font-weight-bold, 600); +} + +/* Weekday pills (multi-day picker in the habit modal) */ + +.habits-weekday-picker:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + flex-wrap: wrap; + gap: 0.35rem; +} + +.habits-weekday-picker button.habits-weekday-pill:where(.tg-habits-surface, .tg-habits-surface *) { + min-width: 2.6em; + padding: 0.25em 0.55em; + border-radius: var(--radius-l); + border: 1px solid var(--background-modifier-border); + background-color: var(--background-secondary); + background-image: none; + color: var(--text-muted); + font-size: var(--font-ui-small); + cursor: pointer; + box-shadow: none; +} + +.habits-weekday-picker button.habits-weekday-pill:hover:where(.tg-habits-surface, .tg-habits-surface *) { + border-color: var(--background-modifier-border-hover); + color: var(--text-normal); +} + +.habits-weekday-picker button.habits-weekday-pill.is-active:where(.tg-habits-surface, .tg-habits-surface *) { + background-color: var(--interactive-accent); + border-color: var(--interactive-accent); + color: var(--text-on-accent); +} + +/* Habits table (`habits-table` code block) */ + +.habits-table-block:where(.tg-habits-surface, .tg-habits-surface *) { + overflow-x: auto; +} + +table.habits-table:where(.tg-habits-surface, .tg-habits-surface *) { + width: 100%; + border-collapse: collapse; + font-size: var(--font-ui-small); + margin: 0; +} + +table.habits-table th:where(.tg-habits-surface, .tg-habits-surface *), +table.habits-table td:where(.tg-habits-surface, .tg-habits-surface *) { + padding: 0.35em 0.6em; + border-bottom: 1px solid var(--background-modifier-border); + text-align: left; + white-space: nowrap; +} + +table.habits-table th:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--text-muted); + font-weight: var(--font-semibold); +} + +table.habits-table th.habits-table-count:where(.tg-habits-surface, .tg-habits-surface *), +table.habits-table td.habits-table-count:where(.tg-habits-surface, .tg-habits-surface *) { + text-align: right; + font-variant-numeric: tabular-nums; +} + +table.habits-table tr.habits-table-group td:where(.tg-habits-surface, .tg-habits-surface *) { + padding-top: 0.9em; + color: var(--text-muted); + font-size: var(--font-ui-smaller); + font-weight: var(--font-semibold); + text-transform: uppercase; + letter-spacing: 0.04em; + border-bottom: none; +} + +table.habits-table a.habits-table-link:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--text-normal); + text-decoration: none; + cursor: pointer; +} + +table.habits-table a.habits-table-link:hover:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--text-accent); + text-decoration: underline; +} + +table.habits-table .habits-table-paused:where(.tg-habits-surface, .tg-habits-surface *) { + display: inline-flex; + vertical-align: middle; + margin-left: 0.4em; + color: var(--text-muted); +} + +table.habits-table .habits-table-paused .svg-icon:where(.tg-habits-surface, .tg-habits-surface *) { + width: 0.85em; + height: 0.85em; +} + +table.habits-table .habits-table-rescheduled:where(.tg-habits-surface, .tg-habits-surface *) { + display: inline-flex; + vertical-align: middle; + margin-left: 0.4em; + color: var(--text-muted); +} + +table.habits-table .habits-table-rescheduled .svg-icon:where(.tg-habits-surface, .tg-habits-surface *) { + width: 0.85em; + height: 0.85em; +} + +table.habits-table td.habits-table-schedule:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--text-muted); +} + +.habits-table-empty:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--text-muted); + font-size: var(--font-ui-small); + padding: 0.5em 0; +} + +/* Habits table — the interactive Today column */ + +table.habits-table td.habits-table-today:where(.tg-habits-surface, .tg-habits-surface *) { + width: 1%; +} + +table.habits-table button.habits-table-toggle:where(.tg-habits-surface, .tg-habits-surface *) { + display: inline-flex; + align-items: center; + gap: 0.35em; + padding: 0.25em 0.7em; + border-radius: var(--radius-m); + background: var(--background-modifier-hover); + color: var(--text-muted); + font-size: var(--font-ui-small); + font-weight: var(--font-semibold); + cursor: pointer; + box-shadow: none; + white-space: nowrap; +} + +table.habits-table button.habits-table-toggle:hover:where(.tg-habits-surface, .tg-habits-surface *) { + background: var(--background-modifier-active-hover); + color: var(--text-normal); +} + +table.habits-table button.habits-table-toggle.is-done:where(.tg-habits-surface, .tg-habits-surface *) { + background: var(--interactive-accent); + color: var(--text-on-accent); +} + +table.habits-table button.habits-table-toggle.habits-table-slip.is-done:where(.tg-habits-surface, .tg-habits-surface *) { + background: var(--background-modifier-error); + color: var(--text-on-accent); +} + +table.habits-table .habits-table-toggle-icon:where(.tg-habits-surface, .tg-habits-surface *) { + display: inline-flex; +} + +table.habits-table .habits-table-toggle-icon .svg-icon:where(.tg-habits-surface, .tg-habits-surface *) { + width: 0.9em; + height: 0.9em; +} + +table.habits-table .habits-table-stepper:where(.tg-habits-surface, .tg-habits-surface *) { + display: inline-flex; + align-items: center; + gap: 0.3em; +} + +table.habits-table .habits-table-value:where(.tg-habits-surface, .tg-habits-surface *) { + min-width: 3em; + text-align: center; + font-variant-numeric: tabular-nums; +} + +table.habits-table .habits-icon-button.habits-table-mini:where(.tg-habits-surface, .tg-habits-surface *) { + padding: 0.15em; +} + +table.habits-table .habits-icon-button.habits-table-mini .svg-icon:where(.tg-habits-surface, .tg-habits-surface *) { + width: 0.85em; + height: 0.85em; +} + +table.habits-table .habits-table-notdue:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--text-faint); +} + +/* Planned-times picker (habit modal) */ + +.habits-time-picker:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + flex-direction: column; + align-items: flex-end; + gap: 0.35rem; +} + +.habits-time-row:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: center; + gap: 0.3rem; +} + +.habits-time-picker button.habits-time-add:where(.tg-habits-surface, .tg-habits-surface *) { + font-size: var(--font-ui-small); + padding: 0.2em 0.7em; + cursor: pointer; +} + +.habits-time-picker .habits-icon-button.habits-time-remove:where(.tg-habits-surface, .tg-habits-surface *) { + padding: 0.15em; +} + +.habits-time-picker .habits-icon-button.habits-time-remove .svg-icon:where(.tg-habits-surface, .tg-habits-surface *) { + width: 0.85em; + height: 0.85em; +} + +/* Habits failed, skipped or snoozed for the day: a "N hidden" disclosure + under the dashboard's cards and the panel's rows, with Undo per habit. */ + +.habits-closed:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + flex-direction: column; + gap: 0.35rem; + margin-top: 0.75rem; +} + +.habits-closed-toggle:where(.tg-habits-surface, .tg-habits-surface *) { + display: inline-flex; + align-items: center; + gap: 0.3rem; + width: fit-content; + padding: 0.2rem 0.5rem; + font-size: var(--font-ui-small); + color: var(--text-muted); + background: transparent; + border: none; + box-shadow: none; + cursor: pointer; +} + +.habits-closed-toggle:hover:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--text-normal); + background: var(--background-modifier-hover); +} + +.habits-closed-chevron:where(.tg-habits-surface, .tg-habits-surface *) { + display: inline-flex; +} + +.habits-closed-chevron .svg-icon:where(.tg-habits-surface, .tg-habits-surface *) { + width: 0.9em; + height: 0.9em; +} + +.habits-closed-list:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + flex-direction: column; + gap: 0.25rem; +} + +.habits-closed-row:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: center; + gap: 0.5rem; + padding: 0.3rem 0.5rem; + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-s); + background: var(--background-primary); + font-size: var(--font-ui-small); +} + +.habits-closed-icon:where(.tg-habits-surface, .tg-habits-surface *) { + display: inline-flex; + color: var(--text-muted); +} + +.habits-closed-name:where(.tg-habits-surface, .tg-habits-surface *) { + flex: 1; + min-width: 0; + overflow-wrap: anywhere; + color: var(--text-muted); +} + +.habits-closed-row.is-failed .habits-closed-name:where(.tg-habits-surface, .tg-habits-surface *) { + text-decoration: line-through; +} + +.habits-closed-status:where(.tg-habits-surface, .tg-habits-surface *) { + display: inline-flex; + align-items: center; + gap: 0.25rem; + color: var(--text-faint); + white-space: nowrap; +} + +.habits-closed-row.is-failed .habits-closed-status:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--color-red, var(--text-error)); +} + +.habits-closed-status-icon:where(.tg-habits-surface, .tg-habits-surface *) { + display: inline-flex; +} + +.habits-closed-status-icon .svg-icon:where(.tg-habits-surface, .tg-habits-surface *) { + width: 0.85em; + height: 0.85em; +} + +.habits-closed-undo:where(.tg-habits-surface, .tg-habits-surface *) { + padding: 0.1rem 0.5rem; + font-size: var(--font-ui-smaller); +} + +table.habits-table .habits-table-toggle.habits-table-closed:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--text-muted); +} + +table.habits-table .habits-table-toggle.habits-table-closed.is-failed:where(.tg-habits-surface, .tg-habits-surface *) { + color: var(--color-red, var(--text-error)); +} + +/* Compact embedded logger: one coloured row per habit. */ +.habits-compact:where(.tg-habits-surface, .tg-habits-surface *) { + position: relative; + border: 1px solid var(--background-modifier-border); + border-radius: 10px; + padding: 8px; + background: var(--background-primary); +} +.habits-compact-header:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + margin-bottom: 8px; +} +.habits-compact-nav:where(.tg-habits-surface, .tg-habits-surface *), .habits-compact-controls:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: center; + gap: 8px; +} +.habits-compact-nav:where(.tg-habits-surface, .tg-habits-surface *) { + position: relative; + justify-content: center; + flex: 0 0 auto; +} +.habits-compact-nav > button:where(.tg-habits-surface, .tg-habits-surface *) { + flex: 0 0 auto; +} +.habits-compact-date:where(.tg-habits-surface, .tg-habits-surface *) { + display: inline-flex; + align-items: center; + justify-content: center; + font-weight: var(--font-semibold); + background: transparent; + box-shadow: none; + padding: 4px; +} +.habits-compact-date-input:where(.tg-habits-surface, .tg-habits-surface *) { + position: absolute !important; + left: 50%; + top: 24px; + width: 1px; + height: 1px; + min-width: 0; + min-height: 0; + max-width: 1px; + max-height: 1px; + margin: 0; + padding: 0; + border: 0; + opacity: 0; + pointer-events: none; +} +.habits-compact-list:where(.tg-habits-surface, .tg-habits-surface *) { display: flex; flex-direction: column; gap: 6px; } +.habits-compact-row:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + min-height: 46px; + padding: 5px 8px; + border: 1px solid var(--background-modifier-border); + border-left: 3px solid var(--habits-accent); + border-radius: 12px; + background: var(--background-secondary); + background: color-mix(in srgb, var(--habits-accent) 8%, var(--background-primary)); +} +/* Match the compact-card reference: completed habits recede but remain usable. */ +.habits-compact-row.is-done:where(.tg-habits-surface, .tg-habits-surface *) { + opacity: 0.58; + filter: saturate(0.45); + border-left-color: var(--background-modifier-border); +} +.habits-compact-row.is-done:hover:where(.tg-habits-surface, .tg-habits-surface *), +.habits-compact-row.is-done:focus-within:where(.tg-habits-surface, .tg-habits-surface *) { + opacity: 0.78; +} +.habits-compact-name:where(.tg-habits-surface, .tg-habits-surface *) { + display: flex; + align-items: center; + gap: 6px; + min-width: 0; + color: var(--text-normal); + font-weight: var(--font-semibold); + text-decoration: none; +} +.habits-compact-name > span:last-child:where(.tg-habits-surface, .tg-habits-surface *) { overflow-wrap: anywhere; } +.habits-compact-icon:where(.tg-habits-surface, .tg-habits-surface *) { display: inline-flex; color: var(--habits-accent); flex-shrink: 0; } +.habits-compact-controls:where(.tg-habits-surface, .tg-habits-surface *) { flex-shrink: 0; color: var(--text-muted); } +.habits-compact-value:where(.tg-habits-surface, .tg-habits-surface *) { font-variant-numeric: tabular-nums; } +.habits-compact-current:where(.tg-habits-surface, .tg-habits-surface *) { color: var(--habits-accent); font-weight: var(--font-semibold); } +.habits-compact .habits-compact-button:where(.tg-habits-surface, .tg-habits-surface *) { width: 32px; height: 32px; padding: 5px; } +.habits-compact .habits-compact-toggle:where(.tg-habits-surface, .tg-habits-surface *) { border-radius: 50%; } +.habits-compact-row.is-done .habits-compact-toggle:where(.tg-habits-surface, .tg-habits-surface *) { color: var(--habits-accent); } +.habits-compact-group:where(.tg-habits-surface, .tg-habits-surface *) { color: var(--text-muted); font-weight: var(--font-semibold); } +.habits-compact-empty:where(.tg-habits-surface, .tg-habits-surface *) { padding: 16px; color: var(--text-muted); text-align: center; } +@media (max-width: 480px) { + .habits-compact-row:where(.tg-habits-surface, .tg-habits-surface *) { flex-wrap: wrap; gap: 6px; padding: 5px 8px; } + .habits-compact-controls:where(.tg-habits-surface, .tg-habits-surface *) { margin-left: auto; } + .habits-compact-value:where(.tg-habits-surface, .tg-habits-surface *) { font-size: var(--font-small); } +} diff --git a/src/integrations/habits/settings.ts b/src/integrations/habits/settings.ts new file mode 100644 index 000000000..27e480305 --- /dev/null +++ b/src/integrations/habits/settings.ts @@ -0,0 +1,1274 @@ +import { t as translate } from "@/translations/helper"; +import { App, Notice, PluginSettingTab, setIcon, Setting } from "obsidian"; +import { t } from "./i18n"; +import type HabitsPlugin from "./main"; +import type { GroupStyle, HabitSortMode } from "./types"; +import { habitAccent, sortHabits } from "./utils"; +import { applyHabitIcon } from "./ui/icon-suggest-modal"; +import { ConfirmModal } from "./ui/confirm-modal"; +import { GroupsModal } from "./ui/groups-modal"; +import { FolderSuggest } from "./ui/vault-suggest"; + +/** + * Feature flags for functionality that is still being tested. + * + * Every flag defaults to off. A flag only ever gates *entry points* (for + * example whether a creation option is offered) — never how existing data + * is interpreted — so turning a flag off can never corrupt or reinterpret + * anything the user created while it was on. Graduating a feature to + * fully-fledged means deleting its flag here and removing the UI guards. + */ +export interface ExperimentalFlags { + /** AI-generated summaries on the weekly and monthly stats tabs. */ + aiSummaries: boolean; + /** + * Note habits: a card backed by a per-day note, completed by reaching a + * character count or checking off every task in it, optionally created + * from a Templater template. + */ + noteHabits: boolean; + /** + * Reviewing and rescheduling missed habits onto a different day, from a + * notification button on the dashboard and sidebar panel. + */ + rescheduling: boolean; +} + +export const DEFAULT_EXPERIMENTAL: ExperimentalFlags = { + aiSummaries: false, + noteHabits: false, + rescheduling: true, +}; + +/** + * The frontmatter property name used for every field a habit note stores. + * Renaming one here only changes what the plugin reads and writes going + * forward — see {@link HabitStore.renameFrontmatterKeys} for moving a + * field's existing value onto its new key across a vault's habit notes. + * + * Defaults match the plugin's original, fixed key names, so an existing + * vault is unaffected until a user changes one in Settings → Advanced. Kept + * deliberately separate from `HabitDefinition`'s field names (in `types.ts`), + * which never change: only the on-disk key is configurable, not the + * in-memory shape the rest of the plugin works with. + * + * `weekday`/`time` each cover two on-disk encodings of the same concept — a + * scalar for a single value, or a `s` list for several — so only the + * singular form is configurable; the plural is always derived from it. + */ +export interface FrontmatterKeys { + type: string; + records: string; + frequency: string; + weekday: string; + monthDay: string; + intervalDays: string; + intervalWindowDays: string; + intervalMode: string; + time: string; + goalDirection: string; + target: string; + unit: string; + step: string; + weeklyTarget: string; + monthlyTarget: string; + weeklyPerfect: string; + monthlyPerfect: string; + startDate: string; + pauses: string; + reschedules: string; + failed: string; + skipped: string; + stopped: string; + stopDate: string; + icon: string; + color: string; + group: string; + useGroupColor: string; + noteFolder: string; + noteFilenameFormat: string; + templatePath: string; + noteCompletionMode: string; + noteChecklistRequirement: string; + noteChecklistMin: string; + noteFailKeyword: string; + /** Legacy: day comments, before they moved into the note body. */ + comments: string; +} + +export const DEFAULT_FRONTMATTER_KEYS: FrontmatterKeys = { + type: "type", + records: "records", + frequency: "frequency", + weekday: "weekday", + monthDay: "monthDay", + intervalDays: "intervalDays", + intervalWindowDays: "intervalWindowDays", + intervalMode: "intervalMode", + time: "time", + goalDirection: "goalDirection", + target: "target", + unit: "unit", + step: "step", + weeklyTarget: "weeklyTarget", + monthlyTarget: "monthlyTarget", + weeklyPerfect: "weeklyPerfect", + monthlyPerfect: "monthlyPerfect", + startDate: "startDate", + pauses: "pauses", + reschedules: "reschedules", + failed: "failed", + skipped: "skipped", + stopped: "stopped", + stopDate: "stopDate", + icon: "icon", + color: "color", + group: "group", + useGroupColor: "useGroupColor", + noteFolder: "noteFolder", + noteFilenameFormat: "noteFilenameFormat", + templatePath: "templatePath", + noteCompletionMode: "noteCompletionMode", + noteChecklistRequirement: "noteChecklistRequirement", + noteChecklistMin: "noteChecklistMin", + noteFailKeyword: "noteFailKeyword", + comments: "comments", +}; + +/** + * Connection details for the AI summaries feature. Any OpenAI-compatible + * chat-completions endpoint works, including local servers (Ollama, + * LM Studio), in which case the API key may be left blank. + */ +export interface AiSummarySettings { + /** Endpoint base URL, e.g. `https://api.openai.com/v1`. */ + baseUrl: string; + /** Bearer token for the endpoint. May be blank for local servers. */ + apiKey: string; + /** Model name to request, e.g. `gpt-4o-mini`. */ + model: string; +} + +export const DEFAULT_AI_SUMMARY: AiSummarySettings = { + baseUrl: "https://api.openai.com/v1", + apiKey: "", + model: "gpt-4o-mini", +}; + +/** + * Where and whether the plugin writes reminder checklist lines for the + * Reminder plugin to pick up. The lines live in a marked block, one per + * planned time of each habit due that day. + */ +export interface ReminderSettings { + /** Master switch; off by default. */ + enabled: boolean; + /** + * `daily-note` writes the block into today's daily note (following the + * core Daily notes plugin's folder and format, once the note exists); + * `fixed-note` keeps it in one dedicated note, created on demand. + */ + target: "daily-note" | "fixed-note"; + /** Vault path of the dedicated note when `target` is `fixed-note`. */ + notePath: string; +} + +export const DEFAULT_REMINDERS: ReminderSettings = { + enabled: false, + target: "daily-note", + notePath: "Habit reminders.md", +}; + +/** How the dashboard presents its habit cards. */ +export type DashboardLayout = "cards" | "carousel" | "grid" | "vertical" | "compact"; + +/** User-configurable settings for the plugin. */ +export interface HabitsPluginSettings { + /** Folder that holds one note per habit. */ + habitsFolder: string; + /** + * How the dashboard shows its cards: a paged carousel, a grid that + * wraps onto new rows, a fixed-height vertically scrolling grid, + * or a compact list with one row per habit. + */ + dashboardLayout: DashboardLayout; + habitColumns?: "auto" | "1" | "2" | "3" | "4"; + nativeLayout?: "cards" | "dashboard"; + layoutUnified?: boolean; + /** How many cards are visible at once in the carousel on wide screens. */ + cardsPerView: number; + /** The base order of habit cards. `name` is the original behaviour. */ + sortMode: HabitSortMode; + /** + * Note paths in the order the user arranged them in settings. Only + * consulted when `sortMode` is `manual`; habits missing from the list + * (created since it was arranged) go to the end. + */ + manualOrder: string[]; + /** + * When true (the original behaviour), completed habits drift to the + * end of the queue and paused ones park behind them. When false every + * card keeps its sorted position. + */ + statusOrdering: boolean; + /** + * Show habits in sections by their group, with a group lip on each + * card. Off by default. + */ + groupsEnabled: boolean; + /** + * Group the rows of `habits-table` blocks by habit group, with a + * heading row per group. When false the table is one flat list, + * ordered by planned time. On by default. + */ + tableGrouping: boolean; + /** Shared group styling (colour, icon), keyed by group name. */ + groups: Record; + /** + * Group names in the order their sections should appear. Groups + * missing from the list append alphabetically. + */ + groupOrder: string[]; + /** How many cards are visible at once on phone-sized screens (1–2). */ + mobileCardsPerView: number; + /** + * When a dashboard is embedded in a daily note (a note whose name + * contains a date), open it on that note's date instead of today. + */ + followDailyNoteDate: boolean; + /** + * Moment.js format used to read the date from a daily note's name, + * e.g. `YYYY-MM-DD` or `YYYYMMDD`. + */ + dailyNoteDateFormat: string; + /** Show the comment flap on dashboard cards. */ + enableComments: boolean; + /** + * Play the completion celebrations: the check swoosh and card + * departure, the perfect-day confetti, and the panel row flash. + * When off, logging updates the view instantly and quietly. + */ + animations: boolean; + /** + * How many habit rows each stats carousel page shows. Only applies + * while the layout is `carousel`; grid and vertical layouts show the + * stats as one flat list. + */ + statsRowsPerPage: number; + /** Opt-in switches for features that are still being tested. */ + experimental: ExperimentalFlags; + /** Connection details used when AI summaries are enabled. */ + aiSummary: AiSummarySettings; + /** Reminder-line generation for the Reminder plugin. */ + reminders: ReminderSettings; + /** + * Snoozed habits: habit note path → when the snooze ends (epoch ms). + * Kept here rather than in the habit note because a snooze is + * short-lived and never affects stats. Expired entries are pruned + * whenever a snooze is set or cleared. + */ + snoozes: Record; + /** + * Frontmatter property names, so a habit note's frontmatter can share a + * note with another plugin's own properties without colliding. + */ + frontmatterKeys: FrontmatterKeys; +} + +export const DEFAULT_SETTINGS: HabitsPluginSettings = { + habitsFolder: "Habits", + dashboardLayout: "carousel", + cardsPerView: 4, + sortMode: "name", + manualOrder: [], + statusOrdering: true, + groupsEnabled: false, + tableGrouping: true, + groups: {}, + groupOrder: [], + mobileCardsPerView: 2, + followDailyNoteDate: true, + dailyNoteDateFormat: "YYYY-MM-DD", + enableComments: true, + animations: true, + statsRowsPerPage: 4, + experimental: { ...DEFAULT_EXPERIMENTAL }, + aiSummary: { ...DEFAULT_AI_SUMMARY }, + reminders: { ...DEFAULT_REMINDERS }, + snoozes: {}, + frontmatterKeys: { ...DEFAULT_FRONTMATTER_KEYS }, +}; + +/** The three top-level tabs the settings UI is split into. */ +type SettingsTabId = "general" | "experimental" | "advanced"; + +/** Settings tab shown under Settings → Community plugins → Habits. */ +export class HabitsSettingTab extends PluginSettingTab { + private plugin: HabitsPlugin; + + constructor(app: App, plugin: HabitsPlugin) { + super(app, plugin); + this.plugin = plugin; + } + + /** + * The drag-to-reorder editor shown when sorting is manual: one slim + * row per habit that can be dragged (mouse or touch) into place. The + * arranged order is stored as note paths in `manualOrder`. + */ + private renderManualOrderEditor(setting: Setting): void { + setting.settingEl.addClass("habits-order-setting"); + const list = setting.settingEl.createDiv({ + cls: "habits-order-list", + }); + this.buildOrderList(list); + } + + private buildOrderList(list: HTMLElement): void { + list.empty(); + const habits = sortHabits( + this.plugin.store.getHabits().filter((habit) => !habit.stopped), + "manual", + this.plugin.settings.manualOrder, + this.plugin.settings.groups, + this.plugin.settings.groupOrder, + ); + for (const habit of habits) { + const row = list.createDiv({ cls: "habits-order-row" }); + row.dataset.path = habit.path; + const accent = habitAccent(habit, this.plugin.settings.groups); + if (accent) { + row.setCssProps({ "--habits-accent": accent }); + } + const grip = row.createSpan({ cls: "habits-order-grip" }); + setIcon(grip, "grip-vertical"); + if (habit.icon) { + const icon = row.createSpan({ cls: "habits-order-icon" }); + applyHabitIcon(icon, habit.icon); + } + row.createSpan({ cls: "habits-order-name", text: habit.name }); + this.registerRowDrag(row, list, ".habits-order-row", () => { + void this.persistOrder(list); + }); + } + } + + /** + * The drag-to-reorder editor for group sections, shown while groups + * are enabled. Stores the arranged names in `groupOrder`. + */ + private renderGroupOrderEditor(setting: Setting): void { + setting.settingEl.addClass("habits-order-setting"); + const list = setting.settingEl.createDiv({ + cls: "habits-order-list", + }); + this.buildGroupOrderList(list); + } + + /** Every known group: in use by a habit, styled, or already ordered. */ + private knownGroups(): string[] { + const names = new Set(); + for (const habit of this.plugin.store.getHabits()) { + const group = habit.group.trim(); + if (group && !habit.stopped) { + names.add(group); + } + } + for (const name of Object.keys(this.plugin.settings.groups)) { + names.add(name); + } + const position = new Map( + this.plugin.settings.groupOrder.map((name, index) => [ + name, + index, + ]), + ); + return Array.from(names).sort((a, b) => { + const pa = position.get(a) ?? Number.MAX_SAFE_INTEGER; + const pb = position.get(b) ?? Number.MAX_SAFE_INTEGER; + return pa - pb || a.localeCompare(b); + }); + } + + private buildGroupOrderList(list: HTMLElement): void { + list.empty(); + for (const name of this.knownGroups()) { + const row = list.createDiv({ cls: "habits-order-row" }); + row.dataset.group = name; + const style = this.plugin.settings.groups[name]; + if (style?.color) { + row.setCssProps({ "--habits-accent": style.color }); + } + const grip = row.createSpan({ cls: "habits-order-grip" }); + setIcon(grip, "grip-vertical"); + if (style?.icon) { + const icon = row.createSpan({ cls: "habits-order-icon" }); + applyHabitIcon(icon, style.icon); + } + row.createSpan({ cls: "habits-order-name", text: name }); + this.registerRowDrag(row, list, ".habits-order-row", () => { + void this.persistGroupOrder(list); + }); + } + } + + /** Store the DOM order of the rows as the new group order. */ + private async persistGroupOrder(list: HTMLElement): Promise { + const names: string[] = []; + for (const el of Array.from( + list.querySelectorAll(".habits-order-row"), + )) { + if (el.dataset.group) { + names.push(el.dataset.group); + } + } + this.plugin.settings.groupOrder = names; + await this.plugin.saveSettings(); + } + + /** + * Pointer-based dragging (rather than HTML5 drag events) so the rows + * can be rearranged by touch on mobile as well as by mouse. The move + * and release listeners sit on the window, not the row: reordering + * re-inserts the row into the list, which would clear any pointer + * capture on it and kill the drag mid-flight. + */ + private registerRowDrag( + row: HTMLElement, + list: HTMLElement, + selector: string, + onDrop: () => void, + ): void { + row.addEventListener("pointerdown", (evt: PointerEvent) => { + if (evt.button !== 0) { + return; + } + evt.preventDefault(); + row.addClass("is-dragging"); + const win = row.win; + + const onMove = (e: PointerEvent): void => { + const rows = Array.from( + list.querySelectorAll(selector), + ).filter((el) => el !== row); + const next = rows.find( + (el) => + e.clientY < + el.getBoundingClientRect().top + el.offsetHeight / 2, + ); + if (next) { + if (next !== row.nextElementSibling) { + list.insertBefore(row, next); + } + } else if (list.lastElementChild !== row) { + list.appendChild(row); + } + }; + const onUp = (): void => { + row.removeClass("is-dragging"); + win.removeEventListener("pointermove", onMove); + win.removeEventListener("pointerup", onUp); + win.removeEventListener("pointercancel", onUp); + onDrop(); + }; + win.addEventListener("pointermove", onMove); + win.addEventListener("pointerup", onUp); + win.addEventListener("pointercancel", onUp); + }); + } + + /** Store the DOM order of the rows as the new manual order. */ + private async persistOrder(list: HTMLElement): Promise { + const paths: string[] = []; + for (const el of Array.from( + list.querySelectorAll(".habits-order-row"), + )) { + if (el.dataset.path) { + paths.push(el.dataset.path); + } + } + this.plugin.settings.manualOrder = paths; + await this.plugin.saveSettings(); + } + + /** Which of the three tabs is currently shown. */ + private activeTab: SettingsTabId = "general"; + + /** + * Renders the settings tab as three persistent top tabs (General, + * Experimental, Advanced) rather than one long scrolling page. Obsidian + * has no built-in tab-bar control, so this is hand-rolled; that also + * means the plugin's settings are no longer indexed by Obsidian's own + * settings search (that only worked through the declarative + * getSettingDefinitions() API this tab used to implement, which cannot + * coexist with custom chrome drawn around its content). + */ + display(): void { + const { containerEl } = this; + containerEl.empty(); + + const tabBar = containerEl.createDiv({ cls: "habits-settings-tabs" }); + const content = containerEl.createDiv({ + cls: "habits-settings-tab-content", + }); + + const tabs: { + id: SettingsTabId; + label: string; + render: (el: HTMLElement) => void; + }[] = [ + { + id: "general", + label: t("General"), + render: (el) => this.displayGeneral(el), + }, + { + id: "experimental", + label: t("Experimental"), + render: (el) => this.displayExperimental(el), + }, + { + id: "advanced", + label: t("Advanced"), + render: (el) => this.displayAdvanced(el), + }, + ]; + + const selectTab = (id: SettingsTabId): void => { + this.activeTab = id; + buttons.forEach((button, i) => + button.toggleClass("is-active", tabs[i].id === id), + ); + content.empty(); + tabs.find((tab) => tab.id === id)?.render(content); + }; + + const buttons = tabs.map((tab) => { + const button = tabBar.createEl("button", { + cls: "habits-settings-tab", + text: tab.label, + }); + button.addEventListener("click", () => selectTab(tab.id)); + return button; + }); + + selectTab(this.activeTab); + } + + /** General settings: everything that isn't Experimental or Advanced. */ + private displayGeneral(containerEl: HTMLElement): void { + new Setting(containerEl).setName(translate("Ignore all past missed habits")).setDesc(translate("Dismiss reminders before today. Habit records and points stay unchanged.")) + .addButton(button => button.setButtonText(translate("Ignore past misses")).onClick(async () => { + button.setDisabled(true); + try { await this.plugin.store.ignoreAllPastMisses(); this.plugin.events.trigger("settings-changed"); new Notice(translate("Past missed habit reminders ignored.")); } + catch (error) { new Notice(String(error)); } + finally { button.setDisabled(false); } + })); + new Setting(containerEl) + .setName(t("Habits folder")) + .setDesc( + t( + "Folder where each habit is stored as its own note. It is created automatically if it does not exist.", + ), + ) + .addText((text) => { + text + .setPlaceholder("Habits") + .setValue(this.plugin.settings.habitsFolder) + .onChange(async (value) => { + this.plugin.settings.habitsFolder = + value.trim() || DEFAULT_SETTINGS.habitsFolder; + await this.plugin.saveSettings(); + }); + new FolderSuggest(this.app, text.inputEl); + }); + + new Setting(containerEl) + .setName(t("Follow daily note date")) + .setDesc( + t( + "When a dashboard is embedded in a daily note (a note whose name contains a date like 2026-07-01), open it on that note's date instead of today.", + ), + ) + .addToggle((toggle) => + toggle + .setValue(this.plugin.settings.followDailyNoteDate) + .onChange(async (value) => { + this.plugin.settings.followDailyNoteDate = value; + await this.plugin.saveSettings(); + }), + ); + + new Setting(containerEl) + .setName(t("Daily note date format")) + .setDesc( + t( + "Moment.js format used to read the date from a daily note's name, such as YYYY-MM-DD or YYYYMMDD.", + ), + ) + .addText((text) => + text + .setPlaceholder("YYYY-MM-DD") + .setValue(this.plugin.settings.dailyNoteDateFormat) + .onChange(async (value) => { + this.plugin.settings.dailyNoteDateFormat = + value.trim() || DEFAULT_SETTINGS.dailyNoteDateFormat; + await this.plugin.saveSettings(); + }), + ); + + new Setting(containerEl) + .setName(t("Comments on cards")) + .setDesc( + t( + "Show a comment flap on dashboard cards for jotting a note about any day.", + ), + ) + .addToggle((toggle) => + toggle + .setValue(this.plugin.settings.enableComments) + .onChange(async (value) => { + this.plugin.settings.enableComments = value; + await this.plugin.saveSettings(); + }), + ); + + new Setting(containerEl) + .setName(t("Completion animations")) + .setDesc( + t( + "Play the check swoosh, card departure, and perfect-day confetti when habits are completed. Turn off for instant, quiet updates.", + ), + ) + .addToggle((toggle) => + toggle + .setValue(this.plugin.settings.animations) + .onChange(async (value) => { + this.plugin.settings.animations = value; + await this.plugin.saveSettings(); + }), + ); + + new Setting(containerEl).setName(t("Layout")).setHeading(); + + new Setting(containerEl).setName(t("Task Genius habit layout")) + .setDesc(t("Choose the page layout. Habit goals, schedules and records stay the same.")) + .addDropdown(dropdown => dropdown + .addOption("cards", t("Task Genius cards")) + .addOption("compact", t("Compact list")) + .addOption("grid", t("Grid")) + .addOption("carousel", t("Carousel")) + .addOption("vertical", t("Vertical scroll")) + .setValue(this.plugin.settings.dashboardLayout).onChange(async value => { + this.plugin.settings.dashboardLayout = value as DashboardLayout; + delete this.plugin.settings.nativeLayout; + await this.plugin.saveSettings(); + renderStatsOptions(); + })); + + new Setting(containerEl).setName(t("Habit columns")).setDesc(t("Choose a fixed column count or fit cards to the available space.")) + .addDropdown(dropdown => dropdown.addOption("auto", t("Automatic")).addOption("1", "1").addOption("2", "2").addOption("3", "3").addOption("4", "4") + .setValue(this.plugin.settings.habitColumns || "auto").onChange(async value => { this.plugin.settings.habitColumns = value as HabitsPluginSettings["habitColumns"]; await this.plugin.saveSettings(); })); + + new Setting(containerEl) + .setName(t("Cards per view")) + .setDesc( + t( + "How many habit cards fit side by side on wider screens.", + ), + ) + .addDropdown((dropdown) => + dropdown + .addOption("1", "1") + .addOption("2", "2") + .addOption("3", "3") + .addOption("4", "4") + .setValue(String(this.plugin.settings.cardsPerView)) + .onChange(async (value) => { + this.plugin.settings.cardsPerView = Number(value); + await this.plugin.saveSettings(); + }), + ); + + new Setting(containerEl) + .setName(t("Cards per view on mobile")) + .setDesc( + t( + "How many habit cards fit side by side on phone-sized screens.", + ), + ) + .addDropdown((dropdown) => + dropdown + .addOption("1", "1") + .addOption("2", "2") + .setValue( + String(this.plugin.settings.mobileCardsPerView), + ) + .onChange(async (value) => { + this.plugin.settings.mobileCardsPerView = + Number(value); + await this.plugin.saveSettings(); + }), + ); + + // In its own container so changing the layout can redraw just + // this block instead of the whole tab. + const statsDetails = containerEl.createDiv(); + const renderStatsOptions = (): void => { + statsDetails.empty(); + if (this.plugin.settings.dashboardLayout !== "carousel") { + return; + } + new Setting(statsDetails) + .setName(t("Stats rows per page")) + .setDesc(t("How many habits each stats page shows.")) + .addDropdown((dropdown) => { + for (let n = 1; n <= 8; n++) { + dropdown.addOption(String(n), String(n)); + } + dropdown + .setValue( + String(this.plugin.settings.statsRowsPerPage), + ) + .onChange(async (value) => { + this.plugin.settings.statsRowsPerPage = + Number(value); + await this.plugin.saveSettings(); + }); + }); + }; + renderStatsOptions(); + + new Setting(containerEl).setName(t("Sorting")).setHeading(); + + new Setting(containerEl) + .setName(t("Sort habits by")) + .setDesc( + t( + "The base order of habit cards in the dashboard and side panel.", + ), + ) + .addDropdown((dropdown) => + dropdown + .addOption("name", t("Name (A–Z)")) + .addOption("color", t("Color")) + .addOption("startDate", t("Start date")) + .addOption("lastLogged", t("Last logged")) + .addOption("time", t("Planned time")) + .addOption("group", t("Group")) + .addOption("manual", t("Manual")) + .setValue(this.plugin.settings.sortMode) + .onChange(async (value) => { + this.plugin.settings.sortMode = [ + "name", + "color", + "startDate", + "lastLogged", + "time", + "group", + "manual", + ].includes(value) + ? (value as HabitSortMode) + : "name"; + await this.plugin.saveSettings(); + manualOrderSetting.settingEl.toggle( + this.plugin.settings.sortMode === "manual", + ); + groupOrderSetting.settingEl.toggle( + this.plugin.settings.sortMode === "group", + ); + }), + ); + + // Always rendered, shown only while sorting is manual. + const manualOrderSetting = new Setting(containerEl) + .setName(t("Manual order")) + .setDesc( + t( + "Drag the cards into the order you want. New habits join the end of the list.", + ), + ); + this.renderManualOrderEditor(manualOrderSetting); + manualOrderSetting.settingEl.toggle( + this.plugin.settings.sortMode === "manual", + ); + + // Always rendered, shown only while sorting by group. + const groupOrderSetting = new Setting(containerEl) + .setName(t("Group order")) + .setDesc( + t( + "Drag the groups into the order you want. Sections follow the same order.", + ), + ); + this.renderGroupOrderEditor(groupOrderSetting); + groupOrderSetting.settingEl.toggle( + this.plugin.settings.sortMode === "group", + ); + + new Setting(containerEl) + .setName(t("Move completed cards to the end")) + .setDesc( + t( + "Completed habits drift to the end of the queue and paused ones park behind them. Turn this off to keep every card in its sorted position.", + ), + ) + .addToggle((toggle) => + toggle + .setValue(this.plugin.settings.statusOrdering) + .onChange(async (value) => { + this.plugin.settings.statusOrdering = value; + await this.plugin.saveSettings(); + }), + ); + + new Setting(containerEl).setName(t("Groups")).setHeading(); + + new Setting(containerEl) + .setName(t("Enable groups")) + .setDesc( + t( + "Show habits in sections by their group, with a group lip on each card.", + ), + ) + .addToggle((toggle) => + toggle + .setValue(this.plugin.settings.groupsEnabled) + .onChange(async (value) => { + this.plugin.settings.groupsEnabled = value; + await this.plugin.saveSettings(); + groupDetails.toggle(value); + }), + ); + + // The group tools only matter while groups are on. + const groupDetails = containerEl.createDiv(); + new Setting(groupDetails) + .setName(t("Manage groups")) + .setDesc( + t("See every habit by group and drag cards between groups."), + ) + .addButton((button) => + button.setButtonText(t("Open")).onClick(() => { + new GroupsModal( + this.app, + this.plugin.store, + () => this.plugin.settings, + () => this.plugin.saveSettings(), + ).open(); + }), + ); + groupDetails.toggle(this.plugin.settings.groupsEnabled); + + this.displayReminders(containerEl); + } + + /** Reminder-line generation for the Reminder plugin. */ + private displayReminders(containerEl: HTMLElement): void { + new Setting(containerEl).setName(t("Reminders")).setHeading(); + + new Setting(containerEl) + .setName(t("Write reminders for due habits")) + .setDesc( + t( + "Each day, write one reminder checklist line per planned time of every habit due that day, in the format the Reminder plugin picks up. The lines live in a marked block and refresh as you log habits.", + ), + ) + .addToggle((toggle) => + toggle + .setValue(this.plugin.settings.reminders.enabled) + .onChange(async (value) => { + this.plugin.settings.reminders.enabled = value; + await this.plugin.saveSettings(); + reminderDetails.toggle(value); + notePathSetting.settingEl.toggle( + value && + this.plugin.settings.reminders.target === + "fixed-note", + ); + }), + ); + + const reminderDetails = containerEl.createDiv(); + new Setting(reminderDetails) + .setName(t("Where to write reminders")) + .setDesc( + t( + "The daily note follows the Daily notes core plugin's folder and date format; the block is added once the note exists. A fixed note is created automatically.", + ), + ) + .addDropdown((dropdown) => + dropdown + .addOption("daily-note", t("Today's daily note")) + .addOption("fixed-note", t("A fixed note")) + .setValue(this.plugin.settings.reminders.target) + .onChange(async (value) => { + this.plugin.settings.reminders.target = + value === "fixed-note" ? "fixed-note" : "daily-note"; + await this.plugin.saveSettings(); + notePathSetting.settingEl.toggle( + this.plugin.settings.reminders.target === + "fixed-note", + ); + }), + ); + + const notePathSetting = new Setting(reminderDetails) + .setName(t("Reminder note path")) + .setDesc( + t("Vault path of the note that holds the reminder block."), + ) + .addText((text) => + text + .setPlaceholder(DEFAULT_REMINDERS.notePath) + .setValue(this.plugin.settings.reminders.notePath) + .onChange(async (value) => { + this.plugin.settings.reminders.notePath = + value.trim() || DEFAULT_REMINDERS.notePath; + await this.plugin.saveSettings(); + }), + ); + reminderDetails.toggle(this.plugin.settings.reminders.enabled); + notePathSetting.settingEl.toggle( + this.plugin.settings.reminders.enabled && + this.plugin.settings.reminders.target === "fixed-note", + ); + } + + /** + * Opt-in toggles for features still being tested. Turning a flag off + * only hides the feature's entry points; anything already created with + * it keeps working and keeps its meaning. + */ + private displayExperimental(containerEl: HTMLElement): void { + containerEl.createEl("p", { + cls: "habits-experimental-note", + text: t( + "These features are still being tested and may change before they become permanent. Turning one off only hides it from menus — anything you created with it keeps working.", + ), + }); + + new Setting(containerEl) + .setName(t("Note habits")) + .setDesc( + t( + "Track a habit by writing in a per-day note instead of logging a value by hand. A day is complete once the note reaches a character count or every task in it is checked. Works with the Templater plugin to create each day's note from a template.", + ), + ) + .addToggle((toggle) => + toggle + .setValue(this.plugin.settings.experimental.noteHabits) + .onChange(async (value) => { + this.plugin.settings.experimental.noteHabits = value; + await this.plugin.saveSettings(); + }), + ); + + + new Setting(containerEl) + .setName(t("AI summaries")) + .setDesc( + t( + "Show an AI-generated summary with feedback and advice on the stats page tabs. Uses an OpenAI-compatible service you configure below; your habit stats are sent to it only when you press the generate button.", + ), + ) + .addToggle((toggle) => + toggle + .setValue(this.plugin.settings.experimental.aiSummaries) + .onChange(async (value) => { + this.plugin.settings.experimental.aiSummaries = value; + await this.plugin.saveSettings(); + // Show or hide the connection fields with the toggle. + renderAiFields(); + }), + ); + + // The connection fields live in their own container so toggling the + // feature can redraw just this block instead of the whole tab. + const aiDetails = containerEl.createDiv(); + const renderAiFields = (): void => { + aiDetails.empty(); + if (this.plugin.settings.experimental.aiSummaries) { + this.displayAiSummary(aiDetails); + } + }; + renderAiFields(); + } + + /** Connection fields for the AI summaries feature (shown only when on). */ + private displayAiSummary(containerEl: HTMLElement): void { + new Setting(containerEl) + .setName(t("AI base URL")) + .setDesc( + t( + "Base URL of an OpenAI-compatible API. Works with OpenAI, OpenRouter, or local servers like Ollama (http://localhost:11434/v1).", + ), + ) + .addText((text) => + text + .setPlaceholder(DEFAULT_AI_SUMMARY.baseUrl) + .setValue(this.plugin.settings.aiSummary.baseUrl) + .onChange(async (value) => { + this.plugin.settings.aiSummary.baseUrl = + value.trim() || DEFAULT_AI_SUMMARY.baseUrl; + await this.plugin.saveSettings(); + }), + ); + + new Setting(containerEl) + .setName(t("AI API key")) + .setDesc( + t( + "Stored locally in this vault's plugin data. Leave blank for local servers that need no key.", + ), + ) + .addText((text) => { + text.inputEl.type = "password"; + text + .setValue(this.plugin.settings.aiSummary.apiKey) + .onChange(async (value) => { + this.plugin.settings.aiSummary.apiKey = value.trim(); + await this.plugin.saveSettings(); + }); + }); + + new Setting(containerEl) + .setName(t("AI model")) + .setDesc(t("Model name the service should use.")) + .addText((text) => + text + .setPlaceholder(DEFAULT_AI_SUMMARY.model) + .setValue(this.plugin.settings.aiSummary.model) + .onChange(async (value) => { + this.plugin.settings.aiSummary.model = + value.trim() || DEFAULT_AI_SUMMARY.model; + await this.plugin.saveSettings(); + }), + ); + } + + /** Content of the "Advanced" tab: frontmatter property-key remapping. */ + private displayAdvanced(containerEl: HTMLElement): void { + new FrontmatterKeysEditor(this.app, this.plugin).render(containerEl); + } +} + +/** + * Human-readable label for each configurable frontmatter key, grouped the + * way they're presented in the Advanced page/section. + */ +const FRONTMATTER_KEY_GROUPS: { + heading: () => string; + fields: [keyof FrontmatterKeys, () => string][]; +}[] = [ + { + heading: () => t("Identity"), + fields: [ + ["type", () => t("Habit type key")], + ["records", () => t("Completion records key")], + ], + }, + { + heading: () => t("Schedule"), + fields: [ + ["frequency", () => t("Frequency key")], + ["weekday", () => t("Weekday key")], + ["monthDay", () => t("Month day key")], + ["intervalDays", () => t("Interval days key")], + ["intervalWindowDays", () => t("Interval window days key")], + ["intervalMode", () => t("Interval schedule key")], + ["time", () => t("Planned time key")], + ], + }, + { + heading: () => t("Goal"), + fields: [ + ["goalDirection", () => t("Goal direction key")], + ["target", () => t("Target key")], + ["unit", () => t("Unit key")], + ["step", () => t("Step size key")], + ["weeklyTarget", () => t("Weekly target key")], + ["monthlyTarget", () => t("Monthly target key")], + ["weeklyPerfect", () => t("Weekly perfect key")], + ["monthlyPerfect", () => t("Monthly perfect key")], + ], + }, + { + heading: () => t("Lifecycle"), + fields: [ + ["startDate", () => t("Start date key")], + ["pauses", () => t("Pauses key")], + ["reschedules", () => t("Reschedules key")], + ["failed", () => t("Failed days key")], + ["skipped", () => t("Skipped days key")], + ["stopped", () => t("Stopped key")], + ["stopDate", () => t("Stop date key")], + ], + }, + { + heading: () => t("Presentation"), + fields: [ + ["icon", () => t("Icon key")], + ["color", () => t("Color key")], + ["group", () => t("Group key")], + ["useGroupColor", () => t("Use group color key")], + ], + }, + { + heading: () => t("Note habit"), + fields: [ + ["noteFolder", () => t("Note folder key")], + ["noteFilenameFormat", () => t("Note filename format key")], + ["templatePath", () => t("Template path key")], + ["noteCompletionMode", () => t("Note completion mode key")], + [ + "noteChecklistRequirement", + () => t("Note checklist requirement key"), + ], + ["noteChecklistMin", () => t("Note checklist minimum key")], + ["noteFailKeyword", () => t("Note fail keyword key")], + ], + }, + { + heading: () => t("Legacy"), + fields: [["comments", () => t("Legacy comments key")]], + }, +]; + +/** + * Editor for the frontmatter-key remapping, rendered inline into the + * "Advanced" tab's content by {@link HabitsSettingTab.displayAdvanced}. + * + * Edits are held locally until "Apply key changes" is pressed: applying + * validates the whole set at once (no blanks, no two fields sharing a key), + * confirms with the user via {@link ConfirmModal}, then moves each renamed + * field's existing value onto its new key across every habit note before + * saving the setting — see {@link HabitStore.renameFrontmatterKeys}. + */ +class FrontmatterKeysEditor { + private pending: FrontmatterKeys; + private applySetting?: Setting; + + constructor( + private app: App, + private plugin: HabitsPlugin, + ) { + this.pending = { ...this.plugin.settings.frontmatterKeys }; + } + + render(containerEl: HTMLElement): void { + containerEl.createEl("p", { + cls: "habits-advanced-note", + text: t( + "Rename the frontmatter properties habit notes use. Useful for avoiding collisions with another plugin's own properties in the same note (for example TaskNotes).", + ), + }); + + for (const group of FRONTMATTER_KEY_GROUPS) { + new Setting(containerEl).setName(group.heading()).setHeading(); + for (const [field, label] of group.fields) { + const setting = new Setting(containerEl).setName(label()); + if (field === "records") { + setting.setDesc( + t( + "Renaming this away from the default also changes how binary habits log a day: instead of {\"2026-08-25\": 1}, a completed day becomes a bare date, like [\"2026-08-25\"] — the shape TaskNotes uses for complete_instances. Repetition and timed habits are unaffected either way; they always need a value, never just a date.", + ), + ); + } + setting.addText((text) => + text.setValue(this.pending[field]).onChange((value) => { + this.pending[field] = value; + this.refreshApplyVisibility(); + }), + ); + } + } + + this.applySetting = new Setting(containerEl).addButton((button) => + button + .setButtonText(t("Apply key changes")) + .setCta() + .onClick(() => { + void this.apply(); + }), + ); + this.refreshApplyVisibility(); + } + + private isDirty(): boolean { + const saved = this.plugin.settings.frontmatterKeys; + return (Object.keys(this.pending) as (keyof FrontmatterKeys)[]).some( + (field) => this.pending[field].trim() !== saved[field], + ); + } + + private refreshApplyVisibility(): void { + this.applySetting?.settingEl.toggle(this.isDirty()); + } + + private async apply(): Promise { + const saved = this.plugin.settings.frontmatterKeys; + const fields = Object.keys(this.pending) as (keyof FrontmatterKeys)[]; + + const seen = new Map(); + for (const field of fields) { + const value = this.pending[field].trim(); + if (!value) { + new Notice(t("Property keys can't be empty.")); + return; + } + this.pending[field] = value; + const clash = seen.get(value); + if (clash) { + new Notice( + t( + '"{a}" and "{b}" can\'t use the same property key ("{value}").', + { a: clash, b: field, value }, + ), + ); + return; + } + seen.set(value, field); + } + + const renames = fields + .filter((field) => this.pending[field] !== saved[field]) + .map((field) => ({ old: saved[field], new: this.pending[field] })); + if (renames.length === 0) { + return; + } + + const summary = renames + .map((r) => `"${r.old}" → "${r.new}"`) + .join(", "); + const count = this.plugin.store.getHabits().length; + new ConfirmModal(this.app, { + title: t("Apply key changes"), + message: t( + "This renames {summary} in every note in your habits folder ({count} habit(s) currently). Existing values are moved, not discarded. Continue?", + { summary, count }, + ), + confirmText: t("Apply"), + onConfirm: async () => { + // Settings are saved *before* the notes are rewritten: the + // rewrite fires metadataCache "changed" events for each + // file as it's touched, and anything reacting to those + // (e.g. a habit-metrics block) must already see the new + // key mapping — otherwise it re-reads a note whose data + // just moved to the new key using the old one, finds + // nothing, and stays empty until something else happens + // to trigger a further refresh. + this.plugin.settings.frontmatterKeys = { ...this.pending }; + await this.plugin.saveSettings(); + const changed = + await this.plugin.store.renameFrontmatterKeys(renames); + new Notice( + t("Updated the frontmatter keys in {count} note(s).", { + count: changed, + }), + ); + this.refreshApplyVisibility(); + }, + }).open(); + } +} diff --git a/src/integrations/habits/stats.ts b/src/integrations/habits/stats.ts new file mode 100644 index 000000000..ae7a8114f --- /dev/null +++ b/src/integrations/habits/stats.ts @@ -0,0 +1,928 @@ +import type { HabitDefinition } from "./types"; +import { + addDays, + daysInMonth, + fromDateKey, + isFlexibleFrequency, + toDateKey, +} from "./utils"; + +const MS_PER_DAY = 86_400_000; + +export type StatsPeriod = "weekly" | "monthly" | "custom"; +export type StatsRangeMode = "rolling" | "calendar"; + +/** + * Longest span a custom range may cover. Keeps the per-habit heatmaps + * renderable — a full year is 366 cells; an accidental decade would be + * thousands. + */ +export const MAX_CUSTOM_DAYS = 366; + +export interface DateRange { + start: Date; + end: Date; +} + +/** Midnight of the given date, in local time. */ +function startOfDay(date: Date): Date { + return new Date(date.getFullYear(), date.getMonth(), date.getDate()); +} + +/** Monday of the week containing the given date. */ +function startOfWeek(date: Date): Date { + const base = startOfDay(date); + const offset = (base.getDay() + 6) % 7; // Monday = 0 + return addDays(base, -offset); +} + +/** True for the two "N times per period, any day" frequencies. */ +export function isFlexible(habit: HabitDefinition): boolean { + return isFlexibleFrequency(habit.frequency); +} + +/** + * Whether a habit's card should show and be interactive on `date`. + * + * For every other frequency this is exactly {@link isDue}. Flexible + * habits are due (in the stats sense) only on their period's last day — + * see {@link isDue} — but need to be actionable every day so the user can + * log an occurrence whenever it actually happens. + */ +export function isActive(habit: HabitDefinition, date: Date): boolean { + const key = toDateKey(date); + if (rescheduleTarget(habit, key) || rescheduleSource(habit, key)) return isDue(habit, date); + if (habit.frequency === "interval" && habit.intervalMode !== "cycle" && (habit.intervalWindowDays || 1) > 1) return !!intervalWindow(habit, date)?.active; + return isDue(habit, date) || isFlexible(habit); +} + +/** The Monday–Sunday week, or calendar month, containing `date`. */ +export function flexiblePeriodRange( + habit: HabitDefinition, + date: Date, +): DateRange { + if (habit.frequency === "flexibleWeekly") { + const start = startOfWeek(date); + return { start, end: addDays(start, 6) }; + } + const base = startOfDay(date); + return { + start: new Date(base.getFullYear(), base.getMonth(), 1), + end: new Date(base.getFullYear(), base.getMonth() + 1, 0), + }; +} + +/** The period immediately before `range` (mirrors its week/month shape). */ +function previousPeriodRange( + habit: HabitDefinition, + range: DateRange, +): DateRange { + if (habit.frequency === "flexibleWeekly") { + const start = addDays(range.start, -7); + return { start, end: addDays(start, 6) }; + } + const prevEnd = addDays(range.start, -1); + return { + start: new Date(prevEnd.getFullYear(), prevEnd.getMonth(), 1), + end: prevEnd, + }; +} + +/** The period immediately after `range` (mirrors its week/month shape). */ +function nextPeriodRange( + habit: HabitDefinition, + range: DateRange, +): DateRange { + if (habit.frequency === "flexibleWeekly") { + const start = addDays(range.start, 7); + return { start, end: addDays(start, 6) }; + } + const nextStart = addDays(range.end, 1); + return { + start: nextStart, + end: new Date(nextStart.getFullYear(), nextStart.getMonth() + 1, 0), + }; +} + +/** Every day in `range` is paused — a whole period to leave out of streaks. */ +function periodFullyPaused(habit: HabitDefinition, range: DateRange): boolean { + let cursor = new Date(range.start); + while (cursor.getTime() <= range.end.getTime()) { + if (!isPausedOn(habit, toDateKey(cursor))) { + return false; + } + cursor = addDays(cursor, 1); + } + return true; +} + +/** Sum of `records` within `range`, from its start through `throughDate`. */ +function periodTotalThrough( + habit: HabitDefinition, + range: DateRange, + throughDate: Date, +): number { + const end = + throughDate.getTime() < range.end.getTime() ? throughDate : range.end; + let total = 0; + let cursor = new Date(range.start); + while (cursor.getTime() <= end.getTime()) { + total += habit.records[toDateKey(cursor)] ?? 0; + cursor = addDays(cursor, 1); + } + return total; +} + +/** + * A flexible habit's period-cumulative total, from the start of the period + * containing `date` through `date` itself. On a non-canonical day this is a + * live "have I hit quota yet this period" reading; on the period's last day + * it is the authoritative full-period total. + */ +export function flexiblePeriodTotal( + habit: HabitDefinition, + date: Date, +): number { + return periodTotalThrough(habit, flexiblePeriodRange(habit, date), date); +} + +/** Whether a period total reaches a flexible habit's "times per period" goal. */ +function meetsFlexibleTarget(habit: HabitDefinition, total: number): boolean { + if (habit.goalDirection === "max") return total <= limitOf(habit); + return habit.target > 0 ? total >= habit.target : total > 0; +} + +/** Number of whole days from start to end, inclusive. */ +export function rangeLength(range: DateRange): number { + return ( + Math.round((range.start.getTime() - range.end.getTime()) / -MS_PER_DAY) + + 1 + ); +} + +/** + * Bring a user-picked custom range into canonical form: reversed ends are + * swapped, times are stripped, and the span is capped at + * {@link MAX_CUSTOM_DAYS} (keeping the chosen end). Without a range, the + * last 14 days are used as a sensible starting point. + */ +export function normalizeCustomRange( + custom: DateRange | undefined, + today: Date, +): DateRange { + const base = startOfDay(today); + if (!custom) { + return { start: addDays(base, -13), end: base }; + } + let start = startOfDay(custom.start); + let end = startOfDay(custom.end); + if (start.getTime() > end.getTime()) { + [start, end] = [end, start]; + } + if (rangeLength({ start, end }) > MAX_CUSTOM_DAYS) { + start = addDays(end, -(MAX_CUSTOM_DAYS - 1)); + } + return { start, end }; +} + +/** + * Resolve the date range for a period and mode. + * + * - rolling: the last 7 or 30 days ending today. + * - calendar: the current week (Monday–Sunday) or current month (dynamic). + * - custom period: the user-picked range (normalized); `mode` is ignored. + */ +export function getStatsRange( + today: Date, + period: StatsPeriod, + mode: StatsRangeMode, + custom?: DateRange, +): DateRange { + if (period === "custom") { + return normalizeCustomRange(custom, today); + } + const base = startOfDay(today); + if (mode === "rolling") { + const length = period === "weekly" ? 7 : 30; + return { start: addDays(base, -(length - 1)), end: base }; + } + if (period === "weekly") { + const start = startOfWeek(base); + return { start, end: addDays(start, 6) }; + } + const start = new Date(base.getFullYear(), base.getMonth(), 1); + const end = new Date(base.getFullYear(), base.getMonth() + 1, 0); + return { start, end }; +} + +/** + * The day of the month a monthly habit falls due in the given month, clamped + * to the month's length. A habit set to the 31st therefore lands on the last + * day of shorter months (e.g. 28 or 29 in February) rather than being skipped. + */ +export function effectiveMonthDay( + year: number, + month: number, + monthDay: number, +): number { + const length = daysInMonth(year, month); + return Math.min(Math.max(1, monthDay), length); +} + +/** + * The day an interval habit's every-N-days cycle counts from: its start + * date, or the earliest record for hand-written notes without one. `null` + * means no anchor exists yet (a brand-new note with no records). + */ +export function intervalAnchor(habit: HabitDefinition): Date | null { + if (habit.startDate !== "") { + return fromDateKey(habit.startDate); + } + const keys = Object.keys(habit.records); + if (keys.length > 0) { + return fromDateKey(keys.reduce((min, key) => (key < min ? key : min))); + } + return null; +} + +function scheduleAnchor(habit: HabitDefinition, date: Date): Date | null { + const latest = (habit.cycleRestarts || []).filter(day => day <= toDateKey(date)).sort().pop(); + return latest ? fromDateKey(latest) : intervalAnchor(habit); +} + +function intervalWindow(habit: HabitDefinition, date: Date) { + const anchor = scheduleAnchor(habit, date); + if (!anchor) return null; + const interval = Math.max(2, habit.intervalDays || 2); + const window = Math.max(1, Math.min(interval, habit.intervalWindowDays || 1)); + const key = toDateKey(date); + let base = anchor; + if (habit.intervalMode === "completion" && habit.goalDirection !== "max") { + for (let cycle = 0; cycle < 10000; cycle++) { + const nextStart = addDays(base, interval); + if (date < nextStart) break; + const startKey = toDateKey(base); + const endKey = toDateKey(addDays(base, window - 1)); + const completed = Object.keys(habit.records).filter(day => day >= startKey && day <= endKey).filter(day => { + const value = habit.records[day] ?? 0; + return value > 0 && !isFailedOn(habit, day) && !isSkippedOn(habit, day) && !isPausedOn(habit, day) && (habit.type === "binary" || value >= habit.target); + }).sort().pop(); + base = completed ? addDays(fromDateKey(completed) || base, interval) : nextStart; + } + } + const elapsed = Math.round((startOfDay(date).getTime() - startOfDay(base).getTime()) / MS_PER_DAY); + if (elapsed < 0) return { active: false, due: false, start: base, end: addDays(base, window - 1) }; + const offset = elapsed % interval; + const start = addDays(date, -offset); + return { active: offset < window, due: offset === window - 1, start, end: addDays(start, window - 1) }; +} + +/** + * True when the habit is due on the given date. + * + * - `daily` habits are due every day. + * - `weekly` habits are due on their chosen weekdays. + * - `monthly` habits are due on their chosen day of the month, clamped to the + * month's last day when the month is shorter. + * - `interval` habits are due every N days counted from their anchor (see + * {@link intervalAnchor}); dates before the anchor are never due, and a + * habit with no anchor yet behaves as daily until one exists. + * - `flexibleWeekly`/`flexibleMonthly` habits are due, in this stats sense, + * only on the last day of their period (Sunday, or the month's last day) + * — the one canonical day a whole period's outcome is scored on. Use + * {@link isActive} for "should this show up today" instead; it is true + * every day for these two frequencies. + */ +export function isDue(habit: HabitDefinition, date: Date): boolean { + const key = toDateKey(date); + if (rescheduleTarget(habit, key)) { + // This day's instance moved elsewhere; it isn't due here any more. + return false; + } + if (rescheduleSource(habit, key)) { + // A moved instance lands here instead, whether or not this day + // would otherwise be due on its own. + return true; + } + if (habit.frequency === "flexibleWeekly") { + return date.getDay() === 0; // Sunday: the last day of a Monday-start week + } + if (habit.frequency === "flexibleMonthly") { + return ( + date.getDate() === daysInMonth(date.getFullYear(), date.getMonth()) + ); + } + if (habit.frequency === "weekly") { + return habit.weekdays.includes(date.getDay()); + } + if (habit.frequency === "monthly") { + return ( + date.getDate() === + effectiveMonthDay( + date.getFullYear(), + date.getMonth(), + habit.monthDay, + ) + ); + } + if (habit.frequency === "interval") { + if (habit.intervalMode === "cycle") { + const anchor = scheduleAnchor(habit, date); + if (!anchor) return true; + const elapsed = Math.round((startOfDay(date).getTime() - anchor.getTime()) / MS_PER_DAY); + const length = Math.max(2, habit.intervalDays || 2); + return elapsed >= 0 && elapsed % length < Math.max(1, Math.min(length, habit.cycleActiveDays || 1)); + } + if ((habit.intervalWindowDays || 1) > 1) return !!intervalWindow(habit, date)?.due; + if (habit.intervalMode === "completion" && habit.goalDirection !== "max") { + // Only earlier successful records can move this day's due date. + // Future records and partial counts never rewrite its history. + const completed = (day: string): boolean => { + const value = habit.records[day] ?? 0; + return !(habit.failed ?? []).includes(day) && !(habit.skipped ?? []).includes(day) + && !isPausedOn(habit, day) && value > 0 + && (habit.type === "binary" || value >= habit.target); + }; + if (completed(key)) return true; + const restartAnchor = scheduleAnchor(habit, date); + const previous = Object.keys(habit.records).filter(day => day < key && (!restartAnchor || day >= toDateKey(restartAnchor)) && completed(day)).sort().pop(); + const anchor = previous ? fromDateKey(previous) : restartAnchor; + if (!anchor) return true; + const days = Math.round((startOfDay(date).getTime() - anchor.getTime()) / MS_PER_DAY); + // An overdue habit remains actionable until it is completed. + return days >= (previous ? Math.max(2, habit.intervalDays) : 0); + } + const anchor = scheduleAnchor(habit, date); + if (!anchor) { + return true; + } + // Both dates are local midnights; rounding absorbs the odd hour a + // DST transition adds or removes inside the span. + const days = Math.round( + (startOfDay(date).getTime() - anchor.getTime()) / MS_PER_DAY, + ); + return days >= 0 && days % Math.max(1, habit.intervalDays) === 0; + } + return true; +} + +/** + * The limit a `max` habit must stay under. Binary limit habits are always + * "none at all" (any logged value is a slip); counter and timed habits use + * `target` as the limit, where `0` is a valid "zero allowed" limit. + */ +export function limitOf(habit: HabitDefinition): number { + if (habit.type === "binary") { + return 0; + } + return Math.max(0, habit.target); +} + +/** + * The first day a habit counts towards scoring. + * + * Days before a habit existed must not count at all: for `max` habits an + * unlogged day scores as "within limit", so without a lower bound every day + * since the beginning of time would count as a success — and for `min` + * habits every pre-start day would count as a failure, deflating rates. + * Habits normally carry a `startDate`; for hand-written notes without one, + * the earliest record is used, and a habit with neither only starts scoring + * today. + */ +export function trackingStartKey( + habit: HabitDefinition, + today: Date = new Date(), +): string { + if (habit.startDate !== "") { + return habit.startDate; + } + const keys = Object.keys(habit.records); + if (keys.length > 0) { + return keys.reduce((min, key) => (key < min ? key : min)); + } + return toDateKey(today); +} + +/** + * True when a habit met its goal on the given day. + * + * For `flexibleWeekly`/`flexibleMonthly` habits: the running total for the + * period containing `dateKey`, summed from the period's start through + * `dateKey` itself, reaches `target`. Well-defined for any day, not just + * the period's canonical last day — see {@link flexiblePeriodTotal}. + * For `min` habits: the logged value reached the target. + * For `max` habits: the logged value stayed at or under the limit — an + * unlogged day counts as within limit, but only from the habit's start + * day onward (see {@link limitStartKey}). + */ +export function isComplete(habit: HabitDefinition, dateKey: string): boolean { + const target = rescheduleTarget(habit, dateKey); + if (target) { + // A rescheduled day's completion lives entirely on its new day — + // reschedules can't chain, so this never recurses more than once. + return isComplete(habit, target); + } + if (isFlexible(habit)) { + if (habit.goalDirection === "max" && dateKey < trackingStartKey(habit)) return false; + const date = fromDateKey(dateKey); + return date ? meetsFlexibleTarget(habit, flexiblePeriodTotal(habit, date)) : false; + } + if (habit.frequency === "interval" && habit.intervalMode !== "cycle" && (habit.intervalWindowDays || 1) > 1) { + const date = fromDateKey(dateKey); + const window = date ? intervalWindow(habit, date) : null; + if (!window?.due) return false; + return Object.keys(habit.records).some(day => { + if (day < toDateKey(window.start) || day > toDateKey(window.end)) return false; + const value = habit.records[day] ?? 0; + return value > 0 && !isFailedOn(habit, day) && !isSkippedOn(habit, day) && !isPausedOn(habit, day) && (habit.type === "binary" || value >= habit.target); + }); + } + // "Fail for today" is a deliberate miss: it wins over any logged value, + // and over a limit habit's "silence is clean" default. + if (isFailedOn(habit, dateKey)) { + return false; + } + const value = habit.records[dateKey] ?? 0; + if (habit.goalDirection === "max") { + if (dateKey < trackingStartKey(habit)) { + return false; + } + return value <= limitOf(habit); + } + if (habit.type === "binary") { + return value >= 1; + } + return habit.target > 0 ? value >= habit.target : value > 0; +} + +/** Daily card completion is independent of the weekly/monthly quota statistics. */ +export function isDailyComplete(habit: HabitDefinition, dateKey: string): boolean { + if (isFlexible(habit) && habit.goalDirection !== "max" && (habit.dailyTarget || 0) > 0) { + if (isFailedOn(habit, dateKey) || isSkippedOn(habit, dateKey)) return false; + return (habit.records[dateKey] || 0) >= habit.dailyTarget! || isComplete(habit, dateKey); + } + return isComplete(habit, dateKey); +} + +/** + * True when the habit was paused on the given day — including a day the + * user skipped ("Skip for today"), which is a one-day pause: it's left out + * of streaks and completion rates exactly like any other paused day. + */ +export function isPausedOn(habit: HabitDefinition, dateKey: string): boolean { + if (isSkippedOn(habit, dateKey)) { + return true; + } + return habit.pauses.some( + (pause) => + dateKey >= pause.start && + (pause.end === "" || dateKey <= pause.end), + ); +} + +/** + * True when the user closed the given day as failed ("Fail for today"). + * Tolerates a habit object built without the list (e.g. a test fixture or + * a habit from an older code path), treating it as empty. + */ +export function isFailedOn(habit: HabitDefinition, dateKey: string): boolean { + return (habit.failed as string[] | undefined)?.includes(dateKey) ?? false; +} + +/** True when the user skipped the given day ("Skip for today"). */ +export function isSkippedOn(habit: HabitDefinition, dateKey: string): boolean { + return (habit.skipped as string[] | undefined)?.includes(dateKey) ?? false; +} + +/** + * The date a due day's instance was moved to, if `dateKey` was rescheduled + * away. `isDue`/`isComplete` use this to make a moved day stop counting and + * its new day count in its place. + */ +export function rescheduleTarget( + habit: HabitDefinition, + dateKey: string, +): string | null { + return habit.reschedules.find((r) => r.from === dateKey)?.to ?? null; +} + +/** + * The original due date `dateKey` covers, if it's a reschedule's + * destination. + */ +export function rescheduleSource( + habit: HabitDefinition, + dateKey: string, +): string | null { + return habit.reschedules.find((r) => r.to === dateKey)?.from ?? null; +} + +/** + * Whether a habit's missed days can be reviewed and rescheduled at all + * (experimental): a fixed-schedule (non-flexible), reach-a-target + * (non-`max`) habit whose value is logged by hand, not derived from a + * note's own content — and, crucially, not due every single day. A daily + * habit has no day that isn't already its own due day, so there would + * never be anywhere open to move a miss onto; interval habits are always + * at least every-other-day (`intervalDays` is clamped to 2+), so they + * always have somewhere free. + */ +export function isRescheduleEligible(habit: HabitDefinition): boolean { + return ( + !habit.stopped && + habit.type !== "note" && + habit.goalDirection !== "max" && + habit.frequency !== "daily" && + !isFlexible(habit) + ); +} + +/** + * Whether `dateKey` is open to become a reschedule's destination for + * `habit`: on or after the habit's tracking start (a day before the habit + * existed couldn't have been due there anyway), not already due on its own + * (that would collide with its own obligation — the "no double entries" + * rule), not paused, and not already claimed by another reschedule as + * either its origin or its destination. Chaining a rescheduled day into a + * second reschedule isn't supported. + */ +export function isRescheduleTargetOpen( + habit: HabitDefinition, + dateKey: string, +): boolean { + const date = fromDateKey(dateKey); + if (!date) { + return false; + } + if (dateKey < trackingStartKey(habit)) { + return false; + } + if (isDue({ ...habit, reschedules: [] }, date) || isDue(habit, date) || isPausedOn(habit, dateKey) || (habit.records[dateKey] || 0) > 0) { + return false; + } + return !habit.reschedules.some( + (r) => r.from === dateKey || r.to === dateKey, + ); +} + +/** One habit's missed due day, as surfaced by {@link missedInstances}. */ +export interface MissedInstance { + habit: HabitDefinition; + dateKey: string; +} + +/** + * Every open (due, not paused, not complete) past due day across + * `habits`, newest first, capped at `limit`. Feeds the "missed habits" + * notification and its review modal (experimental) — only habits passing + * {@link isRescheduleEligible} are scanned, and `isDue`/`isComplete` + * already fold in reschedules, so a day already moved elsewhere is + * correctly skipped and a rescheduled-to day that's since also gone + * unlogged correctly turns up in its place. + */ +export function missedInstances( + habits: HabitDefinition[], + today: Date, + limit = 30, +): MissedInstance[] { + const results: MissedInstance[] = []; + // Guard against a pathological scan on a very old, long-gapped habit. + const maxScan = 366 * 2; + for (const habit of habits) { + if (habit.stopped || habit.type === "note" || habit.goalDirection === "max" || isFlexible(habit)) continue; + const startKey = trackingStartKey(habit, today); + let cursor = addDays(today, -1); + let scanned = 0; + while (scanned < maxScan) { + const key = toDateKey(cursor); + if (key < startKey || habit.ignoredMissesBefore && key < habit.ignoredMissesBefore) { + break; + } + if ( + isDue(habit, cursor) && + !isPausedOn(habit, key) && + // A failed day was decided on purpose, not forgotten, so + // it isn't offered for rescheduling. + !isFailedOn(habit, key) && + !habit.ignoredMisses?.includes(key) && + !isComplete(habit, key) + ) { + results.push({ habit, dateKey: key }); + } + cursor = addDays(cursor, -1); + scanned++; + } + } + results.sort((a, b) => (a.dateKey < b.dateKey ? 1 : -1)); + return results.slice(0, limit); +} + +/** + * {@link currentStreak} for a flexible habit: walks period by period (weeks + * or months) rather than day by day, since evaluating every day of an + * in-progress, not-yet-satisfied period would falsely look like a string of + * broken days. The current, still-open period counts if it is already + * satisfied and otherwise doesn't break anything — there is still time left + * in it, the same idea as the existing "today may still be blank" grace, + * just at period granularity. Every fully elapsed period after that is a + * plain pass/fail, so no grace is needed there. + */ +function flexibleCurrentStreak(habit: HabitDefinition, today: Date): number { + const habitStart = fromDateKey(trackingStartKey(habit, today)); + let range = flexiblePeriodRange(habit, today); + let streak = 0; + + if (toDateKey(range.end) !== toDateKey(startOfDay(today))) { + // An exceeded limit has no grace while the current period is open. + if (habit.goalDirection === "max" && habitStart && today >= habitStart && + !periodFullyPaused(habit, range) && + !meetsFlexibleTarget(habit, periodTotalThrough(habit, range, today))) return 0; + if ( + habitStart && + range.end.getTime() >= habitStart.getTime() && + !periodFullyPaused(habit, range) && + meetsFlexibleTarget(habit, periodTotalThrough(habit, range, today)) + ) { + streak++; + } + range = previousPeriodRange(habit, range); + } + + for (;;) { + if (habitStart && range.end.getTime() < habitStart.getTime()) { + break; + } + if (periodFullyPaused(habit, range)) { + range = previousPeriodRange(habit, range); + continue; + } + if (meetsFlexibleTarget(habit, periodTotalThrough(habit, range, range.end))) { + streak++; + } else { + break; + } + range = previousPeriodRange(habit, range); + } + return streak; +} + +/** {@link longestStreak} for a flexible habit; see {@link flexibleCurrentStreak}. */ +function flexibleLongestStreak(habit: HabitDefinition, today: Date): number { + const habitStart = fromDateKey(trackingStartKey(habit, today)); + if (!habitStart) { + return 0; + } + const todayRange = flexiblePeriodRange(habit, today); + let range = flexiblePeriodRange(habit, habitStart); + let best = 0; + let run = 0; + while (range.start.getTime() <= todayRange.start.getTime()) { + if (periodFullyPaused(habit, range)) { + range = nextPeriodRange(habit, range); + continue; + } + const isCurrent = range.start.getTime() === todayRange.start.getTime(); + const through = isCurrent ? today : range.end; + if (meetsFlexibleTarget(habit, periodTotalThrough(habit, range, through))) { + run++; + best = Math.max(best, run); + } else if (!isCurrent) { + // An unmet but still-open current period doesn't reset the run — + // mirrors flexibleCurrentStreak's grace for it. + run = 0; + } + range = nextPeriodRange(habit, range); + } + return best; +} + +/** + * Consecutive complete due periods ending with the most recent one. + * + * For daily habits every day is a period. For weekly and monthly habits only + * their due dates count, so the streak measures consecutive weeks or months + * completed. Paused due dates are skipped entirely (they neither break nor + * extend a streak), and the most recent due date may still be blank (e.g. a + * due date that is today) without breaking the streak. Flexible habits + * delegate to {@link flexibleCurrentStreak}, which walks whole periods + * instead of days. + */ +export function currentStreak(habit: HabitDefinition, today: Date): number { + if (isFlexible(habit)) { + return flexibleCurrentStreak(habit, today); + } + let cursor = startOfDay(today); + let streak = 0; + let graceUsed = false; + // An interval habit is never due before its anchor, so without a floor + // the walk below would search backwards forever. + const floor = + habit.frequency === "interval" ? intervalAnchor(habit) : null; + for (;;) { + if (floor && cursor.getTime() < floor.getTime()) { + break; + } + if (!isDue(habit, cursor)) { + cursor = addDays(cursor, -1); + continue; + } + const key = toDateKey(cursor); + if (isPausedOn(habit, key)) { + cursor = addDays(cursor, -1); + continue; + } + if (isComplete(habit, key)) { + streak++; + } else if ( + streak === 0 && + !graceUsed && + habit.goalDirection !== "max" + ) { + // The most recent due date may still be blank (e.g. today). Limit + // habits get no grace: for them a blank day already counts as + // within limit, so an incomplete day is a real slip (or a day + // before the habit started) and the streak genuinely ends there. + graceUsed = true; + } else { + break; + } + cursor = addDays(cursor, -1); + } + return streak; +} + +/** + * The longest run of consecutive complete due periods ever recorded. Days on + * which the habit is not due are ignored, and paused due dates inside a run do + * not break it. + * + * `min` habits anchor the scan on logged completions. `max` habits cannot + * (silence is success, so there may be no logged "completions" at all); + * they scan the whole tracked window, from the habit's start day to today. + * Flexible habits delegate to {@link flexibleLongestStreak}. + */ +export function longestStreak( + habit: HabitDefinition, + today: Date = new Date(), +): number { + if (isFlexible(habit)) { + return flexibleLongestStreak(habit, today); + } + let first: Date | null; + let last: Date | null; + if (habit.goalDirection === "max") { + first = fromDateKey(trackingStartKey(habit, today)); + last = startOfDay(today); + if (!first || first.getTime() > last.getTime()) { + return 0; + } + } else { + const completedKeys = Object.keys(habit.records) + .filter((key) => isComplete(habit, key)) + .sort(); + if (completedKeys.length === 0) { + return 0; + } + first = fromDateKey(completedKeys[0]); + last = fromDateKey(completedKeys[completedKeys.length - 1]); + } + if (!first || !last) { + return 0; + } + + let best = 0; + let run = 0; + let cursor = first; + while (cursor.getTime() <= last.getTime()) { + if (isDue(habit, cursor)) { + const key = toDateKey(cursor); + if (isComplete(habit, key)) { + run++; + best = Math.max(best, run); + } else if (!isPausedOn(habit, key)) { + run = 0; + } + } + cursor = addDays(cursor, 1); + } + return best; +} + +export interface HabitPeriodStats { + days: number; + completed: number; + total: number; + rate: number; + current: number; + best: number; +} + +/** The last day of the range to count towards metrics (never in the future). */ +function elapsedEnd(range: DateRange, today: Date): number { + return Math.min(range.end.getTime(), startOfDay(today).getTime()); +} + +/** + * Aggregate a single habit's stats over the elapsed days of a range. + * Days before the habit's tracking start (see {@link trackingStartKey}) are + * excluded entirely — the habit did not exist yet, so they count neither as + * successes nor as failures. + */ +export function habitStats( + habit: HabitDefinition, + range: DateRange, + today: Date, +): HabitPeriodStats { + const end = elapsedEnd(range, today); + const startKey = trackingStartKey(habit, today); + let days = 0; + let completed = 0; + let total = 0; + let cursor = new Date(range.start); + while (cursor.getTime() <= end) { + const key = toDateKey(cursor); + if ( + key < startKey || + !isDue(habit, cursor) || + isPausedOn(habit, key) + ) { + cursor = addDays(cursor, 1); + continue; + } + days++; + const value = habit.records[key] ?? 0; + if (isFlexible(habit)) { + // isDue only gates this loop through on the period's last day, so + // `cursor` is the period end here and this total is the whole + // period's, not just this one day's. + total += flexiblePeriodTotal(habit, cursor); + if (isComplete(habit, key)) { + completed++; + } + } else if (habit.goalDirection === "max") { + // For limit habits `total` is consumption (slips for binary), + // and a completed day is one that stayed within the limit. + total += value; + if (isComplete(habit, key)) { + completed++; + } + } else if (habit.type === "binary") { + if (value >= 1) { + completed++; + total++; + } + } else { + total += value; + if (isComplete(habit, key)) { + completed++; + } + } + cursor = addDays(cursor, 1); + } + return { + days, + completed, + total, + rate: days > 0 ? completed / days : 0, + current: currentStreak(habit, today), + best: longestStreak(habit, today), + }; +} + +/** + * Count elapsed days in the range where every habit was complete. + * Habits paused on a given day are ignored for that day, as are habits not + * yet being tracked; a day with every habit paused or untracked cannot be + * perfect. + */ +export function perfectDays( + habits: HabitDefinition[], + range: DateRange, + today: Date, +): number { + if (habits.length === 0) { + return 0; + } + const end = elapsedEnd(range, today); + const startKeys = habits.map((habit) => trackingStartKey(habit, today)); + let count = 0; + let cursor = new Date(range.start); + while (cursor.getTime() <= end) { + const key = toDateKey(cursor); + const date = cursor; + const active = habits.filter( + (habit, i) => + key >= startKeys[i] && + isDue(habit, date) && + !isPausedOn(habit, key), + ); + if ( + active.length > 0 && + active.every((habit) => isComplete(habit, key)) + ) { + count++; + } + cursor = addDays(cursor, 1); + } + return count; +} diff --git a/src/integrations/habits/task-genius-host.ts b/src/integrations/habits/task-genius-host.ts new file mode 100644 index 000000000..21c6791c6 --- /dev/null +++ b/src/integrations/habits/task-genius-host.ts @@ -0,0 +1,99 @@ +import { PluginSettingTab, type PluginManifest } from "obsidian"; +import type TaskProgressBarPlugin from "@/index"; +import HabitsPlugin from "./main"; +import { HabitsSettingTab, type HabitsPluginSettings } from "./settings"; +import "./scoped.css"; +import "./task-genius.css"; + +/** The integration owns a settings namespace, never a second plugin data.json. */ +export class TaskGeniusHabits extends HabitsPlugin { + readonly ready: Promise; + private resolveReady!: () => void; + private rejectReady!: (reason: unknown) => void; + private disposed = false; + embeddedSettings?: HabitsSettingTab; + + constructor(readonly host: TaskProgressBarPlugin) { + super(host.app, { + ...host.manifest, + id: `${host.manifest.id}-habits`, + name: "Task Genius: Habits", + } as PluginManifest); + this.ready = new Promise((resolve, reject) => { + this.resolveReady = resolve; + this.rejectReady = reject; + }); + } + + async onload(): Promise { + try { + await super.onload(); + this.resolveReady(); + } catch (error) { + this.rejectReady(error); + } + } + + onunload(): void { this.disposed = true; } + protected integrationActive(): boolean { return !this.disposed; } + + /** Read the previous plugin's non-secret configuration only on first use. */ + async loadData(): Promise | null> { + if (this.host.settings.habitsIntegration) { + const saved = JSON.parse(JSON.stringify(this.host.settings.habitsIntegration)); + // Fold the two former selectors into one without changing the visible layout. + if (saved.nativeLayout === "cards" || (!saved.nativeLayout && !saved.layoutUnified)) saved.dashboardLayout = "cards"; + delete saved.nativeLayout; + saved.layoutUnified = true; + saved.experimental = { ...saved.experimental, rescheduling: true }; + return saved; + } + try { + const path = `${this.app.vault.configDir}/plugins/habits/data.json`; + const previous = JSON.parse(await this.app.vault.adapter.read(path)); + const { aiSummary, reminders, ...compatible } = previous; + // Keys and external writes require deliberate configuration in the host. + return { ...compatible, dashboardLayout: "cards", layoutUnified: true }; + } catch { return { dashboardLayout: "cards", layoutUnified: true }; } + } + + async saveData(data: HabitsPluginSettings): Promise { + this.host.settings.habitsIntegration = JSON.parse(JSON.stringify(data)); + await this.host.saveSettings(); + } + + addSettingTab(tab: PluginSettingTab): void { + this.embeddedSettings = tab as HabitsSettingTab; + } + + renderSettings(container: HTMLElement): void { + container.addClass("tg-habits-surface"); + if (this.embeddedSettings) { + this.embeddedSettings.containerEl = container; + this.embeddedSettings.display(); + } + } + + /** Always own prefixed blocks; claim legacy blocks only without Habits. */ + registerMarkdownCodeBlockProcessor( + language: string, + handler: Parameters[1], + sortOrder?: number, + ): ReturnType { + const scoped: typeof handler = (source, el, context) => { + el.addClass("tg-habits-surface"); + return handler(source, el, context); + }; + const result = super.registerMarkdownCodeBlockProcessor(`tg-${language}`, scoped, sortOrder); + if (this.backgroundSyncAllowed()) { + super.registerMarkdownCodeBlockProcessor(language, scoped, sortOrder); + } + return result; + } + + protected backgroundSyncAllowed(): boolean { + const plugins = (this.app as any).plugins; + return !this.disposed && this.host.settings.habit.enableHabits && !plugins?.enabledPlugins?.has("habits"); + } + +} diff --git a/src/integrations/habits/task-genius.css b/src/integrations/habits/task-genius.css new file mode 100644 index 000000000..a7f03f26d --- /dev/null +++ b/src/integrations/habits/task-genius.css @@ -0,0 +1,79 @@ +.tg-habits-surface { + --habits-radius: var(--radius-m); + font-family: var(--font-interface); + color: var(--text-normal); +} +.tg-habits-surface .habits-card, +.tg-habits-surface .habits-compact-row, +.tg-habits-surface .habits-stat-tile { + border-radius: var(--radius-m); + border-color: var(--background-modifier-border); + box-shadow: none; +} +.tg-habits-surface .habits-settings-tabs { border-bottom: 1px solid var(--background-modifier-border); } +.tg-habits-surface .habits-settings-tab.is-active { color: var(--interactive-accent); } +.tg-habits-toolbar { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; padding: 12px 0; } +.tg-habits-toolbar h2 { flex: 1; margin: 0; } +.tg-habits-legacy { margin-top: 24px; border-top: 1px solid var(--background-modifier-border); padding-top: 12px; } + +.tg-habits-surface .tg-native-habit-cards { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; } +.tg-habits-surface .tg-native-habit-card { min-width: 0; margin: 0; } +.tg-habits-surface .tg-native-habit-card.is-done { opacity: .48; } +.tg-habits-surface .tg-native-habit-card.is-done:hover { opacity: .8; } +.tg-habits-surface .tg-native-habit-nav { justify-content: center; flex-wrap: wrap; } +.tg-habits-surface .tg-native-habit-date-label { min-width: 72px; } + +@media (max-width: 650px) { .tg-habits-surface .tg-native-habit-cards { grid-template-columns: 1fr; } } + +.tg-habits-surface .tg-native-habit-body { flex-wrap: wrap; gap: 12px; } +.tg-habits-surface .tg-native-habit-grid { grid-template-columns: repeat(10, minmax(8px, 1fr)); min-width: 160px; } +.tg-habits-surface .tg-native-habit-cell { width: 100%; max-width: 20px; } + +.tg-habits-surface .habits-compact-list { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; } +.tg-habits-surface .habits-compact-group { grid-column: 1 / -1; } +.tg-habits-surface .habits-compact-row { min-width: 0; flex-wrap: wrap; } +@media (max-width: 650px) { .tg-habits-surface .habits-compact-list { grid-template-columns: 1fr; } } + +.tg-habits-surface :is(.tg-native-habit-cards,.habits-compact-list)[data-columns="auto"] { grid-template-columns: repeat(auto-fit, minmax(min(100%, 310px), 1fr)); } +.tg-habits-surface :is(.tg-native-habit-cards,.habits-compact-list)[data-columns="1"] { grid-template-columns: repeat(1, minmax(0, 1fr)); } +.tg-habits-surface :is(.tg-native-habit-cards,.habits-compact-list)[data-columns="2"] { grid-template-columns: repeat(2, minmax(0, 1fr)); } +.tg-habits-surface :is(.tg-native-habit-cards,.habits-compact-list)[data-columns="3"] { grid-template-columns: repeat(3, minmax(0, 1fr)); } +.tg-habits-surface :is(.tg-native-habit-cards,.habits-compact-list)[data-columns="4"] { grid-template-columns: repeat(4, minmax(0, 1fr)); } +.tg-habits-surface :is(.tg-native-habit-card,.habits-compact-row).is-done { opacity: .25; filter: saturate(.35); } +.tg-habits-surface .tg-habit-date-picker { position: absolute; width: 1px; height: 1px; opacity: 0; pointer-events: none; } +.tg-habits-surface .tg-native-habit-nav { display: grid; grid-template-columns: 28px auto 28px 1fr auto auto; } +.tg-habits-surface .tg-habit-add { grid-column: 6; justify-self: end; } +.tg-habits-surface .tg-native-habit-nav .habits-missed-button { position: relative; grid-column: 5; } +.tg-habits-surface .tg-native-habit-icon { display: inline-flex; min-width: 24px; font-size: 22px; } + +.tg-habits-surface .tg-habit-modal-close { position: absolute; top: 10px; right: 10px; z-index: 20; width: 30px; height: 30px; pointer-events: auto; border: 0; background: var(--background-primary); } +.tg-habits-surface:has(> .tg-habit-modal-close) > :is(.modal-close-button,.modal-header-button) { visibility: hidden; } + +.tg-habits-surface .tg-native-habits { max-width: none; width: 100%; box-sizing: border-box; } +.tg-habits-surface .tg-native-habit-nav .habits-missed-button { inset: auto; margin: 0; } +.tg-habits-surface :is(.tg-native-habit-card,.habits-compact-row).is-done:hover { opacity: .42; } + +@media (max-width: 520px) { + .tg-habits-surface :is(.tg-native-habit-cards, .habits-compact-list)[data-columns] { + grid-template-columns: minmax(0, 1fr); + } + + .tg-habits-surface :is(.tg-native-habit-nav, .habits-compact-nav, .tg-native-habit-controls, .habits-compact-controls) { + display: flex; + flex-wrap: wrap; + min-width: 0; + } + + .tg-habits-surface .tg-native-habit-nav { + justify-content: flex-start; + } + + .tg-habits-surface .tg-habit-add { + margin-inline-start: auto; + } + + .tg-habits-surface :is(.tg-native-habit-nav, .habits-compact-nav, .tg-native-habit-controls, .habits-compact-controls) button { + min-width: 40px; + min-height: 40px; + } +} diff --git a/src/integrations/habits/types.ts b/src/integrations/habits/types.ts new file mode 100644 index 000000000..bb524d24e --- /dev/null +++ b/src/integrations/habits/types.ts @@ -0,0 +1,357 @@ +/** + * The four kinds of habit the plugin can track. + * + * - `binary`: done or not done on a given day. + * - `repetition`: a count towards a target (e.g. 8 cups of water). + * - `timed`: minutes spent towards a target (e.g. 30 minutes of exercise). + * - `note`: writing in a per-day note, completed by reaching a character + * count, satisfying a checklist requirement, or both. See the `note*` + * fields below. + */ +export type HabitType = "binary" | "repetition" | "timed" | "note"; + +/** + * How a `note` habit's day is marked complete. + * + * - `chars`: the note's character count (frontmatter stripped) reaches + * `target`. + * - `checklist`: the checklist requirement in {@link NoteChecklistRequirement} + * is met. + * - `both`: both of the above must be true. `records` stores the lower of + * the two fractions, scaled to `target` (the character goal), so the + * plugin's existing `value >= target` completion check only fires once + * neither condition is the bottleneck. + * + * Regardless of mode, a checked item matching `noteFailKeyword` (if set) + * forces the day to `0` — an automatic fail that overrides everything else. + */ +export type NoteCompletionMode = "chars" | "checklist" | "both"; + +/** + * How a `note` habit's checklist requirement is satisfied. + * + * - `all`: every task-list item must be checked. Stored as a 0–100 + * percentage in `records` (against a fixed `target` of 100), since the + * number of tasks can differ from day to day. + * - `count`: at least `noteChecklistMin` items must be checked — any of + * them, not a specific one. Stored as the raw checked count in `records` + * (against `target` = `noteChecklistMin`). Suits a checklist of + * alternatives (e.g. "cardio" / "weights" / "rest day") where doing any + * one of them counts. + */ +export type NoteChecklistRequirement = "all" | "count"; + +/** + * How often a habit is due. + * + * - `daily`: due every day (the original behaviour). + * - `weekly`: due on one or more chosen weekdays each week. + * - `monthly`: due once a month, on a chosen day of the month. + * - `interval`: due every N days, counted from the habit's start date + * (e.g. every 2 days for an alternate-day schedule). + * - `flexibleWeekly`: due a set number of times each week, on any day the + * user chooses (e.g. kayaking once a week, whichever day is free). + * For `max` habits this is a cumulative weekly limit instead. + * - `flexibleMonthly`: the same idea, scored over a calendar month. + * For `max` habits this is a cumulative monthly limit. + * + * `target` holds the "how many times" for the two flexible frequencies — + * see {@link HabitDefinition.target}. + */ +export type HabitFrequency = + | "daily" + | "weekly" + | "monthly" + | "interval" + | "flexibleWeekly" + | "flexibleMonthly"; + +/** + * Which way a habit's goal points. + * + * - `min`: reach a target — the classic habit (do at least this much). + * - `max`: stay under a limit — for habits being reduced or avoided + * (e.g. at most 2 hours of gaming, or no smoking at all). + * + * Absent from frontmatter means `min`, so every note written before this + * field existed keeps its original meaning untouched. + */ +export type GoalDirection = "min" | "max"; + +/** + * The base order of habit cards in the dashboard and side panel. + * + * - `name`: alphabetical by note name (the original behaviour). + * - `color`: by accent colour hue, so similar colours sit together. + * - `startDate`: oldest habit first — the order habits were created in. + * - `lastLogged`: most recently logged first. + * - `time`: by first planned time — the day's timeline; untimed habits last. + * - `group`: by group, following the arranged group order. + * - `manual`: the order the user arranged in settings. + */ +export type HabitSortMode = + | "name" + | "color" + | "startDate" + | "lastLogged" + | "time" + | "group" + | "manual"; + +/** + * Shared styling for a group, stored once in the plugin settings (keyed + * by group name) so every member card stays in step and renaming a + * habit's group re-links it instead of duplicating style per note. + */ +export interface GroupStyle { + /** Optional accent colour shared by the group ("" = none). */ + color: string; + /** Optional Lucide icon id or emoji shown in group lips and headers. */ + icon: string; +} + +/** + * A period during which a habit was paused (inclusive of both ends). + * An empty `end` means the pause is still ongoing. + */ +export interface HabitPause { + start: string; + end: string; +} + +/** + * A missed due day moved onto a different day (experimental). `from` stops + * counting as due; `to` — which must not already be due on its own — + * becomes due in its place and inherits its completion. Each date may + * appear in at most one reschedule, on one side only: chaining a + * rescheduled day into a second reschedule isn't supported. + */ +export interface HabitReschedule { + /** The original due date, `YYYY-MM-DD`, this instance was moved from. */ + from: string; + /** The date, `YYYY-MM-DD`, it was moved to. */ + to: string; +} + +/** + * A single habit, parsed from a note in the habits folder. + * + * The note's frontmatter holds the definition, and a `records` map holds the + * value logged for each day (keyed by `YYYY-MM-DD`). + */ +export interface HabitDefinition { + ignoredMisses?: string[]; + ignoredMissesBefore?: string; + /** Path of the backing note. Used as a stable identifier. */ + path: string; + /** Display name, taken from the note's basename. */ + name: string; + /** The kind of habit. */ + type: HabitType; + /** + * Whether the goal is a target to reach (`min`) or a limit to stay + * under (`max`). For `max` habits `target` is the limit — `0` means + * "none at all" — and a binary `max` habit's limit is always `0` + * (any logged value is a slip). + */ + goalDirection: GoalDirection; + /** How often the habit is due. Defaults to `daily`. */ + frequency: HabitFrequency; + /** + * Days of the week a weekly habit is due, as JavaScript `getDay` values + * (`0` = Sunday … `6` = Saturday), sorted and without duplicates. Only + * meaningful when `frequency` is `weekly`. Stored in frontmatter as a + * scalar `weekday` when there is one day (the original format) or as a + * `weekdays` list when there are several. + */ + weekdays: number[]; + /** + * Day of the month a monthly habit is due (`1`–`31`). Only meaningful when + * `frequency` is `monthly`. In months shorter than the chosen day it is + * clamped to the last day of that month (so `31` acts as "last day"). + */ + monthDay: number; + /** + * Number of days between due dates (`2`–`365`), counted from the habit's + * start date. Only meaningful when `frequency` is `interval`; `2` gives an + * alternate-day schedule. + */ + intervalDays: number; + /** Number of consecutive days available to log one interval occurrence. */ + intervalWindowDays?: number; + /** Fixed calendar cycle, or a new interval after actual completion. */ + intervalMode?: "fixed" | "completion" | "cycle"; + cycleActiveDays?: number; + cycleRestarts?: string[]; + dailyTarget?: number; + /** + * Optional times of day the habit is planned for, as 24-hour `HH:mm` + * strings, sorted and without duplicates — one entry for a once-a-day + * plan, several for e.g. twice-daily medication. Purely informational: + * they are shown alongside the schedule on the habit's card and never + * affect when the habit is due. Stored in frontmatter as a scalar + * `time` when there is one, or a `times` list when there are several. + * Empty means no planned time. + */ + times: string[]; + /** + * Daily target. For `repetition` this is a count; for `timed` it is a + * number of minutes. Ignored for `binary` — except when `frequency` is + * `flexibleWeekly`/`flexibleMonthly`, where `target` instead holds the + * number of times (for `binary`) or the cumulative amount (for + * `repetition`/`timed`) required somewhere within the period. + */ + target: number; + /** Optional unit label shown next to the value (e.g. "cups"). */ + unit: string; + /** + * How much one +/− press adds or removes for a `repetition` habit + * (e.g. 0.25 for litres). `1` by default; ignored for other types. See + * {@link stepOf}. + */ + step: number; + /** + * Optional weekly goal: the number of days the daily goal should be met. + * `0` means no target. Ignored when `weeklyPerfect` is true. + */ + weeklyTarget: number; + /** Optional monthly goal, interpreted like `weeklyTarget`. */ + monthlyTarget: number; + /** When true, the weekly goal is every day of the week. */ + weeklyPerfect: boolean; + /** When true, the monthly goal is every day of the month. */ + monthlyPerfect: boolean; + /** Optional Lucide icon id shown on the card. */ + icon: string; + /** Optional accent colour (any valid CSS colour). */ + color: string; + /** + * Optional group name used to build dashboard sections (e.g. an area + * of responsibility). Empty means ungrouped. + */ + group: string; + /** + * When true and the habit's group has a colour, the card is shown in + * the group colour instead of its own. + */ + useGroupColor: boolean; + /** + * Obsidian tags on the note (no leading `#`), stored in the note's + * native `tags` property rather than through the configurable + * frontmatter keys — useful for making a habit recognisable to another + * plugin's own tag-based rules, e.g. TaskNotes' task tag. + */ + tags: string[]; + /** Date the habit started, as `YYYY-MM-DD`. */ + startDate: string; + /** True while an open pause exists. Paused days are skipped by stats. */ + paused: boolean; + /** Every pause period recorded for the habit, including any open one. */ + pauses: HabitPause[]; + /** + * Missed due days moved onto a different day (experimental — + * `experimental.rescheduling`). See {@link HabitReschedule}. + */ + reschedules: HabitReschedule[]; + /** + * Days the user closed as failed ("Fail for today"), as `YYYY-MM-DD`. + * A failed day is hidden from that day's lists and always counts as a + * miss, even for a limit habit or a value logged earlier. Flexible + * habits only hide the card: one day can't fail a weekly quota. + */ + failed: string[]; + /** + * Days the user skipped ("Skip for today"), as `YYYY-MM-DD`. A skipped + * day is hidden and treated exactly like a one-day pause, so it never + * counts for or against the habit. + */ + skipped: string[]; + /** True when the habit is no longer tracked but keeps its history. */ + stopped: boolean; + /** Date tracking stopped, as `YYYY-MM-DD` (empty when tracking). */ + stopDate: string; + /** + * Logged values keyed by day (`YYYY-MM-DD`). + * + * - `binary`: `1` for done, `0`/absent for not done. + * - `repetition`: the count logged that day. + * - `timed`: the number of minutes logged that day. + */ + records: Record; + /** Per-day comments keyed by `YYYY-MM-DD`. */ + comments: Record; + /** + * Folder that holds this habit's per-day notes. Only meaningful when + * `type` is `note`. + */ + noteFolder: string; + /** + * Moment.js format used to name each day's note (e.g. `YYYY-MM-DD`). + * May contain `/` to file notes into date-based subfolders. Only + * meaningful when `type` is `note`. + */ + noteFilenameFormat: string; + /** + * Optional vault path of a template note applied when a day's note is + * created. Expanded through Templater when that plugin is installed; + * otherwise copied verbatim. Only meaningful when `type` is `note`. + */ + templatePath: string; + /** How a `note` habit's day is marked complete. */ + noteCompletionMode: NoteCompletionMode; + /** + * How a `note` habit's checklist requirement is satisfied. Only + * meaningful when `noteCompletionMode` is `checklist` or `both`. + */ + noteChecklistRequirement: NoteChecklistRequirement; + /** + * Minimum number of checklist items that must be checked when + * `noteChecklistRequirement` is `count`. + */ + noteChecklistMin: number; + /** + * Case-insensitive text a checklist item's label must contain, when + * checked, to force the day to fail regardless of every other + * condition (e.g. a "Slipped" item). Empty disables the feature. Only + * meaningful when `type` is `note`. + */ + noteFailKeyword: string; +} + +/** Options used when creating a new habit note. */ +export interface NewHabitOptions { + name: string; + type: HabitType; + goalDirection: GoalDirection; + frequency: HabitFrequency; + weekdays: number[]; + monthDay: number; + intervalDays: number; + intervalWindowDays?: number; + /** Fixed calendar cycle, or a new interval after actual completion. */ + intervalMode?: "fixed" | "completion" | "cycle"; + cycleActiveDays?: number; + dailyTarget?: number; + restartCycleDate?: string; + restartIntervalCycle?: boolean; + times: string[]; + target: number; + unit: string; + step: number; + weeklyTarget: number; + monthlyTarget: number; + weeklyPerfect: boolean; + monthlyPerfect: boolean; + icon: string; + color: string; + group: string; + useGroupColor: boolean; + tags: string[]; + noteFolder: string; + noteFilenameFormat: string; + templatePath: string; + noteCompletionMode: NoteCompletionMode; + noteChecklistRequirement: NoteChecklistRequirement; + noteChecklistMin: number; + noteFailKeyword: string; +} diff --git a/src/integrations/habits/ui/chart-setup.ts b/src/integrations/habits/ui/chart-setup.ts new file mode 100644 index 000000000..0e4203e1f --- /dev/null +++ b/src/integrations/habits/ui/chart-setup.ts @@ -0,0 +1,32 @@ +import { + BarController, + BarElement, + CategoryScale, + Chart, + Filler, + LineController, + LineElement, + LinearScale, + PointElement, + Tooltip, +} from "chart.js"; +import { MatrixController, MatrixElement } from "chartjs-chart-matrix"; + +/** + * Registers every Chart.js component the plugin's charts and heatmaps use. + * Side-effect only: every file that draws a chart imports this once so + * registration happens regardless of which chart-drawing module loads first. + */ +Chart.register( + BarController, + BarElement, + CategoryScale, + Filler, + LineController, + LineElement, + LinearScale, + MatrixController, + MatrixElement, + PointElement, + Tooltip, +); diff --git a/src/integrations/habits/ui/color-utils.ts b/src/integrations/habits/ui/color-utils.ts new file mode 100644 index 000000000..24bdb50bc --- /dev/null +++ b/src/integrations/habits/ui/color-utils.ts @@ -0,0 +1,60 @@ +/** + * Resolve a CSS colour (including `var(...)` references and a habit's own + * accent) to a concrete `rgb(...)` value Chart.js can use. `root` anchors the + * probe element to the right document/window (relevant for popout windows). + */ +export function resolveColor( + root: HTMLElement, + preferred: string, + fallback: string, +): string { + const probe = root.doc.body.createSpan(); + probe.style.color = preferred || fallback; + const resolved = probe.win.getComputedStyle(probe).color; + probe.remove(); + return resolved || "#888888"; +} + +/** Apply an alpha channel to an `rgb(r, g, b)` colour string. */ +export function withAlpha(color: string, alpha: number): string { + const match = /^rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(color); + if (!match) { + return color; + } + return `rgba(${match[1]}, ${match[2]}, ${match[3]}, ${alpha})`; +} + +/** + * Perceptual brightness of an `rgb()`/`rgba()` colour, 0 (darkest) to 255 + * (lightest), via the fast "YIQ" approximation. Alpha is ignored — this + * reads the colour's own hue and lightness, not how transparent it is. + * Returns `null` when `color` isn't a parseable rgb(a) string (e.g. a + * keyword like `"transparent"`). + */ +function brightness(color: string): number | null { + const match = /rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(color); + if (!match) { + return null; + } + const [, r, g, b] = match.map(Number); + return (r * 299 + g * 587 + b * 114) / 1000; +} + +/** + * Pick whichever of near-white or near-black reads more clearly against + * both `fill` (what's drawn under the border) and `surrounding` (what's + * drawn around it — the page behind the gaps between cells/bars). Contrast + * against the fill alone isn't enough: a pale fill wants a dark border for + * contrast against *it*, but if the page itself is dark, that same dark + * border disappears into the gap right next to it. Picking whichever of + * white/black has the better *worst-case* contrast against the two (not + * just the fill) keeps the border visible against both at once. Unparsable + * colours (e.g. `"transparent"`) are treated as a neutral middle grey. + */ +export function contrastColor(fill: string, surrounding: string): string { + const fillB = brightness(fill) ?? 128; + const surroundB = brightness(surrounding) ?? 128; + const whiteContrast = Math.min(255 - fillB, 255 - surroundB); + const blackContrast = Math.min(fillB, surroundB); + return whiteContrast >= blackContrast ? "#fafafa" : "#1a1a1a"; +} diff --git a/src/integrations/habits/ui/comment-suggest.ts b/src/integrations/habits/ui/comment-suggest.ts new file mode 100644 index 000000000..0fd700538 --- /dev/null +++ b/src/integrations/habits/ui/comment-suggest.ts @@ -0,0 +1,346 @@ +import { + App, + Component, + TFile, + getAllTags, + prepareFuzzySearch, + renderResults, + setIcon, + type SearchResult, +} from "obsidian"; + +/** + * Autocomplete for the day-comment textarea. + * + * Obsidian's own `EditorSuggest` only attaches to CodeMirror editors and + * `AbstractInputSuggest` only to `

( + containerEl: HTMLElement, + charts: Chart[], + title: string, + points: P[], + xLabels: string[], + yLabels: string[], + colors: HeatmapColors, + tooltipLines: (point: P) => string[], + textColor: string, + /** Column tick text, e.g. only the weeks where the month changes. */ + xTickLabels?: string[], +): void { + const config: ChartConfiguration<"matrix", P[], string> = { + type: "matrix", + data: { + datasets: [ + { + data: points, + backgroundColor: colors.background, + borderColor: colors.border, + borderWidth: colors.borderWidth, + borderRadius: 2, + width: (ctx) => { + const area = ctx.chart.chartArea; + return area ? area.width / xLabels.length - 3 : 14; + }, + height: (ctx) => { + const area = ctx.chart.chartArea; + return area ? area.height / yLabels.length - 3 : 14; + }, + }, + ], + }, + options: { + responsive: true, + maintainAspectRatio: false, + animation: { duration: 300 }, + plugins: { + legend: { display: false }, + tooltip: { + displayColors: false, + callbacks: { + title: () => "", + label: (ctx) => tooltipLines(ctx.dataset.data[ctx.dataIndex] as P), + }, + }, + }, + scales: { + x: { + type: "category", + labels: xLabels, + offset: true, + ticks: { + color: textColor, + maxRotation: 0, + autoSkip: false, + ...(xTickLabels + ? { + callback: (_value: unknown, index: number) => + xTickLabels[index] ?? "", + } + : {}), + }, + grid: { display: false }, + }, + y: { + type: "category", + labels: yLabels, + offset: true, + reverse: true, + ticks: { color: textColor, maxRotation: 0, autoSkip: false }, + grid: { display: false }, + }, + }, + }, + }; + + const section = containerEl.createDiv({ cls: "habits-metrics-section" }); + section.createDiv({ cls: "habits-metrics-title", text: title }); + const wrap = section.createDiv({ cls: "habits-metrics-canvas" }); + const canvas = wrap.createEl("canvas"); + charts.push(new Chart(canvas, config)); +} diff --git a/src/integrations/habits/ui/icon-suggest-modal.ts b/src/integrations/habits/ui/icon-suggest-modal.ts new file mode 100644 index 000000000..9e000b037 --- /dev/null +++ b/src/integrations/habits/ui/icon-suggest-modal.ts @@ -0,0 +1,70 @@ +import { + App, + FuzzyMatch, + FuzzySuggestModal, + getIconIds, + setIcon, +} from "obsidian"; +import { t } from "../i18n"; + +/** + * Fuzzy-search modal for picking a built-in Lucide icon. + * + * Uses `getIconIds()` so every icon shown is guaranteed to render with + * `setIcon()` elsewhere in the plugin. + */ +export class IconSuggestModal extends FuzzySuggestModal { + constructor( + app: App, + private onChoose: (icon: string) => void, + ) { + super(app); + this.modalEl.addClass("tg-habits-surface"); + this.setPlaceholder(t("Search icons…")); + this.limit = 150; + } + + getItems(): string[] { + return getIconIds(); + } + + getItemText(item: string): string { + // Include the readable label so fuzzy search matches spaced words too. + return `${item} ${iconLabel(item)}`; + } + + renderSuggestion(match: FuzzyMatch, el: HTMLElement): void { + el.addClass("habits-icon-suggestion"); + const glyph = el.createSpan({ cls: "habits-icon-suggestion-glyph" }); + setIcon(glyph, match.item); + el.createSpan({ + cls: "habits-icon-suggestion-name", + text: iconLabel(match.item), + }); + } + + onChooseItem(item: string): void { + this.onChoose(item); + } +} + +/** Turn an icon id such as "lucide-arrow-up" into a label like "Arrow up". */ +export function iconLabel(iconId: string): string { + const spaced = iconId.replace(/^lucide-/, "").replace(/-/g, " "); + return spaced.charAt(0).toUpperCase() + spaced.slice(1); +} + +/** True when the value is a Lucide icon id rather than an emoji. */ +export function isLucideIcon(icon: string): boolean { + return /^[a-z0-9-]+$/.test(icon); +} + +/** Render a habit icon — a Lucide id via setIcon, or an emoji as text. */ +export function applyHabitIcon(el: HTMLElement, icon: string): void { + el.empty(); + if (isLucideIcon(icon)) { + setIcon(el, icon); + } else { + el.setText(icon); + } +} diff --git a/src/integrations/habits/ui/metrics-suggest.ts b/src/integrations/habits/ui/metrics-suggest.ts new file mode 100644 index 000000000..cc57f4b24 --- /dev/null +++ b/src/integrations/habits/ui/metrics-suggest.ts @@ -0,0 +1,112 @@ +import { + App, + Editor, + EditorPosition, + EditorSuggest, + EditorSuggestContext, + EditorSuggestTriggerInfo, + TFile, +} from "obsidian"; +import type { HabitStore } from "../habit-store"; +import type { HabitDefinition } from "../types"; +import { applyHabitIcon } from "./icon-suggest-modal"; + +/** + * Suggests habit names while typing `habits:` (or the older `habit:`) + * inside a `habit-metrics` code block, so users can point the block at any + * habit by name. `habits:` takes a comma-separated list, so suggestions + * cover whichever name is being typed after the last comma. + */ +export class HabitMetricsSuggest extends EditorSuggest { + /** Lower-cased names already listed on the line, left out of suggestions. */ + private listed = new Set(); + + constructor( + app: App, + private store: HabitStore, + ) { + super(app); + } + + onTrigger( + cursor: EditorPosition, + editor: Editor, + _file: TFile | null, + ): EditorSuggestTriggerInfo | null { + const before = editor.getLine(cursor.line).slice(0, cursor.ch); + const match = /^(\s*habits?\s*:)(.*)$/i.exec(before); + if (!match || !this.inMetricsBlock(editor, cursor.line)) { + return null; + } + const value = match[2]; + const lastComma = value.lastIndexOf(","); + const segment = value.slice(lastComma + 1); + const query = segment.trimStart(); + // The rest of the line (after the cursor) can hold names too. + const after = editor.getLine(cursor.line).slice(cursor.ch); + this.listed = new Set( + [...value.slice(0, lastComma + 1).split(","), ...after.split(",")] + .map((name) => name.trim().toLowerCase()) + .filter((name) => name !== ""), + ); + return { + start: { + line: cursor.line, + ch: match[1].length + lastComma + 1 + segment.length - query.length, + }, + end: cursor, + query, + }; + } + + /** True when the nearest fence above the line opens a metrics block. */ + private inMetricsBlock(editor: Editor, lineNo: number): boolean { + for (let i = lineNo - 1; i >= 0; i--) { + const line = editor.getLine(i).trim(); + if (line.startsWith("```")) { + return /^`{3,}\s*(?:tg-)?habit-metrics\s*$/.test(line); + } + } + return false; + } + + getSuggestions(context: EditorSuggestContext): HabitDefinition[] { + const needle = context.query.toLowerCase(); + return this.store + .getHabits() + .filter( + (habit) => + habit.name.toLowerCase().includes(needle) && + !this.listed.has(habit.name.toLowerCase()), + ); + } + + renderSuggestion(habit: HabitDefinition, el: HTMLElement): void { + const row = el.createDiv({ cls: "habits-icon-suggestion" }); + const glyph = row.createSpan({ + cls: "habits-icon-suggestion-glyph", + }); + if (habit.icon) { + applyHabitIcon(glyph, habit.icon); + } + row.createSpan({ text: habit.name }); + } + + selectSuggestion(habit: HabitDefinition): void { + const context = this.context; + if (!context) { + return; + } + // Keep list entries readable ("A, B") when typed straight after a comma. + const previous = context.editor + .getLine(context.start.line) + .charAt(context.start.ch - 1); + const text = previous === "," || previous === ":" ? ` ${habit.name}` : habit.name; + context.editor.replaceRange(text, context.start, context.end); + context.editor.setCursor({ + line: context.start.line, + ch: context.start.ch + text.length, + }); + this.close(); + } +} diff --git a/src/integrations/habits/ui/missed-habits-modal.ts b/src/integrations/habits/ui/missed-habits-modal.ts new file mode 100644 index 000000000..6ec26c0e7 --- /dev/null +++ b/src/integrations/habits/ui/missed-habits-modal.ts @@ -0,0 +1,268 @@ +import { installHabitClose } from "./modal-close"; +import { + App, + ButtonComponent, + Modal, + Notice, + Setting, + setIcon, + setTooltip, +} from "obsidian"; +import { t } from "../i18n"; +import type { HabitStore } from "../habit-store"; +import type { HabitDefinition } from "../types"; +import { + isRescheduleTargetOpen, + isRescheduleEligible, + missedInstances, + trackingStartKey, + type MissedInstance, +} from "../stats"; +import { addDays, fromDateKey, friendlyDateLabel, toDateKey } from "../utils"; +import { applyHabitIcon } from "./icon-suggest-modal"; + +/** How far past/future the date picker's own min/max reach, as a soft guardrail. */ +const PICKER_WINDOW_DAYS = 180; + +/** + * Review missed habits and move one onto a different day (experimental). + * The list re-scans on every return to it, so working through several + * misses in one sitting updates live instead of going stale after the + * first reschedule. + */ +export class MissedHabitsModal extends Modal { + private removeCloseControl = () => {}; + constructor( + app: App, + private store: HabitStore, + private habits: HabitDefinition[], + private onChanged: () => void, + ) { + super(app); + this.modalEl.addClass("tg-habits-surface"); + } + + onOpen(): void { + this.modalEl.addClass("habits-modal"); + this.removeCloseControl(); this.removeCloseControl = installHabitClose(this); + this.renderList(); + } + + onClose(): void { + this.removeCloseControl(); + this.contentEl.empty(); + } + + private renderList(): void { + const { contentEl } = this; + contentEl.empty(); + new Setting(contentEl).setName(t("Missed habits")).setHeading(); + + const today = new Date(); + const missed = missedInstances(this.habits, today); + + if (missed.length === 0) { + contentEl.createEl("p", { + cls: "habits-missed-empty", + text: t("Nothing missed right now."), + }); + return; + } + + contentEl.createEl("p", { + cls: "habits-missed-intro", + text: t("Move a missed habit to an open day or record it on its original date."), + }); + + const list = contentEl.createDiv({ cls: "habits-missed-list" }); + for (const instance of missed) { + this.renderCard(list, instance, today); + } + } + + private renderCard( + list: HTMLElement, + instance: MissedInstance, + today: Date, + ): void { + const { habit, dateKey } = instance; + const date = fromDateKey(dateKey); + const card = list.createDiv({ cls: "habits-missed-card" }); + card.setCssProps({ + "--habits-accent": habit.color || "var(--interactive-accent)", + }); + + const icon = card.createDiv({ cls: "habits-missed-icon" }); + if (habit.icon) { + applyHabitIcon(icon, habit.icon); + } else { + setIcon(icon, "circle"); + } + + const info = card.createDiv({ cls: "habits-missed-info" }); + info.createDiv({ cls: "habits-missed-name", text: habit.name }); + info.createDiv({ + cls: "habits-missed-date", + text: date ? friendlyDateLabel(date, today) : dateKey, + }); + + const canMove = isRescheduleEligible(habit); + const button = card.createEl("button", { + cls: "habits-icon-button habits-missed-reschedule", + attr: { type: "button" }, + text: canMove ? t("Reschedule") : t("Backfill"), + }); + setTooltip(button, canMove ? t("Move this missed day onto a different one") : t("Record on the original date")); + button.addEventListener("click", () => canMove ? this.renderPicker(instance) : this.renderOriginalDay(instance)); + const ignore = card.createEl("button", { text: t("Ignore"), attr: { type: "button" } }); + ignore.addEventListener("click", async () => { + ignore.disabled = true; + try { await this.store.ignoreMissedDay(habit, dateKey); this.habits = this.habits.map(item => item.path === habit.path ? { ...item, ignoredMisses: [...(item.ignoredMisses || []), dateKey] } : item); this.onChanged(); this.renderList(); } + catch (error) { new Notice(String(error)); ignore.disabled = false; } + }); + } + + private renderOriginalDay({ habit, dateKey }: MissedInstance): void { + const { contentEl } = this; + contentEl.empty(); + new Setting(contentEl).setName(t("Backfill")).setHeading(); + contentEl.createEl("p", { text: `${habit.name} · ${dateKey}` }); + contentEl.createEl("p", { text: t("This habit is already due every day. Ignore this miss or record it on its original day.") }); + + const previous = habit.records[dateKey] || 0; + let value = habit.type === "binary" ? 1 : previous; + let confirm: ButtonComponent | undefined; + if (habit.type !== "binary") { + new Setting(contentEl).setName(habit.unit || t("Value")).addText(text => { + text.inputEl.type = "number"; + text.inputEl.min = "0"; + text.inputEl.step = "any"; + text.setValue(previous ? String(previous) : "").onChange(input => { + value = Number(input); + confirm?.setDisabled(!Number.isFinite(value) || value <= 0); + }); + }); + } + new Setting(contentEl) + .addButton(button => button.setButtonText(t("Back")).onClick(() => this.renderList())) + .addButton(button => { + confirm = button; + button.setButtonText(t("Confirm")).setCta().setDisabled(value <= 0).onClick(async () => { + const recordedValue = value; + if (!Number.isFinite(recordedValue) || recordedValue <= 0) return; + button.setDisabled(true); + try { + await this.store.setRecord(habit, dateKey, recordedValue, previous); + this.habits = this.habits.map(item => item.path === habit.path + ? { ...item, records: { ...item.records, [dateKey]: recordedValue } } + : item); + this.onChanged(); + this.renderList(); + } catch (error) { + new Notice(String(error)); + button.setDisabled(false); + } + }); + }); + } + + private renderPicker(instance: MissedInstance): void { + const { habit, dateKey } = instance; + const { contentEl } = this; + contentEl.empty(); + new Setting(contentEl).setName(t("Missed habits")).setHeading(); + + const today = new Date(); + const missedDate = fromDateKey(dateKey); + contentEl.createEl("p", { + cls: "habits-missed-intro", + text: t('Rescheduling "{name}" — missed {date}.', { + name: habit.name, + date: missedDate ? friendlyDateLabel(missedDate, today) : dateKey, + }), + }); + + // A reschedule target before the habit started couldn't have been + // due there anyway; keep the picker from offering it. + const windowStart = toDateKey(addDays(today, -PICKER_WINDOW_DAYS)); + const min = + windowStart > trackingStartKey(habit, today) + ? windowStart + : trackingStartKey(habit, today); + const max = toDateKey(addDays(today, PICKER_WINDOW_DAYS)); + + let chosen = ""; + for (let offset = 0; offset <= PICKER_WINDOW_DAYS; offset++) { + const key = toDateKey(addDays(today, offset)); + if (key !== dateKey && isRescheduleTargetOpen(habit, key)) { + chosen = key; + break; + } + } + let confirmButton: ButtonComponent | null = null; + const errorEl = contentEl.createDiv({ cls: "habits-missed-error" }); + + const validate = (): void => { + if (!chosen) { + errorEl.setText(""); + confirmButton?.setDisabled(true); + return; + } + const open = chosen >= min && chosen <= max && isRescheduleTargetOpen(habit, chosen); + errorEl.setText( + open + ? "" + : t( + "That day won't work — it's either already due for this habit or already claimed by another reschedule.", + ), + ); + confirmButton?.setDisabled(!open); + }; + + new Setting(contentEl).setName(t("Move to")).addText((text) => { + text.inputEl.type = "date"; + text.inputEl.min = min; + text.inputEl.max = max; + text.setValue(chosen).onChange((value) => { + chosen = value; + validate(); + }); + }); + + new Setting(contentEl) + .addButton((button) => + button.setButtonText(t("Back")).onClick(() => this.renderList()), + ) + .addButton((button) => { + confirmButton = button; + button + .setButtonText(t("Confirm")) + .setCta() + .setDisabled(true) + .onClick(async () => { + if (!chosen || chosen < min || chosen > max) return; + button.setDisabled(true); + await this.confirm(habit, dateKey, chosen); + validate(); + }); + }); + validate(); + } + + private async confirm( + habit: HabitDefinition, + from: string, + to: string, + ): Promise { + if (!isRescheduleTargetOpen(habit, to)) { + new Notice(t("That day no longer works — pick another.")); + return; + } + try { + const reschedules = await this.store.rescheduleHabit(habit, from, to); + this.habits = this.habits.map(item => item.path === habit.path ? { ...item, reschedules } : item); + } catch (error) { new Notice(String(error)); return; } + this.onChanged(); + this.renderList(); + } +} diff --git a/src/integrations/habits/ui/missed-notification.ts b/src/integrations/habits/ui/missed-notification.ts new file mode 100644 index 000000000..aaba2e4be --- /dev/null +++ b/src/integrations/habits/ui/missed-notification.ts @@ -0,0 +1,12 @@ +import { App, Component, setIcon } from "obsidian"; +import { HabitStore } from "../habit-store"; +import { missedInstances } from "../stats"; +import { MissedHabitsModal } from "./missed-habits-modal"; +import { t } from "../i18n"; +export function renderMissedNotification(root: HTMLElement, owner: Component, app: App, store: HabitStore, refresh: () => void): void { + const habits = store.getHabits(), count = missedInstances(habits, new Date()).length; + if (!count) return; + const button = root.createEl("button", { cls: "clickable-icon habits-missed-button", attr: { "aria-label": t("Missed habits"), title: t("Missed habits") } }); + setIcon(button, "bell"); button.createSpan({ text: String(count), cls: "habits-missed-badge" }); + owner.registerDomEvent(button, "click", () => new MissedHabitsModal(app, store, habits, refresh).open()); +} diff --git a/src/integrations/habits/ui/modal-close.ts b/src/integrations/habits/ui/modal-close.ts new file mode 100644 index 000000000..542cab0e8 --- /dev/null +++ b/src/integrations/habits/ui/modal-close.ts @@ -0,0 +1,14 @@ +import { t } from "../i18n"; +import { Modal, setIcon } from "obsidian"; +/** Own a predictable close control rather than depending on theme/native header variants. */ +export function installHabitClose(modal: Modal): () => void { + const native = modal.modalEl.querySelector(".modal-close-button, .modal-header-button"); + const button = modal.modalEl.createEl("button", { cls: "clickable-icon tg-habit-modal-close", attr: { type: "button", "aria-label": t("Close") } }); + setIcon(button, "x"); + const close = (event: Event) => { event.preventDefault(); event.stopImmediatePropagation(); Modal.prototype.close.call(modal); }; + button.addEventListener("click", close, true); + button.addEventListener("pointerup", close, true); + native?.addEventListener("click", close, true); + native?.addEventListener("pointerup", close, true); + return () => { button.removeEventListener("pointerup", close, true); native?.removeEventListener("pointerup", close, true); native?.removeEventListener("click", close, true); button.removeEventListener("click", close, true); button.remove(); }; +} diff --git a/src/integrations/habits/ui/native-card-state.ts b/src/integrations/habits/ui/native-card-state.ts new file mode 100644 index 000000000..d032ac001 --- /dev/null +++ b/src/integrations/habits/ui/native-card-state.ts @@ -0,0 +1,17 @@ +import type { HabitDefinition } from "../types"; +import { flexiblePeriodTotal, isDailyComplete, isFlexible, isPausedOn, isFailedOn, isSkippedOn, limitOf } from "../stats"; +import { fromDateKey } from "../utils"; + +/** Presentation only: scoring and completion stay owned by Habits. */ +export function nativeCardHeat(habit: HabitDefinition, key: string): { level: 0 | 1 | 2 | 3; overLimit: boolean } { + const date = fromDateKey(key), value = habit.records[key] || 0; + if (!date || isPausedOn(habit, key) || isSkippedOn(habit, key) || isFailedOn(habit, key)) return { level: 0, overLimit: false }; + if (habit.goalDirection === "max") { + const actual = isFlexible(habit) ? flexiblePeriodTotal(habit, date) : value; + return { level: isDailyComplete(habit, key) ? 2 : actual > 0 ? 1 : 0, overLimit: actual > limitOf(habit) }; + } + if (value <= 0) return { level: 0, overLimit: false }; + const target = isFlexible(habit) && (habit.dailyTarget || 0) > 0 ? habit.dailyTarget! : habit.type === "binary" && !isFlexible(habit) ? 1 : habit.target; + const total = isFlexible(habit) && !(habit.dailyTarget! > 0) ? flexiblePeriodTotal(habit, date) : value; + return { level: target > 0 && total >= target * 2 ? 3 : isDailyComplete(habit, key) ? 2 : 1, overLimit: false }; +} diff --git a/src/integrations/habits/ui/native-cards.ts b/src/integrations/habits/ui/native-cards.ts new file mode 100644 index 000000000..445c45e0c --- /dev/null +++ b/src/integrations/habits/ui/native-cards.ts @@ -0,0 +1,137 @@ +import { calendarWeekNumber } from "@/utils/date/calendar-week"; +import { renderMissedNotification } from "./missed-notification"; +import { applyHabitIcon } from "./icon-suggest-modal"; +import { App, Component, Events, MarkdownRenderChild, Menu, Notice, setIcon } from "obsidian"; +import type { HabitStore } from "../habit-store"; +import type { HabitsPluginSettings } from "../settings"; +import type { HabitDefinition } from "../types"; +import { isDailyComplete, isActive, flexiblePeriodTotal, isFlexible, isPausedOn, limitOf } from "../stats"; +import { addDays, toDateKey, fromDateKey, habitAccent, stepOf, sortHabits, formatValue, roundValue, friendlyDateLabel } from "../utils"; +import { HabitModal } from "./habit-modal"; +import { t } from "../i18n"; +import { nativeCardHeat } from "./native-card-state"; +import { renderClosedHabits, dayStatus, scheduleSnoozeRefresh } from "./day-status"; +import { createNoteHabitEntry, notePathForDate } from "../note-habit"; +import { addDayStatusItems } from "./day-status"; +import { ConfirmModal } from "./confirm-modal"; +import { watchHabitFiles } from "./habit-file-refresh"; + +/** Task Genius cards, backed by the same Markdown notes as the dashboard. */ +export class NativeHabitCards extends MarkdownRenderChild { + private disposed = false; + private selectedDate = new Date(); + private query = ""; + private events?: Component; + private pending = new Set(); + private saved = new Map>(); + private closedOpen = false; + private cancelSnooze = () => {}; + constructor(private app: App, private store: HabitStore, private settings: HabitsPluginSettings, private bus: Events, root: HTMLElement) { super(root); } + setSearchQuery(query: string): void { const next = query.trim().toLocaleLowerCase(); if (next === this.query) return; this.query = next; this.render(); } + onload(): void { + this.disposed = false; + this.containerEl.addClass("tg-native-habits"); + watchHabitFiles(this, this.app, this.store, path => this.saved.delete(path), () => this.render()); + this.registerEvent(this.bus.on("settings-changed", () => this.render())); + this.render(); + } + private button(root: HTMLElement, icon: string, label: string, action: () => void): HTMLButtonElement { + const button = root.createEl("button", { cls: "clickable-icon", attr: { "aria-label": label, title: label } }); + setIcon(button, icon); this.events?.registerDomEvent(button, "click", action); return button; + } + private render(): void { + if (this.disposed) return; + if (this.events) this.removeChild(this.events); + this.events = this.addChild(new Component()); this.containerEl.empty(); + const nav = this.containerEl.createDiv({ cls: "tg-native-habit-nav" }); + this.button(nav, "chevron-left", t("Previous day"), () => { this.selectedDate = addDays(this.selectedDate, -1); this.render(); }); + const label = nav.createEl("button", { text: friendlyDateLabel(this.selectedDate, new Date()), cls: "tg-native-habit-date-label", attr: { title: toDateKey(this.selectedDate), "aria-label": t("Today") } }); + this.events.registerDomEvent(label, "click", () => { this.selectedDate = new Date(); this.render(); }); + const date = this.containerEl.createEl("input", { cls: "tg-habit-date-picker", attr: { type: "date", tabindex: "-1", "aria-label": t("Date") } }); date.value = toDateKey(this.selectedDate); + this.events.registerDomEvent(date, "change", () => { const next = fromDateKey(date.value); if (next) { this.selectedDate = next; this.render(); } }); + this.events.registerDomEvent(label, "contextmenu", event => { event.preventDefault(); if (typeof date.showPicker === "function") date.showPicker(); else date.click(); }); + this.button(nav, "chevron-right", t("Next day"), () => { this.selectedDate = addDays(this.selectedDate, 1); this.render(); }); + renderMissedNotification(nav, this.events, this.app, this.store, () => this.render()); + const add = this.button(nav, "plus", t("Add habit"), () => new HabitModal(this.app, this.store, () => this.render(), null, this.settings.experimental.noteHabits).open()); add.addClass("tg-habit-add"); + const key = toDateKey(this.selectedDate); + const habits = sortHabits(this.store.getHabits().filter(habit => !habit.stopped && (!this.query || `${habit.name} ${habit.group}`.toLocaleLowerCase().includes(this.query))).map(original => { + const habit = { ...original, records: { ...original.records } }; + for (const [day, value] of this.saved.get(habit.path) || []) { if (value > 0) habit.records[day] = value; else delete habit.records[day]; } + return habit; + }), this.settings.sortMode, this.settings.manualOrder, this.settings.groups, this.settings.groupOrder); + this.cancelSnooze(); this.cancelSnooze = scheduleSnoozeRefresh(this.containerEl.win, this.store, habits, () => this.render()); + const scheduled = habits.filter(habit => isActive(habit, this.selectedDate) && (!habit.startDate || key >= habit.startDate)); + const closed = scheduled.flatMap(habit => { const status = dayStatus(habit, key, this.store); return status ? [{ habit, status }] : []; }); + const visible = scheduled.filter(habit => !closed.some(item => item.habit.path === habit.path)); + const ordered = [...visible.filter(habit => !isDailyComplete(habit, key) && !isPausedOn(habit, key)), ...visible.filter(habit => isDailyComplete(habit, key) && !isPausedOn(habit, key)), ...visible.filter(habit => isPausedOn(habit, key))]; + const cards = this.containerEl.createDiv({ cls: "tg-native-habit-cards" }); + cards.dataset.columns = this.settings.habitColumns || "auto"; + for (const habit of ordered) { + const original = habit; + const card = cards.createDiv({ cls: "tg-native-habit-card" }); + card.toggleClass("is-done", isDailyComplete(habit, key)); card.style.setProperty("--habit-accent", habitAccent(habit, this.settings.groups)); + const header = card.createDiv({ cls: "tg-native-habit-heading" }); + const icon = header.createSpan({ cls: "tg-native-habit-icon" }); + if (habit.icon || this.settings.groups[habit.group]?.icon) applyHabitIcon(icon, habit.icon || this.settings.groups[habit.group].icon); else setIcon(icon, "circle-check"); header.createEl("strong", { text: habit.name }); + this.button(header, "more-horizontal", t("More actions"), () => { + const menu = new Menu(); + addDayStatusItems(menu, this.app, this.store, original, key, () => this.render()); + menu.addItem(item => item.setTitle(t("Edit habit")).setIcon("pencil").onClick(() => new HabitModal(this.app, this.store, () => this.render(), original, this.settings.experimental.noteHabits).open())); + menu.addItem(item => item.setTitle(t("Open note")).setIcon("file-text").onClick(() => void this.app.workspace.openLinkText(habit.path, "", false))); + menu.addItem(item => item.setTitle(habit.paused ? t("Resume habit") : t("Pause habit")).setIcon(habit.paused ? "play" : "pause").onClick(async () => { + if (habit.paused) await this.store.resumeHabit(original); else await this.store.pauseHabit(original); this.render(); + })); + menu.addItem(item => item.setTitle(t("Stop habit")).setIcon("circle-stop").onClick(async () => { + const message = t("Stop tracking \"{name}\"? It leaves the dashboard and stats, but its note and full history are kept. You can resume tracking any time from the note's metrics view.", { name: habit.name }); + if (!await ConfirmModal.ask(this.app, t("Stop tracking"), message)) return; + try { await this.store.stopHabit(original); this.render(); } + catch (error) { new Notice(String(error)); } + })); + menu.addItem(item => item.setTitle(t("Remove habit")).setIcon("trash").onClick(async () => { + if (await ConfirmModal.ask(this.app, t("Remove habit"), t('Remove "{name}"? Its note will be moved to the trash.', { name: habit.name }))) { await this.store.deleteHabit(original); this.render(); } + })); + menu.showAtPosition({ x: header.getBoundingClientRect().right, y: header.getBoundingClientRect().bottom }); + }); + const body = card.createDiv({ cls: "tg-native-habit-body" }); + const grid = body.createDiv({ cls: "tg-native-habit-grid" }); + for (let offset = -29; offset <= 0; offset++) { + const day = addDays(this.selectedDate, offset), dayKey = toDateKey(day), value = habit.records[dayKey] || 0; + const heat = nativeCardHeat(habit, dayKey); + const cell = grid.createEl("button", { cls: "tg-native-habit-cell", attr: { title: `${dayKey}: ${value}`, "aria-label": `${habit.name} ${dayKey}: ${value}` } }); + cell.toggleClass("is-complete", heat.level >= 2); + cell.setAttribute("data-heat", String(heat.level)); + cell.toggleClass("is-over-limit", heat.overLimit); + cell.toggleClass("is-rest", !isActive(habit, day)); + cell.disabled = this.pending.has(habit.path); + this.events.registerDomEvent(cell, "click", () => { this.selectedDate = day; this.render(); }); + } + const controls = body.createDiv({ cls: "tg-native-habit-controls" }); + const value = habit.records[key] || 0, done = isDailyComplete(habit, key), max = habit.goalDirection === "max"; + const total = isFlexible(habit) ? flexiblePeriodTotal(habit, this.selectedDate) : value; + const goal = max ? limitOf(habit) : habit.type === "binary" && !isFlexible(habit) ? 1 : habit.target; + const readout = card.createDiv({ cls: "tg-native-habit-goal" }); + readout.setText(`${max ? t("At most") : t("At least")}: ${formatValue(total)} / ${formatValue(goal)}${habit.unit ? ` ${habit.unit}` : ""}${isFlexible(habit) ? ` · ${habit.frequency === "flexibleWeekly" ? (t("This week") + " · W" + calendarWeekNumber(this.selectedDate)) : t("This month")}` : ""}`); + if (isFlexible(habit) && habit.dailyTarget) readout.createSpan({ text: ` · ${t("Daily goal")}: ${habit.dailyTarget}` }); + if (isPausedOn(habit, key)) { controls.createSpan({ text: t("Paused") }); continue; } + if (habit.type === "binary" && !isFlexible(habit)) { + const toggle = this.button(controls, max ? value > 0 ? "x" : "circle-check" : done ? "check-square" : "square", max ? value > 0 ? t("Mark as clean") : t("Mark as slipped") : t("Check in"), () => void this.commit(original, key, value > 0 ? 0 : 1)); + toggle.disabled = this.pending.has(habit.path); toggle.toggleClass("is-complete", done); toggle.toggleClass("is-over-limit", max && !done); + } else if (habit.type === "note") { + this.button(controls, "file-text", t("Open this day's note"), () => void (async () => { const path = notePathForDate(habit, key); if (!this.app.vault.getAbstractFileByPath(path)) await createNoteHabitEntry(this.app, habit, key); await this.app.workspace.openLinkText(path, "", false); })()); + } else { + const minus = this.button(controls, "minus", t("Decrease"), () => void this.commit(original, key, roundValue(Math.max(0, value - (habit.type === "timed" ? 5 : stepOf(habit)))))); + controls.createSpan({ text: `${value}${habit.unit ? ` ${habit.unit}` : ""}` }); + const plus = this.button(controls, "plus", t("Increase"), () => void this.commit(original, key, roundValue(value + (habit.type === "timed" ? 5 : stepOf(habit))))); + minus.disabled = this.pending.has(habit.path) || value <= 0; plus.disabled = this.pending.has(habit.path); + } + } + renderClosedHabits(this.containerEl, this.events, this.store, closed, key, this.closedOpen, open => { this.closedOpen = open; this.render(); }, () => this.render()); + } + onunload(): void { this.disposed = true; this.cancelSnooze(); } + private async commit(habit: HabitDefinition, key: string, value: number): Promise { + if (this.pending.has(habit.path)) return; this.pending.add(habit.path); this.render(); + try { await this.store.setRecord(habit, key, value); const saved = this.saved.get(habit.path) || new Map(); saved.set(key, value); this.saved.set(habit.path, saved); } + catch (error) { new Notice(String(error)); } + finally { this.pending.delete(habit.path); this.render(); } + } +} diff --git a/src/integrations/habits/ui/panel-view.ts b/src/integrations/habits/ui/panel-view.ts new file mode 100644 index 000000000..61eaa0c53 --- /dev/null +++ b/src/integrations/habits/ui/panel-view.ts @@ -0,0 +1,952 @@ +import { + debounce, + Events, + ItemView, + Menu, + normalizePath, + setIcon, + setTooltip, + TFile, + WorkspaceLeaf, +} from "obsidian"; +import type { HabitStore } from "../habit-store"; +import type { HabitsPluginSettings } from "../settings"; +import type { HabitDefinition } from "../types"; +import { + flexiblePeriodTotal, + isActive, + isComplete, + isFlexible, + isPausedOn, + limitOf, + missedInstances, + rescheduleSource, +} from "../stats"; +import { createNoteHabitEntry, notePathForDate } from "../note-habit"; +import { + allowsDecimals, + cleanValue, + formatTimeOfDay, + formatValue, + friendlyDateLabel, + fromDateKey, + groupHabits, + habitAccent, + registerLongPress, + sectionLabel, + roundValue, + sortHabits, + stepOf, + toDateKey, + type HabitSection, +} from "../utils"; +import { t } from "../i18n"; +import { HabitModal } from "./habit-modal"; +import { MissedHabitsModal } from "./missed-habits-modal"; +import { + addDayStatusItems, + dayStatus, + renderClosedHabits, + scheduleSnoozeRefresh, + type ClosedHabit, +} from "./day-status"; +import { ConfirmModal } from "./confirm-modal"; +import { applyHabitIcon } from "./icon-suggest-modal"; + +export const HABITS_PANEL_VIEW_TYPE = "tg-habits-panel"; + +/** + * Compact sidebar view for logging today's habits on the fly. + * + * Designed for narrow widths: one slim row per habit with the smallest + * possible controls, a today summary in the header, and the same + * incomplete → completed → paused ordering as the dashboard. + */ +export class HabitsPanelView extends ItemView { + private habits: HabitDefinition[] = []; + /** Suppresses event-driven reloads while a row celebration plays. */ + private suppressAutoReload = false; + /** Whether the "hidden for today" list under the rows is expanded. */ + private closedOpen = false; + /** Cancels the pending refresh for when a snooze ends. */ + private cancelSnoozeRefresh: () => void = () => {}; + + constructor( + leaf: WorkspaceLeaf, + private store: HabitStore, + private getSettings: () => HabitsPluginSettings, + private pluginEvents: Events, + ) { + super(leaf); + } + + getViewType(): string { + return HABITS_PANEL_VIEW_TYPE; + } + + getDisplayText(): string { + return t("Habits"); + } + + getIcon(): string { + return "list-checks"; + } + + async onOpen(): Promise { + this.contentEl.addClass("tg-habits-panel"); + + const requestReload = debounce(() => this.autoReload(), 250, true); + this.registerEvent( + this.app.metadataCache.on("changed", (file) => { + if (this.isHabitFile(file.path)) { + requestReload(); + } + }), + ); + this.registerEvent( + this.app.vault.on("create", (file) => { + if (this.isHabitFile(file.path)) { + requestReload(); + } + }), + ); + this.registerEvent( + this.app.vault.on("delete", (file) => { + if (this.isHabitFile(file.path)) { + requestReload(); + } + }), + ); + this.registerEvent( + this.app.vault.on("rename", (file, oldPath) => { + if ( + this.isHabitFile(file.path) || + this.isHabitFile(oldPath) + ) { + requestReload(); + } + }), + ); + this.registerEvent( + this.pluginEvents.on("settings-changed", () => { + requestReload(); + }), + ); + this.registerEvent( + this.pluginEvents.on("comments-changed", () => { + requestReload(); + }), + ); + + this.reload(); + } + + async onClose(): Promise { + this.cancelSnoozeRefresh(); + this.contentEl.empty(); + } + + /** True when the path lives inside the configured habits folder. */ + private isHabitFile(path: string): boolean { + const folder = normalizePath(this.getSettings().habitsFolder); + return path === folder || path.startsWith(`${folder}/`); + } + + private autoReload(): void { + if (this.suppressAutoReload) { + return; + } + const active = this.contentEl.doc.activeElement; + if ( + active instanceof HTMLInputElement && + this.contentEl.contains(active) + ) { + return; + } + this.reload(); + } + + private reload(): void { + const settings = this.getSettings(); + this.habits = sortHabits( + this.store.getHabits().filter((habit) => !habit.stopped), + settings.sortMode, + settings.manualOrder, + settings.groups, + settings.groupOrder, + ); + this.render(); + } + + private todayKey(): string { + return toDateKey(new Date()); + } + + private valueOf(habit: HabitDefinition): number { + return habit.records[this.todayKey()] ?? 0; + } + + private isDone(habit: HabitDefinition): boolean { + return isComplete(habit, this.todayKey()); + } + + private isPausedToday(habit: HabitDefinition): boolean { + return isPausedOn(habit, this.todayKey()); + } + + /** + * Whether the habit should show/be interactive today — its normal due + * date, or every day for a flexible habit (see {@link isActive}). + */ + private isActiveToday(habit: HabitDefinition): boolean { + return isActive(habit, new Date()); + } + + /** + * Incomplete first, completed next, paused parked at the end. Weekly and + * monthly habits are included only on the days they are due. + */ + private ordered(): HabitDefinition[] { + const flat: HabitDefinition[] = []; + for (const section of this.sections()) { + flat.push(...section.habits); + } + return flat; + } + + /** + * Whether the panel partitions into group sections; mirrors the + * dashboard — sections only while sorting by group, so other sort + * orders (manual especially) are honoured exactly. + */ + private sectioned(): boolean { + const settings = this.getSettings(); + return settings.groupsEnabled && settings.sortMode === "group"; + } + + /** Whether the habit was failed, skipped or snoozed for today. */ + private isClosedToday(habit: HabitDefinition): boolean { + return dayStatus(habit, this.todayKey(), this.store) !== null; + } + + /** Habits due today but taken off the list, in order. */ + private closedHabits(): ClosedHabit[] { + const closed: ClosedHabit[] = []; + for (const habit of this.habits) { + const status = this.isActiveToday(habit) + ? dayStatus(habit, this.todayKey(), this.store) + : null; + if (status) { + closed.push({ habit, status }); + } + } + return closed; + } + + /** Sections mirroring the dashboard's grouping behaviour. */ + private sections(): HabitSection[] { + const due = this.habits.filter( + (habit) => this.isActiveToday(habit) && !this.isClosedToday(habit), + ); + return groupHabits( + due, + this.sectioned(), + this.getSettings().groupOrder, + ) + .map((section) => ({ + key: section.key, + habits: this.applyStatusOrder(section.habits), + })) + .filter((section) => section.habits.length > 0); + } + + /** Status partition applied to an already-sorted run of due habits. */ + private applyStatusOrder(due: HabitDefinition[]): HabitDefinition[] { + // With status ordering off, every row keeps its sorted position. + if (!this.getSettings().statusOrdering) { + return due; + } + const active = due.filter((habit) => !this.isPausedToday(habit)); + return [ + ...active.filter((habit) => !this.isDone(habit)), + ...active.filter((habit) => this.isDone(habit)), + ...due.filter((habit) => this.isPausedToday(habit)), + ]; + } + + private render(): void { + const root = this.contentEl; + root.empty(); + + const header = root.createDiv({ cls: "habits-panel-header" }); + const title = header.createDiv({ cls: "habits-panel-title" }); + title.createSpan({ text: t("Today") }); + title.createSpan({ + cls: "habits-panel-date", + text: new Date().toLocaleDateString(undefined, { + weekday: "short", + day: "numeric", + month: "short", + }), + }); + + const trackable = this.habits.filter( + (habit) => + this.isActiveToday(habit) && !this.isPausedToday(habit), + ); + const doneCount = trackable.filter((habit) => + this.isDone(habit), + ).length; + if (trackable.length > 0) { + const count = header.createDiv({ cls: "habits-panel-count" }); + count.setText(`${doneCount}/${trackable.length}`); + count.toggleClass("is-all-done", doneCount === trackable.length); + setTooltip(count, t("Habits completed today")); + } + + if (this.getSettings().experimental.rescheduling) { + const missedCount = missedInstances(this.habits, new Date()).length; + if (missedCount > 0) { + const missed = header.createEl("button", { + cls: "habits-icon-button habits-panel-missed", + attr: { type: "button", "aria-label": t("Missed habits") }, + }); + setIcon(missed, "bell"); + const badge = missed.createSpan({ cls: "habits-missed-badge" }); + badge.setText(String(missedCount)); + setTooltip( + missed, + missedCount === 1 + ? t("1 missed habit") + : t("{count} missed habits", { count: missedCount }), + ); + this.registerDomEvent(missed, "click", () => { + new MissedHabitsModal(this.app, this.store, this.habits, () => + this.reload(), + ).open(); + }); + } + } + + const add = header.createEl("button", { + cls: "habits-icon-button habits-panel-add", + attr: { type: "button", "aria-label": t("Add habit") }, + }); + setIcon(add, "plus"); + this.registerDomEvent(add, "click", () => { + new HabitModal( + this.app, + this.store, + () => this.reload(), + null, + this.getSettings().experimental.noteHabits, + ).open(); + }); + + if (this.habits.length === 0) { + const empty = root.createDiv({ cls: "habits-panel-empty" }); + empty.createEl("p", { text: t("No habits yet.") }); + const button = empty.createEl("button", { + cls: "mod-cta", + text: t("Create habit"), + attr: { type: "button" }, + }); + this.registerDomEvent(button, "click", () => { + new HabitModal( + this.app, + this.store, + () => this.reload(), + null, + this.getSettings().experimental.noteHabits, + ).open(); + }); + return; + } + + this.cancelSnoozeRefresh(); + this.cancelSnoozeRefresh = scheduleSnoozeRefresh( + root.win, + this.store, + this.habits, + () => this.reload(), + ); + const closed = this.closedHabits(); + const showClosed = (): void => + renderClosedHabits( + root, + this, + this.store, + closed, + this.todayKey(), + this.closedOpen, + (open) => { + this.closedOpen = open; + this.render(); + }, + () => this.render(), + ); + + const due = this.ordered(); + if (due.length === 0) { + const none = root.createDiv({ cls: "habits-panel-empty" }); + none.createEl("p", { + text: + closed.length > 0 + ? t("Nothing left on today's list.") + : t("Nothing due today."), + }); + showClosed(); + return; + } + + const list = root.createDiv({ cls: "habits-panel-list" }); + const settings = this.getSettings(); + for (const section of this.sections()) { + if (this.sectioned()) { + const header = list.createDiv({ + cls: "habits-panel-group", + }); + const style = settings.groups[section.key]; + if (style?.icon) { + const icon = header.createSpan({ + cls: "habits-group-icon", + }); + applyHabitIcon(icon, style.icon); + if (style.color) { + icon.setCssProps({ + "--habits-accent": style.color, + }); + } + } else if (style?.color) { + const swatch = header.createSpan({ + cls: "habits-group-swatch", + }); + swatch.setCssProps({ + "--habits-accent": style.color, + }); + } + header.createSpan({ + text: sectionLabel(section.key), + }); + } + for (const habit of section.habits) { + this.renderRow(list, habit); + } + } + showClosed(); + } + + private renderRow(list: HTMLElement, habit: HabitDefinition): void { + const row = list.createDiv({ cls: "habits-panel-row" }); + const accent = habitAccent(habit, this.getSettings().groups); + if (accent) { + row.setCssProps({ "--habits-accent": accent }); + } + this.registerDomEvent(row, "contextmenu", (evt: MouseEvent) => { + evt.preventDefault(); + this.showRowMenu(habit, evt.clientX, evt.clientY); + }); + registerLongPress(this, row, (x, y) => { + this.showRowMenu(habit, x, y); + }); + + const main = row.createDiv({ cls: "habits-panel-row-main" }); + if (habit.icon) { + const icon = main.createSpan({ cls: "habits-panel-icon" }); + applyHabitIcon(icon, habit.icon); + } + const name = main.createEl("button", { + cls: "habits-panel-name", + text: habit.name, + attr: { + type: "button", + "aria-label": t("Open the note for {name}", { name: habit.name }), + }, + }); + setTooltip(name, `${habit.name} — ${t("Open habit note")}`); + this.registerDomEvent(name, "click", () => { + void this.app.workspace.openLinkText(habit.path, "", false); + }); + + if (habit.times.length > 0) { + // All times stay visible; the name truncates instead and its + // tooltip already reveals the full name. + main.createSpan({ + cls: "habits-panel-time", + text: habit.times.map(formatTimeOfDay).join(", "), + }); + } + + if (this.getSettings().experimental.rescheduling) { + const movedFrom = rescheduleSource(habit, toDateKey(new Date())); + if (movedFrom) { + const badge = main.createSpan({ + cls: "habits-panel-rescheduled", + }); + setIcon(badge, "calendar"); + const movedFromDate = fromDateKey(movedFrom); + setTooltip( + badge, + t("Rescheduled from {date}", { + date: movedFromDate + ? friendlyDateLabel(movedFromDate, new Date()) + : movedFrom, + }), + ); + } + } + + if (this.isPausedToday(habit)) { + row.addClass("is-paused"); + const resume = main.createEl("button", { + cls: "habits-icon-button habits-panel-mini", + attr: { type: "button", "aria-label": t("Resume habit") }, + }); + setIcon(resume, "play"); + setTooltip(resume, t("Resume habit")); + this.registerDomEvent(resume, "click", async () => { + await this.store.resumeHabit(habit); + this.reload(); + }); + return; + } + + const done = this.isDone(habit); + row.toggleClass("is-done", done); + + if (isFlexible(habit)) { + this.renderFlexibleRow(main, habit, row); + return; + } + + if (habit.type === "binary" && habit.goalDirection === "max") { + // A limit day is clean unless a slip is logged, so the toggle + // inverts: it records the slip, and records it back away. + const slipped = this.valueOf(habit) >= 1; + row.toggleClass("is-slipped", slipped); + const toggle = main.createEl("button", { + cls: "habits-panel-toggle habits-panel-slip-toggle", + attr: { + type: "button", + "aria-label": slipped + ? t("Mark as clean") + : t("Mark as slipped"), + "aria-pressed": String(slipped), + }, + }); + setIcon(toggle, slipped ? "x" : "check"); + this.registerDomEvent(toggle, "click", async () => { + await this.commit(habit, slipped ? 0 : 1, row); + }); + return; + } + + if (habit.type === "binary") { + const toggle = main.createEl("button", { + cls: "habits-panel-toggle", + attr: { + type: "button", + "aria-label": done ? t("Mark as not done") : t("Mark as done"), + "aria-pressed": String(done), + }, + }); + setIcon(toggle, done ? "check" : "circle"); + this.registerDomEvent(toggle, "click", async () => { + await this.commit(habit, done ? 0 : 1, row); + }); + return; + } + + if (habit.type === "note") { + this.renderNoteRow(main, habit); + return; + } + + const value = this.valueOf(habit); + const timed = habit.type === "timed"; + const step = stepOf(habit); + const isMax = habit.goalDirection === "max"; + const goalValue = isMax ? limitOf(habit) : habit.target; + row.toggleClass("is-slipped", isMax && !done); + const valueBtn = main.createEl("button", { + cls: "habits-panel-value", + text: `${formatValue(value)}/${formatValue(goalValue)}`, + attr: { type: "button", "aria-label": t("Edit value") }, + }); + setTooltip(valueBtn, t("Click to type a value")); + this.registerDomEvent(valueBtn, "click", () => { + this.editRowValue(habit, row, valueBtn); + }); + + const minus = main.createEl("button", { + cls: "habits-icon-button habits-panel-mini", + attr: { + type: "button", + "aria-label": t("Decrease by {n}", { n: formatValue(step) }), + }, + }); + setIcon(minus, "minus"); + this.registerDomEvent(minus, "click", async () => { + await this.commit(habit, value - step, row); + }); + + if (timed) { + // Time gets logged in chunks, so offer 1, 5 and 10 minutes. + for (const step of [1, 5, 10]) { + const btn = main.createEl("button", { + cls: "habits-icon-button habits-panel-mini habits-panel-step", + text: `+${step}`, + attr: { + type: "button", + "aria-label": t("Increase by {n}", { n: step }), + }, + }); + this.registerDomEvent(btn, "click", async () => { + await this.commit(habit, value + step, row); + }); + } + } else { + const plus = main.createEl("button", { + cls: "habits-icon-button habits-panel-mini", + attr: { + type: "button", + "aria-label": t("Increase by {n}", { n: formatValue(step) }), + }, + }); + setIcon(plus, "plus"); + this.registerDomEvent(plus, "click", async () => { + await this.commit(habit, value + step, row); + }); + } + + const progress = row.createDiv({ cls: "habits-panel-progress" }); + const fill = progress.createDiv({ + cls: "habits-panel-progress-fill", + }); + const pct = isMax + ? goalValue > 0 + ? Math.min(100, Math.round((value / goalValue) * 100)) + : value > 0 + ? 100 + : 0 + : habit.target > 0 + ? Math.min(100, Math.round((value / habit.target) * 100)) + : 0; + fill.setCssProps({ "--habits-progress": `${pct}%` }); + if (isMax && !done) { + progress.addClass("is-over"); + } else if (done) { + progress.addClass("is-complete"); + } + } + + /** + * Compact row for a flexible weekly/monthly habit: the same +1/−1 (and + * +5/+10 for timed) buttons as the plain counter row, still logging + * today's own value, but the readout and progress bar show the running + * total for the whole period (see {@link flexiblePeriodTotal}) instead + * of just today's — read-only, since it isn't itself what gets stored. + */ + private renderFlexibleRow( + main: HTMLElement, + habit: HabitDefinition, + row: HTMLElement, + ): void { + const value = this.valueOf(habit); + const timed = habit.type === "timed"; + const step = stepOf(habit); + const goalValue = habit.goalDirection === "max" ? limitOf(habit) : habit.target > 0 ? habit.target : 1; + const periodTotal = flexiblePeriodTotal(habit, new Date()); + main.createSpan({ + cls: "habits-panel-value habits-panel-readout-value", + text: `${formatValue(periodTotal)}/${formatValue(goalValue)}`, + }); + + const minus = main.createEl("button", { + cls: "habits-icon-button habits-panel-mini", + attr: { + type: "button", + "aria-label": t("Decrease by {n}", { n: formatValue(step) }), + }, + }); + setIcon(minus, "minus"); + this.registerDomEvent(minus, "click", async () => { + await this.commit(habit, value - step, row); + }); + + if (timed) { + for (const step of [1, 5, 10]) { + const btn = main.createEl("button", { + cls: "habits-icon-button habits-panel-mini habits-panel-step", + text: `+${step}`, + attr: { + type: "button", + "aria-label": t("Increase by {n}", { n: step }), + }, + }); + this.registerDomEvent(btn, "click", async () => { + await this.commit(habit, value + step, row); + }); + } + } else { + const plus = main.createEl("button", { + cls: "habits-icon-button habits-panel-mini", + attr: { + type: "button", + "aria-label": t("Increase by {n}", { n: formatValue(step) }), + }, + }); + setIcon(plus, "plus"); + this.registerDomEvent(plus, "click", async () => { + await this.commit(habit, value + step, row); + }); + } + + const progress = row.createDiv({ cls: "habits-panel-progress" }); + const fill = progress.createDiv({ cls: "habits-panel-progress-fill" }); + const pct = goalValue > 0 ? Math.min(100, Math.round((periodTotal / goalValue) * 100)) : periodTotal > 0 ? 100 : 0; + fill.setCssProps({ "--habits-progress": `${pct}%` }); + if (habit.goalDirection === "max") { + progress.toggleClass("is-over", periodTotal > goalValue); + } else if (periodTotal >= goalValue) { + progress.addClass("is-complete"); + } + } + + /** + * Compact row for a note habit: a read-only char-count/percentage + * readout (machine-derived, so not click-to-edit like other types) plus + * a single Write/Open action for today's note. + */ + private renderNoteRow(main: HTMLElement, habit: HabitDefinition): void { + const value = this.valueOf(habit); + main.createSpan({ + cls: "habits-panel-value habits-panel-readout-value", + text: `${value}/${habit.target} ${habit.unit || "chars"}`, + }); + + const dateKey = this.todayKey(); + const notePath = notePathForDate(habit, dateKey); + const exists = + this.app.vault.getAbstractFileByPath(notePath) instanceof TFile; + + const action = main.createEl("button", { + cls: "habits-icon-button habits-panel-mini", + attr: { type: "button" }, + }); + if (exists) { + setIcon(action, "file-text"); + setTooltip(action, t("Open today's note")); + this.registerDomEvent(action, "click", () => { + void this.app.workspace.openLinkText(notePath, "", false); + }); + } else { + setIcon(action, "square-pen"); + setTooltip(action, t("Write today's note")); + this.registerDomEvent(action, "click", async () => { + const file = await createNoteHabitEntry( + this.app, + habit, + dateKey, + ); + if (file) { + void this.app.workspace.openLinkText(file.path, "", false); + this.reload(); + } + }); + } + } + + /** Swap the value readout for an input so the user can type a value. */ + private editRowValue( + habit: HabitDefinition, + row: HTMLElement, + valueBtn: HTMLElement, + ): void { + const input = createEl("input", { + cls: "habits-panel-value-input", + attr: { + type: "number", + min: "0", + step: allowsDecimals(habit) ? "any" : "1", + inputmode: allowsDecimals(habit) ? "decimal" : "numeric", + "aria-label": t("Value"), + }, + }); + input.value = formatValue(this.valueOf(habit)); + valueBtn.replaceWith(input); + input.focus(); + input.select(); + + let done = false; + const finish = async (save: boolean): Promise => { + if (done) { + return; + } + done = true; + if (save) { + const parsed = Number(input.value); + if (Number.isFinite(parsed)) { + await this.commit(habit, cleanValue(habit, parsed), row); + return; + } + } + this.reload(); + }; + + this.registerDomEvent(input, "keydown", (evt: KeyboardEvent) => { + if (evt.key === "Enter") { + evt.preventDefault(); + void finish(true); + } else if (evt.key === "Escape") { + evt.preventDefault(); + void finish(false); + } + }); + this.registerDomEvent(input, "blur", () => { + void finish(true); + }); + } + + /** Write a value for today, celebrating a fresh completion briefly. */ + private async commit( + habit: HabitDefinition, + value: number, + row: HTMLElement, + ): Promise { + const wasDone = this.isDone(habit); + const clamped = roundValue(Math.max(0, value)); + const dateKey = this.todayKey(); + if (clamped > 0) { + habit.records[dateKey] = clamped; + } else { + delete habit.records[dateKey]; + } + + this.suppressAutoReload = true; + try { + await this.store.setRecord(habit, dateKey, clamped); + // Limit habits celebrate quietly: recovering from a slip or + // logging under the limit should not flash a completion check. + if ( + !wasDone && + this.isDone(habit) && + habit.goalDirection !== "max" && + this.getSettings().animations + ) { + row.addClass("is-celebrating"); + const flash = row.createDiv({ cls: "habits-panel-flash" }); + const icon = flash.createSpan({ + cls: "habits-panel-flash-icon", + }); + setIcon(icon, "circle-check"); + await sleep(650); + } + } finally { + this.suppressAutoReload = false; + } + this.reload(); + } + + /** Last time a row menu opened; guards double-fire on long-press. */ + private lastMenuAt = 0; + + private showRowMenu(habit: HabitDefinition, x: number, y: number): void { + const now = Date.now(); + if (now - this.lastMenuAt < 500) { + return; + } + this.lastMenuAt = now; + const menu = new Menu(); + addDayStatusItems(menu, this.app, this.store, habit, this.todayKey(), () => + this.render(), + ); + menu.addItem((item) => + item + .setTitle(t("Open note")) + .setIcon("file-text") + .onClick(() => { + void this.app.workspace.openLinkText( + habit.path, + "", + false, + ); + }), + ); + menu.addItem((item) => + item + .setTitle(t("Edit habit")) + .setIcon("pencil") + .onClick(() => { + new HabitModal( + this.app, + this.store, + () => this.reload(), + habit, + this.getSettings().experimental.noteHabits, + ).open(); + }), + ); + if (habit.paused) { + menu.addItem((item) => + item + .setTitle(t("Resume habit")) + .setIcon("play") + .onClick(async () => { + await this.store.resumeHabit(habit); + this.reload(); + }), + ); + } else { + menu.addItem((item) => + item + .setTitle(t("Pause habit")) + .setIcon("pause") + .onClick(async () => { + await this.store.pauseHabit(habit); + this.reload(); + }), + ); + } + menu.addItem((item) => + item + .setTitle(t("Stop tracking")) + .setIcon("circle-stop") + .onClick(() => { + new ConfirmModal(this.app, { + title: t("Stop tracking"), + message: t( + 'Stop tracking "{name}"? It leaves the dashboard and stats, but its note and full history are kept. You can resume tracking any time from the note\'s metrics view.', + { name: habit.name }, + ), + confirmText: t("Stop tracking"), + onConfirm: async () => { + await this.store.stopHabit(habit); + this.reload(); + }, + }).open(); + }), + ); + menu.addItem((item) => + item + .setTitle(t("Remove habit")) + .setIcon("trash") + .onClick(() => { + new ConfirmModal(this.app, { + title: t("Remove habit"), + message: t( + 'Remove "{name}"? Its note will be moved to the trash.', + { name: habit.name }, + ), + confirmText: t("Remove"), + danger: true, + onConfirm: async () => { + await this.store.deleteHabit(habit); + this.reload(); + }, + }).open(); + }), + ); + menu.showAtPosition({ x, y }); + } +} diff --git a/src/integrations/habits/ui/stats-view.ts b/src/integrations/habits/ui/stats-view.ts new file mode 100644 index 000000000..6e3808ca5 --- /dev/null +++ b/src/integrations/habits/ui/stats-view.ts @@ -0,0 +1,513 @@ +import { calendarWeekNumber } from "@/utils/date/calendar-week"; +import { Notice, setIcon } from "obsidian"; +import { t } from "../i18n"; +import type { AiSummarySettings } from "../settings"; +import type { GroupStyle, HabitDefinition } from "../types"; +import { addDays, formatValue, habitAccent, toDateKey } from "../utils"; +import { applyHabitIcon } from "./icon-suggest-modal"; +import { + buildStatsDigest, + generateSummary, + getCachedSummary, +} from "../ai-summary"; +import { + getStatsRange, + habitStats, + isActive, + isComplete, + isFlexible, + isPausedOn, + perfectDays, + trackingStartKey, + rangeLength, + type DateRange, + type StatsPeriod, + type StatsRangeMode, +} from "../stats"; + +function formatShort(date: Date): string { + return date.toLocaleDateString(undefined, { + day: "numeric", + month: "short", + }); +} + +function tile(parent: HTMLElement, value: string, label: string): void { + const el = parent.createDiv({ cls: "habits-stat-tile" }); + el.createDiv({ cls: "habits-stat-value", text: value }); + el.createDiv({ cls: "habits-stat-label", text: label }); +} + +/** Render the stats view (summary tiles + per-habit heatmaps) into a container. */ +export function renderStatsView( + container: HTMLElement, + habits: HabitDefinition[], + period: StatsPeriod, + mode: StatsRangeMode, + today: Date, + /** The user-picked range; only used when `period` is `custom`. */ + customRange?: DateRange, + /** When set, an AI summary section is offered (experimental feature). */ + aiSettings?: AiSummarySettings, + /** + * When set (> 0), the per-habit rows are split into carousel pages of + * this many rows. Left unset, all rows render as one flat list. + */ + rowsPerPage?: number, + /** + * When set, grouping is enabled: rows carry a group lip and use + * the group colour where the habit opted into it. + */ + groups?: Record, + /** + * Vertical layout: cap the list's height and scroll it in place, + * saving space in the note. + */ + scrollable?: boolean, +): void { + container.empty(); + container.addClass("habits-stats"); + + const range = getStatsRange(today, period, mode, customRange); + const length = rangeLength(range); + + const title = + period === "custom" + ? t("Custom range") + : mode === "rolling" + ? period === "weekly" + ? t("Last 7 days") + : t("Last 30 days") + : period === "weekly" + ? (t("This week") + " · W" + calendarWeekNumber(today)) + : t("This month"); + const subtitle = + period === "monthly" && mode === "calendar" + ? today.toLocaleDateString(undefined, { + month: "long", + year: "numeric", + }) + : `${formatShort(range.start)} – ${formatShort(range.end)}`; + + container.createDiv({ + cls: "habits-stats-range", + text: `${title} · ${subtitle}`, + }); + + if (habits.length === 0) { + container.createDiv({ + cls: "habits-empty", + text: t("No habits to show stats for yet."), + }); + return; + } + + const todayKey = toDateKey(today); + const allStats = habits.map((habit) => habitStats(habit, range, today)); + const totalDays = allStats.reduce((sum, s) => sum + s.days, 0); + const totalCompleted = allStats.reduce((sum, s) => sum + s.completed, 0); + const overallRate = + totalDays > 0 ? Math.round((totalCompleted / totalDays) * 100) : 0; + const bestCurrent = allStats.reduce((max, s) => Math.max(max, s.current), 0); + const perfect = perfectDays(habits, range, today); + + // Weekly and monthly goals don't map onto an arbitrary date range, so + // the custom period shows no goal tiles or bars at all. + const isPerfect = (habit: HabitDefinition): boolean => + period === "weekly" + ? habit.weeklyPerfect + : period === "monthly" + ? habit.monthlyPerfect + : false; + const goalOf = (habit: HabitDefinition): number => { + if (period === "custom") { + return 0; + } + if (isPerfect(habit)) { + return length; + } + return period === "weekly" ? habit.weeklyTarget : habit.monthlyTarget; + }; + const progressOf = (i: number): number => allStats[i].completed; + let goalsTotal = 0; + let goalsMet = 0; + habits.forEach((habit, i) => { + if (goalOf(habit) > 0) { + goalsTotal++; + if (progressOf(i) >= goalOf(habit)) { + goalsMet++; + } + } + }); + + const summary = container.createDiv({ cls: "habits-stats-summary" }); + tile(summary, `${overallRate}%`, t("Completion")); + tile(summary, `${bestCurrent}`, t("Best streak")); + tile(summary, `${perfect}`, t("Perfect days")); + tile(summary, `${totalCompleted}`, t("Completions")); + if (goalsTotal > 0) { + tile(summary, `${goalsMet}/${goalsTotal}`, t("Goals met")); + } + + if (aiSettings) { + renderAiSummary( + container, + habits, + period, + mode, + today, + customRange, + aiSettings, + ); + } + + // Carousel mode splits the rows into sliding pages; it only engages + // when there are more habits than fit a single page. + const pageSize = rowsPerPage !== undefined && rowsPerPage > 0 + ? rowsPerPage + : 0; + const paged = pageSize > 0 && habits.length > pageSize; + const pages: HTMLElement[] = []; + let track: HTMLElement | null = null; + let list: HTMLElement | null = null; + if (paged) { + const viewport = container.createDiv({ + cls: "habits-stats-carousel-viewport", + }); + track = viewport.createDiv({ cls: "habits-stats-carousel-track" }); + const pageCount = Math.ceil(habits.length / pageSize); + for (let p = 0; p < pageCount; p++) { + pages.push( + track.createDiv({ + cls: "habits-stats-list habits-stats-page", + }), + ); + } + } else { + list = container.createDiv({ cls: "habits-stats-list" }); + if (scrollable) { + list.addClass("is-scrollable"); + } + } + + habits.forEach((habit, i) => { + const stats = allStats[i]; + const parent = paged + ? pages[Math.floor(i / pageSize)] + : (list as HTMLElement); + const row = parent.createDiv({ cls: "habits-stats-row" }); + const accent = habitAccent(habit, groups ?? {}); + if (accent) { + row.setCssProps({ "--habits-accent": accent }); + } + + // With grouping on, the row carries the same group lip as the + // dashboard cards, flush along its top edge. + const groupName = habit.group.trim(); + if (groups && groupName) { + const lip = row.createDiv({ + cls: "habits-card-group-lip habits-stats-group-lip", + }); + const style = groups[groupName]; + if (style?.color) { + lip.setCssProps({ + "--habits-group-color": style.color, + }); + } + if (style?.icon) { + const icon = lip.createSpan({ + cls: "habits-card-group-icon", + }); + applyHabitIcon(icon, style.icon); + } + lip.createSpan({ + cls: "habits-card-group-name", + text: groupName, + }); + } + + const top = row.createDiv({ cls: "habits-stats-row-top" }); + const name = top.createDiv({ cls: "habits-stats-name" }); + if (habit.icon) { + const icon = name.createSpan({ cls: "habits-card-icon" }); + applyHabitIcon(icon, habit.icon); + } + name.createSpan({ text: habit.name }); + const streak = top.createSpan({ cls: "habits-stats-streak" }); + const flame = streak.createSpan({ cls: "habits-stats-flame" }); + setIcon(flame, "flame"); + streak.createSpan({ text: `${stats.current}` }); + + const heatmap = row.createDiv({ cls: "habits-stats-heatmap" }); + const startKey = trackingStartKey(habit, today); + for (let d = 0; d < length; d++) { + const date = addDays(range.start, d); + const key = toDateKey(date); + const value = habit.records[key] ?? 0; + const cell = heatmap.createDiv({ cls: "habits-stats-cell" }); + if (key === startKey) { + // A filled play icon marks the first tracked day — small + // rings proved too subtle at this cell size. + cell.addClass("is-start"); + setIcon(cell, "play"); + } + if (key < startKey) { + // The habit didn't exist yet: neither success nor failure. + cell.addClass("is-prestart"); + cell.setAttr( + "aria-label", + `${key}: ${t("not tracked yet")}`, + ); + continue; + } + if (!isActive(habit, date)) { + cell.addClass("is-notdue"); + } else if (key > todayKey) { + cell.addClass("is-future"); + } else if (isPausedOn(habit, key)) { + cell.addClass("is-paused"); + } else if (isComplete(habit, key)) { + cell.addClass("is-complete"); + } else if (habit.goalDirection === "max") { + cell.addClass("is-over"); + } else if (value > 0) { + cell.addClass("is-partial"); + } + // Obsidian renders aria-label as the hover tooltip, so the start + // note has to live in the same attribute (a separate setTooltip + // call would just be overwritten). + cell.setAttr( + "aria-label", + key === startKey + ? `${key}: ${value} · ${t("started tracking on {date}", { + date: formatShort(date), + })}` + : `${key}: ${value}`, + ); + } + + const unit = habit.unit || (habit.type === "timed" ? "min" : ""); + const totalText = isFlexible(habit) + ? habit.frequency === "flexibleWeekly" + ? t("{completed}/{days} weeks", { + completed: stats.completed, + days: stats.days, + }) + : t("{completed}/{days} months", { + completed: stats.completed, + days: stats.days, + }) + : habit.type === "binary" + ? t("{completed}/{days} days", { + completed: stats.completed, + days: stats.days, + }) + : t("{total} total", { + total: `${formatValue(stats.total)}${unit ? ` ${unit}` : ""}`, + }); + const meta = row.createDiv({ cls: "habits-stats-meta" }); + meta.createSpan({ + text: `${Math.round(stats.rate * 100)}% · ${totalText} · ${t("best")} `, + }); + const bestFlame = meta.createSpan({ cls: "habits-stats-flame" }); + setIcon(bestFlame, "flame"); + meta.createSpan({ text: `${stats.best}` }); + + const goal = goalOf(habit); + if (goal > 0) { + const progress = progressOf(i); + const pct = Math.min(100, Math.round((progress / goal) * 100)); + const bar = row.createDiv({ cls: "habits-goal-bar" }); + if (progress >= goal) { + bar.addClass("is-complete"); + } + bar + .createDiv({ cls: "habits-goal-fill" }) + .setCssProps({ "--habits-progress": `${pct}%` }); + const goalName = isPerfect(habit) + ? period === "weekly" + ? t("perfect week") + : t("perfect month") + : period === "weekly" + ? t("weekly goal") + : t("monthly goal"); + row.createDiv({ + cls: "habits-stats-goal-label", + text: t("{progress}/{goal} days · {label} · {pct}%", { + progress, + goal, + label: goalName, + pct, + }), + }); + } + }); + + if (paged && track) { + renderStatsCarouselControls(container, track, pages.length); + } +} + +/** + * Prev/next arrows plus dots (or a counter beyond seven pages) for the + * stats carousel, mirroring the dashboard carousel controls. Page flips + * only translate the track — nothing is re-rendered. + */ +function renderStatsCarouselControls( + container: HTMLElement, + track: HTMLElement, + pageCount: number, +): void { + let index = 0; + const controls = container.createDiv({ + cls: "habits-carousel-controls habits-stats-carousel-controls", + }); + + const prev = controls.createEl("button", { + cls: "habits-icon-button habits-carousel-prev", + attr: { type: "button", "aria-label": t("Previous") }, + }); + setIcon(prev, "chevron-left"); + + const dots: HTMLElement[] = []; + let counter: HTMLElement | null = null; + if (pageCount <= 7) { + const dotsEl = controls.createDiv({ cls: "habits-dots" }); + for (let i = 0; i < pageCount; i++) { + const dot = dotsEl.createEl("button", { + cls: "habits-dot", + attr: { + type: "button", + "aria-label": t("Go to position {n}", { n: i + 1 }), + }, + }); + dot.addEventListener("click", () => { + index = i; + apply(); + }); + dots.push(dot); + } + } else { + counter = controls.createSpan({ cls: "habits-carousel-count" }); + } + + const next = controls.createEl("button", { + cls: "habits-icon-button habits-carousel-next", + attr: { type: "button", "aria-label": t("Next") }, + }); + setIcon(next, "chevron-right"); + + const apply = (): void => { + track.setCssProps({ + "--habits-stats-translate": `-${index * 100}%`, + }); + prev.toggleClass("is-disabled", index <= 0); + next.toggleClass("is-disabled", index >= pageCount - 1); + dots.forEach((dot, i) => dot.toggleClass("is-active", i === index)); + counter?.setText(`${index + 1} / ${pageCount}`); + }; + + prev.addEventListener("click", () => { + if (index > 0) { + index--; + apply(); + } + }); + next.addEventListener("click", () => { + if (index < pageCount - 1) { + index++; + apply(); + } + }); + apply(); +} + +/** + * The AI summary card: a header with a generate/regenerate button and a body + * holding the summary text. Summaries are only ever requested when the button + * is pressed; a summary already generated for this exact data (see the cache + * in ai-summary.ts) is shown immediately instead. + */ +function renderAiSummary( + container: HTMLElement, + habits: HabitDefinition[], + period: StatsPeriod, + mode: StatsRangeMode, + today: Date, + customRange: DateRange | undefined, + settings: AiSummarySettings, +): void { + const section = container.createDiv({ cls: "habits-ai-summary" }); + const header = section.createDiv({ cls: "habits-ai-summary-header" }); + const title = header.createSpan({ cls: "habits-ai-summary-title" }); + const spark = title.createSpan({ cls: "habits-ai-summary-icon" }); + setIcon(spark, "sparkles"); + title.createSpan({ text: t("AI summary") }); + + const button = header.createEl("button", { + cls: "habits-ai-summary-button", + attr: { type: "button" }, + }); + const body = section.createDiv({ cls: "habits-ai-summary-body" }); + + const showText = (text: string): void => { + body.empty(); + body.removeClass("is-muted"); + for (const paragraph of text.split(/\n{2,}/)) { + body.createEl("p", { text: paragraph.trim() }); + } + }; + const showHint = (text: string): void => { + body.empty(); + body.addClass("is-muted"); + body.createEl("p", { text }); + }; + + const digest = buildStatsDigest(habits, period, mode, today, customRange); + const cached = getCachedSummary(settings, period, mode, digest); + if (cached) { + showText(cached); + button.setText(t("Regenerate")); + } else { + showHint( + t( + "Get feedback and advice on your habits for this period. Your stats are sent to the AI service you configured only when you press the button.", + ), + ); + button.setText(t("Generate summary")); + } + + button.addEventListener("click", () => { + void (async () => { + button.disabled = true; + section.addClass("is-loading"); + showHint(t("Thinking…")); + try { + // Force: the button only shows "Regenerate" when a cached + // summary is already on screen, so a click always means the + // user wants a fresh one. + const text = await generateSummary( + settings, + period, + mode, + digest, + true, + ); + showText(text); + button.setText(t("Regenerate")); + } catch (error) { + const message = + error instanceof Error ? error.message : String(error); + showHint( + t("Could not generate a summary: {message}", { message }), + ); + new Notice( + t("Could not generate a summary: {message}", { message }), + ); + } finally { + button.disabled = false; + section.removeClass("is-loading"); + } + })(); + }); +} diff --git a/src/integrations/habits/ui/vault-suggest.ts b/src/integrations/habits/ui/vault-suggest.ts new file mode 100644 index 000000000..9fc18cc39 --- /dev/null +++ b/src/integrations/habits/ui/vault-suggest.ts @@ -0,0 +1,61 @@ +import { AbstractInputSuggest, App, TFile, TFolder } from "obsidian"; + +/** Suggests matching vault folders while typing in a folder field. */ +export class FolderSuggest extends AbstractInputSuggest { + constructor( + app: App, + private textInputEl: HTMLInputElement, + ) { + super(app, textInputEl); + } + + getSuggestions(query: string): TFolder[] { + const needle = query.toLowerCase(); + return this.app.vault + .getAllLoadedFiles() + .filter( + (file): file is TFolder => + file instanceof TFolder && file.path !== "/", + ) + .filter((folder) => folder.path.toLowerCase().includes(needle)) + .slice(0, 20); + } + + renderSuggestion(folder: TFolder, el: HTMLElement): void { + el.setText(folder.path); + } + + selectSuggestion(folder: TFolder): void { + this.textInputEl.value = folder.path; + this.textInputEl.trigger("input"); + this.close(); + } +} + +/** Suggests matching markdown notes while typing in a template field. */ +export class MarkdownFileSuggest extends AbstractInputSuggest { + constructor( + app: App, + private textInputEl: HTMLInputElement, + ) { + super(app, textInputEl); + } + + getSuggestions(query: string): TFile[] { + const needle = query.toLowerCase(); + return this.app.vault + .getMarkdownFiles() + .filter((file) => file.path.toLowerCase().includes(needle)) + .slice(0, 20); + } + + renderSuggestion(file: TFile, el: HTMLElement): void { + el.setText(file.path); + } + + selectSuggestion(file: TFile): void { + this.textInputEl.value = file.path; + this.textInputEl.trigger("input"); + this.close(); + } +} diff --git a/src/integrations/habits/upstream.css b/src/integrations/habits/upstream.css new file mode 100644 index 000000000..4a9febea1 --- /dev/null +++ b/src/integrations/habits/upstream.css @@ -0,0 +1,3225 @@ +/* Habits plugin — dashboard styles. + Colours use Obsidian theme variables so the plugin adapts to light/dark and + custom themes. Each card exposes an optional --habits-accent override. */ + +.habits-dashboard { + --habits-accent: var(--interactive-accent); + position: relative; + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-m); + padding: 0.75rem; + background: var(--background-secondary); +} + +.habits-header { + display: grid; + grid-template-columns: 1fr auto 1fr; + align-items: center; + gap: 0.5rem; + margin-bottom: 0.75rem; +} + +.habits-date-nav { + grid-column: 2; + justify-self: center; +} + +.habits-header-left { + grid-column: 1; + justify-self: start; +} + +.habits-header-right { + grid-column: 3; + justify-self: end; +} + +.habits-stats-tabs { + grid-column: 2; + justify-self: center; + display: flex; + gap: 0.25rem; +} + +.habits-date-nav { + display: flex; + align-items: center; + gap: 0.5rem; +} + +.habits-date-display { + position: relative; + display: inline-flex; +} + +.habits-dashboard .habits-date-label { + display: inline-flex; + align-items: center; + justify-content: center; + padding: 0.25rem 0.6rem; + font-weight: var(--font-semibold); + color: var(--text-normal); + background: transparent; + border: none; + border-radius: var(--radius-s); + cursor: pointer; + box-shadow: none; +} + +.habits-dashboard .habits-date-label:hover { + background: var(--background-modifier-hover); +} + +.habits-dashboard .habits-date-input { + position: absolute; + left: 0; + bottom: 0; + width: 1px; + height: 1px; + margin: 0; + padding: 0; + border: 0; + opacity: 0; + pointer-events: none; +} + +.habits-icon-button { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 0.25rem; + padding: 0.35rem; + border-radius: var(--radius-s); + background: transparent; + color: var(--text-normal); + cursor: pointer; + box-shadow: none; +} + +.habits-icon-button:hover { + background: var(--background-modifier-hover); +} + +.habits-empty { + text-align: center; + padding: 1.5rem 0.5rem; + color: var(--text-muted); +} + +/* Vertical slack (padding + negative margin) so hovered cards can lift + and cast a shadow without being clipped by the carousel. */ +.habits-carousel-viewport { + overflow: hidden; + padding: 8px 0; + margin: -8px 0; +} + +.habits-carousel-track { + display: flex; + transform: translateX(var(--habits-translate, 0)); + transition: transform 0.25s ease; +} + +/* Grid and vertical-scroll layouts: rows of cards instead of a paged + track, gathered into one or more sections (one per group when + grouping is on). The slack padding + negative margin mirror the + carousel viewport so hovered cards can lift without being clipped. */ +.habits-grid-wrap { + display: flex; + flex-direction: column; + gap: 0.75rem; + padding: 8px 4px; + margin: -8px -4px; +} + +.habits-grid { + display: grid; + grid-template-columns: repeat(var(--habits-per-row, 4), minmax(0, 1fr)); + gap: 0.6rem; +} + +/* The vertical variant caps its height (set from JS at about a row and + a half, so a partial row peeks out below as the "there is more" cue) + and scrolls the cards inside the widget. Wheel and touch-drag both + work natively; `overscroll-behavior` keeps the note from scrolling + along once the cards run out, and proximity snapping settles rows + cleanly after a flick without fighting free scrolling. */ +.habits-grid-wrap.is-vertical { + /* The fallback cap keeps vertical mode scrollable even before the + exact height (1.55 card heights) has been measured. */ + max-height: var(--habits-vertical-max, min(60vh, 480px)); + overflow-y: auto; + overflow-x: hidden; + overscroll-behavior: contain; + scroll-snap-type: y proximity; + -webkit-overflow-scrolling: touch; +} + +.habits-grid-wrap.is-vertical .habits-card { + scroll-snap-align: start; + scroll-margin-top: 8px; +} + +/* Section headers shown when grouping is on: a small muted label, with + a colour swatch in colour mode. */ +.habits-group-header { + display: flex; + align-items: center; + gap: 0.4rem; + margin-bottom: -0.35rem; + font-size: var(--font-ui-small); + font-weight: 600; + color: var(--text-muted); +} + +.habits-group-swatch { + width: 10px; + height: 10px; + border-radius: 3px; + flex-shrink: 0; + background: var(--habits-accent); +} + +.habits-group-swatch.is-none { + background: var(--background-modifier-border); +} + +.habits-group-icon { + display: flex; + align-items: center; + color: var(--habits-accent, var(--text-muted)); + flex-shrink: 0; +} + +.habits-group-icon svg { + width: 14px; + height: 14px; +} + +/* Lip along the top edge of a card naming its group, tinted with the + group colour when one is set. Sits flush against the card edges by + cancelling the card's padding. */ +.habits-card-group-lip { + align-self: stretch; + display: flex; + align-items: center; + justify-content: center; + gap: 0.3rem; + margin: -1.1rem -0.65rem 0; + padding: 0.3rem 0.6rem; + border-radius: var(--radius-m) var(--radius-m) 0 0; + background: color-mix( + in srgb, + var(--habits-group-color, var(--habits-accent, var(--text-muted))) + 14%, + transparent + ); + color: var(--text-muted); + font-size: var(--font-ui-smaller); + font-weight: 600; + min-width: 0; +} + +.habits-card-group-lip .habits-card-group-icon { + display: flex; + align-items: center; + color: var(--habits-group-color, var(--habits-accent, var(--text-muted))); + flex-shrink: 0; +} + +.habits-card-group-lip .habits-card-group-icon svg { + width: 13px; + height: 13px; +} + +.habits-card-group-name { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +/* Group lip on stats rows: the card lip re-margined to sit flush with + the stats row's own padding. */ +.habits-stats-group-lip { + margin: -0.7rem -0.8rem 0; +} + +/* Vertical layout: the stats list caps its height and scrolls in + place — shorter than the dashboard's cap, so the stats block stays + compact inside a note. */ +.habits-stats-list.is-scrollable { + max-height: min(45vh, 340px); + overflow-y: auto; + overflow-x: hidden; + overscroll-behavior: contain; + padding-right: 4px; +} + +/* Groups manager modal: one dashed container per group, habits as + draggable chips. The container under the pointer highlights while a + chip is being dragged. */ +.habits-groups-hint { + color: var(--text-muted); + font-size: var(--font-ui-small); + margin: 0 0 0.5rem; +} + +.habits-groups-board { + display: flex; + flex-direction: column; + gap: 0.6rem; + margin-top: 0.75rem; +} + +.habits-groups-section { + border: 1px dashed var(--background-modifier-border); + border-radius: var(--radius-m); + padding: 0.6rem; +} + +.habits-groups-section.is-drop-target { + border-color: var(--interactive-accent); + background: color-mix( + in srgb, + var(--interactive-accent) 8%, + transparent + ); +} + +.habits-groups-actions { + margin-left: auto; + display: flex; + gap: 2px; +} + +.habits-groups-actions .habits-icon-button.is-active { + color: var(--interactive-accent); +} + +/* Inline group style editor (colour + icon) inside a section. */ +.habits-groups-style { + margin-top: 0.4rem; + border-top: 1px solid var(--background-modifier-border); +} + +.habits-groups-style .setting-item { + border: none; + padding: 0.45rem 0; +} + +.habits-groups-chips { + display: flex; + flex-wrap: wrap; + gap: 0.4rem; + margin-top: 0.45rem; +} + +.habits-groups-chip { + display: inline-flex; + align-items: center; + gap: 0.35rem; + padding: 0.25rem 0.6rem; + background: var(--background-primary); + border: 1px solid var(--background-modifier-border); + border-left: 3px solid + var(--habits-accent, var(--background-modifier-border)); + border-radius: var(--radius-s); + cursor: grab; + touch-action: none; + -webkit-user-select: none; + user-select: none; +} + +.habits-groups-chip.is-dragging { + opacity: 0.6; + cursor: grabbing; +} + +.habits-groups-chip-icon { + display: flex; + align-items: center; +} + +.habits-groups-empty { + color: var(--text-faint); + font-size: var(--font-ui-smaller); +} + +.habits-panel-group { + display: flex; + align-items: center; + gap: 0.4rem; + margin: 0.6rem 0 0.15rem; + font-size: var(--font-ui-smaller); + font-weight: 600; + color: var(--text-muted); +} + +.habits-panel-group:first-child { + margin-top: 0; +} + +/* Manual sort order editor in settings: one slim draggable row per + habit, mirroring the card's accent stripe and icon. `touch-action: + none` lets pointer events drive the drag on touchscreens too. */ +.habits-order-setting { + display: block; +} + +.habits-order-list { + display: flex; + flex-direction: column; + gap: 4px; + margin-top: 0.75rem; +} + +.habits-order-row { + display: flex; + align-items: center; + gap: 0.5rem; + padding: 6px 10px; + background: var(--background-primary); + border: 1px solid var(--background-modifier-border); + border-left: 3px solid + var(--habits-accent, var(--background-modifier-border)); + border-radius: var(--radius-s); + cursor: grab; + touch-action: none; + -webkit-user-select: none; + user-select: none; +} + +.habits-order-row.is-dragging { + opacity: 0.85; + cursor: grabbing; + box-shadow: var(--shadow-s); + z-index: 2; + position: relative; +} + +.habits-order-grip, +.habits-order-icon { + display: flex; + align-items: center; + color: var(--text-muted); +} + +.habits-order-name { + flex: 1; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.habits-card { + position: relative; + overflow: hidden; + min-width: 0; + perspective: 1000px; + -webkit-user-select: none; + user-select: none; + -webkit-touch-callout: none; + flex: 0 0 calc(100% / var(--habits-per-view, 1)); + box-sizing: border-box; + display: flex; + flex-direction: column; + align-items: center; + gap: 0.85rem; + padding: 1.1rem 0.65rem; + background: var(--background-primary); + border: 1px solid var(--background-modifier-border); + border-left: 3px solid var(--habits-accent); + border-radius: var(--radius-m); + box-shadow: var(--shadow-s); +} + +/* Comment flip: the card body lives in a 3D inner wrapper with a front + and back face; the lip along the bottom edge flips between them. */ + +.habits-card-inner { + position: relative; + width: 100%; + flex: 1 1 auto; + transform-style: preserve-3d; + transition: transform 0.45s cubic-bezier(0.4, 0.2, 0.2, 1); +} + +.habits-card.is-flipped .habits-card-inner { + transform: rotateY(180deg); +} + +.habits-card-front, +.habits-card-back { + -webkit-backface-visibility: hidden; + backface-visibility: hidden; +} + +.habits-card-front { + display: flex; + flex-direction: column; + align-items: center; + gap: 0.85rem; +} + +.habits-card-back { + position: absolute; + inset: 0; + display: flex; + flex-direction: column; + gap: 0.4rem; + transform: rotateY(180deg); +} + +.habits-card-back-title { + text-align: center; + font-size: var(--font-ui-smaller); + font-weight: var(--font-semibold); + color: var(--text-muted); +} + +/* Holds the two faces of the comment area: the rendered read view and + the textarea that replaces it while editing. */ +.habits-comment-stage { + position: relative; + flex: 1; + min-height: 0; + display: flex; +} + +.habits-card .habits-comment-input { + flex: 1; + width: 100%; + min-height: 0; + resize: none; + padding: 0.4rem 0.5rem; + font-size: var(--font-ui-small); + font-family: inherit; + color: var(--text-normal); + background: var(--background-modifier-form-field); + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-s); + -webkit-user-select: text; + user-select: text; +} + +/* Only one face is shown at a time. */ +.habits-comment-stage:not(.is-editing) .habits-comment-input, +.habits-comment-stage.is-editing .habits-comment-read { + display: none; +} + +.habits-comment-read { + flex: 1; + min-height: 0; + overflow-y: auto; + padding: 0.4rem 0.5rem; + font-size: var(--font-ui-small); + line-height: 1.45; + white-space: pre-wrap; + overflow-wrap: anywhere; + color: var(--text-normal); + background: var(--background-modifier-form-field); + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-s); + cursor: text; + -webkit-user-select: text; + user-select: text; +} + +.habits-comment-read:focus-visible { + outline: 2px solid var(--background-modifier-border-focus); + outline-offset: -2px; +} + +/* Placeholder styling when the day has no comment yet. */ +.habits-comment-read.is-empty { + color: var(--text-faint); + font-style: italic; +} + +/* Tags render as compact accent-tinted chips. */ +.habits-comment-read a.habits-comment-tag { + display: inline; + padding: 0.05em 0.35em; + margin: 0 0.05em; + font-size: 0.85em; + font-weight: var(--font-medium); + line-height: 1.4; + text-decoration: none; + color: var(--habits-accent); + background: color-mix(in srgb, var(--habits-accent) 14%, transparent); + border-radius: var(--radius-s); + cursor: pointer; +} + +.habits-comment-read a.habits-comment-tag:hover { + background: color-mix(in srgb, var(--habits-accent) 26%, transparent); +} + +.habits-comment-read a.habits-comment-link { + color: var(--link-color); + text-decoration: none; + cursor: pointer; +} + +.habits-comment-read a.habits-comment-link:hover { + text-decoration: underline; +} + +/* Links whose target note does not exist yet, matching Obsidian. */ +.habits-comment-read a.habits-comment-link.is-unresolved { + color: var(--link-unresolved-color, var(--text-accent)); + opacity: var(--link-unresolved-opacity, 0.7); +} + +/* Autocomplete popup for # and [[ inside the comment textarea. It is + appended to the body so the card's 3D transform cannot clip it. */ +.habits-comment-suggest { + position: fixed; + z-index: var(--layer-menu); + top: var(--habits-suggest-top); + left: var(--habits-suggest-left); + width: var(--habits-suggest-width); + max-height: 15rem; + overflow-y: auto; + padding: 0.25rem; + background: var(--background-secondary); + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-m); + box-shadow: var(--shadow-s); +} + +.habits-comment-suggest-item { + display: flex; + align-items: center; + gap: 0.5rem; + padding: 0.3rem 0.45rem; + border-radius: var(--radius-s); + cursor: pointer; +} + +.habits-comment-suggest-item.is-selected { + background: var(--background-modifier-hover); +} + +.habits-comment-suggest-icon { + display: inline-flex; + flex: 0 0 auto; + color: var(--text-muted); +} + +.habits-comment-suggest-icon .svg-icon { + width: 0.9rem; + height: 0.9rem; +} + +.habits-comment-suggest-body { + min-width: 0; +} + +.habits-comment-suggest-title { + font-size: var(--font-ui-small); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.habits-comment-suggest-detail { + font-size: var(--font-ui-smaller); + color: var(--text-faint); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +/* The comment lip along the bottom edge of the card. */ +.habits-dashboard button.habits-card-lip { + width: 100%; + margin-top: auto; + display: flex; + align-items: center; + justify-content: center; + padding: 0.2rem 0; + background: transparent; + border: none; + border-top: 1px solid var(--background-modifier-border); + border-radius: 0; + box-shadow: none; + color: var(--text-faint); + cursor: pointer; +} + +.habits-dashboard button.habits-card-lip:hover { + color: var(--habits-accent); + background: var(--background-modifier-hover); +} + +/* Days with a comment: accent-tinted, lightly filled speech bubble. */ +.habits-dashboard button.habits-card-lip.has-comment { + color: var(--habits-accent); +} + +.habits-dashboard button.habits-card-lip.has-comment .svg-icon { + fill: color-mix(in srgb, var(--habits-accent) 30%, transparent); +} + +.habits-card-lip-icon { + display: inline-flex; +} + +.habits-card-lip-icon .svg-icon { + width: 0.95rem; + height: 0.95rem; +} + +/* Hover: a gentle lift with a deeper shadow and an accent-tinted border. + Departing cards are excluded so the exit animation owns the transform. */ +.habits-card:not(.is-departing) { + transition: + transform 0.18s ease, + box-shadow 0.18s ease, + border-color 0.18s ease; +} + +/* Only lift on devices with a real pointer, so the effect can't get + "stuck" after a tap on touchscreens. */ +@media (hover: hover) { + .habits-card:not(.is-departing):hover { + transform: translateY(-3px) scale(1.015); + box-shadow: 0 6px 16px rgba(0, 0, 0, 0.22); + border-color: var(--habits-accent); + z-index: 2; + } +} + +.habits-card-title { + display: flex; + align-items: center; + justify-content: center; + gap: 0.3rem; + width: 100%; + min-width: 0; + font-size: calc(var(--font-ui-medium) + 2px); + font-weight: var(--font-semibold); + text-align: center; +} + +.habits-card-icon { + display: inline-flex; + color: var(--habits-accent); +} + +/* The card name is a button that opens the habit's note. Names stay on + a single line and ellipsize when the card runs out of room; the + tooltip always shows the full name. */ +.habits-dashboard button.habits-card-name { + max-width: 100%; + min-width: 0; + padding: 0; + font-size: inherit; + font-weight: inherit; + line-height: 1.3; + color: var(--text-normal); + background: transparent; + border: none; + border-radius: var(--radius-s); + cursor: pointer; + box-shadow: none; + white-space: normal; + text-align: center; +} + +.habits-card-name-text { + display: block; + max-width: 100%; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.habits-dashboard button.habits-card-name:hover { + color: var(--habits-accent); + text-decoration: underline; +} + +/* "Every Monday" / "Monthly · day 15" caption on weekly and monthly cards. */ +.habits-card-frequency { + width: 100%; + margin-top: 0.15rem; + color: var(--text-muted); + font-size: var(--font-ui-small); + font-weight: var(--font-normal); + text-align: center; +} + +.habits-card-body { + display: flex; + flex-direction: column; + align-items: center; + gap: 0.75rem; +} + +.habits-binary-toggle { + display: flex; + flex-direction: column; + align-items: center; + gap: 0.35rem; + padding: 1rem 1.5rem; + border-radius: var(--radius-m); + background: var(--background-primary); + color: var(--text-muted); + cursor: pointer; +} + +.habits-binary-toggle.is-done { + background: var(--habits-accent); + color: var(--text-on-accent); +} + +.habits-binary-label { + font-weight: var(--font-semibold); +} + +.habits-readout { + display: flex; + align-items: baseline; + gap: 0.35rem; +} + +.habits-dashboard button.habits-value { + padding: 0 0.15rem; + font-size: 1.8rem; + font-weight: var(--font-bold); + line-height: 1; + color: var(--habits-accent); + background: transparent; + border: none; + border-radius: var(--radius-s); + cursor: pointer; + box-shadow: none; +} + +.habits-dashboard button.habits-value:hover { + background: var(--background-modifier-hover); +} + +.habits-dashboard .habits-value-input { + width: 4rem; + padding: 0 0.25rem; + font-size: 1.8rem; + font-weight: var(--font-bold); + line-height: 1; + text-align: center; + color: var(--habits-accent); + background: var(--background-modifier-form-field); + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-s); +} + +.habits-target { + color: var(--text-muted); +} + +.habits-progress { + width: 100%; + height: 0.4rem; + border-radius: var(--radius-s); + background: var(--background-modifier-border); + overflow: hidden; +} + +.habits-progress-fill { + width: var(--habits-progress, 0%); + height: 100%; + background: var(--habits-accent); + transition: width 0.2s ease; +} + +.habits-progress.is-complete .habits-progress-fill { + background: var(--color-green, var(--habits-accent)); +} + +/* A big, read-only derived number — a note habit's char/checklist count, + or a flexible habit's running total for the period. */ +.habits-readout-value { + padding: 0 0.15rem; + font-size: 1.8rem; + font-weight: var(--font-bold); + line-height: 1; + color: var(--habits-accent); + font-variant-numeric: tabular-nums; +} + +.habits-note-action { + display: flex; + align-items: center; + gap: 0.4rem; + padding: 0.5rem 1.25rem; + border-radius: var(--radius-m); + background: var(--interactive-accent); + color: var(--text-on-accent); + font-weight: var(--font-semibold); + border: none; + cursor: pointer; +} + +.habits-note-action:hover { + background: var(--interactive-accent-hover); +} + +.habits-counter-buttons { + display: flex; + align-items: center; + gap: 1.5rem; +} + +.habits-counter-buttons .habits-icon-button { + padding: 0.5rem; + border: 1px solid var(--background-modifier-border); +} + +/* Timed habits show +1/+5/+10 chips: spread them across the card. */ +.habits-counter-buttons.is-compact { + width: 100%; + gap: 0.4rem; + justify-content: center; +} + +.habits-counter-buttons.is-compact .habits-icon-button { + flex: 1 1 0; + min-width: 0; + max-width: 4.5rem; + padding: 0.45rem 0.3rem; +} + +.habits-dashboard .habits-step-button { + padding: 0.45rem 0.55rem; + font-size: var(--font-ui-small); + font-weight: var(--font-semibold); + font-variant-numeric: tabular-nums; + line-height: 1; +} + +.habits-carousel-controls { + display: flex; + align-items: center; + justify-content: center; + gap: 0.75rem; + margin-top: 0.75rem; +} + +.habits-dots { + display: flex; + align-items: center; + gap: 0.35rem; +} + +.habits-dot { + width: 0.5rem; + height: 0.5rem; + padding: 0; + border-radius: 50%; + background: var(--background-modifier-border); + cursor: pointer; + box-shadow: none; +} + +.habits-dot.is-active { + background: var(--habits-accent); +} + +/* Completion animation: a green circle-check swooshes in with a springy + spin while a ring pulses outward behind it, then the card is re-queued to + the end of the carousel. Colour comes from the theme palette. */ + +.habits-complete-overlay { + position: absolute; + inset: 0; + z-index: 1; + display: flex; + align-items: center; + justify-content: center; + background: var(--background-primary); + border-radius: inherit; + opacity: 1; + transition: opacity 0.2s ease; + animation: habits-complete-fade-in 0.15s ease-out; +} + +.habits-complete-overlay.is-leaving { + opacity: 0; +} + +.habits-complete-icon { + display: inline-flex; + color: var(--color-green, var(--text-success)); + animation: habits-complete-swoosh 0.55s cubic-bezier(0.34, 1.56, 0.64, 1) forwards; +} + +.habits-complete-icon .svg-icon { + width: 3rem; + height: 3rem; +} + +/* Soft ring that pulses outward just as the check lands. */ +.habits-complete-ring { + position: absolute; + inset: 0; + margin: auto; + width: 3.4rem; + height: 3.4rem; + border-radius: 50%; + border: 2px solid var(--color-green, var(--text-success)); + opacity: 0; + animation: habits-complete-ring 0.6s ease-out 0.3s forwards; +} + +@keyframes habits-complete-fade-in { + from { + opacity: 0; + } + to { + opacity: 1; + } +} + +@keyframes habits-complete-swoosh { + 0% { + transform: rotate(-180deg) scale(0.2); + opacity: 0; + } + 50% { + opacity: 1; + } + 100% { + transform: rotate(0deg) scale(1); + opacity: 1; + } +} + +@keyframes habits-complete-ring { + 0% { + transform: scale(0.8); + opacity: 0.65; + } + 100% { + transform: scale(2); + opacity: 0; + } +} + +/* Departure: the completed card swooshes off to the right and its slot + collapses, so the rest of the queue slides in to close the gap. + + The slot collapsing to zero width reflows the card's own contents into + a very tall, very narrow column. Both the carousel track and the grid + stretch their items to the tallest one, so without the height clamp + below that momentary column drags every sibling card taller for the + length of the animation. The card is already fully transparent by the + time the collapse starts (opacity finishes at 0.25s, which is exactly + when flex-basis begins), so its height is pinned to zero at that same + moment — invisible, and no longer able to set the row's height. */ +.habits-card.is-departing { + opacity: 0; + transform: translateX(45%) scale(0.9); + flex-basis: 0; + max-height: 0; + padding-left: 0; + padding-right: 0; + border-left-width: 0; + border-right-width: 0; + transition: + opacity 0.25s ease-in, + transform 0.3s ease-in, + flex-basis 0.3s ease-in-out 0.25s, + padding 0.3s ease-in-out 0.25s, + border-width 0.3s ease-in-out 0.25s, + max-height 0s linear 0.25s; +} + +/* Perfect day: glow, confetti and "Perfect!" spanning the dashboard when + every habit for the selected day is complete. Pointer-transparent. */ + +.habits-perfect-overlay { + position: absolute; + inset: 0; + z-index: 10; + display: flex; + align-items: center; + justify-content: center; + overflow: hidden; + pointer-events: none; + border-radius: var(--radius-m); + opacity: 1; + transition: opacity 0.25s ease; +} + +.habits-perfect-overlay.is-leaving { + opacity: 0; +} + +.habits-perfect-glow { + position: absolute; + inset: 0; + background: radial-gradient( + ellipse at center, + color-mix( + in srgb, + var(--color-green, var(--interactive-accent)) 22%, + transparent + ), + transparent 70% + ); + animation: habits-perfect-glow 1.85s ease-out forwards; +} + +@keyframes habits-perfect-glow { + 0% { + opacity: 0; + } + 25% { + opacity: 1; + } + 100% { + opacity: 0.5; + } +} + +.habits-perfect-text { + position: relative; + font-size: clamp(2rem, 8vw, 3.2rem); + font-weight: 800; + letter-spacing: 0.02em; + line-height: 1; + background: linear-gradient( + 120deg, + var(--color-green, var(--text-success)), + var(--interactive-accent) + ); + -webkit-background-clip: text; + background-clip: text; + -webkit-text-fill-color: transparent; + animation: habits-perfect-pop 0.6s cubic-bezier(0.34, 1.56, 0.64, 1) forwards; +} + +@keyframes habits-perfect-pop { + 0% { + transform: scale(0.3) rotate(-6deg); + opacity: 0; + } + 60% { + opacity: 1; + } + 100% { + transform: scale(1) rotate(0deg); + opacity: 1; + } +} + +.habits-perfect-confetti { + position: absolute; + inset: 0; + display: flex; + align-items: center; + justify-content: center; +} + +.habits-perfect-piece { + position: absolute; + width: 7px; + height: 11px; + border-radius: 1px; + background: var(--hc-color, var(--interactive-accent)); + opacity: 0; + animation: habits-perfect-confetti 1.4s ease-out var(--hc-delay, 0ms) + forwards; +} + +@keyframes habits-perfect-confetti { + 0% { + transform: translate(0, 0) rotate(0deg); + opacity: 1; + } + 30% { + transform: translate(calc(var(--hc-x) * 0.5), var(--hc-my)) + rotate(calc(var(--hc-r) * 0.5)); + opacity: 1; + } + 100% { + transform: translate(var(--hc-x), var(--hc-y)) + rotate(var(--hc-r)); + opacity: 0; + } +} + +/* New-habit modal: live preview and icon picker */ + +.habits-modal-preview { + display: flex; + align-items: center; + gap: 0.75rem; + padding: 0.75rem 0; + margin-bottom: 0.25rem; + border-bottom: 1px solid var(--background-modifier-border); +} + +.habits-modal-preview-icon { + --habits-accent: var(--interactive-accent); + display: flex; + align-items: center; + justify-content: center; + width: 3rem; + height: 3rem; + border-radius: 50%; + color: var(--text-on-accent); + background: var(--habits-accent); + flex: 0 0 auto; +} + +.habits-modal-preview-icon .svg-icon { + width: 1.6rem; + height: 1.6rem; +} + +.habits-modal-preview-name { + font-size: var(--font-ui-large); + font-weight: var(--font-semibold); + color: var(--text-normal); +} + +.habits-button-icon { + display: inline-flex; + align-items: center; + margin-right: 0.4rem; + vertical-align: middle; +} + +.habits-button-icon .svg-icon { + width: 1em; + height: 1em; +} + +.habits-icon-suggestion { + display: flex; + align-items: center; + gap: 0.6rem; +} + +.habits-icon-suggestion-glyph { + display: inline-flex; + color: var(--text-muted); +} + +.habits-icon-suggestion-glyph .svg-icon { + width: 1.1rem; + height: 1.1rem; +} + +/* Theme colour swatches */ + +.habits-swatches { + display: flex; + flex-wrap: wrap; + gap: 0.35rem; + margin-right: 0.5rem; +} + +.habits-swatches button.habits-swatch { + width: 1.5rem; + height: 1.5rem; + min-width: 0; + padding: 0; + border-radius: 50%; + background-color: var(--habits-swatch); + background-image: none; + border: 2px solid transparent; + cursor: pointer; + box-shadow: none; +} + +.habits-swatches button.habits-swatch:hover { + border-color: var(--background-modifier-border-hover); +} + +.habits-swatches button.habits-swatch.is-selected { + border-color: var(--text-normal); +} + +/* Emoji icons */ + +.habits-modal-preview-icon { + font-size: 1.5rem; + line-height: 1; +} + +.habits-card-icon { + font-size: 1.1rem; + line-height: 1; +} + +.habits-emoji-suggestion { + display: flex; + align-items: center; + gap: 0.6rem; +} + +.habits-emoji-suggestion-glyph { + font-size: 1.2rem; + line-height: 1; +} + +/* Carousel arrow disabled state and position counter */ + +.habits-carousel-prev.is-disabled, +.habits-carousel-next.is-disabled { + opacity: 0.3; + pointer-events: none; +} + +.habits-carousel-count { + min-width: 3rem; + text-align: center; + color: var(--text-muted); + font-size: var(--font-ui-small); +} + +/* Stats view */ + +.habits-dashboard .habits-stats-tab { + padding: 0.25rem 0.7rem; + font-weight: var(--font-semibold); + color: var(--text-muted); + background: transparent; + border: none; + border-radius: var(--radius-s); + cursor: pointer; + box-shadow: none; +} + +.habits-dashboard .habits-stats-tab.is-active { + color: var(--text-on-accent); + background: var(--interactive-accent); +} + +.habits-stats-range { + margin-bottom: 0.75rem; + text-align: center; + color: var(--text-muted); + font-size: var(--font-ui-small); +} + +/* From/to pickers on the custom stats tab. */ +.habits-custom-range { + display: flex; + align-items: center; + justify-content: center; + gap: 0.4rem; +} + +.habits-dashboard input.habits-custom-date { + font-size: var(--font-ui-small); + padding: 0.15rem 0.45rem; + background: var(--background-primary); + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-s); + color: var(--text-normal); +} + +.habits-custom-range-sep { + color: var(--text-muted); +} + +.habits-stats-summary { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(4.5rem, 1fr)); + gap: 0.5rem; + margin-bottom: 0.85rem; +} + +.habits-stat-tile { + display: flex; + flex-direction: column; + align-items: center; + gap: 0.15rem; + padding: 0.6rem 0.3rem; + background: var(--background-primary); + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-m); +} + +.habits-stat-value { + font-size: 1.4rem; + font-weight: var(--font-bold); + color: var(--interactive-accent); + line-height: 1; +} + +.habits-stat-label { + text-align: center; + color: var(--text-muted); + font-size: var(--font-ui-smaller); +} + +.habits-ai-summary { + margin-bottom: 0.85rem; + padding: 0.7rem 0.8rem; + background: var(--background-primary); + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-m); +} + +.habits-ai-summary-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 0.5rem; + margin-bottom: 0.4rem; +} + +.habits-ai-summary-title { + display: inline-flex; + align-items: center; + gap: 0.35rem; + font-weight: var(--font-semibold); + font-size: var(--font-ui-small); +} + +.habits-ai-summary-icon { + display: inline-flex; + color: var(--interactive-accent); +} + +.habits-ai-summary-icon svg { + width: 1em; + height: 1em; +} + +.habits-ai-summary-button { + font-size: var(--font-ui-smaller); + padding: 0.25rem 0.7rem; + border-radius: var(--radius-s); + cursor: pointer; +} + +.habits-ai-summary-button:disabled { + opacity: 0.6; + cursor: default; +} + +.habits-ai-summary-body p { + margin: 0 0 0.5rem; + font-size: var(--font-ui-small); + line-height: 1.45; +} + +.habits-ai-summary-body p:last-child { + margin-bottom: 0; +} + +.habits-ai-summary-body.is-muted p { + color: var(--text-muted); +} + +.habits-ai-summary.is-loading .habits-ai-summary-body p { + animation: habits-ai-pulse 1.2s ease-in-out infinite; +} + +@keyframes habits-ai-pulse { + 0%, + 100% { + opacity: 1; + } + 50% { + opacity: 0.45; + } +} + +.habits-stats-list { + display: flex; + flex-direction: column; + gap: 0.6rem; +} + +/* Stats carousel: pages of habit rows sliding horizontally. */ +.habits-stats-carousel-viewport { + overflow: hidden; +} + +.habits-stats-carousel-track { + display: flex; + align-items: flex-start; + transform: translateX(var(--habits-stats-translate, 0%)); + transition: transform 0.3s ease; +} + +.habits-stats-page { + flex: 0 0 100%; + min-width: 0; +} + +.habits-stats-carousel-controls { + margin-top: 0.6rem; +} + +.habits-stats-row { + --habits-accent: var(--interactive-accent); + display: flex; + flex-direction: column; + gap: 0.45rem; + padding: 0.7rem 0.8rem; + background: var(--background-primary); + border: 1px solid var(--background-modifier-border); + border-left: 3px solid var(--habits-accent); + border-radius: var(--radius-m); +} + +.habits-stats-row-top { + display: flex; + align-items: center; + justify-content: space-between; + gap: 0.5rem; +} + +.habits-stats-name { + display: flex; + align-items: center; + gap: 0.4rem; + font-weight: var(--font-semibold); +} + +.habits-stats-streak { + display: inline-flex; + align-items: center; + gap: 0.2rem; + font-weight: var(--font-semibold); + white-space: nowrap; +} + +/* Lucide flame used for streaks, tinted with the habit's accent. */ +.habits-stats-flame { + display: inline-flex; + align-items: center; + vertical-align: text-bottom; + color: var(--habits-accent); +} + +.habits-stats-flame .svg-icon { + width: 1em; + height: 1em; +} + +.habits-stats-heatmap { + display: flex; + flex-wrap: wrap; + gap: 3px; +} + +.habits-stats-cell { + width: 0.85rem; + height: 0.85rem; + border-radius: 3px; + background: var(--background-modifier-border); +} + +.habits-stats-cell.is-partial { + background: var(--habits-accent); + opacity: 0.45; +} + +.habits-stats-cell.is-complete { + background: var(--habits-accent); +} + +.habits-stats-meta { + color: var(--text-muted); + font-size: var(--font-ui-small); +} + +/* Stats range toggle (rolling vs calendar) */ + +.habits-range-toggle { + display: flex; + justify-content: center; + gap: 0.25rem; + margin-bottom: 0.75rem; + padding: 0.2rem; + background: var(--background-primary); + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-m); +} + +.habits-dashboard .habits-range-btn { + flex: 1; + max-width: 12rem; + padding: 0.3rem 0.6rem; + font-size: var(--font-ui-small); + font-weight: var(--font-semibold); + color: var(--text-muted); + background: transparent; + border: none; + border-radius: var(--radius-s); + cursor: pointer; + box-shadow: none; +} + +.habits-dashboard .habits-range-btn.is-active { + color: var(--text-normal); + background: var(--background-modifier-hover); +} + +.habits-stats-cell.is-future { + background: transparent; + border: 1px dashed var(--background-modifier-border); +} + +.habits-stats-cell.is-paused { + background: transparent; + border: 1px solid var(--background-modifier-border); + opacity: 0.6; +} + +/* Days a weekly/monthly habit is not due: faint, so due days stand out. */ +.habits-stats-cell.is-notdue { + background: transparent; + opacity: 0.25; +} + +.habits-stats-cell.is-prestart { + background: transparent; + border: 1px dotted var(--background-modifier-border); + opacity: 0.35; +} + +.habits-stats-cell.is-start { + display: flex; + align-items: center; + justify-content: center; +} + +/* Filled play icon marking the first tracked day. Accent-coloured on + neutral cells; flipped to the on-accent text colour when the cell + itself is filled with the accent (start day already complete). */ +.habits-stats-cell.is-start svg { + width: 72%; + height: 72%; + color: var(--habits-accent); + fill: currentcolor; +} + +.habits-stats-cell.is-start.is-complete svg { + color: var(--text-on-accent); +} + +/* A partial start cell would fade the icon along with the whole-cell + opacity; keep the icon solid and fade only the background instead. */ +.habits-stats-cell.is-start.is-partial { + opacity: 1; + background: color-mix(in srgb, var(--habits-accent) 45%, transparent); +} + +.habits-stats-cell.is-start.is-partial svg { + color: var(--text-on-accent); +} + +/* Stats per-habit goal progress */ + +.habits-goal-bar { + width: 100%; + height: 0.4rem; + margin-top: 0.15rem; + border-radius: var(--radius-s); + background: var(--background-modifier-border); + overflow: hidden; +} + +.habits-goal-fill { + width: var(--habits-progress, 0%); + height: 100%; + background: var(--habits-accent); + transition: width 0.2s ease; +} + +.habits-goal-bar.is-complete .habits-goal-fill { + background: var(--color-green, var(--habits-accent)); +} + +.habits-stats-goal-label { + color: var(--text-muted); + font-size: var(--font-ui-smaller); +} + +/* Collapsible targets section in the habit modal */ + +.habits-targets { + margin: 0.25rem 0 0.5rem; + padding: 0.4rem 0.6rem; + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-m); + background: var(--background-secondary); +} + +.habits-targets-summary { + cursor: pointer; + font-weight: var(--font-semibold); + color: var(--text-normal); + list-style: none; + display: flex; + align-items: center; + gap: 0.4rem; + padding: 0.15rem 0; +} + +.habits-targets-summary::-webkit-details-marker { + display: none; +} + +.habits-targets-summary::before { + content: "▸"; + color: var(--text-muted); + transition: transform 0.15s ease; +} + +.habits-targets[open] .habits-targets-summary::before { + transform: rotate(90deg); +} + +.habits-targets-intro { + margin: 0.25rem 0 0.5rem; + color: var(--text-muted); + font-size: var(--font-ui-small); +} + +/* Missed-habits review modal (experimental rescheduling) */ + +.habits-missed-intro { + margin: 0.25rem 0 0.5rem; + color: var(--text-muted); + font-size: var(--font-ui-small); +} + +.habits-missed-empty { + margin: 0.5rem 0 0; + color: var(--text-muted); +} + +.habits-missed-error { + min-height: 1.2em; + margin: 0.25rem 0; + color: var(--color-red, var(--text-error)); + font-size: var(--font-ui-small); +} + +.habits-missed-list { + display: flex; + flex-direction: column; + gap: 0.4rem; + max-height: 60vh; + overflow-y: auto; +} + +.habits-missed-card { + --habits-accent: var(--interactive-accent); + display: flex; + align-items: center; + gap: 0.6rem; + padding: 0.5rem 0.6rem; + border: 1px solid var(--background-modifier-border); + border-left: 3px solid var(--habits-accent); + border-radius: var(--radius-m); + background: var(--background-primary); +} + +.habits-missed-icon { + display: inline-flex; + align-items: center; + justify-content: center; + width: 1.6rem; + height: 1.6rem; + flex-shrink: 0; + color: var(--habits-accent); +} + +.habits-missed-info { + display: flex; + flex-direction: column; + min-width: 0; + flex: 1; +} + +.habits-missed-name { + font-weight: var(--font-semibold); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.habits-missed-date { + color: var(--text-muted); + font-size: var(--font-ui-small); +} + +.habits-missed-reschedule { + flex-shrink: 0; + padding: 0.3rem 0.7rem; + font-size: var(--font-ui-small); + font-weight: var(--font-semibold); +} + +/* Dashboard/panel: notification button and rescheduled-card indicators */ + +/* Same size and shape as the other header icon buttons (habits-header-left/ + -right) — .habits-icon-button already supplies that; this just anchors it + to the corner and adds the pulse. */ +.habits-missed-button { + position: absolute; + right: 0.75rem; + bottom: 0.75rem; + z-index: 2; + animation: habits-missed-pulse 2.2s ease-in-out infinite; +} + +.habits-missed-badge { + position: absolute; + top: -0.3rem; + right: -0.3rem; + display: inline-flex; + align-items: center; + justify-content: center; + min-width: 1.1rem; + height: 1.1rem; + padding: 0 0.25rem; + border-radius: 1rem; + background: var(--color-red, var(--text-error)); + color: var(--text-on-accent); + font-size: 0.65rem; + font-weight: var(--font-semibold); + line-height: 1; +} + +@keyframes habits-missed-pulse { + 0%, + 100% { + box-shadow: 0 0 0 0 rgba(var(--color-red-rgb, 224, 93, 93), 0.4); + } + 50% { + box-shadow: 0 0 0 6px rgba(var(--color-red-rgb, 224, 93, 93), 0); + } +} + +.habits-panel-missed { + position: relative; +} + +.habits-card-rescheduled { + display: flex; + align-items: center; + gap: 0.3rem; + margin-top: 0.1rem; + color: var(--text-muted); + font-size: var(--font-ui-smaller); +} + +.habits-card-rescheduled-icon { + display: inline-flex; +} + +.habits-card-rescheduled-icon .svg-icon { + width: 0.85em; + height: 0.85em; +} + +.habits-panel-rescheduled { + display: inline-flex; + align-items: center; + color: var(--text-muted); + flex-shrink: 0; +} + +.habits-panel-rescheduled .svg-icon { + width: 0.85em; + height: 0.85em; +} + +/* Trim the last setting's bottom border inside the section */ +.habits-targets .setting-item:last-child { + border-bottom: none; + padding-bottom: 0; +} + +/* Mobile: tighter cards and controls, stacked export modal. */ +@media (max-width: 768px) { + .habits-dashboard { + padding: 0.5rem; + } + + .habits-card { + padding: 0.75rem 0.6rem; + gap: 0.6rem; + } + + /* Match the tighter card padding so the lip stays flush. */ + .habits-card-group-lip { + margin: -0.75rem -0.6rem 0; + } + + .habits-card-title { + font-size: var(--font-ui-medium); + } + + .habits-dashboard button.habits-value { + font-size: 1.5rem; + } + + .habits-dashboard .habits-value-input { + font-size: 1.5rem; + width: 3.4rem; + } + + .habits-counter-buttons { + gap: 0.75rem; + } + + .habits-counter-buttons.is-compact { + flex-wrap: wrap; + gap: 0.3rem; + } + + .habits-counter-buttons.is-compact .habits-icon-button { + padding: 0.35rem 0.25rem; + } + + .habits-binary-toggle { + padding: 0.75rem 1.1rem; + } + + .habits-stats-cell { + width: 0.7rem; + height: 0.7rem; + } + + .habits-export-body { + flex-direction: column; + max-height: none; + } + + .habits-export-controls { + flex: none; + width: 100%; + max-height: none; + padding-right: 0; + } + + .habits-export-preview { + width: 100%; + max-height: 50vh; + } +} + +/* Habit metrics (rendered by the habit-metrics code block) */ + +.habits-metrics { + display: flex; + flex-direction: column; + gap: 0.85rem; + padding: 0.75rem; + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-m); + background: var(--background-secondary); +} + +.habits-metrics-empty { + margin: 0; + text-align: center; + color: var(--text-muted); +} + +.habits-metrics-section { + display: flex; + flex-direction: column; + gap: 0.4rem; +} + +.habits-metrics-title { + font-weight: var(--font-semibold); + font-size: var(--font-ui-small); + color: var(--text-muted); +} + +.habits-metrics-canvas { + position: relative; + height: var(--habits-metrics-height, 220px); +} + +/* Comparison view: a habit-metrics block listing several habits */ + +.habits-metrics-range { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.5rem 0.75rem; +} + +.habits-metrics-range .habits-metrics-tabs { + flex-wrap: wrap; + margin-bottom: 0; +} + +.habits-metrics-range-label { + color: var(--text-muted); + font-size: var(--font-ui-small); +} + +.habits-metrics input.habits-custom-date { + font-size: var(--font-ui-small); + padding: 0.15rem 0.45rem; + background: var(--background-primary); + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-s); + color: var(--text-normal); +} + +.habits-metrics-compare { + overflow-x: auto; +} + +.habits-metrics-compare-table { + width: 100%; + border-collapse: collapse; + font-size: var(--font-ui-small); +} + +.habits-metrics-compare-table th, +.habits-metrics-compare-table td { + padding: 0.35rem 0.5rem; + text-align: right; + border-bottom: 1px solid var(--background-modifier-border); + font-variant-numeric: tabular-nums; +} + +.habits-metrics-compare-table th { + color: var(--text-muted); + font-weight: var(--font-semibold); +} + +.habits-metrics-compare-table th:first-child, +.habits-metrics-compare-table td:first-child { + text-align: left; +} + +.habits-metrics-compare-table tr:last-child td { + border-bottom: none; +} + +.habits-metrics-compare-swatch { + display: inline-block; + width: 0.7rem; + height: 0.7rem; + margin-right: 0.45rem; + border-radius: 50%; + background: var(--habits-compare-color); + vertical-align: middle; +} + +.habits-metrics-compare-badge { + margin-left: 0.45rem; + padding: 0 0.35rem; + border-radius: var(--radius-s); + background: var(--background-modifier-hover); + color: var(--text-muted); + font-size: var(--font-ui-smaller); +} + +/* Charts/Heatmap tab bar in a habit-metrics block */ + +.habits-metrics-tabs { + display: flex; + gap: 0.25rem; + width: fit-content; + margin-bottom: 0.75rem; + padding: 0.2rem; + background: var(--background-primary); + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-m); +} + +.habits-metrics-tab { + padding: 0.3rem 0.75rem; + font-size: var(--font-ui-small); + font-weight: var(--font-semibold); + color: var(--text-muted); + background: transparent; + border: none; + border-radius: var(--radius-s); + cursor: pointer; + box-shadow: none; +} + +.habits-metrics-tab.is-active { + color: var(--text-normal); + background: var(--background-modifier-hover); +} + +/* Paused and stopped habit states */ + +.habits-card.is-paused { + opacity: 0.75; + border-left-style: dashed; +} + +.habits-paused-badge { + display: flex; + align-items: center; + gap: 0.4rem; + padding: 0.5rem 1rem; + border-radius: var(--radius-m); + background: var(--background-modifier-hover); + color: var(--text-muted); + font-weight: var(--font-semibold); +} + +.habits-paused-icon { + display: inline-flex; +} + +/* Overlay icon shown while a freshly paused card departs the queue. */ +.habits-paused-overlay-icon { + display: inline-flex; + color: var(--text-muted); + animation: habits-complete-swoosh 0.45s cubic-bezier(0.34, 1.56, 0.64, 1) forwards; +} + +.habits-paused-overlay-icon .svg-icon { + width: 3rem; + height: 3rem; +} + +.habits-paused-note { + color: var(--text-faint); + font-size: var(--font-ui-smaller); + text-align: center; +} + +.habits-metrics-banner { + display: flex; + align-items: center; + gap: 0.6rem; + padding: 0.5rem 0.75rem; + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-m); + background: var(--background-primary); + color: var(--text-muted); +} + +.habits-metrics-banner-icon { + display: inline-flex; +} + +.habits-metrics-banner-text { + flex: 1; + font-size: var(--font-ui-small); +} + +/* Sidebar quick-log panel */ + +.habits-panel { + display: flex; + flex-direction: column; + gap: 0.5rem; + padding: 0.5rem; +} + +.habits-panel-header { + display: flex; + align-items: center; + gap: 0.5rem; +} + +.habits-panel-title { + flex: 1; + display: flex; + align-items: baseline; + gap: 0.4rem; + min-width: 0; + font-weight: var(--font-semibold); +} + +.habits-panel-date { + color: var(--text-muted); + font-size: var(--font-ui-smaller); + font-weight: var(--font-normal); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.habits-panel-count { + padding: 0.1rem 0.5rem; + border-radius: 1rem; + background: var(--background-modifier-hover); + color: var(--text-muted); + font-size: var(--font-ui-smaller); + font-weight: var(--font-semibold); + white-space: nowrap; +} + +.habits-panel-count.is-all-done { + background: var(--color-green, var(--text-success)); + color: var(--text-on-accent); +} + +.habits-panel-empty { + text-align: center; + padding: 1rem 0.5rem; + color: var(--text-muted); +} + +.habits-panel-list { + display: flex; + flex-direction: column; + gap: 0.35rem; +} + +.habits-panel-row { + --habits-accent: var(--interactive-accent); + position: relative; + overflow: hidden; + -webkit-user-select: none; + user-select: none; + -webkit-touch-callout: none; + display: flex; + flex-direction: column; + gap: 0.3rem; + padding: 0.4rem 0.55rem; + background: var(--background-primary); + border: 1px solid var(--background-modifier-border); + border-left: 2px solid var(--habits-accent); + border-radius: var(--radius-s); +} + +.habits-panel-row.is-done { + opacity: 0.75; +} + +.habits-panel-row.is-paused { + opacity: 0.6; + border-left-style: dashed; +} + +.habits-panel-row-main { + display: flex; + align-items: center; + gap: 0.4rem; + min-width: 0; +} + +.habits-panel-icon { + display: inline-flex; + flex: 0 0 auto; + color: var(--habits-accent); + font-size: 1rem; + line-height: 1; +} + +.habits-panel-icon .svg-icon { + width: 1rem; + height: 1rem; +} + +.habits-panel .habits-panel-name { + display: block; + flex: 1 1 auto; + min-width: 0; + width: auto; + margin: 0; + padding: 0; + justify-content: flex-start; + text-align: left; + font-size: var(--font-ui-small); + font-weight: var(--font-semibold); + color: var(--text-normal); + background: transparent; + border: none; + box-shadow: none; + cursor: pointer; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.habits-panel .habits-panel-name:hover { + color: var(--habits-accent); + text-decoration: underline; +} + +.habits-panel-time { + flex: 0 0 auto; + color: var(--text-muted); + font-size: var(--font-ui-smaller); + font-variant-numeric: tabular-nums; + white-space: nowrap; +} + +.habits-panel .habits-panel-value { + flex: 0 0 auto; + margin: 0; + padding: 0 0.15rem; + background: transparent; + border: none; + border-radius: var(--radius-s); + box-shadow: none; + cursor: pointer; + color: var(--text-muted); + font-size: var(--font-ui-smaller); + font-variant-numeric: tabular-nums; + white-space: nowrap; +} + +.habits-panel .habits-panel-value:hover { + color: var(--text-normal); + background: var(--background-modifier-hover); +} + +.habits-panel .habits-panel-value-input { + flex: 0 0 auto; + width: 3rem; + padding: 0 0.2rem; + font-size: var(--font-ui-smaller); + text-align: center; + color: var(--text-normal); + background: var(--background-modifier-form-field); + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-s); +} + +/* Note and flexible habits: the readout is machine-derived (a note's + char/checklist count, or a flexible habit's period total), so it is + plain text rather than the click-to-edit button other types use. */ +.habits-panel .habits-panel-readout-value { + cursor: default; +} + +.habits-panel .habits-panel-readout-value:hover { + color: var(--text-muted); + background: transparent; +} + +.habits-panel .habits-panel-mini { + flex: 0 0 auto; + padding: 0.2rem; + border: 1px solid var(--background-modifier-border); +} + +.habits-panel .habits-panel-mini .svg-icon { + width: 0.85rem; + height: 0.85rem; +} + +.habits-panel .habits-panel-step { + padding: 0.2rem 0.3rem; + font-size: var(--font-ui-smaller); + font-weight: var(--font-semibold); + font-variant-numeric: tabular-nums; + line-height: 1; +} + +.habits-panel .habits-panel-toggle { + flex: 0 0 auto; + display: inline-flex; + align-items: center; + justify-content: center; + padding: 0.25rem; + border-radius: 50%; + background: transparent; + color: var(--text-muted); + cursor: pointer; + box-shadow: none; +} + +.habits-panel .habits-panel-toggle:hover { + background: var(--background-modifier-hover); +} + +.habits-panel-row.is-done .habits-panel-toggle { + color: var(--color-green, var(--text-success)); +} + +.habits-panel-progress { + width: 100%; + height: 3px; + border-radius: var(--radius-s); + background: var(--background-modifier-border); + overflow: hidden; +} + +.habits-panel-progress-fill { + width: var(--habits-progress, 0%); + height: 100%; + background: var(--habits-accent); + transition: width 0.2s ease; +} + +.habits-panel-progress.is-complete .habits-panel-progress-fill { + background: var(--color-green, var(--habits-accent)); +} + +/* Brief celebration when a row is completed from the panel. */ +.habits-panel-flash { + position: absolute; + inset: 0; + display: flex; + align-items: center; + justify-content: center; + background: var(--background-primary); + border-radius: inherit; + animation: habits-complete-fade-in 0.15s ease-out; +} + +.habits-panel-flash-icon { + display: inline-flex; + color: var(--color-green, var(--text-success)); + animation: habits-complete-swoosh 0.45s cubic-bezier(0.34, 1.56, 0.64, 1) forwards; +} + +.habits-panel-flash-icon .svg-icon { + width: 1.4rem; + height: 1.4rem; +} + +/* Export modal: options left, live A4 preview right. */ + +.modal.habits-export-modal { + width: 1020px; + max-width: 96vw; +} + +.habits-export-body { + display: flex; + gap: 1rem; + align-items: flex-start; + max-height: 80vh; +} + +.habits-export-controls { + flex: 0 0 320px; + max-height: 80vh; + overflow-y: auto; + padding-right: 0.5rem; +} + +.habits-export-controls .setting-item { + padding: 0.45rem 0; + border-top: none; +} + +.habits-export-hidden { + display: none; +} + +.habits-export-preview { + flex: 1; + max-height: 80vh; + overflow-y: auto; + overflow-x: hidden; + padding: 0.75rem; + background: var(--background-secondary-alt, var(--background-secondary)); + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-m); +} + +.habits-export-pages { + display: flex; + flex-direction: column; + align-items: center; + gap: 0.75rem; +} + +.habits-export-empty { + color: var(--text-muted); + padding: 1.5rem; + text-align: center; +} + +/* Scaled wrapper: reserves the on-screen footprint of the scaled page. */ +.habits-export-page-outer { + position: relative; + flex: 0 0 auto; + width: var(--hx-outer-w); + height: var(--hx-outer-h); + overflow: hidden; +} + +.habits-export-page-outer.is-zoomable { + cursor: zoom-in; +} + +/* Magnifying-glass badge shown while hovering a preview page. */ +.habits-export-zoom-hint { + position: absolute; + top: 6px; + right: 6px; + z-index: 2; + display: flex; + align-items: center; + justify-content: center; + width: 26px; + height: 26px; + border-radius: 50%; + background: rgba(0, 0, 0, 0.55); + color: #ffffff; + opacity: 0; + transition: opacity 0.15s ease; + pointer-events: none; +} + +.habits-export-zoom-hint .svg-icon { + width: 14px; + height: 14px; +} + +.habits-export-page-outer.is-zoomable:hover .habits-export-zoom-hint { + opacity: 1; +} + +/* Full-size lightbox overlaying the whole window. */ +.habits-export-lightbox { + position: absolute; + inset: 0; + z-index: 100; + display: flex; + flex-direction: column; + align-items: center; + overflow-y: auto; + padding: 1.5rem; + background: rgba(0, 0, 0, 0.7); + cursor: zoom-out; +} + +.habits-export-lightbox-pages { + display: flex; + flex-direction: column; + align-items: center; + gap: 1rem; + margin: auto; +} + +.habits-export-lightbox-close { + position: sticky; + top: 0; + z-index: 2; + align-self: flex-end; + display: flex; + align-items: center; + justify-content: center; + width: 2rem; + height: 2rem; + padding: 0; + border-radius: 50%; + background: rgba(0, 0, 0, 0.6); + color: #ffffff; + border: 1px solid rgba(255, 255, 255, 0.25); + cursor: pointer; + box-shadow: none; +} + +/* The preview page is always paper-white regardless of theme. */ +.habits-export-page { + transform: scale(var(--hx-scale, 1)); + transform-origin: top left; +} + +.habits-export-page { + position: relative; + flex: 0 0 auto; + box-sizing: border-box; + overflow: hidden; + width: var(--hx-page-w); + height: var(--hx-page-h); + padding: var(--hx-page-pad); + background: #ffffff; + color: #222222; + box-shadow: var(--shadow-s); + border-radius: 2px; +} + +.habits-export-block { + height: var(--hx-block-h); + margin-bottom: var(--hx-block-gap); +} + +.habits-export-text { + font-size: var(--hx-font); +} + +.habits-export-page-number { + position: absolute; + bottom: 4px; + left: 0; + right: 0; + text-align: center; + font-size: 6px; + color: #6e6e6e; +} + +.habits-export-block { + overflow: hidden; +} + +.habits-export-title { + font-weight: 700; + color: #222222; + line-height: 1.3; +} + +.habits-export-subtitle { + color: #6e6e6e; + line-height: 1.4; +} + +.habits-export-summary { + display: flex; + gap: 9px; +} + +.habits-export-tile { + flex: 1; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 2px; + background: #f6f6f6; + border: 1px solid #cdcdcd; + border-radius: 3px; +} + +.habits-export-tile-value { + font-weight: 700; + color: #222222; + line-height: 1; +} + +.habits-export-tile-label { + color: #6e6e6e; + line-height: 1; +} + +.habits-export-section { + font-weight: 700; + color: #222222; + margin-bottom: 2px; +} + +.habits-export-chart { + display: block; + width: 100%; + height: auto; +} + +.habits-export-habit { + border-left: 3px solid var(--hx-accent, #888888); + padding-left: 8px; +} + +.habits-export-habit-name { + font-weight: 700; + color: #222222; + line-height: 1.4; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.habits-export-habit-meta { + color: #6e6e6e; + line-height: 1.4; + margin-bottom: 3px; +} + +.habits-export-grid { + display: flex; + flex-wrap: wrap; + gap: var(--hx-cell-gap, 2px); +} + +.habits-export-cell { + box-sizing: border-box; + width: var(--hx-cell, 8px); + height: var(--hx-cell, 8px); + background: var(--hx-fill, #ffffff); + border: 1px solid var(--hx-border, transparent); + border-radius: 1px; +} + +.habits-export-goal { + color: #6e6e6e; + margin-top: 3px; +} + +.habits-export-comment { + height: var(--hx-line-h, 10px); + line-height: var(--hx-line-h, 10px); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + color: #555555; +} + +/* == Limit habits (experimental) ================================== */ + +/* Clean / Slipped boxes on binary limit-habit cards. The two boxes act + like radio buttons; Clean is highlighted by default because an + unlogged day already counts as clean. */ +.habits-limit-boxes { + display: flex; + /* If both labels don't fit side by side, the boxes stack vertically + instead of truncating or breaking the text. */ + flex-wrap: wrap; + gap: 6px; + width: 100%; +} + +.habits-limit-box { + flex: 1 1 0; + /* Never smaller than the label, so the text always shows in full. */ + min-width: fit-content; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 3px; + /* Obsidian buttons have a fixed height (--input-height); this box + stacks an icon over a label, so it must size to its content. */ + height: auto; + min-height: 0; + padding: 8px 4px; + border-radius: 8px; + border: 1px solid var(--background-modifier-border); + background: var(--background-secondary); + color: var(--text-muted); + cursor: pointer; + box-sizing: border-box; + box-shadow: none; + line-height: 1.2; + transition: + background-color 0.15s ease, + border-color 0.15s ease, + color 0.15s ease; +} + +.habits-limit-box-icon { + display: flex; + align-items: center; + justify-content: center; +} + +.habits-limit-box-icon svg { + width: 16px; + height: 16px; +} + +.habits-limit-box-label { + font-size: var(--font-ui-smaller); + line-height: 1.2; + text-align: center; + white-space: nowrap; +} + +.habits-limit-box.habits-limit-clean.is-active { + border-color: var(--color-green, var(--text-success)); + background: rgba(var(--color-green-rgb, 76, 175, 80), 0.12); + color: var(--color-green, var(--text-success)); +} + +.habits-limit-box.habits-limit-slipped.is-active { + border-color: var(--color-red, var(--text-error)); + background: rgba(var(--color-red-rgb, 224, 93, 93), 0.12); + color: var(--color-red, var(--text-error)); +} + +/* Counter/timed limit habits: the bar turns red once over the limit. */ +.habits-progress.is-over .habits-progress-fill, +.habits-panel-progress.is-over .habits-panel-progress-fill { + background: var(--color-red, var(--text-error)); +} + +/* Stats heatmap: a day over the limit. */ +.habits-stats-cell.is-over { + background: var(--color-red, var(--text-error)); + opacity: 0.75; +} + +/* Panel row for a slipped/over-limit day: tint the toggle red. */ +.habits-panel-row.is-slipped .habits-panel-slip-toggle { + color: var(--color-red, var(--text-error)); +} + +/* Note shown at the top of the experimental settings section. */ +.habits-experimental-note { + margin: 0 0 12px; + color: var(--text-muted); + font-size: var(--font-ui-small); +} + +.habits-advanced-note { + margin: 0 0 12px; + color: var(--text-muted); + font-size: var(--font-ui-small); +} + +/* Hand-rolled top tab bar for the settings tab (General/Experimental/ + Advanced) — Obsidian has no native tab component. */ +.habits-settings-tabs { + display: flex; + gap: 4px; + margin-bottom: 12px; + border-bottom: 1px solid var(--background-modifier-border); +} + +.habits-settings-tab { + padding: 6px 14px; + background: transparent; + border: none; + border-bottom: 2px solid transparent; + border-radius: 0; + box-shadow: none; + color: var(--text-muted); + font-size: var(--font-ui-medium); + cursor: pointer; +} + +.habits-settings-tab:hover { + color: var(--text-normal); + background: transparent; +} + +.habits-settings-tab.is-active { + color: var(--text-normal); + border-bottom-color: var(--interactive-accent); + font-weight: var(--font-weight-bold, 600); +} + +/* Weekday pills (multi-day picker in the habit modal) */ + +.habits-weekday-picker { + display: flex; + flex-wrap: wrap; + gap: 0.35rem; +} + +.habits-weekday-picker button.habits-weekday-pill { + min-width: 2.6em; + padding: 0.25em 0.55em; + border-radius: var(--radius-l); + border: 1px solid var(--background-modifier-border); + background-color: var(--background-secondary); + background-image: none; + color: var(--text-muted); + font-size: var(--font-ui-small); + cursor: pointer; + box-shadow: none; +} + +.habits-weekday-picker button.habits-weekday-pill:hover { + border-color: var(--background-modifier-border-hover); + color: var(--text-normal); +} + +.habits-weekday-picker button.habits-weekday-pill.is-active { + background-color: var(--interactive-accent); + border-color: var(--interactive-accent); + color: var(--text-on-accent); +} + +/* Habits table (`habits-table` code block) */ + +.habits-table-block { + overflow-x: auto; +} + +table.habits-table { + width: 100%; + border-collapse: collapse; + font-size: var(--font-ui-small); + margin: 0; +} + +table.habits-table th, +table.habits-table td { + padding: 0.35em 0.6em; + border-bottom: 1px solid var(--background-modifier-border); + text-align: left; + white-space: nowrap; +} + +table.habits-table th { + color: var(--text-muted); + font-weight: var(--font-semibold); +} + +table.habits-table th.habits-table-count, +table.habits-table td.habits-table-count { + text-align: right; + font-variant-numeric: tabular-nums; +} + +table.habits-table tr.habits-table-group td { + padding-top: 0.9em; + color: var(--text-muted); + font-size: var(--font-ui-smaller); + font-weight: var(--font-semibold); + text-transform: uppercase; + letter-spacing: 0.04em; + border-bottom: none; +} + +table.habits-table a.habits-table-link { + color: var(--text-normal); + text-decoration: none; + cursor: pointer; +} + +table.habits-table a.habits-table-link:hover { + color: var(--text-accent); + text-decoration: underline; +} + +table.habits-table .habits-table-paused { + display: inline-flex; + vertical-align: middle; + margin-left: 0.4em; + color: var(--text-muted); +} + +table.habits-table .habits-table-paused .svg-icon { + width: 0.85em; + height: 0.85em; +} + +table.habits-table .habits-table-rescheduled { + display: inline-flex; + vertical-align: middle; + margin-left: 0.4em; + color: var(--text-muted); +} + +table.habits-table .habits-table-rescheduled .svg-icon { + width: 0.85em; + height: 0.85em; +} + +table.habits-table td.habits-table-schedule { + color: var(--text-muted); +} + +.habits-table-empty { + color: var(--text-muted); + font-size: var(--font-ui-small); + padding: 0.5em 0; +} + +/* Habits table — the interactive Today column */ + +table.habits-table td.habits-table-today { + width: 1%; +} + +table.habits-table button.habits-table-toggle { + display: inline-flex; + align-items: center; + gap: 0.35em; + padding: 0.25em 0.7em; + border-radius: var(--radius-m); + background: var(--background-modifier-hover); + color: var(--text-muted); + font-size: var(--font-ui-small); + font-weight: var(--font-semibold); + cursor: pointer; + box-shadow: none; + white-space: nowrap; +} + +table.habits-table button.habits-table-toggle:hover { + background: var(--background-modifier-active-hover); + color: var(--text-normal); +} + +table.habits-table button.habits-table-toggle.is-done { + background: var(--interactive-accent); + color: var(--text-on-accent); +} + +table.habits-table button.habits-table-toggle.habits-table-slip.is-done { + background: var(--background-modifier-error); + color: var(--text-on-accent); +} + +table.habits-table .habits-table-toggle-icon { + display: inline-flex; +} + +table.habits-table .habits-table-toggle-icon .svg-icon { + width: 0.9em; + height: 0.9em; +} + +table.habits-table .habits-table-stepper { + display: inline-flex; + align-items: center; + gap: 0.3em; +} + +table.habits-table .habits-table-value { + min-width: 3em; + text-align: center; + font-variant-numeric: tabular-nums; +} + +table.habits-table .habits-icon-button.habits-table-mini { + padding: 0.15em; +} + +table.habits-table .habits-icon-button.habits-table-mini .svg-icon { + width: 0.85em; + height: 0.85em; +} + +table.habits-table .habits-table-notdue { + color: var(--text-faint); +} + +/* Planned-times picker (habit modal) */ + +.habits-time-picker { + display: flex; + flex-direction: column; + align-items: flex-end; + gap: 0.35rem; +} + +.habits-time-row { + display: flex; + align-items: center; + gap: 0.3rem; +} + +.habits-time-picker button.habits-time-add { + font-size: var(--font-ui-small); + padding: 0.2em 0.7em; + cursor: pointer; +} + +.habits-time-picker .habits-icon-button.habits-time-remove { + padding: 0.15em; +} + +.habits-time-picker .habits-icon-button.habits-time-remove .svg-icon { + width: 0.85em; + height: 0.85em; +} + +/* Habits failed, skipped or snoozed for the day: a "N hidden" disclosure + under the dashboard's cards and the panel's rows, with Undo per habit. */ + +.habits-closed { + display: flex; + flex-direction: column; + gap: 0.35rem; + margin-top: 0.75rem; +} + +.habits-closed-toggle { + display: inline-flex; + align-items: center; + gap: 0.3rem; + width: fit-content; + padding: 0.2rem 0.5rem; + font-size: var(--font-ui-small); + color: var(--text-muted); + background: transparent; + border: none; + box-shadow: none; + cursor: pointer; +} + +.habits-closed-toggle:hover { + color: var(--text-normal); + background: var(--background-modifier-hover); +} + +.habits-closed-chevron { + display: inline-flex; +} + +.habits-closed-chevron .svg-icon { + width: 0.9em; + height: 0.9em; +} + +.habits-closed-list { + display: flex; + flex-direction: column; + gap: 0.25rem; +} + +.habits-closed-row { + display: flex; + align-items: center; + gap: 0.5rem; + padding: 0.3rem 0.5rem; + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-s); + background: var(--background-primary); + font-size: var(--font-ui-small); +} + +.habits-closed-icon { + display: inline-flex; + color: var(--text-muted); +} + +.habits-closed-name { + flex: 1; + min-width: 0; + overflow-wrap: anywhere; + color: var(--text-muted); +} + +.habits-closed-row.is-failed .habits-closed-name { + text-decoration: line-through; +} + +.habits-closed-status { + display: inline-flex; + align-items: center; + gap: 0.25rem; + color: var(--text-faint); + white-space: nowrap; +} + +.habits-closed-row.is-failed .habits-closed-status { + color: var(--color-red, var(--text-error)); +} + +.habits-closed-status-icon { + display: inline-flex; +} + +.habits-closed-status-icon .svg-icon { + width: 0.85em; + height: 0.85em; +} + +.habits-closed-undo { + padding: 0.1rem 0.5rem; + font-size: var(--font-ui-smaller); +} + +table.habits-table .habits-table-toggle.habits-table-closed { + color: var(--text-muted); +} + +table.habits-table .habits-table-toggle.habits-table-closed.is-failed { + color: var(--color-red, var(--text-error)); +} + +/* Compact embedded logger: one coloured row per habit. */ +.habits-compact { + position: relative; + border: 1px solid var(--background-modifier-border); + border-radius: 10px; + padding: 8px; + background: var(--background-primary); +} +.habits-compact-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + margin-bottom: 8px; +} +.habits-compact-nav, .habits-compact-controls { + display: flex; + align-items: center; + gap: 8px; +} +.habits-compact-nav { + position: relative; + justify-content: center; + flex: 0 0 auto; +} +.habits-compact-nav > button { + flex: 0 0 auto; +} +.habits-compact-date { + display: inline-flex; + align-items: center; + justify-content: center; + font-weight: var(--font-semibold); + background: transparent; + box-shadow: none; + padding: 4px; +} +.habits-compact-date-input { + position: absolute !important; + left: 50%; + top: 24px; + width: 1px; + height: 1px; + min-width: 0; + min-height: 0; + max-width: 1px; + max-height: 1px; + margin: 0; + padding: 0; + border: 0; + opacity: 0; + pointer-events: none; +} +.habits-compact-list { display: flex; flex-direction: column; gap: 6px; } +.habits-compact-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + min-height: 46px; + padding: 5px 8px; + border: 1px solid var(--background-modifier-border); + border-left: 3px solid var(--habits-accent); + border-radius: 12px; + background: var(--background-secondary); + background: color-mix(in srgb, var(--habits-accent) 8%, var(--background-primary)); +} +/* Match the compact-card reference: completed habits recede but remain usable. */ +.habits-compact-row.is-done { + opacity: 0.58; + filter: saturate(0.45); + border-left-color: var(--background-modifier-border); +} +.habits-compact-row.is-done:hover, +.habits-compact-row.is-done:focus-within { + opacity: 0.78; +} +.habits-compact-name { + display: flex; + align-items: center; + gap: 6px; + min-width: 0; + color: var(--text-normal); + font-weight: var(--font-semibold); + text-decoration: none; +} +.habits-compact-name > span:last-child { overflow-wrap: anywhere; } +.habits-compact-icon { display: inline-flex; color: var(--habits-accent); flex-shrink: 0; } +.habits-compact-controls { flex-shrink: 0; color: var(--text-muted); } +.habits-compact-value { font-variant-numeric: tabular-nums; } +.habits-compact-current { color: var(--habits-accent); font-weight: var(--font-semibold); } +.habits-compact .habits-compact-button { width: 32px; height: 32px; padding: 5px; } +.habits-compact .habits-compact-toggle { border-radius: 50%; } +.habits-compact-row.is-done .habits-compact-toggle { color: var(--habits-accent); } +.habits-compact-group { color: var(--text-muted); font-weight: var(--font-semibold); } +.habits-compact-empty { padding: 16px; color: var(--text-muted); text-align: center; } +@media (max-width: 480px) { + .habits-compact-row { flex-wrap: wrap; gap: 6px; padding: 5px 8px; } + .habits-compact-controls { margin-left: auto; } + .habits-compact-value { font-size: var(--font-small); } +} diff --git a/src/integrations/habits/utils.ts b/src/integrations/habits/utils.ts new file mode 100644 index 000000000..7c0b93279 --- /dev/null +++ b/src/integrations/habits/utils.ts @@ -0,0 +1,614 @@ +import { moment, type Component } from "obsidian"; +import { t } from "./i18n"; +import type { + GroupStyle, + HabitDefinition, + HabitFrequency, + HabitSortMode, +} from "./types"; + +/** + * Invoke `onTrigger` when the user holds a touch on `el` for half a second + * without moving — the mobile stand-in for a right-click. + */ +export function registerLongPress( + component: Component, + el: HTMLElement, + onTrigger: (x: number, y: number) => void, +): void { + let timer: number | null = null; + let startX = 0; + let startY = 0; + const clear = (): void => { + if (timer !== null) { + el.win.clearTimeout(timer); + timer = null; + } + }; + component.registerDomEvent(el, "touchstart", (evt: TouchEvent) => { + const touch = evt.touches[0]; + if (!touch) { + return; + } + startX = touch.clientX; + startY = touch.clientY; + clear(); + timer = el.win.setTimeout(() => { + timer = null; + onTrigger(startX, startY); + }, 500); + }); + component.registerDomEvent(el, "touchmove", (evt: TouchEvent) => { + const touch = evt.touches[0]; + if (!touch) { + return; + } + if ( + Math.abs(touch.clientX - startX) > 10 || + Math.abs(touch.clientY - startY) > 10 + ) { + clear(); + } + }); + component.registerDomEvent(el, "touchend", clear); + component.registerDomEvent(el, "touchcancel", clear); + component.register(clear); +} + +/** + * Locale-aware display form of a 24-hour `HH:mm` time of day (e.g. "9:00 PM" + * or "21:00", following the system locale). Invalid input is returned as-is. + */ +export function formatTimeOfDay(time: string): string { + const match = /^(\d{2}):(\d{2})$/.exec(time); + if (!match) { + return time; + } + return new Date( + 2024, + 0, + 1, + Number(match[1]), + Number(match[2]), + ).toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" }); +} + +/** Locale-aware weekday name for a `getDay` value (2024-01-07 = Sunday). */ +export function weekdayName(value: number, style: "long" | "short"): string { + return new Date(2024, 0, 7 + value).toLocaleDateString(undefined, { + weekday: style, + }); +} + +/** + * A short "due" descriptor for non-daily habits ("Every Mon, Wed, Fri", + * "Monthly · day 15", "Every other day"); empty for daily. + */ +export function habitScheduleLabel(habit: HabitDefinition): string { + if (habit.frequency === "weekly") { + if (habit.weekdays.length === 1) { + return t("Every {day}", { + day: weekdayName(habit.weekdays[0], "long"), + }); + } + // Monday-first reads as a week plan ("Mon, Wed, Fri") whatever + // the underlying Sunday-based getDay values are. + const days = [...habit.weekdays] + .sort((a, b) => ((a + 6) % 7) - ((b + 6) % 7)) + .map((day) => weekdayName(day, "short")) + .join(", "); + return t("Every {day}", { day: days }); + } + if (habit.frequency === "monthly") { + return t("Monthly · day {day}", { day: habit.monthDay }); + } + if (habit.frequency === "interval") { + if (habit.intervalMode === "cycle") return t("{active} active days / {days}-day cycle", { active: habit.cycleActiveDays || 1, days: habit.intervalDays }); + return habit.intervalDays === 2 + ? t("Every other day") + : t("Every {n} days", { n: habit.intervalDays }); + } + if (habit.frequency === "flexibleWeekly") { + if (habit.goalDirection === "max") return t("Weekly total limit · any day"); + return t("{n}× a week · any day", { n: Math.max(1, habit.target) }); + } + if (habit.frequency === "flexibleMonthly") { + if (habit.goalDirection === "max") return t("Monthly total limit · any day"); + return t("{n}× a month · any day", { n: Math.max(1, habit.target) }); + } + return ""; +} + +/** True for the two "N times per period, any day" frequencies. */ +/** + * Whether a habit's logged values and target may be fractional (e.g. 1.5 + * litres). Only counted habits: timed habits are whole minutes, and binary + * and note habits are never typed by hand. + */ +export function allowsDecimals(habit: Pick): boolean { + return habit.type === "repetition"; +} + +/** + * How much one +/− press changes a habit's value: a counted habit's own + * step size (1 by default, or e.g. 0.25 for litres), otherwise 1. + */ +export function stepOf(habit: Pick): number { + return allowsDecimals(habit) && habit.step > 0 ? habit.step : 1; +} + +/** + * Round away floating-point noise (0.1 + 0.2 = 0.30000000000000004) so + * stored and displayed values stay tidy. Three decimal places is plenty for + * anything a person logs by hand. + */ +export function roundValue(value: number): number { + return Math.round(value * 1000) / 1000; +} + +/** A logged value, total or target as display text, e.g. "1.5". */ +export function formatValue(value: number): string { + return String(roundValue(value)); +} + +/** + * A value ready to store: never negative, and a whole number for every + * habit type except counted habits, which keep their decimals. + */ +export function cleanValue( + habit: Pick, + value: number, +): number { + const positive = Math.max(0, value); + return allowsDecimals(habit) ? roundValue(positive) : Math.round(positive); +} + +export function isFlexibleFrequency(frequency: HabitFrequency): boolean { + return frequency === "flexibleWeekly" || frequency === "flexibleMonthly"; +} + +/** Format a date as a `YYYY-MM-DD` key using local time. */ +export function toDateKey(date: Date): string { + const year = date.getFullYear(); + const month = String(date.getMonth() + 1).padStart(2, "0"); + const day = String(date.getDate()).padStart(2, "0"); + return `${year}-${month}-${day}`; +} + +/** Return a new date offset from `date` by the given number of days. */ +export function addDays(date: Date, days: number): Date { + const next = new Date(date); + next.setDate(next.getDate() + days); + return next; +} + +/** True when two dates fall on the same calendar day. */ +export function isSameDay(a: Date, b: Date): boolean { + return toDateKey(a) === toDateKey(b); +} + +/** + * Remove characters that are not allowed in vault file names so a habit name + * can be safely used as a note title. + */ +export function sanitizeFileName(name: string): string { + return name + .replace(/[\\/:*?"<>|#^[\]]/g, " ") + .replace(/\s+/g, " ") + .replace(/^\.+/, "") + .trim(); +} + +/** Human-readable label for a date, e.g. "Today", "Yesterday" or a full date. */ +export function friendlyDateLabel(date: Date, today: Date): string { + if (isSameDay(date, today)) { + return t("Today"); + } + if (isSameDay(date, addDays(today, -1))) { + return t("Yesterday"); + } + if (isSameDay(date, addDays(today, 1))) { + return t("Tomorrow"); + } + return date.toLocaleDateString(undefined, { + weekday: "short", + day: "numeric", + month: "short", + year: "numeric", + }); +} + +/** Number of days in the given month (`month` is 0-based, as in `Date`). */ +export function daysInMonth(year: number, month: number): number { + return new Date(year, month + 1, 0).getDate(); +} + +/** Parse a `YYYY-MM-DD` key into a local date, or null if malformed. */ +export function fromDateKey(key: string): Date | null { + const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(key); + if (!match) { + return null; + } + return new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3])); +} + +/** + * Moment.js format tokens the note-date extractor understands, longest + * first so `MMMM` wins over `MM`. Each maps to a regex snippet and notes + * whether it matches digits (used to add digit boundaries around the + * pattern, so `YYYYMMDD` does not match inside a longer number). + */ +const FORMAT_TOKENS: [token: string, pattern: string, digits: boolean][] = [ + ["YYYY", "\\d{4}", true], + ["YY", "\\d{2}", true], + ["MMMM", "\\p{L}+", false], + ["MMM", "\\p{L}+\\.?", false], + ["MM", "\\d{2}", true], + ["M", "\\d{1,2}", true], + ["DD", "\\d{2}", true], + ["Do", "\\d{1,2}\\p{L}*", true], + ["D", "\\d{1,2}", true], + ["dddd", "\\p{L}+", false], + ["ddd", "\\p{L}+\\.?", false], + ["dd", "\\p{L}+", false], +]; + +/** + * Build a regex that finds text shaped like `format` inside a note name, + * or null when the format uses tokens the extractor does not know. + */ +function noteDatePattern(format: string): RegExp | null { + let source = ""; + let startsWithDigits = false; + let endsWithDigits = false; + let i = 0; + outer: while (i < format.length) { + // Moment treats [bracketed] text as literal characters. + if (format[i] === "[") { + const close = format.indexOf("]", i); + const literal = format.slice(i + 1, close < 0 ? undefined : close); + source += escapeRegExp(literal); + if (literal.length > 0) { + endsWithDigits = false; + } + i = close < 0 ? format.length : close + 1; + continue; + } + for (const [token, pattern, digits] of FORMAT_TOKENS) { + if (format.startsWith(token, i)) { + source += pattern; + if (source === pattern) { + startsWithDigits = digits; + } + endsWithDigits = digits; + i += token.length; + continue outer; + } + } + if (/[A-Za-z]/.test(format[i])) { + // An unrecognised format token; let the caller fall back to + // parsing the whole note name with Moment instead. + return null; + } + source += escapeRegExp(format[i]); + endsWithDigits = false; + i++; + } + if (source.length === 0) { + return null; + } + // Wrap the date in a capture group and require digit boundaries where + // the pattern starts or ends with digits, so `YYYYMMDD` cannot match + // inside a longer number. A lookbehind would be neater, but iOS + // versions before 16.4 do not support them. + source = "(" + source + ")"; + if (startsWithDigits) { + source = "(?:^|\\D)" + source; + } + if (endsWithDigits) { + source += "(?!\\d)"; + } + return new RegExp(source, "u"); +} + +function escapeRegExp(text: string): string { + return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + +/** The slice of a parsed Moment object that note-date parsing uses. */ +interface ParsedMoment { + isValid(): boolean; + toDate(): Date; +} + +/** + * Obsidian's bundled Moment.js, typed by hand. Moment's own type + * definitions are not always resolvable in stricter lint setups, which + * would otherwise make every call through `moment` unsafely typed. + */ +const parseMoment = moment as unknown as ( + input: string, + format: string, + strict: boolean, +) => ParsedMoment; + +/** + * Extract a date from a note name using a Moment.js format such as + * `YYYY-MM-DD` or `YYYYMMDD`. The date may sit anywhere in the name + * ("20260701 Monday" matches with `YYYYMMDD`), and the matched text must + * also parse strictly so ordinary numbers are not mistaken for dates. + */ +export function parseNoteDate(name: string, format: string): Date | null { + const trimmed = format.trim(); + if (!trimmed) { + return null; + } + const pattern = noteDatePattern(trimmed); + if (pattern) { + const match = pattern.exec(name); + if (match) { + const parsed = parseMoment(match[1], trimmed, true); + if (parsed.isValid()) { + return parsed.toDate(); + } + } + return null; + } + // Formats with tokens the extractor does not know still work when the + // note name is exactly the date. + const whole = parseMoment(name, trimmed, true); + return whole.isValid() ? whole.toDate() : null; +} + +/** + * The theme palette the habit modal's swatches store, ordered by hue. + * The theme accent gets `-1` so default-coloured habits lead, and greys + * would land at 360; the actual rendered colour depends on the theme, + * so the palette order is by the colours' conventional hues. + */ +const PALETTE_HUES: Record = { + "var(--interactive-accent)": -1, + "var(--color-red)": 0, + "var(--color-orange)": 30, + "var(--color-yellow)": 60, + "var(--color-green)": 120, + "var(--color-cyan)": 180, + "var(--color-blue)": 240, + "var(--color-purple)": 280, + "var(--color-pink)": 330, +}; + +/** + * Hue (0–360) of a habit's accent colour, used to order colours so + * similar ones sit together. Handles the theme-palette CSS variables the + * habit modal's swatches store as well as hex colours from the custom + * picker; anything else returns `null` and sorts after the coloured + * habits. + */ +function colorHue(color: string): number | null { + const palette = PALETTE_HUES[color.trim()]; + if (palette !== undefined) { + return palette; + } + const match = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(color.trim()); + if (!match) { + return null; + } + let hex = match[1]; + if (hex.length === 3) { + hex = hex.replace(/./g, (c) => c + c); + } + const r = parseInt(hex.slice(0, 2), 16) / 255; + const g = parseInt(hex.slice(2, 4), 16) / 255; + const b = parseInt(hex.slice(4, 6), 16) / 255; + const max = Math.max(r, g, b); + const min = Math.min(r, g, b); + if (max === min) { + // Greys have no hue; park them just after the coloured habits. + return 360; + } + const d = max - min; + let hue: number; + if (max === r) { + hue = ((g - b) / d + (g < b ? 6 : 0)) * 60; + } else if (max === g) { + hue = ((b - r) / d + 2) * 60; + } else { + hue = ((r - g) / d + 4) * 60; + } + return hue; +} + +/** + * The colour a habit's card actually shows: the group colour when the + * habit opted into it and its group has one, its own colour otherwise. + */ +export function habitAccent( + habit: HabitDefinition, + groups: Record, +): string { + if (habit.useGroupColor) { + const style = groups[habit.group.trim()]; + if (style?.color) { + return style.color; + } + } + return habit.color; +} + +/** The most recent day a habit was logged, or "" when it never was. */ +function lastLoggedDay(habit: HabitDefinition): string { + let latest = ""; + for (const day of Object.keys(habit.records)) { + if (day > latest) { + latest = day; + } + } + return latest; +} + +/** + * Order habits for display. `habits` arrives name-sorted from the store, + * and every mode falls back to that name order for ties, so the result + * is always stable. `manualOrder` holds note paths as arranged in + * settings; habits missing from it (created since) go to the end. + */ +export function sortHabits( + habits: HabitDefinition[], + mode: HabitSortMode, + manualOrder: readonly string[], + groups: Record = {}, + groupOrder: readonly string[] = [], +): HabitDefinition[] { + const sorted = [...habits]; + switch (mode) { + case "color": { + sorted.sort((a, b) => { + const ca = habitAccent(a, groups); + const cb = habitAccent(b, groups); + const ha = ca ? colorHue(ca) : null; + const hb = cb ? colorHue(cb) : null; + if (ha === null && hb === null) { + return a.name.localeCompare(b.name); + } + if (ha === null || hb === null) { + return ha === null ? 1 : -1; + } + return ha - hb || a.name.localeCompare(b.name); + }); + break; + } + case "startDate": { + sorted.sort( + (a, b) => + a.startDate.localeCompare(b.startDate) || + a.name.localeCompare(b.name), + ); + break; + } + case "lastLogged": { + sorted.sort( + (a, b) => + lastLoggedDay(b).localeCompare(lastLoggedDay(a)) || + a.name.localeCompare(b.name), + ); + break; + } + case "time": { + // The day's timeline: habits with a planned time first, + // earliest first (times are stored sorted, so the first entry + // is the earliest), then untimed habits by name. + const first = (habit: HabitDefinition) => habit.times[0] ?? ""; + sorted.sort( + (a, b) => + Number(first(a) === "") - Number(first(b) === "") || + first(a).localeCompare(first(b)) || + a.name.localeCompare(b.name), + ); + break; + } + case "group": { + // Group-mates stay adjacent, ordered by the arranged group + // order; ungrouped habits trail, matching the section order. + // Within a group, the manual order (arranged by dragging in + // the groups manager) wins, then names. + const position = new Map( + groupOrder.map((name, index) => [name, index]), + ); + const cardPosition = new Map( + manualOrder.map((path, index) => [path, index]), + ); + sorted.sort((a, b) => { + const ga = a.group.trim(); + const gb = b.group.trim(); + if (ga === gb) { + const ca = + cardPosition.get(a.path) ?? Number.MAX_SAFE_INTEGER; + const cb = + cardPosition.get(b.path) ?? Number.MAX_SAFE_INTEGER; + return ca - cb || a.name.localeCompare(b.name); + } + if (!ga || !gb) { + return !ga ? 1 : -1; + } + const pa = position.get(ga) ?? Number.MAX_SAFE_INTEGER; + const pb = position.get(gb) ?? Number.MAX_SAFE_INTEGER; + return pa - pb || ga.localeCompare(gb); + }); + break; + } + case "manual": { + const position = new Map( + manualOrder.map((path, index) => [path, index]), + ); + sorted.sort((a, b) => { + const pa = position.get(a.path) ?? Number.MAX_SAFE_INTEGER; + const pb = position.get(b.path) ?? Number.MAX_SAFE_INTEGER; + return pa - pb || a.name.localeCompare(b.name); + }); + break; + } + case "name": + // Already the store's order; nothing to do. + break; + } + return sorted; +} + +/** One visual section of the dashboard when grouping is active. */ +export interface HabitSection { + /** + * Raw section key: the group name, the colour value, or "" for the + * catch-all section (ungrouped or colourless habits). + */ + key: string; + habits: HabitDefinition[]; +} + +/** + * Gather habits into sections by group name, preserving the incoming + * (sorted) order within each section. Sections follow the user's + * arranged `groupOrder`; groups missing from it append alphabetically, + * and the catch-all "ungrouped" section always comes last. When + * grouping is disabled, everything lands in one unnamed section. + */ +export function groupHabits( + habits: HabitDefinition[], + enabled: boolean, + groupOrder: readonly string[] = [], +): HabitSection[] { + if (!enabled) { + return [{ key: "", habits }]; + } + const sections = new Map(); + for (const habit of habits) { + const key = habit.group.trim(); + const bucket = sections.get(key); + if (bucket) { + bucket.push(habit); + } else { + sections.set(key, [habit]); + } + } + const position = new Map( + groupOrder.map((name, index) => [name, index]), + ); + const keys = Array.from(sections.keys()).sort((a, b) => { + // The catch-all section always trails. + if (a === "" || b === "") { + return a === "" ? 1 : -1; + } + const pa = position.get(a) ?? Number.MAX_SAFE_INTEGER; + const pb = position.get(b) ?? Number.MAX_SAFE_INTEGER; + return pa - pb || a.localeCompare(b); + }); + return keys.map((key) => ({ + key, + habits: sections.get(key) as HabitDefinition[], + })); +} + +/** Label for a section header; the catch-all gets a placeholder. */ +export function sectionLabel(key: string): string { + return key || t("Ungrouped"); +} diff --git a/src/managers/__tests__/daily-points.test.ts b/src/managers/__tests__/daily-points.test.ts new file mode 100644 index 000000000..d3af35ef9 --- /dev/null +++ b/src/managers/__tests__/daily-points.test.ts @@ -0,0 +1,41 @@ +import { calculateDailyHabitPoints, pointListItems, pointDate } from "../daily-points"; + +test("YAML date keys returned as Date strings keep their original local day", () => { + expect(pointDate(new Date(2026, 2, 8).toString())).toBe("2026-03-08"); +}); + +const habit = (frontmatter: Record, name = "Writing") => ({ name, path: `Habits/${name}.md`, frontmatter }); + +test("habit rates override panel rules, including zero, and records are recalculated without ledger copies", () => { + const data = { defaultPointRule: { baseRate: 0.1 }, pointRules: [{ habit: "Writing", baseRate: 4 }] }; + const source = habit({ type: "repetition", bravoPoints: 2, records: { "2026-11-01": 3, "2026-11-02": 1 } }); + expect(calculateDailyHabitPoints([source], data, "2026-11-02")[0]).toMatchObject({ rate: 2, points: 8, todayPoints: 2 }); + expect(calculateDailyHabitPoints([habit({ ...source.frontmatter, bravoPoints: 0 })], data)[0].points).toBe(0); + delete source.frontmatter.records["2026-11-01"]; + expect(calculateDailyHabitPoints([source], data)[0].points).toBe(2); +}); + +test("negative rates deduct only excess consumption in the daily or weekly allowance", () => { + const records = { "2026-11-02": 1, "2026-11-03": 2, "2026-11-09": 1 }; + const weekly = habit({ type: "repetition", bravoPoints: -10, target: 2, frequency: "flexibleWeekly", records }); + expect(calculateDailyHabitPoints([weekly], {}, "2026-11-03")[0]).toMatchObject({ points: -10, todayPoints: -10 }); + expect(calculateDailyHabitPoints([habit({ ...weekly.frontmatter, frequency: "daily" })], {})[0].points).toBe(0); +}); + +test("binary check-ins, fractional counters, and disabled defaults retain their original meanings", () => { + expect(calculateDailyHabitPoints([habit({ type: "binary", bravoPoints: 0.5, records: { "2026-11-01": 1, "2026-11-02": 1 } })], {})[0].points).toBe(1); + expect(calculateDailyHabitPoints([habit({ type: "repetition", records: { "2026-11-01": 2.5 } })], {})[0].points).toBe(0.25); + expect(calculateDailyHabitPoints([habit({ type: "binary", records: {} })], { defaultPointRule: { enabled: false } })).toEqual([]); +}); + +test("bonus and reward descriptions remain intact, including debts and items without a price", () => { + const values = ["Read a book + 50", "Create a video", "Furniture - 2000", "Rent - 700 * 6 - 4200"]; + expect(pointListItems(values).map(item => item.text)).toEqual(values); + expect(pointListItems(values).map(item => item.amount)).toEqual([50, null, -2000, -4200]); +}); + + +test("daily point deltas keep a weekly allowance when filtering a recent date range", () => { + const [summary] = calculateDailyHabitPoints([habit({ type: "repetition", frequency: "weekly", target: 3, bravoPoints: -10, records: { "2026-11-02": 3, "2026-11-03": 2, "2026-11-09": 1 } })], {}); + expect(summary.points).toBe(-20);expect(summary.dailyPoints).toEqual({ "2026-11-02": 0, "2026-11-03": -20, "2026-11-09": 0 }); +}); diff --git a/src/managers/__tests__/daily-task-points.test.ts b/src/managers/__tests__/daily-task-points.test.ts new file mode 100644 index 000000000..847a6596e --- /dev/null +++ b/src/managers/__tests__/daily-task-points.test.ts @@ -0,0 +1,38 @@ +import { dailyTaskPoints } from "../daily-task-points"; +import type { Task } from "@/types/task"; +const date = "2026-11-01"; +const task = (id: number, extra: any = {}): Task => ({ id: `task-${id}`, line: id, content: "Task", originalMarkdown: "- [x] Task", filePath: "Tasks.md", completed: true, status: "x", metadata: { tags: [], completedDate: new Date(`${date}T12:00:00`).getTime(), ...extra } }); +const habits = [{ name: "Tasks", path: "Habits/Tasks.md", frontmatter: { habit: true, type: "repetition", bravoHabitMetricKey: "tasks", bravoPoints: 1, records: { [date]: 2 } } }]; + +test("existing daily task check-ins are preserved and only the unrecorded difference earns points", () => { + const result = dailyTaskPoints([task(1),task(2),task(3)],habits,{},[]); + expect(result.rate).toBe(1);expect(result.days[0]).toMatchObject({count:3,points:3,credited:2,supplement:1}); + expect(habits[0].frontmatter.records).toEqual({[date]:2}); + expect(dailyTaskPoints([task(1)],habits,{},[]).days[0].supplement).toBe(0); +}); +test("legacy task award transactions offset the supplement and repeated calculation is idempotent", () => { + const ledger=[{source:"task",delta:1,createdAt:new Date(`${date}T12:00:00`).getTime()}]; + const calculate=()=>dailyTaskPoints([task(1),task(2),task(3),task(4)],habits,{},ledger); + expect(calculate().days[0].supplement).toBe(1);expect(calculate()).toEqual(calculate());expect(ledger).toHaveLength(1); +}); +test("explicit task points, including zero, override the default rate", () => { + const result=dailyTaskPoints([task(1,{points:0}),task(2,{points:5}),task(3)],[],{},[],{},2); + expect(result.days[0].points).toBe(7);expect(result.rate).toBe(2); +}); +test("uncompleted, undated, file tasks, project plans and duplicate index entries earn no extra points", () => { + const source=task(1);const result=dailyTaskPoints([source,source,{...task(2),completed:false},task(3,{completedDate:undefined}),{...task(4),isFileTask:true} as any,task(5,{projectPlan:true}),task(6,{source:"file-source"}),task(7,{completedDate:NaN})],[],{},[]); + expect(result.days).toHaveLength(1);expect(result.days[0]).toMatchObject({count:1,points:1,supplement:1}); +}); +test("undoing a completed task removes its derived supplement and keeps recorded points untouched", () => { + expect(dailyTaskPoints([task(1)],[],{},[]).days[0].supplement).toBe(1); + expect(dailyTaskPoints([{...task(1),completed:false}],[],{},[]).days).toEqual([]); +}); +test("completion-day accounting never moves yesterday's points into today's history", () => { + const result=dailyTaskPoints([task(1),task(2,{completedDate:new Date("2026-11-02T12:00:00").getTime()})],habits,{},[]); + expect(result.days.map(day=>[day.date,day.supplement])).toEqual([["2026-11-02",1],[date,0]]); +}); + +test("backdated completions offset an old award using its completion day rather than its later save date", () => { + const ledger=[{id:`task:task-1:${date}`,source:"task",delta:1,createdAt:new Date("2026-11-03T12:00:00").getTime()}]; + expect(dailyTaskPoints([task(1)],[],{},ledger).days[0]).toMatchObject({date,credited:1,supplement:0}); +}); diff --git a/src/managers/__tests__/points-service.test.ts b/src/managers/__tests__/points-service.test.ts new file mode 100644 index 000000000..a658725f7 --- /dev/null +++ b/src/managers/__tests__/points-service.test.ts @@ -0,0 +1,115 @@ +jest.mock("obsidian", () => ({ + ...jest.requireActual("obsidian"), + getFrontMatterInfo: (text: string) => ({ exists: true, frontmatter: text.split("---\n")[1] }), + parseYaml: (text: string) => JSON.parse(text), + normalizePath: (value: string) => value.replace(/\\/g, "/").replace(/\/+$/, ""), +})); +import { TFile } from "obsidian"; +import { PointsService } from "../points-service"; + +function harness() { + const pointsPath = "99_System/01_Data/积分系统数据.md"; + const entries = new Map(); + const add = (path: string, data: any) => entries.set(path, { file: Object.assign(new TFile(), { path, basename: path.split("/").pop()!.replace(/\.md$/, "") }), data }); + add(pointsPath, { manualPointRecords: [{ id: "old", date: "2026-11-01", text: "Original", points: 10 }], examplePropertyLeft: ["Book + 50"], examplePropertyRight: ["Trip - 5000"], custom: "keep" }); + add("Habits/Exercise.md", { habit: true, type: "binary", bravoPoints: 0.5, records: { "2026-11-01": 1 } }); + const app: any = { vault: { + getAbstractFileByPath: (path: string) => entries.get(path)?.file, + getMarkdownFiles: () => [...entries.values()].map(entry => entry.file), + read: async (file: TFile) => `---\n${JSON.stringify(entries.get(file.path)!.data)}---\nBody`, + }, fileManager: { processFrontMatter: jest.fn(async (file: TFile, update: (data: any) => void) => update(entries.get(file.path)!.data)) }, workspace: { trigger: jest.fn() } }; + const plugin: any = { app, settings: { rewards: { rewardItems: [], pointsLedger: [] } }, saveSettings: jest.fn(async () => {}) }; + return { app, plugin, service: new PointsService(app, plugin), entries, pointsPath }; +} + +test("the native page reads the original records and lists, including habit-derived points", async () => { + const { service } = harness(); + const snapshot = await service.snapshot(); + expect(snapshot.balance).toBe(10.5); + expect(snapshot.manual).toHaveLength(1); + expect(snapshot.bonuses[0].text).toBe("Book + 50"); + expect(snapshot.wishes[0].text).toBe("Trip - 5000"); +}); + +test("new manual records preserve the original records, lists and unrelated properties", async () => { + const { service, entries, pointsPath } = harness(); + await service.addRecord("New", -2, "2026-11-02"); + const data = entries.get(pointsPath)!.data; + expect(data.manualPointRecords[0].id).toBe("old"); + expect(data.manualPointRecords).toHaveLength(2); + expect(data.custom).toBe("keep"); + expect(data.examplePropertyLeft).toEqual(["Book + 50"]); + expect(data.examplePropertyRight).toEqual(["Trip - 5000"]); +}); + +test("concurrent redemptions recheck the balance and cannot spend it twice", async () => { + const { service } = harness(); + const outcomes = await Promise.allSettled([service.redeem("Reward", 8), service.redeem("Reward", 8)]); + expect(outcomes.map(item => item.status)).toEqual(["fulfilled", "rejected"]); + expect((await service.snapshot()).balance).toBe(2.5); +}); + +test("editing a habit's point rule never overwrites its check-in history", async () => { + const { service, entries } = harness(); + await service.saveHabitRate("Habits/Exercise.md", 2); + expect(entries.get("Habits/Exercise.md")!.data.records).toEqual({ "2026-11-01": 1 }); + expect((await service.snapshot()).balance).toBe(12); +}); + +test("a failed inventory save cannot charge the Markdown ledger", async () => { + const { service, plugin } = harness(); + plugin.settings.rewards.rewardItems = [{ id: "stock", inventory: 1, pointCost: 2 }]; + plugin.saveSettings.mockRejectedValueOnce(new Error("save failed")); + await expect(service.redeem("Stock", 2, "stock")).rejects.toThrow("save failed"); + expect((await service.snapshot()).manual).toHaveLength(1); + expect(plugin.settings.rewards.rewardItems[0].inventory).toBe(1); +}); + +test("a failed ledger write restores a finite reward's inventory", async () => { + const { service, plugin, app } = harness(); + plugin.settings.rewards.rewardItems = [{ id: "stock", inventory: 1, pointCost: 2 }]; + app.fileManager.processFrontMatter.mockRejectedValueOnce(new Error("ledger failed")); + await expect(service.redeem("Stock", 2, "stock")).rejects.toThrow("ledger failed"); + expect(plugin.settings.rewards.rewardItems[0].inventory).toBe(1); + expect((await service.snapshot()).manual).toHaveLength(1); +}); + + +test("task index refresh adds daily task points without changing habit records or ledger files", async () => { + const {service,plugin,entries}=harness();const before=JSON.stringify([...entries.values()].map(entry=>entry.data)); + plugin.dataflowOrchestrator={getQueryAPI:()=>({getAllTasks:async()=>[{id:"t",line:1,filePath:"Tasks.md",completed:true,metadata:{completedDate:new Date("2026-11-02T12:00:00").getTime()},originalMarkdown:"- [x] Task"}]})}; + const first=await service.snapshot();expect(first.balance).toBe(11.5);expect(first.automaticTasks.days[0].supplement).toBe(1); + expect((await service.snapshot()).balance).toBe(11.5);expect(JSON.stringify([...entries.values()].map(entry=>entry.data))).toBe(before); +}); + + +test("bulk reward text edits preserve metadata, unrelated rewards and the original ledger", async () => { + const {service,plugin,entries,pointsPath}=harness(); + const old={id:"tea",name:"Tea",pointCost:20,inventory:3,occurrence:"rare",imageUrl:"keep.png",condition:"#milestone"}; + const random={id:"random",name:"Random",inventory:-1,occurrence:"common"};plugin.settings.rewards.rewardItems=[random,old]; + const {rewardCatalogRows}=await import('../reward-catalog'); + await service.saveRewardCatalog('Tea -25 | 2\nTrip -5000\nNew -10',rewardCatalogRows(['Trip - 5000'],plugin.settings.rewards.rewardItems)); + expect(plugin.settings.rewards.rewardItems).toEqual([random,{...old,pointCost:25,inventory:2}]); + expect(entries.get(pointsPath)!.data).toMatchObject({custom:"keep",examplePropertyLeft:["Book + 50"],examplePropertyRight:["Trip -5000","New -10"],manualPointRecords:[{id:"old",points:10}]}); +}); + +test("failed catalog writes restore reward inventory and do not change point history", async () => { + const {service,plugin,app,entries,pointsPath}=harness(); + const old={id:"tea",name:"Tea",pointCost:20,inventory:3,occurrence:"rare"};plugin.settings.rewards.rewardItems=[old]; + const {rewardCatalogRows}=await import('../reward-catalog'); + const original=rewardCatalogRows(['Trip - 5000'],plugin.settings.rewards.rewardItems); + app.fileManager.processFrontMatter.mockRejectedValueOnce(new Error('write failed')); + await expect(service.saveRewardCatalog('Trip -100\nTea -30 | 1',original)).rejects.toThrow('write failed'); + expect(plugin.settings.rewards.rewardItems).toEqual([old]);expect(entries.get(pointsPath)!.data.examplePropertyRight).toEqual(['Trip - 5000']); + plugin.saveSettings.mockRejectedValueOnce(new Error('settings failed')); + await expect(service.saveRewardCatalog('Trip -100\nTea -30 | 1',original)).rejects.toThrow('settings failed'); + expect(plugin.settings.rewards.rewardItems).toEqual([old]);expect((await service.snapshot()).manual).toHaveLength(1); +}); + +test("a redemption while the catalog is open cannot be overwritten by stale inventory", async () => { + const {service,plugin}=harness();plugin.settings.rewards.rewardItems=[{id:'tea',name:'Tea',pointCost:2,inventory:3,occurrence:'common'}]; + const {rewardCatalogRows}=await import('../reward-catalog');const original=rewardCatalogRows(['Trip - 5000'],plugin.settings.rewards.rewardItems); + await service.redeem('Tea',2,'tea'); + await expect(service.saveRewardCatalog('Trip -100\nTea -2 | 3',original)).rejects.toThrow('Rewards changed'); + expect(plugin.settings.rewards.rewardItems[0].inventory).toBe(2);expect((await service.snapshot()).manual).toHaveLength(2); +}); diff --git a/src/managers/__tests__/project-file-manager.test.ts b/src/managers/__tests__/project-file-manager.test.ts new file mode 100644 index 000000000..efe4fd5b5 --- /dev/null +++ b/src/managers/__tests__/project-file-manager.test.ts @@ -0,0 +1,153 @@ +import { App, TFile, TFolder } from "obsidian"; +import { ProjectFileManager } from "../project-file-manager"; +import { buildProjectPlan } from "../project-plan"; +import { saveCapture } from "@/utils/file/file-operations"; +import { filterTasks } from "@/utils/task/task-filter-utils"; + +test("deleting a project trashes only its canonical note and preserves other notes", async () => { + const { app, files, addFile } = createVaultHarness(); + addFile("Projects/Research.md", "- [ ] Research", { project: "Research" }); + addFile("Inbox.md", "- [ ] Unrelated"); + app.fileManager.trashFile = jest.fn(async (file: TFile) => { files.delete(file.path); }); + expect(await new ProjectFileManager(app).remove("Research")).toBe(true); + expect(app.fileManager.trashFile).toHaveBeenCalledWith(expect.objectContaining({ path: "Projects/Research.md" })); + expect(files.get("Inbox.md")?.text).toBe("- [ ] Unrelated"); +}); + +function createVaultHarness() { + const app = new App() as any; + const files = new Map }>(); + const folder = Object.assign(new TFolder(), { path: "Projects" }); + app.vault.getAbstractFileByPath = (path: string) => path === "Projects" ? folder : files.get(path)?.file || null; + app.vault.getMarkdownFiles = () => [...files.values()].map(value => value.file); + app.vault.createFolder = jest.fn(async () => folder); + app.vault.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: path.split("/").pop()?.replace(/\.md$/, "") } }); + return file; + }); + app.vault.read = jest.fn(async (file: TFile) => files.get(file.path)!.text); + app.vault.modify = jest.fn(async (file: TFile, text: string) => { files.get(file.path)!.text = text; }); + app.vault.process = jest.fn(async (file: TFile, update: (text: string) => string) => { + const entry = files.get(file.path)!; + entry.text = update(entry.text); + }); + app.metadataCache.getFileCache = (file: TFile) => ({ frontmatter: files.get(file.path)?.fm }); + app.fileManager.processFrontMatter = jest.fn(async (file: TFile, update: (fm: Record) => void) => { + const entry = files.get(file.path)!; + entry.fm ||= {}; + update(entry.fm); + }); + const addFile = (path: string, text: string, fm: Record = {}) => { + const file = Object.assign(new TFile(), { path, name: path.split("/").pop() || path }); + files.set(path, { file, text, fm }); + return file; + }; + return { app, files, addFile }; +} + +describe("project Markdown files", () => { + test("archived project tasks are excluded by the common task filter", () => { + const { app, addFile } = createVaultHarness(); + addFile("Tasks/Projects/Active.md", "", { project: "Active" }); + addFile("Tasks/Projects/Done.md", "", { project: "Done", archived: true }); + const tasks = ["Active", "Done"].map(name => ({ id: name, content: name, completed: false, status: " ", metadata: { project: name, tags: [], children: [] } } as any)); + const plugin = { app, settings: { viewConfiguration: [{ id: "projects", name: "Projects", type: "default", filterRules: {}, filterBlanks: false, hideCompletedAndAbandonedTasks: false }], taskStatuses: { completed: "x", abandoned: "-" } } } as any; + expect(filterTasks(tasks, "projects", plugin, {}).map(task => task.id)).toEqual(["Active"]); + }); + test("existing project notes outside Projects can be edited and archived, and project plans contain only projects", async () => { + const { app, addFile } = createVaultHarness(); + addFile("Tasks/Projects/Research.md", "# Research", { project: "Research", startDate: "2026-11-01", dueDate: "2026-11-10" }); + addFile("Tasks/Archive/Done.md", "# Done", { project: "Done", archived: true }); + const manager = new ProjectFileManager(app); + expect(manager.find("Research")?.file.path).toBe("Tasks/Projects/Research.md"); + const plans = buildProjectPlan(app, [{ id: "ordinary", content: "Unassigned task", metadata: {} } as any]); + expect(plans.map(project => project.content)).toEqual(["Research"]); + expect(plans[0].metadata.projectPlan).toBe(true); + await manager.update("Research", { name: "New Research", description: "Updated" }); + expect(manager.find("New Research")?.description).toBe("Updated"); + await manager.setArchived("New Research", true); + expect(buildProjectPlan(app, [])).toEqual([]); + }); + + test("quick capture saves a project task in its note and strips inline ownership markers", async () => { + const { app, files, addFile } = createVaultHarness(); + addFile("Inbox.md", "Original inbox"); + await saveCapture(app, "- [ ] Draft #project/Old", { targetFile: "Inbox.md", project: "Writing", appendToFile: "append" } as any); + expect(files.get("Inbox.md")?.text).toBe("Original inbox"); + expect(files.get("Projects/Writing.md")?.text).toContain("- [ ] Draft"); + expect(files.get("Projects/Writing.md")?.text).not.toContain("#project/"); + }); + test("creates project notes with canonical properties and archives them", async () => { + const { app, files } = createVaultHarness(); + const manager = new ProjectFileManager(app); + const project = await manager.create("Research Plan", "A short description"); + expect(project?.file.path).toBe("Projects/Research-Plan.md"); + expect(files.get("Projects/Research-Plan.md")?.text).toContain('project: "Research Plan"'); + await manager.setArchived("Research Plan", true); + expect(manager.find("Research Plan")?.archived).toBe(true); + }); + + test("moves a parent and its subtasks together", async () => { + const { app, files, addFile } = createVaultHarness(); + const source = addFile("Notes.md", "# Notes\n- [ ] Parent task\n - [ ] Child task\n- [ ] Keep this task\n"); + const manager = new ProjectFileManager(app); + await manager.create("Writing"); + const moved = await manager.moveTask({ id: "task-1", filePath: source.path, line: 1, originalMarkdown: "- [ ] Parent task" } as any, "Writing"); + expect(moved).toBe(true); + expect(files.get("Notes.md")?.text).toContain("Keep this task"); + expect(files.get("Notes.md")?.text).not.toContain("Parent task"); + expect(files.get("Projects/Writing.md")?.text).toContain("- [ ] Parent task\n - [ ] Child task"); + }); + + test("moving a task retains its indented notes, blank lines, and subtasks", async () => { + const { app, files, addFile } = createVaultHarness(); + const source = addFile("Notes.md", "- [ ] Parent #project/Old\n Details mentioning #project/reference\n\n - [ ] Child\n- [ ] Keep\n"); + const manager = new ProjectFileManager(app); + await manager.moveTask({ id: "root", filePath: source.path, line: 0, originalMarkdown: "- [ ] Parent #project/Old" } as any, "Writing"); + expect(files.get("Projects/Writing.md")?.text).toContain("- [ ] Parent\n Details mentioning #project/reference\n\n - [ ] Child"); + expect(files.get("Notes.md")?.text).toBe("- [ ] Keep\n"); + }); + + test("removes legacy project properties and tags from the moved task block", async () => { + const { app, files, addFile } = createVaultHarness(); + const source = addFile("Notes.md", "- [ ] Parent #project/Writing [project:: Writing]\n - [ ] Child #project/Writing\n"); + const manager = new ProjectFileManager(app); + await manager.create("Writing"); + await manager.moveTask({ id: "task-1", filePath: source.path, line: 0, originalMarkdown: "- [ ] Parent #project/Writing [project:: Writing]" } as any, "Writing"); + const destination = files.get("Projects/Writing.md")?.text || ""; + expect(destination).toContain("- [ ] Parent"); + expect(destination).not.toContain("#project/Writing"); + expect(destination).not.toContain("[project::"); + }); + + test("refuses to treat Canvas JSON files as Markdown task sources", async () => { + const { app } = createVaultHarness(); + const manager = new ProjectFileManager(app); + await expect(manager.moveTasks([{ + id: "canvas-task", + filePath: "Board.canvas", + metadata: { sourceType: "canvas" }, + } as any], "Writing")).rejects.toThrow("Canvas tasks must be moved through Task Genius."); + }); test("restores the source note if appending to the project fails", async () => { + const { app, files, addFile } = createVaultHarness(); + const original = "- [ ] Parent task\n - [ ] Child task\n- [ ] Keep task\n"; + const source = addFile("Notes.md", original); + const manager = new ProjectFileManager(app); + const project = await manager.create("Writing"); + app.vault.modify.mockImplementation(async (file: TFile, text: string) => { + if (file.path === project?.file.path) throw new Error("disk write failed"); + files.get(file.path)!.text = text; + }); + await expect(manager.moveTask({ id: "task-1", filePath: source.path, line: 0, originalMarkdown: "- [ ] Parent task" } as any, "Writing")).rejects.toThrow("disk write failed"); + expect(files.get("Notes.md")?.text).toBe(original); + }); +}); + + +test("daily capture writes the selected diary date instead of always using today", async () => { + const { app, files } = createVaultHarness(); + app.vault.getFileByPath = (path: string) => files.get(path)?.file || null; + await saveCapture(app, "- [ ] On the selected day", { targetType: "daily-note", dailyNoteDate: "2026-12-25", appendToFile: "append", dailyNoteSettings: { folder: "Journal", format: "YYYY-MM-DD", template: "" } }); + expect(files.get("Journal/2026-12-25.md")?.text).toContain("On the selected day"); +}); diff --git a/src/managers/__tests__/reward-catalog.test.ts b/src/managers/__tests__/reward-catalog.test.ts new file mode 100644 index 000000000..6a4fa4b36 --- /dev/null +++ b/src/managers/__tests__/reward-catalog.test.ts @@ -0,0 +1,16 @@ +import {parseRewardCatalog,rewardCatalogRows} from '../reward-catalog'; +const tea={id:'tea',name:'Tea',pointCost:20,inventory:3,occurrence:'rare',imageUrl:'tea.png'}; +test('reordering and editing stock preserves reward identity and custom properties',()=>{ + const result=parseRewardCatalog('Tea -25 | 2\nTrip -100',rewardCatalogRows(['Trip -5000'],[tea])); + expect(result).toEqual({wishes:['Trip -100'],rewards:[{...tea,pointCost:25,inventory:2}]}); +}); +test('renaming a reward in place preserves its ID; removing lines removes the item',()=>{ + const original=rewardCatalogRows(['Trip -5000'],[tea]); + expect(parseRewardCatalog('Trip -5000\nGreen tea -25 | 3',original).rewards[0]).toEqual({...tea,name:'Green tea',pointCost:25}); + expect(parseRewardCatalog('',original)).toEqual({wishes:[],rewards:[]}); +}); +test('new finite rewards, unlimited stock, plain wishes and decimal costs are accepted',()=>{ + const result=parseRewardCatalog('Future trip\nWalk -2.5\nCoffee -10 | 2\nBook -15 | -1',[]); + expect(result.wishes).toEqual(['Future trip','Walk -2.5']);expect(result.rewards.map(r=>[r.name,r.pointCost,r.inventory])).toEqual([['Coffee',10,2],['Book',15,-1]]); +}); +test.each(['Tea -0 | 3','Tea -10 | -2','Tea -10 | 1.5','Tea -10 | abc','Tea | 3','Tea -10 | 99999999999999999'])('invalid reward line %s cannot be saved',(line: string)=>expect(()=>parseRewardCatalog(line,[])).toThrow()); diff --git a/src/managers/daily-points.ts b/src/managers/daily-points.ts new file mode 100644 index 000000000..cbfd34bad --- /dev/null +++ b/src/managers/daily-points.ts @@ -0,0 +1,90 @@ +/** Calculation shared by the native check-in page and its settings page. */ +export interface DailyHabitInput { + name: string; + path: string; + frontmatter: Record; +} +export interface HabitPointSummary { + name: string; + path: string; + rate: number; + units: number; + points: number; + todayPoints: number; + dailyPoints: Record; + dailyEntries: Record; + entries: number; + source: "habit" | "rule" | "default"; +} +export const pointNumber = (value: unknown, fallback = 0): number => { + const parsed = Number(value); + return Number.isFinite(parsed) ? parsed : fallback; +}; +export const roundPoints = (value: number): number => Math.round((value + Number.EPSILON) * 10000) / 10000; +export function pointDate(value: unknown): string { + if (value instanceof Date) return localPointDate(value); + const text = String(value ?? "").trim(); + if (/^\d{4}-\d{2}-\d{2}$/.test(text)) return text; + const parsed = new Date(text); + return Number.isNaN(parsed.getTime()) ? text : localPointDate(parsed); +} +export function localPointDate(date = new Date()): string { + return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; +} +function periodKey(day: string, frequency: string): string { + if (/Monthly$|^monthly$/.test(frequency)) return day.slice(0, 7); + if (/Weekly$|^weekly$/.test(frequency)) { + const [y, m, d] = day.split("-").map(Number); + const date = new Date(Date.UTC(y, m - 1, d)); + date.setUTCDate(date.getUTCDate() - (date.getUTCDay() + 6) % 7); + return date.toISOString().slice(0, 10); + } + return day; +} +export function calculateDailyHabitPoints( + habits: DailyHabitInput[], data: Record, today = localPointDate(), + keys: Record = {}, +): HabitPointSummary[] { + const defaults = data.defaultPointRule ?? {}; + const rules = Array.isArray(data.pointRules) ? data.pointRules : []; + return habits.flatMap(habit => { + const fm = habit.frontmatter; + const rule = rules.find((entry: any) => (entry.habit ?? entry.name) === habit.name); + const hasOverride = Object.prototype.hasOwnProperty.call(fm, "bravoPoints"); + if (!hasOverride && !rule && defaults.enabled === false) return []; + const rate = pointNumber(hasOverride ? fm.bravoPoints : rule ? rule.baseRate ?? rule.pointsPerUnit : defaults.baseRate ?? defaults.pointsPerUnit, hasOverride || rule ? 0 : 0.1); + const records = Object.entries(fm[keys.records || "records"] || {}).map(([day, value]) => ({ day: pointDate(day), value: pointNumber(value) })).filter(entry => /^\d{4}-\d{2}-\d{2}$/.test(entry.day) && entry.value !== 0); + const type = fm[keys.type || "type"]; + const count = type === "binary" || type !== "repetition" && !records.some(entry => Math.abs(entry.value) !== 1); + const allowance = rate < 0 ? Math.max(0, pointNumber(fm[keys.target || "target"])) : 0; + const frequency = String(fm[keys.frequency || "frequency"] || "daily"); + const total = (entries: typeof records) => { + const periods = new Map(); + for (const entry of entries) { + const key = periodKey(entry.day, frequency); + periods.set(key, (periods.get(key) || 0) + (count ? 1 : Math.max(0, entry.value))); + } + return roundPoints([...periods.values()].reduce((sum, units) => sum + Math.max(0, units - allowance) * rate, 0)); + }; + const points = total(records); + const cumulative = new Map(), dailyPoints: Record = {}; + for (const entry of records.slice().sort((a, b) => a.day.localeCompare(b.day))) { + const key = periodKey(entry.day, frequency), previous = cumulative.get(key) || 0; + const units = previous + (count ? 1 : Math.max(0, entry.value)); cumulative.set(key, units); + dailyPoints[entry.day] = roundPoints((dailyPoints[entry.day] || 0) + (Math.max(0, units - allowance) - Math.max(0, previous - allowance)) * rate); + } + return [{ name: habit.name, path: habit.path, rate, entries: records.length, + units: roundPoints(records.reduce((sum, entry) => sum + (count ? 1 : entry.value), 0)), + points, dailyPoints, dailyEntries: Object.fromEntries(records.map(entry => [entry.day, 1])), todayPoints: roundPoints(points - total(records.filter(entry => entry.day !== today))), + source: hasOverride ? "habit" as const : rule ? "rule" as const : "default" as const }]; + }); +} +export interface PointListItem { text: string; amount: number | null; index: number; } +/** Keep the original wording; the final signed number is only an action hint. */ +export function pointListItems(values: unknown): PointListItem[] { + return (Array.isArray(values) ? values : []).map((value, index) => { + const text = String(value); + const match = text.match(/([+\-−])\s*(\d+(?:\.\d+)?)\s*$/); + return { text, index, amount: match ? (match[1] === "+" ? 1 : -1) * Number(match[2]) : null }; + }); +} diff --git a/src/managers/daily-task-points.ts b/src/managers/daily-task-points.ts new file mode 100644 index 000000000..a8db21808 --- /dev/null +++ b/src/managers/daily-task-points.ts @@ -0,0 +1,36 @@ +import type { Task } from "@/types/task"; +import { calculateDailyHabitPoints, DailyHabitInput, localPointDate, pointDate, pointNumber, roundPoints } from "./daily-points"; +import { resolveTaskPoints, pointLedgerDate } from "./points-utils"; + +export interface DailyTaskPoints { date: string; count: number; points: number; credited: number; supplement: number; } +interface LedgerEntry { id?: string; source: string; delta: number; createdAt: number; } + +/** Supplement recorded daily task totals, without rewriting any original check-in. */ +export function dailyTaskPoints(tasks: Task[], habits: DailyHabitInput[], data: Record, ledger: LedgerEntry[], keys: Record = {}, configuredRate = 0) { + const metricHabits = habits.filter(habit => habit.frontmatter.bravoHabitMetricKey === "tasks"); + const metricRate = calculateDailyHabitPoints(metricHabits, data, localPointDate(), keys).find(summary => summary.rate > 0)?.rate; + const rate = configuredRate > 0 ? configuredRate : metricRate ?? 1; + const days = new Map(); + const seen = new Set(); + for (const task of tasks) { + const metadata = task.metadata; + if (!task.completed || !metadata?.completedDate || (task as any).isFileTask || metadata.projectPlan || + metadata.source === "file-source" || /^(file-source:|project-plan:|ics:)/.test(task.id) || !task.filePath?.toLowerCase().endsWith(".md")) continue; + const rawDate = metadata.completedDate; + const date = typeof rawDate === "number" ? localPointDate(new Date(rawDate)) : pointDate(rawDate); + if (!/^\d{4}-\d{2}-\d{2}$/.test(date) || !Number.isFinite(new Date(`${date}T00:00:00`).getTime()) || date > localPointDate()) continue; + const identity = `${task.filePath}:${task.line}`; + if (seen.has(identity)) continue; + seen.add(identity); + const points = resolveTaskPoints(task, rate); + const day = days.get(date) || { date, count: 0, points: 0, credited: 0, supplement: 0 }; + day.count++; day.points = roundPoints(day.points + points); days.set(date, day); + } + for (const day of days.values()) { + const recorded = calculateDailyHabitPoints(metricHabits, data, day.date, keys).reduce((sum, summary) => sum + Math.max(0, summary.todayPoints), 0); + const transactions = ledger.filter(entry => entry.source === "task" && pointLedgerDate(entry) === day.date).reduce((sum, entry) => sum + pointNumber(entry.delta), 0); + day.credited = roundPoints(recorded + transactions); + day.supplement = roundPoints(Math.max(0, day.points - day.credited)); + } + return { rate, habitPaths: metricHabits.map(habit => habit.path), days: [...days.values()].sort((a, b) => b.date.localeCompare(a.date)) }; +} diff --git a/src/managers/icon-manager.ts b/src/managers/icon-manager.ts index 8c64b9fe2..ed02d1bf3 100644 --- a/src/managers/icon-manager.ts +++ b/src/managers/icon-manager.ts @@ -1,3 +1,4 @@ +import { getPausedTaskMarks } from "@/utils/status-cycle-resolver"; import { Component } from "obsidian"; import TaskProgressBarPlugin from "../index"; import { getStatusIcon } from "../icon"; @@ -19,6 +20,7 @@ export class TaskGeniusIconManager extends Component { } async onload() { + this.installPauseIcons(); // Initialize if enabled if (this.plugin.settings.enableTaskGeniusIcons) { this.enable(); @@ -27,6 +29,47 @@ export class TaskGeniusIconManager extends Component { onunload() { this.disable(); + document.getElementById("task-genius-pause-icons")?.remove(); + document.body.classList.remove("task-genius-pause-icons"); + } + + private installPauseIcons(): void { + document.getElementById("task-genius-pause-icons")?.remove(); + const style = document.createElement("style"); + style.id = "task-genius-pause-icons"; + const encoded = this.encodeSvgForCSS(getStatusIcon("pause")); + const marks = getPausedTaskMarks(this.plugin.settings); + style.textContent = marks.map(mark => { + const selector = JSON.stringify(mark); + const inputs = [ + `body.task-genius-pause-icons [data-task=${selector}] > input[type=checkbox]`, + `body.task-genius-pause-icons [data-task=${selector}] > p > input[type=checkbox]`, + `body.task-genius-pause-icons input[type=checkbox][data-task=${selector}]`, + ]; + return ` +${inputs.join(",\n")} { + appearance: none !important; + position: relative; + background: transparent !important; + border: 0 !important; +} +${inputs.map(input => input + "::before").join(",\n")} { + display: none !important; +} +${inputs.map(input => input + "::after").join(",\n")} { + content: "" !important; + display: block !important; + position: absolute; + inset: 0 !important; + width: var(--checkbox-size, 16px) !important; + height: var(--checkbox-size, 16px) !important; + background: var(--text-muted) !important; + mask: url("${encoded}") center / contain no-repeat !important; + -webkit-mask: url("${encoded}") center / contain no-repeat !important; +}`; + }).join("\n"); + document.body.classList.add("task-genius-pause-icons"); + document.head.appendChild(style); } /** @@ -57,6 +100,7 @@ export class TaskGeniusIconManager extends Component { * Update functionality when settings change */ update() { + this.installPauseIcons(); if (this.plugin.settings.enableTaskGeniusIcons) { this.enable(); } else { @@ -147,7 +191,7 @@ export class TaskGeniusIconManager extends Component { | "inProgress" | "completed" | "abandoned" - | "planned"; + | "planned" | "archived"; chars: string[]; }> { const result: Array<{ @@ -156,19 +200,22 @@ export class TaskGeniusIconManager extends Component { | "inProgress" | "completed" | "abandoned" - | "planned"; + | "planned" | "archived"; chars: string[]; }> = []; const statusMap: Record< string, - "notStarted" | "inProgress" | "completed" | "abandoned" | "planned" + "notStarted" | "inProgress" | "completed" | "abandoned" | "planned" | "archived" > = { notStarted: "notStarted", inProgress: "inProgress", completed: "completed", abandoned: "abandoned", planned: "planned", + archived: "archived", + paused: "archived", + pause: "archived", }; for (const [statusKey, charString] of Object.entries( diff --git a/src/managers/period-notes.ts b/src/managers/period-notes.ts new file mode 100644 index 000000000..d138ebd38 --- /dev/null +++ b/src/managers/period-notes.ts @@ -0,0 +1,50 @@ +import { App, TFile, normalizePath, moment } from "obsidian"; +export type NotePeriod = "daily" | "weekly" | "monthly" | "yearly"; +const defaults = { daily: "YYYY-MM-DD", weekly: "GGGG-[W]WW", monthly: "YYYY-MM", yearly: "YYYY" }; +const pending = new WeakMap>>(); +async function readConfig(app: App, file: string): Promise { + try { return JSON.parse(await app.vault.adapter.read(`${app.vault.configDir}/${file}`)); } catch { return {}; } +} +/** Use the user's existing Periodic Notes / Calendar / Daily Notes folders and templates. */ +export async function openPeriodNote(app: App, period: NotePeriod, date: Date): Promise { + const plugins = (app as any).plugins; + const settings = plugins?.getPlugin?.("periodic-notes")?.settings || await readConfig(app, "plugins/periodic-notes/data.json"); + let config = settings[period]; + if (!config || config.enabled === false) { + if (period === "daily") config = (app as any).internalPlugins?.getPluginById?.("daily-notes")?.instance?.options || await readConfig(app, "daily-notes.json"); + else if (period === "weekly") { const calendar = await readConfig(app, "plugins/calendar/data.json"); config = { format: calendar.weeklyNoteFormat, folder: calendar.weeklyNoteFolder, template: calendar.weeklyNoteTemplate }; } + } + config ||= {}; + const day = moment(date), title = day.format(config.format || defaults[period]); + const path = normalizePath(`${config.folder ? config.folder + "/" : ""}${title}.md`); + if (path.split("/").some(segment => segment === "..") || /^[A-Za-z]:/.test(path)) throw new Error("Invalid periodic note path"); + let operations = pending.get(app); if (!operations) { operations = new Map(); pending.set(app, operations); } + let operation = operations.get(path); + if (!operation) { + operation = (async () => { + const existing = app.vault.getAbstractFileByPath(path); + if (existing instanceof TFile) return existing; + if (existing) throw new Error("The periodic note path is occupied by a folder"); + let content = ""; + if (config.template) { + const templatePath = normalizePath(String(config.template).replace(/\.md$/i, "") + ".md"); + const template = app.vault.getAbstractFileByPath(templatePath); + if (!(template instanceof TFile)) throw new Error(`Template not found: ${templatePath}`); + content = await app.vault.read(template); + content = content.replace(/\{\{date(?::([^}]+))?\}\}/gi, (_match, format) => day.format(format || "YYYY-MM-DD")) + .replace(/\{\{time(?::([^}]+))?\}\}/gi, (_match, format) => moment().format(format || "HH:mm")) + .replace(/\{\{title\}\}/gi, () => title.split("/").pop() || title); + } + const parts = path.split("/"); parts.pop(); + for (let index = 1; index <= parts.length; index++) { + const folder = parts.slice(0, index).join("/"); + if (!app.vault.getAbstractFileByPath(folder)) { try { await app.vault.createFolder(folder); } catch (error) { if (!app.vault.getAbstractFileByPath(folder)) throw error; } } + } + const raced = app.vault.getAbstractFileByPath(path); + return raced instanceof TFile ? raced : app.vault.create(path, content); + })(); + operations.set(path, operation); + } + try { const file = await operation; await app.workspace.getLeaf(false).openFile(file); return file; } + finally { operations.delete(path); } +} diff --git a/src/managers/points-service.ts b/src/managers/points-service.ts new file mode 100644 index 000000000..4d362e3b1 --- /dev/null +++ b/src/managers/points-service.ts @@ -0,0 +1,151 @@ +import { pointLedgerDate } from "./points-utils"; +import { dailyTaskPoints } from "./daily-task-points"; +import { App, getFrontMatterInfo, normalizePath, parseYaml, TFile } from "obsidian"; +import type TaskProgressBarPlugin from "@/index"; +import { calculateDailyHabitPoints, localPointDate, pointDate, pointListItems, pointNumber, roundPoints } from "./daily-points"; +import { t } from "@/translations/helper"; +import { parseRewardCatalog, RewardCatalogRow, rewardCatalogRows } from "./reward-catalog"; + +export interface ManualPointRecord { + id: string; date: string; text: string; points: number; source: string; createdAt: string; + [key: string]: unknown; +} +const services = new WeakMap(); +export function pointsService(plugin: TaskProgressBarPlugin): PointsService { + let service = services.get(plugin); + if (!service) { service = new PointsService(plugin.app, plugin); services.set(plugin, service); } + return service; +} + +export class PointsService { + private writes: Promise = Promise.resolve(); + constructor(private app: App, private plugin: TaskProgressBarPlugin) {} + get dataPath(): string { + const configured = this.plugin.settings.rewards.pointsDataFile?.trim(); + if (configured) { + if (/^(?:[a-zA-Z]:|[\\/])/.test(configured) || configured.split(/[\\/]/).includes("..")) throw new Error(t("Choose a Markdown file inside the vault.")); + return normalizePath(configured); + } + const legacy = "99_System/01_Data/积分系统数据.md"; + return this.app.vault.getAbstractFileByPath(legacy) ? legacy : "Task Genius/Points.md"; + } + private async read(file: TFile): Promise> { + const text = await this.app.vault.read(file); + const info = getFrontMatterInfo(text); + const data = info.exists ? parseYaml(info.frontmatter) : {}; + return data && typeof data === "object" ? data : {}; + } + async snapshot() { + const file = this.app.vault.getAbstractFileByPath(this.dataPath); + const data = file instanceof TFile ? await this.read(file) : {}; + const config = this.plugin.habitsIntegration?.settings || this.plugin.settings.habitsIntegration; + const folder = normalizePath(config?.habitsFolder || "Habits"); + const keys = { type: "type", records: "records", target: "target", frequency: "frequency", ...config?.frontmatterKeys }; + const habits = await Promise.all(this.app.vault.getMarkdownFiles().filter(note => note.path.startsWith(`${folder}/`)).map(async note => ({ name: note.basename, path: note.path, frontmatter: await this.read(note) }))); + const defined = habits.filter(habit => habit.frontmatter.habit || ["binary", "repetition", "timed", "note"].includes(habit.frontmatter[keys.type])); + const today = localPointDate(); + const summaries = calculateDailyHabitPoints(defined, data, today, keys); + const manual: ManualPointRecord[] = (Array.isArray(data.manualPointRecords) ? data.manualPointRecords : []).map((record: any, index: number) => ({ ...record, id: String(record.id ?? `legacy-${index}`), date: pointDate(record.date), text: String(record.text ?? ""), points: pointNumber(record.points), source: String(record.source || "manual"), createdAt: String(record.createdAt || "") })); + const ledger = this.plugin.settings.rewards.pointsLedger || []; + const tasks = this.plugin.dataflowOrchestrator ? await this.plugin.dataflowOrchestrator.getQueryAPI().getAllTasks() : []; + const automaticTasks = dailyTaskPoints(tasks, defined, data, ledger, keys, Number(this.plugin.settings.rewards.pointsPerTask ?? 0)); + const extra = automaticTasks.days.reduce((sum, item) => sum + item.supplement, 0); + const todayExtra = automaticTasks.days.find(item => item.date === today)?.supplement || 0; + const balance = roundPoints(extra + summaries.reduce((sum, item) => sum + item.points, 0) + manual.reduce((sum, item) => sum + item.points, 0) + ledger.reduce((sum, entry) => sum + entry.delta, 0)); + const todayPoints = roundPoints(todayExtra + summaries.reduce((sum, item) => sum + item.todayPoints, 0) + manual.filter(item => item.date === today).reduce((sum, item) => sum + item.points, 0) + ledger.filter(entry => pointLedgerDate(entry) === today).reduce((sum, entry) => sum + entry.delta, 0)); + return { automaticTasks, data, file, path: this.dataPath, summaries, manual, ledger, balance, todayPoints, + bonuses: pointListItems(data.examplePropertyLeft), wishes: pointListItems(data.examplePropertyRight), + habitCount: defined.length, recordCount: defined.reduce((sum, item) => sum + Object.keys(item.frontmatter[keys.records] || {}).length, 0) }; + } + private enqueue(operation: () => Promise): Promise { + const next = this.writes.catch(() => undefined).then(operation); + this.writes = next; + return next; + } + private async ensureFile(): Promise { + const path = this.dataPath; + const existing = this.app.vault.getAbstractFileByPath(path); + if (existing instanceof TFile) return existing; + if (existing) throw new Error(t("The points data path is occupied by a folder.")); + const parts = path.split("/"); parts.pop(); + for (let index = 1; index <= parts.length; index++) { + const folder = parts.slice(0, index).join("/"); + if (!this.app.vault.getAbstractFileByPath(folder)) await this.app.vault.createFolder(folder); + } + return this.app.vault.create(path, "---\nmanualPointRecords: []\nexamplePropertyLeft: []\nexamplePropertyRight: []\n---\n"); + } + private async update(change: (data: Record) => void) { + const file = await this.ensureFile(); + await this.app.fileManager.processFrontMatter(file, change); + this.app.workspace.trigger("task-genius:points-updated"); + } + addRecord(text: string, points: number, date = localPointDate(), source = "manual") { + return this.enqueue(async () => { + if (!text.trim() || !Number.isFinite(points) || points === 0 || !/^\d{4}-\d{2}-\d{2}$/.test(date)) throw new Error(t("Enter a description, a valid date, and a non-zero amount.")); + await this.update(data => { + if (!Array.isArray(data.manualPointRecords)) data.manualPointRecords = []; + data.manualPointRecords.push({ id: `points-${Date.now()}-${Math.random().toString(36).slice(2)}`, date, text: text.trim(), points: roundPoints(points), source, createdAt: new Date().toISOString() }); + }); + }); + } + deleteRecord(id: string) { + return this.enqueue(() => this.update(data => { data.manualPointRecords = (data.manualPointRecords || []).filter((record: any) => String(record.id) !== id); })); + } + saveList(key: "examplePropertyLeft" | "examplePropertyRight", values: string[]) { + return this.enqueue(() => this.update(data => { data[key] = values.filter(value => value.trim()); })); + } + saveRewardCatalog(value: string, original: RewardCatalogRow[]) { + return this.enqueue(async () => { + const { wishes, rewards } = parseRewardCatalog(value, original); + const snapshot = await this.snapshot(); + const current = this.plugin.settings.rewards.rewardItems; + if (JSON.stringify(rewardCatalogRows(snapshot.wishes.map(item => item.text), current)) !== JSON.stringify(original)) throw new Error(t("Rewards changed while editing. Reopen the editor and try again.")); + const next = [...current.filter(item => item.pointCost === undefined), ...rewards]; + this.plugin.settings.rewards.rewardItems = next; + try { await this.plugin.saveSettings(); } + catch (error) { this.plugin.settings.rewards.rewardItems = current; throw error; } + try { + await this.update(data => { + // A sync write may have landed after the snapshot was read. + if (JSON.stringify(data.examplePropertyRight || []) !== JSON.stringify(snapshot.wishes.map(item => item.text))) throw new Error(t("Rewards changed while editing. Reopen the editor and try again.")); + data.examplePropertyRight = wishes; + }); + } catch (error) { + this.plugin.settings.rewards.rewardItems = current; + await this.plugin.saveSettings(); + throw error; + } + }); + } + + saveDefaultRate(rate: number, enabled: boolean) { + return this.enqueue(() => this.update(data => { data.defaultPointRule = { ...data.defaultPointRule, baseRate: rate, enabled }; })); + } + async saveHabitRate(path: string, rate: number | null) { + const file = this.app.vault.getAbstractFileByPath(path); + if (!(file instanceof TFile)) throw new Error(t("Habit note not found.")); + await this.app.fileManager.processFrontMatter(file, data => { if (rate === null) delete data.bravoPoints; else data.bravoPoints = rate; }); + this.app.workspace.trigger("task-genius:points-updated"); + } + redeem(label: string, cost: number, rewardId?: string) { + return this.enqueue(async () => { + const snapshot = await this.snapshot(); + if (!Number.isFinite(cost) || cost <= 0 || snapshot.balance < cost) throw new Error(t("Not enough points.")); + const reward = rewardId ? this.plugin.settings.rewards.rewardItems.find(item => item.id === rewardId) : undefined; + if (rewardId && (!reward || reward.inventory === 0)) throw new Error(t("This reward is out of stock.")); + const inventory = reward?.inventory; + if (reward && reward.inventory > 0) { + reward.inventory--; + try { await this.plugin.saveSettings(); } catch (error) { reward.inventory = inventory!; throw error; } + } + try { await this.update(data => { + if (!Array.isArray(data.manualPointRecords)) data.manualPointRecords = []; + data.manualPointRecords.push({ id: `redeem-${Date.now()}-${Math.random().toString(36).slice(2)}`, date: localPointDate(), text: label, points: -cost, source: "redemption", createdAt: new Date().toISOString() }); + }); } catch (error) { + if (reward && inventory !== undefined && inventory > 0) { reward.inventory = inventory; await this.plugin.saveSettings(); } + throw error; + } + }); + } +} +export type PointsSnapshot = Awaited>; diff --git a/src/managers/points-utils.ts b/src/managers/points-utils.ts new file mode 100644 index 000000000..8d2a0f156 --- /dev/null +++ b/src/managers/points-utils.ts @@ -0,0 +1,35 @@ +import { localPointDate, pointDate } from "./daily-points"; + +export interface PointAwardTask { + id?: string; + filePath?: string; + line?: number; + content?: string; + originalMarkdown?: string; + metadata?: { points?: number | string; completedDate?: string | number }; +} + +export function resolveTaskPoints(task: PointAwardTask, defaultPoints: number): number { + const explicit = task.metadata?.points; + if (explicit !== undefined && explicit !== null && String(explicit).trim() !== "") { + const value = Number(explicit); + return Number.isFinite(value) ? Math.max(0, value) : 0; + } + const inline = String(task.originalMarkdown || task.content || "").match(/\[(?:points|积分)::\s*(-?\d+(?:\.\d+)?)\]/i); + if (inline) return Math.max(0, Number(inline[1])); + return Number.isFinite(defaultPoints) ? Math.max(0, defaultPoints) : 0; +} + +export function taskCompletionTransactionId(task: PointAwardTask, now = new Date()): string { + const id = String(task.id || `${task.filePath || ""}:${task.line ?? 0}`); + const completed = task.metadata?.completedDate; + const day = completed ? typeof completed === "number" ? localPointDate(new Date(completed)) : pointDate(completed) : localPointDate(now); + return `task:${id}:${day}`; +} + + +/** Old awards store their completion day in the transaction id, even for catch-up. */ +export function pointLedgerDate(entry: { id?: string; source: string; createdAt: number }): string { + const completed = entry.source === "task" ? entry.id?.match(/:(\d{4}-\d{2}-\d{2})$/)?.[1] : undefined; + return completed || localPointDate(new Date(entry.createdAt)); +} diff --git a/src/managers/project-dates.ts b/src/managers/project-dates.ts new file mode 100644 index 000000000..7e8ba6105 --- /dev/null +++ b/src/managers/project-dates.ts @@ -0,0 +1,10 @@ +export type ProjectDateEdge = "move" | "start" | "end"; +export function projectDateChange(start: number, end: number, days: number, edge: ProjectDateEdge): { startDate: string; dueDate: string } { + const from = new Date(start), to = new Date(end); + from.setHours(0, 0, 0, 0); to.setHours(0, 0, 0, 0); + if (edge !== "end") from.setDate(from.getDate() + days); + if (edge !== "start") to.setDate(to.getDate() + days); + if (from > to) { if (edge === "start") from.setTime(to.getTime()); else to.setTime(from.getTime()); } + const key = (date: Date) => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; + return { startDate: key(from), dueDate: key(to) }; +} diff --git a/src/managers/project-file-manager.ts b/src/managers/project-file-manager.ts new file mode 100644 index 000000000..2575ebc7c --- /dev/null +++ b/src/managers/project-file-manager.ts @@ -0,0 +1,387 @@ +import { App, Modal, Notice, Setting, TFile, TFolder, Menu } from "obsidian"; +import { Task } from "@/types/task"; +import { t } from "@/translations/helper"; + +export interface ProjectFileInfo { name: string; file: TFile; archived: boolean; description: string; dueDate?: string; startDate?: string; color?: string; order?: number; folder?: string; } + +/** Markdown project notes are the canonical home for project tasks and settings. */ +export class ProjectFileManager { + static readonly folder = "Projects"; + constructor(private app: App, private tagPrefixes: string[] = ["project"]) {} + get folder(): string { return this.app.vault.getAbstractFileByPath("Tasks/Projects") instanceof TFolder ? "Tasks/Projects" : ProjectFileManager.folder; } + + list(): ProjectFileInfo[] { + return this.app.vault.getMarkdownFiles().filter(file => !/(^|\/)(templates?|模板)(\/|$)/i.test(file.path)).flatMap(file => { + const fm = this.app.metadataCache.getFileCache(file)?.frontmatter; + if (typeof fm?.project !== "string" || !fm.project.trim() || /\{\{|<%/.test(fm.project)) return []; + return [{ name: fm.project.trim(), file, archived: fm.archived === true || fm.status === "archived", description: String(fm.description || ""), dueDate: typeof fm.dueDate === "string" ? fm.dueDate : undefined, startDate: typeof fm.startDate === "string" ? fm.startDate : undefined, color: /^#[0-9a-f]{6}$/i.test(fm.projectColor) ? fm.projectColor : undefined, order: Number.isFinite(fm.projectOrder) ? fm.projectOrder : undefined, folder: this.parentFolder(file) }]; + }); + } + + find(name: string): ProjectFileInfo | undefined { + const clean = name.trim(); + const cached = this.list().find(project => project.name.toLocaleLowerCase() === clean.toLocaleLowerCase()); + if (cached) return cached; + // MetadataCache may not have indexed a just-created note yet. Resolve its + // deterministic path directly so the first task can be moved immediately. + const slug = clean.replace(/[\\/:*?"<>|]/g, "-").replace(/\s+/g, "-"); + const matches = this.app.vault.getMarkdownFiles().filter(file => file.path.startsWith(this.folder + "/") && file.path.split("/").pop() === `${slug}.md`); + const file = this.app.vault.getAbstractFileByPath(`${this.folder}/${slug}.md`) || (matches.length === 1 ? matches[0] : null); + if (!(file instanceof TFile)) return undefined; + const fm = this.app.metadataCache.getFileCache(file)?.frontmatter; + return { + name: typeof fm?.project === "string" ? fm.project : clean, + file, + archived: fm?.archived === true || fm?.status === "archived", + description: String(fm?.description || ""), + dueDate: typeof fm?.dueDate === "string" ? fm.dueDate : undefined, + folder: this.parentFolder(file), color: fm?.projectColor, order: fm?.projectOrder, + }; + } + + async create(name: string, description = "", parent = ""): Promise { + const clean = name.trim(); + if (!clean) return null; + const existing = this.find(clean); + if (existing) return existing; + const destinationFolder = this.projectFolder(parent); + await this.ensureFolder(destinationFolder); + const slug = clean.replace(/[\\/:*?"<>|]/g, "-").replace(/\s+/g, "-"); + const path = `${destinationFolder}/${slug}.md`; + if (this.app.vault.getAbstractFileByPath(path)) { new Notice(t("A project file already exists at that path.")); return null; } + const body = `---\nproject: ${JSON.stringify(clean)}\nstatus: active\narchived: false\ndescription: ${JSON.stringify(description)}\n---\n\n# ${clean}\n\n## ${t("Project Gantt")}\n\n## ${t("Tasks")}\n\n`; + const file = await this.app.vault.create(path, body); + return { name: clean, file, archived: false, description, folder: parent }; + } + + async setArchived(name: string, archived: boolean): Promise { + const project = this.find(name); if (!project) return false; + if (!archived && /(^|\/)(archive|archives|归档)(\/|$)/i.test(project.file.path)) { + await this.ensureFolder(this.folder); + const destination = `${this.folder}/${project.file.name || project.file.path.split("/").pop()}`; + const collision = this.app.vault.getAbstractFileByPath(destination); + if (collision && collision !== project.file) throw new Error(t("A project file already exists at that path.")); + await this.app.fileManager.renameFile(project.file, destination); + } + await this.app.fileManager.processFrontMatter(project.file, fm => { + fm.project = project.name; fm.archived = archived; fm.status = archived ? "archived" : "active"; + }); + return true; + } + + async update(name: string, values: { name?: string; description?: string; dueDate?: string; startDate?: string; color?: string; order?: number; folder?: string }): Promise { + const project = this.find(name); if (!project) return false; + const nextName = values.name?.trim() || project.name; + const conflict = this.find(nextName); + if (conflict && conflict.file.path !== project.file.path) throw new Error(t("A project with that name already exists.")); + if (values.folder !== undefined && values.folder !== this.parentFolder(project.file)) { + const folder = this.projectFolder(values.folder), destination = `${folder}/${project.file.path.split("/").pop()}`; + const occupied = this.app.vault.getAbstractFileByPath(destination); + if (occupied && occupied !== project.file) throw new Error(t("A project file already exists at that path.")); + await this.ensureFolder(folder); await this.app.fileManager.renameFile(project.file, destination); + } + await this.app.fileManager.processFrontMatter(project.file, fm => { + fm.project = nextName; + if (values.color !== undefined) { if (/^#[0-9a-f]{6}$/i.test(values.color)) fm.projectColor = values.color; else if (!values.color) delete fm.projectColor; else throw new Error("Invalid project color"); } + if (values.order !== undefined && Number.isFinite(values.order)) fm.projectOrder = values.order; + if (values.description !== undefined) fm.description = values.description; + if (values.startDate !== undefined) { if (values.startDate) fm.startDate = values.startDate; else delete fm.startDate; } + if (values.dueDate !== undefined) { if (values.dueDate) fm.dueDate = values.dueDate; else delete fm.dueDate; } + }); + return true; + } + + /** Reorder canonical notes without touching their task content. */ + async reorder(names: string[]): Promise { + const records = this.list(); + for (const [order, name] of [...new Set(names)].entries()) { + const record = records.find(project => project.name === name); + if (!record || record.order === order) continue; + await this.app.fileManager.processFrontMatter(record.file, fm => { fm.projectOrder = order; }); + } + } + + compareNames(a: string, b: string): number { + const records = this.list(); + return (records.find(p => p.name === a)?.order ?? Number.MAX_SAFE_INTEGER) - (records.find(p => p.name === b)?.order ?? Number.MAX_SAFE_INTEGER) || a.localeCompare(b); + } + + bindReorder(el: HTMLElement, name: string, ordered: () => string[], changed: () => void): void { + el.draggable = true; + el.addEventListener("dragstart", event => { event.stopPropagation(); event.dataTransfer?.setData("application/x-taskgenius-project", name); }); + el.addEventListener("dragover", event => { if (event.dataTransfer?.types.includes("application/x-taskgenius-project")) { event.preventDefault(); event.stopPropagation(); } }); + el.addEventListener("drop", event => { + const source = event.dataTransfer?.getData("application/x-taskgenius-project"); + if (!source || source === name) return; + event.preventDefault(); event.stopPropagation(); + const names = ordered().filter(value => value !== source), index = names.indexOf(name); + if (index < 0) return; + const after = event.clientY > el.getBoundingClientRect().top + el.getBoundingClientRect().height / 2; + names.splice(index + Number(after), 0, source); + void this.reorder(names).then(changed).catch(error => new Notice(String(error))); + }); + } + + parentFolder(file: TFile): string { + const directory = file.path.split("/").slice(0, -1).join("/"); + return directory.startsWith(this.folder + "/") ? directory.slice(this.folder.length + 1) : ""; + } + private projectFolder(parent: string): string { + const clean = parent.trim().replace(/\\/g, "/").replace(/^\/+|\/+$/g, ""); + if (clean.split("/").some(part => part === ".." || part === "." || /[:*?"<>|]/.test(part))) throw new Error(t("Enter a valid folder name.")); + return this.folder + (clean ? "/" + clean : ""); + } + folderNames(): string[] { + const loaded = this.app.vault.getAllLoadedFiles?.() || []; + const folders = loaded.filter(file => file instanceof TFolder && file.path.startsWith(this.folder + "/")).map(file => file.path.slice(this.folder.length + 1)); + return [...new Set([...folders, ...this.list().map(project => project.folder || "")])].filter(Boolean).sort(); + } + + async addTask(name: string, content: string): Promise { + const project = this.find(name); if (!project || !content.trim()) return false; + await this.app.vault.process(project.file, text => `${text.replace(/\s*$/, "")}\n- [ ] ${content.trim()}\n`); + return true; + } + + async remove(name: string): Promise { + const project = this.find(name); + if (!project) return false; + await this.app.fileManager.trashFile(project.file); + return true; + } + + async moveTask(task: Task, name: string): Promise { + return (await this.moveTasks([task], name)) > 0; + } + + /** Move a selection of tasks from legacy tagged files into one project note. */ + async moveTasks(tasks: Task[], name: string): Promise { + if (tasks.some(task => task.metadata?.sourceType === "canvas" || task.filePath.toLowerCase().endsWith(".canvas"))) { + throw new Error(t("Canvas tasks must be moved through Task Genius.")); + } + const project = this.find(name) || await this.create(name); + if (!project || tasks.length === 0) return 0; + const selectedIds = new Set(tasks.map(task => task.id)); + const roots = tasks.filter(task => !task.metadata?.parent || !selectedIds.has(task.metadata.parent)); + const byPath = new Map(); + for (const task of roots) { + if (task.filePath === project.file.path) continue; + const group = byPath.get(task.filePath) || []; + group.push(task); + byPath.set(task.filePath, group); + } + if (!byPath.size) return 0; + + const sourceSnapshots = new Map(); + const movedBlocks: string[] = []; + for (const [path, group] of byPath) { + const source = this.app.vault.getAbstractFileByPath(path); + if (!(source instanceof TFile)) throw new Error(t("The task file could not be found.")); + const before = await this.app.vault.read(source); + const newline = before.includes("\r\n") ? "\r\n" : "\n"; + const lines = before.split(/\r?\n/); + const ranges: Array<{ start: number; end: number }> = []; + for (const task of group.slice().sort((a, b) => b.line - a.line)) { + const expected = String(task.originalMarkdown || "").trim(); + let start = Math.max(0, task.line); + if (lines[start]?.trim() !== expected) { + const matches = lines.map((line, index) => line.trim() === expected ? index : -1).filter(index => index >= 0); + start = matches.length === 1 ? matches[0] : -1; + } + if (start < 0 || !expected) throw new Error(t("The task changed before it could be moved.")); + if (ranges.some(range => start >= range.start && start < range.end)) continue; + const baseIndent = (lines[start].match(/^\s*/) || [""])[0].replace(/\t/g, " ").length; + let end = start + 1; + while (end < lines.length) { + if (!lines[end].trim()) { + let next = end + 1; + while (next < lines.length && !lines[next].trim()) next++; + if (next >= lines.length || (lines[next].match(/^\s*/) || [""])[0].replace(/\t/g, " ").length <= baseIndent) break; + end++; continue; + } + const childIndent = (lines[end].match(/^\s*/) || [""])[0].replace(/\t/g, " ").length; + if (childIndent <= baseIndent) break; + end++; + } + ranges.push({ start, end }); + const block = lines.slice(start, end).map(line => { + if (/^\s*[-*+]\s+\[[^\]]*\]/.test(line)) return this.stripProjectMarkers(line, name, baseIndent); + const indent = (line.match(/^\s*/) || [""])[0].replace(/\t/g, " ").length; + return " ".repeat(Math.max(0, indent - baseIndent)) + line.trimStart(); + }); + movedBlocks.unshift(block.join(newline)); + lines.splice(start, end - start); + } + sourceSnapshots.set(source, { before, after: lines.join(newline) }); + } + if (!movedBlocks.length) return 0; + + const oldDestination = await this.app.vault.read(project.file); + const destination = `${oldDestination.replace(/\s*$/, "")}\n${movedBlocks.join("\n")}\n`; + const changed: TFile[] = []; + try { + for (const [file, snapshot] of sourceSnapshots) { + await this.app.vault.modify(file, snapshot.after); + changed.push(file); + } + await this.app.vault.modify(project.file, destination); + } catch (error) { + for (const file of changed.reverse()) { + const snapshot = sourceSnapshots.get(file); + if (snapshot) await this.app.vault.modify(file, snapshot.before); + } + throw error; + } + return movedBlocks.length; + } + + stripProjectMarkers(line: string, projectName: string, baseIndent = 0): string { + let result = line; + for (const prefix of new Set(this.tagPrefixes.filter(Boolean))) { + const escaped = prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + result = result.replace(new RegExp(`\\s+\\[${escaped}::\\s*[^\\]]+\\]`, "gi"), ""); + // Project ownership is stored in the project note. Strip any legacy + // marker for this prefix so moving between projects cannot retain a + // conflicting old assignment. + result = result.replace(new RegExp(`\\s+#${escaped}/[^\\s#@+]+`, "gi"), ""); + } + const leading = (result.match(/^\s*/) || [""])[0].replace(/\t/g, " ").length; + return `${" ".repeat(Math.max(0, leading - baseIndent))}${result.trimStart()}`.trimEnd(); + } + + async appendTaskBlock(name: string, lines: string[]): Promise { + const project = this.find(name); + const cleaned = lines.map(line => /^\s*[-*+]\s+\[[^\]]*\]/.test(line) ? this.stripProjectMarkers(line, name) : line); + if (!project || !cleaned.some(line => line.trim())) return false; + const block = cleaned.join("\n"); + const before = await this.app.vault.read(project.file); + await this.app.vault.modify(project.file, `${before.replace(/\s*$/, "")}\n${block}\n`); + return true; + } + + async removeTaskBlock(name: string, block: string): Promise { + const project = this.find(name); + if (!project || !block) return false; + const before = await this.app.vault.read(project.file); + const index = before.lastIndexOf(block); + if (index < 0) return false; + const after = `${before.slice(0, index)}${before.slice(index + block.length)}`.replace(/\n{3,}/g, "\n\n"); + await this.app.vault.modify(project.file, after); + return true; + } + private async ensureFolder(path: string) { + const existing = this.app.vault.getAbstractFileByPath(path); + if (existing instanceof TFolder) return; + if (existing) throw new Error(t("The project folder path is occupied by a file.")); + const parts = path.split("/"); + for (let index = 1; index <= parts.length; index++) { + const directory = parts.slice(0, index).join("/"); + if (!this.app.vault.getAbstractFileByPath(directory)) await this.app.vault.createFolder(directory); + } + } +} + +export class ProjectCreateModal extends Modal { + constructor(app: App, private manager: ProjectFileManager, private onSave: () => void) { super(app); } + onOpen() { + this.setTitle(t("New project")); const folder = projectFolderPicker(this.contentEl, this.manager, ""); let name = "", description = "", color = "#5985b1"; + new Setting(this.contentEl).setName(t("Project name")).addText(text => text.onChange(value => name = value)); + new Setting(this.contentEl).setName(t("Description")).addText(text => text.onChange(value => description = value)); + const colorSetting = new Setting(this.contentEl).setName(t("Project color")); + const picker = colorSetting.controlEl.createEl("input", { type: "color", attr: { "aria-label": t("Project color") } }); picker.value = "#5985b1"; + picker.addEventListener("input", () => color = picker.value); + new Setting(this.contentEl).addButton(button => button.setButtonText(t("Create project")).setCta().onClick(async () => { + if (!name.trim()) { new Notice(t("Enter a project name.")); return; } + button.setDisabled(true); + try { if (await this.manager.create(name, description, folder())) { if (color) await this.manager.update(name, { color }); this.onSave(); this.close(); } } + catch (error) { new Notice(String(error)); } + finally { button.setDisabled(false); } + })); + } +} + +export class ProjectTaskModal extends Modal { + constructor(app: App, private manager: ProjectFileManager, private project: string, private onSave: () => void) { super(app); } + onOpen() { + this.setTitle(t("Add task to project")); let content = ""; + new Setting(this.contentEl).setName(t("Task")).addText(text => text.onChange(value => content = value)); + new Setting(this.contentEl).addButton(button => button.setButtonText(t("Add task")).setCta().onClick(async () => { + if (!content.trim()) return; + button.setDisabled(true); + try { if (await this.manager.addTask(this.project, content)) { this.onSave(); this.close(); } } + catch (error) { new Notice(String(error)); } + finally { button.setDisabled(false); } + })); + } +} + +export class ProjectEditModal extends Modal { + constructor(app: App, private manager: ProjectFileManager, private project: ProjectFileInfo, private onSave: () => void) { super(app); } + onOpen() { + this.setTitle(t("Edit project details")); + const folder = projectFolderPicker(this.contentEl, this.manager, this.project.folder || ""); + let description = this.project.description; + let name = this.project.name; + let color = this.project.color || "#5985b1"; + const colorSetting = new Setting(this.contentEl).setName(t("Project color")); + const picker = colorSetting.controlEl.createEl("input", { type: "color", attr: { "aria-label": t("Project color") } }); picker.value = color || "#5985b1"; + picker.addEventListener("input", () => color = picker.value); + new Setting(this.contentEl).setName(t("Project name")).addText(text => text.setValue(name).onChange(value => name = value)); + let dueDate = this.project.dueDate || ""; + let startDate = String(this.app.metadataCache.getFileCache(this.project.file)?.frontmatter?.startDate || ""); + new Setting(this.contentEl).setName(t("Start date")).addText(text => { text.inputEl.type = "date"; text.setValue(startDate).onChange(value => startDate = value); }); + new Setting(this.contentEl).setName(t("Description")).addText(text => text.setValue(description).onChange(value => description = value)); + new Setting(this.contentEl).setName(t("Due date")).addText(text => { text.inputEl.type = "date"; text.setValue(dueDate).onChange(value => dueDate = value); }); + new Setting(this.contentEl).addButton(button => button.setButtonText(t("Save")).setCta().onClick(async () => { + button.setDisabled(true); + try { if (await this.manager.update(this.project.name, { name, description, dueDate, startDate, color, folder: folder() })) { this.onSave(); this.close(); } } + catch (error) { new Notice(String(error)); } + finally { button.setDisabled(false); } + })); + new Setting(this.contentEl).setName(t("Delete project")).setDesc(t("Move the project note and its tasks to the trash.")) + .addButton(button => button.setButtonText(t("Delete project")).setWarning().onClick(() => { + new ProjectDeleteModal(this.app, this.manager, this.project, () => { this.onSave(); this.close(); }).open(); + })); + } +} + +export class ProjectDeleteModal extends Modal { + constructor(app: App, private manager: ProjectFileManager, private project: ProjectFileInfo, private onDeleted: () => void) { super(app); } + onOpen(): void { + this.setTitle(t("Delete project")); + this.contentEl.createEl("p", { text: this.project.name }); + this.contentEl.createEl("p", { text: t("Move the project note and its tasks to the trash.") }); + this.contentEl.createEl("p", { text: this.project.file.path }); + new Setting(this.contentEl).addButton(button => button.setButtonText(t("Cancel")).onClick(() => this.close())) + .addButton(button => button.setButtonText(t("Delete")).setWarning().onClick(async () => { + button.setDisabled(true); + try { if (await this.manager.remove(this.project.name)) { this.onDeleted(); this.close(); } } + catch (error) { new Notice(String(error)); button.setDisabled(false); } + })); + } +} + +export class ProjectArchiveModal extends Modal { + constructor(app: App, private manager: ProjectFileManager, private onChange: () => void) { super(app); } + onOpen() { + this.setTitle(t("Archived projects")); this.contentEl.empty(); + const archived = this.manager.list().filter(project => project.archived); + if (!archived.length) this.contentEl.createDiv({ text: t("No archived projects") }); + for (const project of archived) new Setting(this.contentEl).setName(project.name).setDesc(project.file.path) + .addButton(button => button.setButtonText(t("Open")).onClick(() => void this.app.workspace.openLinkText(project.file.path, "", false))) + .addButton(button => button.setButtonText(t("Restore project")).onClick(async () => { await this.manager.setArchived(project.name, false); this.onChange(); this.onOpen(); })) + .addButton(button => button.setButtonText(t("Delete project")).setWarning().onClick(() => new ProjectDeleteModal(this.app, this.manager, project, () => { this.onChange(); this.onOpen(); }).open())); + } +} + + +function projectFolderPicker(root: HTMLElement, manager: ProjectFileManager, current: string): () => string { + let selected = current, added = ""; + new Setting(root).setName(t("Parent folder")).addDropdown(dropdown => { + dropdown.addOption("", t("Projects root")); + for (const folder of [...new Set([current, ...manager.folderNames()])].filter(Boolean)) dropdown.addOption(folder, folder); + dropdown.setValue(current).onChange(value => selected = value); + }); + new Setting(root).setName(t("New parent folder (optional)")).addText(text => text.setPlaceholder(t("Folder name")).onChange(value => added = value.trim())); + return () => added || selected; +} diff --git a/src/managers/project-plan.ts b/src/managers/project-plan.ts new file mode 100644 index 000000000..16749d81b --- /dev/null +++ b/src/managers/project-plan.ts @@ -0,0 +1,24 @@ +import type { App } from "obsidian"; +import type { Task } from "@/types/task"; +import { getEffectiveProject } from "@/utils/task/task-operations"; +import { ProjectFileManager } from "./project-file-manager"; + +/** One row per project note, rather than a row for every task. */ +export function buildProjectPlan(app: App, tasks: Task[]): Task[] { + return new ProjectFileManager(app).list().filter(project => !project.archived).sort((a, b) => (a.order ?? Number.MAX_SAFE_INTEGER) - (b.order ?? Number.MAX_SAFE_INTEGER) || a.name.localeCompare(b.name)).map(project => { + const members = tasks.filter(task => getEffectiveProject(task) === project.name); + const fm = app.metadataCache.getFileCache(project.file)?.frontmatter || {}; + const date = (value: unknown) => { const parsed = value ? (/^\d{4}-\d{2}-\d{2}$/.test(String(value)) ? new Date(Number(String(value).slice(0, 4)), Number(String(value).slice(5, 7)) - 1, Number(String(value).slice(8, 10))) : new Date(value as string)).getTime() : NaN; return Number.isFinite(parsed) ? parsed : undefined; }; + const starts = members.map(task => task.metadata.startDate || task.metadata.scheduledDate).filter((value): value is number => typeof value === "number" && Number.isFinite(value)); + const ends = members.map(task => task.metadata.dueDate).filter((value): value is number => typeof value === "number" && Number.isFinite(value)); + const start = date(fm.startDate) ?? (starts.length ? Math.min(...starts) : project.file.stat?.ctime || Date.now()); + const end = date(fm.dueDate) ?? (ends.length ? Math.max(...ends) : start); + const completed = fm.status === "completed" || fm.status === "done" || members.length > 0 && members.every(task => task.completed); + return { + id: `project-plan:${project.file.path}`, content: project.name, filePath: project.file.path, line: 0, + originalMarkdown: project.name, completed, status: completed ? "x" : " ", + metadata: { project: project.name, tags: [], children: [], startDate: start, dueDate: Math.max(start, end), projectPlan: true, projectColor: project.color, + progress: members.length ? members.filter(task => task.completed).length / members.length : 0 }, + }; + }); +} diff --git a/src/managers/reward-catalog.ts b/src/managers/reward-catalog.ts new file mode 100644 index 000000000..444a06ad6 --- /dev/null +++ b/src/managers/reward-catalog.ts @@ -0,0 +1,55 @@ +import type { RewardItem } from "@/common/setting-definition"; +import { t } from "@/translations/helper"; + +export interface RewardCatalogRow { text: string; reward?: RewardItem; } + +export function rewardCatalogRows(wishes: string[], items: RewardItem[]): RewardCatalogRow[] { + return [ + ...wishes.map(text => ({ text })), + ...items.filter(item => item.pointCost !== undefined).map(reward => ({ + text: `${reward.name} -${reward.pointCost} | ${reward.inventory ?? -1}`, reward: { ...reward }, + })), + ]; +} + +function readRow(text: string) { + const stock = text.match(/\s+\|\s*(-?\d+)\s*$/); + if (!stock && /\s[+\-−]\s*\d+(?:\.\d+)?\s+\|/.test(text)) throw new Error(t("Check the reward details")); + const priced = stock ? text.slice(0, stock.index).trim() : text; + const price = priced.match(/\s+([+\-−])\s*(\d+(?:\.\d+)?)\s*$/); + const name = price ? priced.slice(0, price.index).trim() : priced.trim(); + const cost = price ? Number(price[2]) : undefined; + const inventory = stock ? Number(stock[1]) : undefined; + if (!name || cost !== undefined && (!Number.isFinite(cost) || cost <= 0) || inventory !== undefined && (!Number.isSafeInteger(inventory) || inventory < -1 || cost === undefined)) throw new Error(t("Check the reward details")); + return { name, cost, inventory }; +} + +/** Match unchanged/reordered entries first, so metadata remains attached to its reward. */ +export function parseRewardCatalog(value: string, original: RewardCatalogRow[]) { + const lines = value.split(/\r?\n/).map(line => line.trim()).filter(Boolean); + const parsed = lines.map(readRow); + const remaining = new Set(original.map((_, index) => index)); + const matches: Array = lines.map(() => undefined); + for (const match of [ + (i: number, j: number) => lines[i] === original[j].text.trim(), + (i: number, j: number) => parsed[i].name === readRow(original[j].text).name, + ]) for (let i = 0; i < lines.length; i++) { + if (matches[i] !== undefined) continue; + const j = [...remaining].find(j => match(i, j)); + if (j !== undefined) { matches[i] = j; remaining.delete(j); } + } + // A rename in place retains its ID and custom properties. New rows otherwise get new IDs. + if (lines.length === original.length) for (let i = 0; i < lines.length; i++) { + if (matches[i] === undefined && remaining.has(i)) { matches[i] = i; remaining.delete(i); } + } + const wishes: string[] = [], rewards: RewardItem[] = []; + lines.forEach((line, i) => { + const previous = matches[i] === undefined ? undefined : original[matches[i]!].reward; + const { name, cost, inventory } = parsed[i]; + if (previous || inventory !== undefined) { + if (cost === undefined) throw new Error(t("Check the reward details")); + rewards.push({ ...(previous || { id: `reward-${Date.now()}-${Math.random().toString(36).slice(2)}`, occurrence: "common" as const }), name, pointCost: cost, inventory: inventory ?? previous?.inventory ?? -1 }); + } else wishes.push(line); + }); + return { wishes, rewards }; +} diff --git a/src/managers/reward-manager.ts b/src/managers/reward-manager.ts index ad274be08..74aaa3cfa 100644 --- a/src/managers/reward-manager.ts +++ b/src/managers/reward-manager.ts @@ -8,6 +8,7 @@ import { FilterNode, } from "../utils/task/filter-compatibility"; import { Task } from "../types/task"; +import { resolveTaskPoints, taskCompletionTransactionId } from "./points-utils"; export class RewardManager extends Component { private plugin: TaskProgressBarPlugin; @@ -24,12 +25,25 @@ export class RewardManager extends Component { this.app.workspace.on( "task-genius:task-completed", (task: Task) => { - this.triggerReward(task); + void this.awardTaskPoints(task); } ) ); } + private async awardTaskPoints(task: Task): Promise { + const settings = this.plugin.settings.rewards; + const ledger = settings.pointsLedger || (settings.pointsLedger = []); + const taskId = String(task.id || `${task.filePath}:${task.line}`); + const transactionId = taskCompletionTransactionId(task); + if (ledger.some(entry => entry.id === transactionId)) return; + const points = resolveTaskPoints(task, Number(settings.pointsPerTask ?? 0)); + if (!Number.isFinite(points) || points === 0) return; + ledger.push({ id: transactionId, delta: points, label: task.content || task.originalMarkdown || "Task completed", createdAt: Date.now(), source: "task", taskId }); + await this.plugin.saveSettings(); + this.app.workspace.trigger("task-genius:points-updated"); + } + /** * Call this method when a task is completed. * @param task The completed task object. diff --git a/src/mcp/auth/AuthMiddleware.ts b/src/mcp/auth/AuthMiddleware.ts index 3f7bce2d4..7fc2f1048 100644 --- a/src/mcp/auth/AuthMiddleware.ts +++ b/src/mcp/auth/AuthMiddleware.ts @@ -106,8 +106,15 @@ export class AuthMiddleware { const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; let token = ""; - for (let i = 0; i < 32; i++) { - token += chars.charAt(Math.floor(Math.random() * chars.length)); + const bytes = new Uint8Array(64); + while (token.length < 32) { + globalThis.crypto.getRandomValues(bytes); + for (const byte of bytes) { + // Reject the short final bucket rather than biasing modulo 62. + if (byte >= 248) continue; + token += chars.charAt(byte % chars.length); + if (token.length === 32) break; + } } return token; } diff --git a/src/pages/FluentTaskView.ts b/src/pages/FluentTaskView.ts index 24be05b24..976f9a70c 100644 --- a/src/pages/FluentTaskView.ts +++ b/src/pages/FluentTaskView.ts @@ -31,6 +31,8 @@ import { FluentWorkspaceStateManager } from "@/components/features/fluent/manage import { FluentActionHandlers } from "@/components/features/fluent/managers/FluentActionHandlers"; import { TaskSelectionManager } from "@/components/features/task/selection/TaskSelectionManager"; import { getViewSettingOrDefault } from "@/common/setting-definition"; +import { PresetTaskFilter } from "@/common/setting-definition"; +import { savedTaskFilters } from "@/utils/task/saved-task-filters"; export const FLUENT_TASK_VIEW = "fluent-task-genius-view"; @@ -92,6 +94,31 @@ export class FluentTaskView extends ItemView { // Filter state private currentFilterState: RootFilterState | null = null; private liveFilterState: RootFilterState | null = null; + private activeTaskPreset: PresetTaskFilter["options"] | null = null; + private activeTaskPresetId: string | null = null; + + private loadedFilterKey = ""; + private viewFilterKey(): string { return `${this.workspaceId}:${this.currentViewId}`; } + private saveViewFilters(): void { + if (this.isInitializing || this.loadedFilterKey !== this.viewFilterKey()) return; + const all = this.app.loadLocalStorage("task-genius-view-filters-v2") || {}; + all[this.viewFilterKey()] = structuredClone({ presetId: this.activeTaskPresetId, filters: this.viewState.filters, advanced: this.liveFilterState, project: this.viewState.selectedProject }); + this.app.saveLocalStorage("task-genius-view-filters-v2", all); + } + private restoreViewFilters(): void { + const key = this.viewFilterKey(); + const legacy = this.plugin.workspaceManager?.getEffectiveSettings(this.workspaceId)?.fluentFilterState?.[this.currentViewId]; + const stored = this.app.loadLocalStorage("task-genius-view-filters-v2")?.[key] || (legacy ? { filters: legacy.filters, advanced: legacy.advancedFilter, project: legacy.selectedProject } : undefined); + this.loadedFilterKey = key; + this.activeTaskPresetId = stored?.presetId && savedTaskFilters(this.plugin.settings.taskFilter?.presetTaskFilters).some(preset => preset.id === stored.presetId) ? stored.presetId : null; + this.activeTaskPreset = null; + this.liveFilterState = stored?.advanced ? structuredClone(stored.advanced) : null; + this.currentFilterState = this.liveFilterState; + this.viewState.filters = structuredClone(stored?.filters || {}); + this.viewState.selectedProject = stored?.project; + this.topNavigation?.setActivePreset(this.activeTaskPresetId, !!this.liveFilterState?.filterGroups?.length); + this.app.saveLocalStorage("task-genius-view-filter", this.liveFilterState); + } // Selection state private selectedTask: Task | null = null; @@ -155,7 +182,9 @@ export class FluentTaskView extends ItemView { * Delay: 150ms to balance responsiveness and performance */ private handleFilterChanged = debounce( - (filterState: RootFilterState, leafId?: string) => { + (filterState: RootFilterState, leafId?: string, originKey?: string) => { + if (originKey && originKey !== this.viewFilterKey()) return; + if (!leafId || leafId !== (this.leaf as any)?.id) return; // Only update if it's from a live filter component if ( leafId && @@ -201,6 +230,7 @@ export class FluentTaskView extends ItemView { } // Persist and update header UI + this.saveViewFilters(); this.workspaceStateManager.saveFilterStateToWorkspace(); this.layoutManager.updateActionButtons(); @@ -360,7 +390,7 @@ export class FluentTaskView extends ItemView { const restored = this.workspaceStateManager.restoreFilterStateFromWorkspace(); if (restored?.activeViewId) { - this.currentViewId = restored.activeViewId; + this.currentViewId = restored.activeViewId === "review" ? "projects" : restored.activeViewId === "rewards" ? "points" : restored.activeViewId; } this.workspaceStateManager.syncFilterState(restored, { setLiveFilterState: (state) => { @@ -409,6 +439,7 @@ export class FluentTaskView extends ItemView { } }, onAfterSync: () => { + this.restoreViewFilters(); this.layoutManager?.updateActionButtons(); }, }); @@ -417,8 +448,8 @@ export class FluentTaskView extends ItemView { // PHASE 6: Load Data (KEY PHASE) // ==================== console.log("[Task Genius] Loading tasks..."); - await this.dataManager.loadTasks(false); // Will trigger onTasksLoaded callback await this.dataManager.registerDataflowListeners(); + await this.dataManager.loadTasks(false); // Listeners precede the first snapshot. console.log( `[Task Genius] ✅ Loaded ${this.tasks.length} tasks, ${this.filteredTasks.length} after filters` ); @@ -450,6 +481,7 @@ export class FluentTaskView extends ItemView { } this.isInitializing = false; + await this.dataManager?.finishInitialization(); if (this.DEBUG_MODE) { console.log("[Task Genius] Calling final updateView()..."); @@ -474,6 +506,7 @@ export class FluentTaskView extends ItemView { selectedProject: this.viewState.selectedProject || undefined, searchQuery: this.viewState.searchQuery || "", filterInputValue: this.viewState.filterInputValue || "", + activeTaskPreset: this.activeTaskPresetId ? savedTaskFilters(this.plugin.settings.taskFilter?.presetTaskFilters).find(preset => preset.id === this.activeTaskPresetId)?.options || null : this.activeTaskPreset, }), () => this.isInitializing ); @@ -530,9 +563,8 @@ export class FluentTaskView extends ItemView { this.actionHandlers.setCallbacks({ onTaskSelectionChanged: (task) => { this.selectedTask = task; - if (task) { - this.layoutManager.showTaskDetails(task); - } + if (task) this.layoutManager.showTaskDetails(task); + else this.layoutManager.closeTaskEditor(); }, onTaskUpdated: (taskId, updatedTask) => { // Update task in cache @@ -575,7 +607,9 @@ export class FluentTaskView extends ItemView { this.currentViewId, this.viewState.viewMode ); + this.saveViewFilters(); this.currentViewId = viewId; + this.restoreViewFilters(); console.log(`[Task Genius] currentViewId updated to: ${this.currentViewId}`); // When navigating to projects view directly, clear project selection @@ -614,7 +648,7 @@ export class FluentTaskView extends ItemView { // Broadcast filter change this.app.workspace.trigger( "task-genius:filter-changed", - nextState + nextState, (this.leaf as any).id ); } } catch (e) { @@ -644,14 +678,16 @@ export class FluentTaskView extends ItemView { }, onProjectSelected: (projectId) => { console.log(`[Task Genius] Project selected: ${projectId}`); - this.viewState.selectedProject = projectId; // Switch to projects view this.recordViewModeForView( this.currentViewId, this.viewState.viewMode ); + this.saveViewFilters(); this.currentViewId = "projects"; + this.restoreViewFilters(); + this.viewState.selectedProject = projectId; this.filteredTasks = this.dataManager.applyFilters(this.tasks); const projectsViewMode = this.ensureViewModeForView( this.currentViewId @@ -705,12 +741,9 @@ export class FluentTaskView extends ItemView { nextState ); - // Broadcast so any open filter UI reacts and header button shows reset - // The filter-changed event listener will handle applyFilters and updateView - this.app.workspace.trigger( - "task-genius:filter-changed", - nextState - ); + this.saveViewFilters(); + this.filteredTasks = this.dataManager.applyFilters(this.tasks); + this.updateView(); } catch (e) { console.warn( "[Task Genius] Failed to project-sync filter UI state", @@ -734,13 +767,7 @@ export class FluentTaskView extends ItemView { // Save to workspace this.workspaceStateManager.saveFilterStateToWorkspace(); }, - showDetailsPanel: (task) => { - this.layoutManager.showTaskDetails(task); - }, - toggleDetailsVisibility: (visible) => { - this.layoutManager.toggleDetailsVisibility(visible); - }, - getIsDetailsVisible: () => this.layoutManager.isDetailsVisible, + }); this.addChild(this.actionHandlers); @@ -806,10 +833,17 @@ export class FluentTaskView extends ItemView { cls: "tg-fluent-main-container", }); - // Top navigation - const topNavEl = mainContainer.createDiv({ - cls: "tg-fluent-top-nav", - }); + // Phone controls live in the view so they are available even when the + // host title bar is hidden. + const navigationParent = Platform.isPhone + ? mainContainer.createDiv({ cls: "tg-fluent-phone-toolbar" }) + : mainContainer; + const topNavEl = navigationParent.createDiv({ cls: "tg-fluent-top-nav" }); + if (!Platform.isPhone) { + this.headerEl?.querySelector(".view-header-title-container")?.replaceChildren(topNavEl); + } + this.registerDomEvent(topNavEl, "pointerdown", event => event.stopPropagation()); + this.register(() => topNavEl.remove()); // Content wrapper (IMPORTANT: this was missing!) const contentWrapper = mainContainer.createDiv({ @@ -836,30 +870,17 @@ export class FluentTaskView extends ItemView { () => this.filteredTasks.length ); this.layoutManager.setOnSidebarNavigate((viewId) => { - this.actionHandlers.handleNavigate(viewId); + this.actionHandlers.handleNavigate(viewId, this.viewState.selectedProject); }); this.layoutManager.setOnProjectSelect((projectId) => { this.actionHandlers.handleProjectSelect(projectId); }); - this.layoutManager.setTaskCallbacks({ - onTaskToggleComplete: (task) => { - this.actionHandlers.toggleTaskCompletion(task); - }, - onTaskEdit: (task) => { - void this.actionHandlers.handleTaskEditInFile(task); - }, - onTaskUpdate: async (originalTask, updatedTask) => { - await this.actionHandlers.handleTaskUpdate( - originalTask, - updatedTask - ); - }, - }); + this.addChild(this.layoutManager); if (!useWorkspaceSideLeaves) { // Initialize details component (non-leaves mode only) - this.layoutManager.initializeDetailsComponent(); + // Initialize sidebar (non-leaves mode only) this.layoutManager.initializeSidebar(sidebarEl); @@ -881,9 +902,18 @@ export class FluentTaskView extends ItemView { this.plugin, (query: string) => this.actionHandlers.handleSearch(query), (mode: ViewMode) => this.actionHandlers.handleViewModeChange(mode), - () => { - // Filter click callback (currently unused) - // Note: Filter functionality is implemented in FluentLayoutManager via addAction + (presetId) => { + this.activeTaskPresetId = presetId; + this.liveFilterState = null; + this.currentFilterState = null; + this.viewState.filters = {}; + this.app.saveLocalStorage("task-genius-view-filter", null); + this.activeTaskPreset = presetId + ? savedTaskFilters(this.plugin.settings.taskFilter?.presetTaskFilters).find(preset => preset.id === presetId)?.options || null + : null; + this.saveViewFilters(); + this.filteredTasks = this.dataManager.applyFilters(this.tasks); + this.updateView(); }, () => { // Sort click callback (future extension point) @@ -990,11 +1020,15 @@ export class FluentTaskView extends ItemView { * Register workspace and global events */ private registerEvents() { + this.registerEvent(this.app.workspace.on("task-genius:view-config-changed", () => { + void this.refreshSettings().catch(error => console.error("Task Genius view settings refresh", error)); + })); // Workspace switch event if (this.plugin.workspaceManager) { this.registerEvent( onWorkspaceSwitched(this.app, async (payload) => { if (payload.workspaceId !== this.workspaceId) { + this.saveViewFilters(); // Save current workspace state immediately (before switching) const snapshot = this.workspaceStateManager.captureFilterStateSnapshot(); @@ -1015,7 +1049,7 @@ export class FluentTaskView extends ItemView { const restored = this.workspaceStateManager.restoreFilterStateFromWorkspace(); if (restored?.activeViewId) { - this.currentViewId = restored.activeViewId; + this.currentViewId = restored.activeViewId === "review" ? "projects" : restored.activeViewId === "rewards" ? "points" : restored.activeViewId; } this.workspaceStateManager.syncFilterState(restored, { setLiveFilterState: (state) => { @@ -1065,6 +1099,7 @@ export class FluentTaskView extends ItemView { } }, onAfterSync: () => { + this.restoreViewFilters(); this.layoutManager?.updateActionButtons(); }, }); @@ -1099,7 +1134,7 @@ export class FluentTaskView extends ItemView { this.app.workspace.on( "task-genius:filter-changed", (filterState: RootFilterState, leafId?: string) => { - this.handleFilterChanged(filterState, leafId); + this.handleFilterChanged(filterState, leafId, this.viewFilterKey()); } ) ); @@ -1113,7 +1148,9 @@ export class FluentTaskView extends ItemView { payload.selectionType === "view" && payload.selectionId ) { + this.saveViewFilters(); this.currentViewId = payload.selectionId; + this.restoreViewFilters(); this.filteredTasks = this.dataManager.applyFilters( this.tasks ); @@ -1151,12 +1188,25 @@ export class FluentTaskView extends ItemView { /** * Update view with current state */ + public async refreshSettings(): Promise { + if (this.isInitializing) return; + this.layoutManager.sidebar?.render(); + this.componentManager.refreshConfiguration(); + this.layoutManager.updateActionButtons(); + await this.dataManager.loadTasks(false); + } + private updateView() { if (this.isInitializing) { console.log("[Task Genius] Skip update during initialization"); return; } + if (this.loadedFilterKey !== this.viewFilterKey()) { + this.restoreViewFilters(); + this.filteredTasks = this.dataManager.applyFilters(this.tasks); + } + this.topNavigation?.setActivePreset(this.activeTaskPresetId, !!this.liveFilterState?.filterGroups?.length); console.log( `[Task Genius] Proceeding with view update for ${this.currentViewId}` ); @@ -1167,6 +1217,7 @@ export class FluentTaskView extends ItemView { this.currentViewId, this.viewState.selectedProject ) ?? []; + this.topNavigation?.updateContext(this.currentViewId); this.topNavigation?.updateAvailableModes(availableModes); // Update task count @@ -1175,13 +1226,8 @@ export class FluentTaskView extends ItemView { // Update sidebar active item this.layoutManager.setSidebarActiveItem(this.currentViewId); - // Control project list interaction based on view state - // Disable project list when showing full projects overview (no project selected) - // Enable it when in other views or when a specific project is selected - const isProjectsOverview = - this.currentViewId === "projects" && - !this.viewState.selectedProject; - this.layoutManager.sidebar?.setProjectListEnabled(!isProjectsOverview); + this.layoutManager.sidebar?.setProjectListEnabled(true); + this.layoutManager.setActiveProject(this.viewState.selectedProject || null); // Show loading state if (this.isLoading) { @@ -1205,7 +1251,7 @@ export class FluentTaskView extends ItemView { } // Show empty state - if (this.tasks.length === 0) { + if (this.tasks.length === 0 && this.componentManager.isContentBasedView(this.currentViewId)) { this.componentManager.renderEmptyState(); return; } @@ -1222,6 +1268,7 @@ export class FluentTaskView extends ItemView { } // Switch to appropriate component + this.componentManager.setSearchQuery?.(this.viewState.searchQuery || ""); this.componentManager.switchView( this.currentViewId, this.tasks, @@ -1238,6 +1285,7 @@ export class FluentTaskView extends ItemView { private resetCurrentFilter(): void { console.log("[Task Genius] Resetting filter"); + this.activeTaskPresetId = null; this.activeTaskPreset = null; this.viewState.filters = {}; // Clear filter states this.liveFilterState = null; this.currentFilterState = null; @@ -1246,6 +1294,7 @@ export class FluentTaskView extends ItemView { // Clear localStorage this.app.saveLocalStorage("task-genius-view-filter", null); + this.saveViewFilters(); // Save the cleared filter state to workspace this.workspaceStateManager.saveFilterStateToWorkspace(); @@ -1253,7 +1302,7 @@ export class FluentTaskView extends ItemView { this.app.workspace.trigger("task-genius:filter-changed", { rootCondition: "all", filterGroups: [], - } as any); + } as any, (this.leaf as any).id); // Clear any active project selection in sidebar this.layoutManager.setActiveProject(null); @@ -1306,6 +1355,7 @@ export class FluentTaskView extends ItemView { * Clean up on close */ async onClose() { + this.saveViewFilters(); console.log("[Task Genius] onClose started"); // Save workspace layout before closing diff --git a/src/pages/RightDetailView.ts b/src/pages/RightDetailView.ts deleted file mode 100644 index 9098b3ae5..000000000 --- a/src/pages/RightDetailView.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { ItemView, WorkspaceLeaf } from "obsidian"; -import type TaskProgressBarPlugin from "@/index"; -import { - onTaskSelected, - TaskSelectionPayload, -} from "@/components/features/fluent/events/ui-event"; -import { TaskDetailsComponent } from "@/components/features/task/view/details"; -import { t } from "@/translations/helper"; -import { Repository } from "@/dataflow/indexer/Repository"; - -export const TG_RIGHT_DETAIL_VIEW_TYPE = "tg-right-detail" as const; - -export class RightDetailView extends ItemView { - private rootEl!: HTMLElement; - private details!: TaskDetailsComponent; - - constructor( - leaf: WorkspaceLeaf, - private plugin: TaskProgressBarPlugin, - ) { - super(leaf); - } - - getViewType(): string { - return TG_RIGHT_DETAIL_VIEW_TYPE; - } - - getDisplayText(): string { - return "Task Genius" + t("Details"); - } - - getIcon(): string { - return "panel-right-dashed"; - } - - async onOpen() { - const el = this.containerEl.children[1]; - el.empty(); - this.rootEl = el.createDiv({ cls: "tg-right-detail-view" }); - - // Mount TaskDetailsComponent - this.details = new TaskDetailsComponent( - this.rootEl, - this.app, - this.plugin, - ); - this.addChild(this.details); - // this.details.onload(); - - // Wire callbacks to WriteAPI - this.details.onTaskUpdate = async (originalTask, updatedTask) => { - if (!this.plugin.writeAPI) return; - await this.plugin.writeAPI.updateTask({ - taskId: originalTask.id, - updates: updatedTask, - }); - }; - this.details.onTaskToggleComplete = async (task) => { - if (!this.plugin.writeAPI) return; - await this.plugin.writeAPI.updateTaskStatus({ - taskId: task.id, - completed: !task.completed, - }); - }; - - // Subscribe to cross-view task selection - this.registerEvent( - onTaskSelected(this.app, async (payload: TaskSelectionPayload) => { - // Filter by active workspace correctly - console.log(this.app, payload); - try { - const activeId = - this.plugin.workspaceManager?.getActiveWorkspace().id; - console.log(activeId, payload.workspaceId); - if ( - payload.workspaceId && - activeId && - payload.workspaceId !== activeId - ) - return; - } catch {} - - // Reveal this leaf on selection - if (payload.taskId) this.app.workspace.revealLeaf(this.leaf); - - if (!payload.taskId) { - this.details.showTaskDetails(null as never); - return; - } - try { - const repo = - this.plugin.dataflowOrchestrator?.getRepository(); - const task = - repo && - (await (repo as Repository).getTaskById( - payload.taskId, - )); - - console.log(task); - if (task) this.details.showTaskDetails(task); - } catch (e) { - console.warn("[TG] RightDetailView failed to load task", e); - } - }), - ); - } - - async onClose() { - // cleanup handled by Component lifecycle - } -} diff --git a/src/pages/bases/examples/sample-tasks-base.md b/src/pages/bases/examples/sample-tasks-base.md index c1a4740c8..79369cd64 100644 --- a/src/pages/bases/examples/sample-tasks-base.md +++ b/src/pages/bases/examples/sample-tasks-base.md @@ -86,9 +86,9 @@ config: taskTags: tags ``` -### 6. Review View for Daily Processing +### 6. Project View for Active Tasks ```base -view: task-genius-review +view: task-genius-projects from: "Tasks" where: status != "x" AND (due_date <= date("today") OR priority >= 3) config: diff --git a/src/pages/bases/index.ts b/src/pages/bases/index.ts index ff166a435..fed1522de 100644 --- a/src/pages/bases/index.ts +++ b/src/pages/bases/index.ts @@ -45,8 +45,7 @@ export { * - task-genius-calendar: Calendar layout * - task-genius-kanban: Kanban board * - task-genius-gantt: Gantt chart - * - task-genius-review: Task review interface - * - task-genius-habits: Habit tracking + * * - task-genius-habits: Habit tracking * - task-genius-flagged: High-priority flagged tasks * - task-genius-unified: Configurable unified view * - task-genius-custom: Fully customizable view diff --git a/src/pages/bases/registerBasesViews.ts b/src/pages/bases/registerBasesViews.ts index ff788cc86..9513e4d61 100644 --- a/src/pages/bases/registerBasesViews.ts +++ b/src/pages/bases/registerBasesViews.ts @@ -67,13 +67,6 @@ const TASK_GENIUS_BASES_VIEWS: TaskGeniusBasesViewType[] = [ defaultViewMode: 'gantt', description: 'View tasks in Gantt chart' }, - { - id: 'task-genius-review', - name: 'Review (Task Genius)', - icon: 'lucide-list-checks', - defaultViewMode: 'review', - description: 'Review and process tasks' - }, { id: 'task-genius-habits', name: 'Habits (Task Genius)', diff --git a/src/services/markdown-status-sync.ts b/src/services/markdown-status-sync.ts new file mode 100644 index 000000000..35ca73bc9 --- /dev/null +++ b/src/services/markdown-status-sync.ts @@ -0,0 +1,77 @@ +import { Component, TFile, moment } from "obsidian"; +import type TaskProgressBarPlugin from "@/index"; + +const completion = /\s*(?:✅\s*\d{4}-\d{2}-\d{2}(?:[ T]\d{2}:\d{2}(?::\d{2})?)?|\[completion::\s*[^\]]+\])/g; +const taskLine = /^(\s*(?:>\s*)*(?:[-*+]|\d+[.)])\s+\[)([^\]])(\]\s*)(.*)$/; + +/** Only real status transitions are stamped; importing or opening old tasks is read-only. */ +export function stampStatusTransitions(before: string, after: string, completedMarks: string, format: "tasks" | "dataview", date: string): string { + const completed = new Set(completedMarks.split("|")); + const oldTasks = new Map(); + const visit = (text: string, action: (line: string, index: number) => string): string => { + let fence = "", frontmatter = false; + return text.split("\n").map((line, index) => { + const trimmed = line.trim(); + if (index === 0 && trimmed === "---") { frontmatter = true; return line; } + if (frontmatter) { if (trimmed === "---") frontmatter = false; return line; } + const match = /^(`{3,}|~{3,})/.exec(trimmed); + if (match) { if (!fence) fence = match[1][0]; else if (match[1][0] === fence) fence = ""; return line; } + return fence ? line : action(line, index); + }).join("\n"); + }; + const identity = (match: RegExpExecArray) => `${match[1]}${match[3]}${match[4].replace(completion, "").trim()}`; + visit(before, line => { const match = taskLine.exec(line); if (match) { const key = identity(match), previous = oldTasks.get(key); oldTasks.set(key, { mark: match[2], count: (previous?.count || 0) + 1 }); } return line; }); + return visit(after, line => { + const match = taskLine.exec(line); if (!match) return line; + const previous = oldTasks.get(identity(match)); + if (!previous || previous.count !== 1 || completed.has(previous.mark) === completed.has(match[2])) return line; + if (!completed.has(match[2])) return line.replace(completion, ""); + if (/(?:✅\s*\d{4}-\d{2}-\d{2}|\[completion::)/.test(line)) return line; + return `${line.trimEnd()} ${format === "dataview" ? `[completion:: ${date}]` : `✅ ${date}`}`; + }); +} + +/** Covers reading-view clicks and other vault writes as well as source edits. */ +export class MarkdownStatusSync extends Component { + private snapshots = new Map(); + private queues = new Map>(); + private disposed = false; + constructor(private plugin: TaskProgressBarPlugin) { super(); } + onload(): void { + const { app } = this.plugin; + const remember = async (file: TFile | null) => { + if (file?.extension !== "md" || this.snapshots.has(file.path)) return; + const text = await app.vault.read(file); + if (!this.disposed && !this.snapshots.has(file.path)) this.snapshots.set(file.path, text); + }; + this.registerEvent(app.workspace.on("file-open", file => { void remember(file).catch(console.error); })); + this.registerEvent(app.vault.on("modify", file => { + if (!(file instanceof TFile) || file.extension !== "md") return; + const queue = (this.queues.get(file.path) || Promise.resolve()).then(() => this.sync(file)).catch(console.error); + this.queues.set(file.path, queue); + void queue.finally(() => { if (this.queues.get(file.path) === queue) this.queues.delete(file.path); }); + })); + this.registerEvent(app.vault.on("delete", file => this.snapshots.delete(file.path))); + this.registerEvent(app.vault.on("rename", (file, oldPath) => { const text = this.snapshots.get(oldPath); this.snapshots.delete(oldPath); if (text !== undefined) this.snapshots.set(file.path, text); })); + app.workspace.onLayoutReady(() => { + void remember(app.workspace.getActiveFile()).catch(console.error); + // Seed only task-bearing notes; never rewrite the initial contents. + const files = app.vault.getMarkdownFiles().filter(file => app.metadataCache.getFileCache(file)?.listItems?.some(item => item.task !== undefined)); + void (async () => { for (const file of files) { if (this.disposed) return; await remember(file); } })().catch(console.error); + }); + } + private async sync(file: TFile): Promise { + if (this.disposed) return; + const before = this.snapshots.get(file.path), after = await this.plugin.app.vault.read(file); + this.snapshots.set(file.path, after); + if (before === undefined) return; + const settings = this.plugin.settings; + const next = stampStatusTransitions(before, after, settings.taskStatuses.completed || "x|X", settings.preferMetadataFormat, moment().format("YYYY-MM-DD")); + if (next === after || this.disposed) return; + await this.plugin.app.vault.process(file, current => { + if (current !== after) return current; + this.snapshots.set(file.path, next); return next; + }); + } + onunload(): void { this.disposed = true; this.snapshots.clear(); } +} diff --git a/src/services/view-settings-signature.ts b/src/services/view-settings-signature.ts new file mode 100644 index 000000000..df2eede05 --- /dev/null +++ b/src/services/view-settings-signature.ts @@ -0,0 +1,9 @@ +/** UI configuration only; saving workspace navigation must not refresh every view. */ +export function snapshotViewSettings(settings: any): string { + return JSON.stringify([ + settings.viewConfiguration, + settings.customCalendarViews, + settings.defaultViewMode, + settings.fluentView, + ]); +} diff --git a/src/setting.ts b/src/setting.ts index 7c6438df6..979abf84e 100644 --- a/src/setting.ts +++ b/src/setting.ts @@ -1,3 +1,4 @@ +import { t as settingsText } from "@/translations/helper"; import { App, PluginSettingTab, @@ -38,19 +39,21 @@ import { renderCalendarViewSettingsTab, } from "./components/features/settings"; import { renderFileFilterSettingsTab } from "./components/features/settings/tabs/FileFilterSettingsTab"; -import { renderTimeParsingSettingsTab } from "./components/features/settings/tabs/TimeParsingSettingsTab"; + import { SettingsSearchComponent } from "./components//features/settings/components/SettingsSearchComponent"; import { renderMcpIntegrationSettingsTab } from "./components/features/settings/tabs/McpIntegrationSettingsTab"; import { IframeModal } from "@/components/ui/modals/IframeModal"; import { renderTaskTimerSettingTab } from "./components/features/settings/tabs/TaskTimerSettingsTab"; import { renderBasesSettingsTab } from "./components/features/settings/tabs/BasesSettingsTab"; import { renderWorkspaceSettingsTab } from "@/components/features/settings/tabs/WorkspaceSettingTab"; +import type { PointsDashboard } from "./components/features/rewards/PointsDashboard"; export class TaskProgressBarSettingTab extends PluginSettingTab { plugin: TaskProgressBarPlugin; private debouncedApplySettings: () => void; private debouncedApplyNotifications: () => void; private searchComponent: SettingsSearchComponent | null = null; + private pointsSettingsDashboard?: PointsDashboard; // Tabs management private currentTab: string = "general"; @@ -79,13 +82,13 @@ export class TaskProgressBarSettingTab extends PluginSettingTab { id: "view-settings", name: t("Views"), icon: "layout", - category: "core", + category: "display", }, { id: "interface", name: t("Interface"), icon: "layout-dashboard", - category: "core", + category: "display", }, { id: "file-filter", @@ -126,7 +129,7 @@ export class TaskProgressBarSettingTab extends PluginSettingTab { id: "project", name: t("Projects"), icon: "folder-open", - category: "core", + category: "management", }, // Workflow & Automation @@ -146,31 +149,26 @@ export class TaskProgressBarSettingTab extends PluginSettingTab { id: "quick-capture", name: t("Quick Capture"), icon: "zap", - category: "workflow", + category: "management", }, { id: "task-timer", - name: "Task Timer", + name: settingsText("Task Timer"), icon: "timer", category: "workflow", }, - { - id: "time-parsing", - name: t("Time Parsing"), - icon: "clock", - category: "workflow", - }, + { id: "timeline-sidebar", name: t("Timeline Sidebar"), icon: "clock", - category: "workflow", + category: "display", }, // Gamification { id: "reward", - name: t("Rewards"), + name: t("Points and rewards"), icon: "gift", category: "gamification", }, @@ -186,7 +184,7 @@ export class TaskProgressBarSettingTab extends PluginSettingTab { id: "calendar-views", name: t("Calendar Views"), icon: "calendar-range", - category: "integration", + category: "display", }, { id: "ics-integration", @@ -303,7 +301,7 @@ export class TaskProgressBarSettingTab extends PluginSettingTab { const categories = { core: { name: t("Core Settings"), tabs: [] as typeof this.tabs }, display: { - name: t("Display & Progress"), + name: t("Views & Display"), tabs: [] as typeof this.tabs, }, management: { @@ -315,7 +313,7 @@ export class TaskProgressBarSettingTab extends PluginSettingTab { tabs: [] as typeof this.tabs, }, gamification: { - name: t("Gamification"), + name: t("Habits and points"), tabs: [] as typeof this.tabs, }, integration: { @@ -612,12 +610,14 @@ export class TaskProgressBarSettingTab extends PluginSettingTab { } display(): void { + this.pointsSettingsDashboard?.unload(); + this.pointsSettingsDashboard = undefined; const { containerEl } = this; containerEl.empty(); // Ensure we start with general tab if no tab is set - if (!this.currentTab) { + if (!this.currentTab || this.currentTab !== "workspaces" && !this.tabs.some(tab => tab.id === this.currentTab)) { this.currentTab = "general"; } @@ -656,9 +656,6 @@ export class TaskProgressBarSettingTab extends PluginSettingTab { const taskTimerSection = this.createTabSection("task-timer"); this.displayTaskTimerSettings(taskTimerSection); - // Time Parsing Tab - const timeParsingSection = this.createTabSection("time-parsing"); - this.displayTimeParsingSettings(timeParsingSection); // Timeline Sidebar Tab const timelineSidebarSection = @@ -769,8 +766,6 @@ export class TaskProgressBarSettingTab extends PluginSettingTab { return `${base}/quick-capture`; case "task-timer": return `${base}/task-timer`; - case "time-parsing": - return `${base}/time-parsing`; case "workflow": return `${base}/workflows`; case "timeline-sidebar": @@ -838,9 +833,6 @@ export class TaskProgressBarSettingTab extends PluginSettingTab { this.renderTaskTimerSettingsTab(containerEl); } - private displayTimeParsingSettings(containerEl: HTMLElement): void { - renderTimeParsingSettingsTab(this, containerEl); - } private displayTimelineSidebarSettings(containerEl: HTMLElement): void { renderTimelineSidebarSettingsTab(this, containerEl); @@ -902,7 +894,12 @@ export class TaskProgressBarSettingTab extends PluginSettingTab { // START: New Reward Settings Section private displayRewardSettings(containerEl: HTMLElement): void { - renderRewardSettingsTab(this, containerEl); + this.pointsSettingsDashboard = renderRewardSettingsTab(this, containerEl); + } + + hide(): void { + this.pointsSettingsDashboard?.unload(); + this.pointsSettingsDashboard = undefined; } private displayHabitSettings(containerEl: HTMLElement): void { diff --git a/src/styles/calendar/view.css b/src/styles/calendar/view.css index e693ff703..2cd9b82f0 100644 --- a/src/styles/calendar/view.css +++ b/src/styles/calendar/view.css @@ -879,3 +879,14 @@ min-width: 28px; } } + +/* Keep the existing year grid; give its actual clipped container a scrollport. */ +.full-calendar-container, +.full-calendar-container .calendar-view-container { min-height: 0; } +.full-calendar-container .calendar-view-container { flex: 1 1 0%; } +.full-calendar-container .calendar-view-container.view-year .tg-view-container, +.full-calendar-container .tg-view-container.tg-year-view { + min-height: 0; + overflow-y: auto; + display: block; +} diff --git a/src/styles/fluent/fluent-main.css b/src/styles/fluent/fluent-main.css index 06eb3a795..598ecdd90 100644 --- a/src/styles/fluent/fluent-main.css +++ b/src/styles/fluent/fluent-main.css @@ -17,6 +17,7 @@ } .tg-fluent-layout { + position: relative; display: flex; height: 100%; width: 100%; @@ -621,7 +622,7 @@ button.fluent-new-task-btn:hover { .bases-view .tg-kanban-filters, .tg-fluent-content .content-header, -.tg-fluent-main-container:has(.fluent-top-navigation:not(.other-view)) +.workspace-leaf-content:has(.view-header .fluent-top-navigation:not(.other-view)) .tg-fluent-main-container .tg-fluent-content .tg-kanban-filters { display: none; @@ -656,12 +657,6 @@ button.fluent-new-task-btn:hover { /* Mobile-specific media query */ @media (max-width: 480px) { - /* Ensure drawer takes appropriate width on small screens */ - .tg-fluent-sidebar-container.is-mobile-drawer { - width: 75vw !important; - max-width: 320px !important; - } - /* Make hamburger button more prominent on mobile */ .fluent-hamburger-button { width: 44px; @@ -765,7 +760,7 @@ button.fluent-new-task-btn:hover { /* ===== Mobile Drawer Styles ===== */ .drawer-overlay { - position: fixed; + position: absolute; top: 0; left: 0; right: 0; @@ -784,13 +779,14 @@ button.fluent-new-task-btn:hover { /* Mobile drawer sidebar */ .tg-fluent-sidebar-container.is-mobile-drawer { - position: fixed; + position: absolute; top: 0; left: 0; bottom: 0; - width: 280px !important; - max-width: 85vw !important; - min-width: 280px !important; + width: min(300px, 85%); + max-width: 85%; + min-width: 0; + visibility: hidden; z-index: 1000; transform: translateX(-100%); transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1); @@ -799,6 +795,7 @@ button.fluent-new-task-btn:hover { /* When drawer is open */ .drawer-open .tg-fluent-sidebar-container.is-mobile-drawer { + visibility: visible; transform: translateX(0); } @@ -1016,3 +1013,174 @@ button.fluent-new-task-btn:hover { border-radius: 4px; z-index: 1000; } + +/* Keep navigation inside Obsidian's existing title bar. */ +.view-header:has(.tg-fluent-top-nav) { height: auto; min-height: 48px; flex-wrap: wrap; } +.view-header:has(.tg-fluent-top-nav) .view-header-title-container { flex: 1; min-width: 0; padding: 0; overflow: visible; } +.view-header .tg-fluent-top-nav { width: 100%; min-width: 0; border: 0; background: transparent; } +.view-header .fluent-top-navigation { height: auto; min-height: 42px; padding: 4px 8px; gap: 12px; flex-wrap: wrap; -webkit-app-region: no-drag; } +.view-header .fluent-nav-left { flex: 1 1 220px; min-width: 140px; } +.view-header .fluent-search-container { max-width: none; } +.view-header .fluent-nav-center, .view-header .fluent-nav-right { flex-shrink: 0; } +.view-header .fluent-view-tabs { display: flex; } +.view-header .fluent-nav-center { display: flex; } + +.view-header .tg-fluent-top-nav { pointer-events: auto; } +.tg-saved-filter-select { max-width: 180px; min-width: 92px; } + +.view-header:has(.tg-fluent-top-nav) { --icon-size: 16px; min-height: 38px; gap: 4px; } +.view-header .fluent-top-navigation { min-height: 34px; padding: 0 4px; gap: 8px; background: transparent; } +.view-header .fluent-nav-icon-button, .view-header .tg-quick-filter-button, .view-header .fluent-view-tab, .view-header .view-action, .view-header .fluent-nav-custom-button-wrapper .clickable-icon { height: 28px; min-height: 28px; width: 28px; padding: 5px; border: 0; border-radius: var(--radius-s); box-shadow: none; background: transparent; color: var(--icon-color); } +.view-header .fluent-view-tab { width: auto; gap: 5px; padding: 5px 8px; } +.view-header .fluent-view-tabs { padding: 0; background: transparent; } +.view-header .fluent-nav-right { gap: 4px; } +.view-header .fluent-search-container { align-items: center; } +.view-header .fluent-nav-icon-button:hover, .view-header .fluent-view-tab:hover { background: var(--background-modifier-hover); color: var(--icon-color-hover); } +.view-header .fluent-view-tab.is-active, .view-header .tg-quick-filter-button.is-active { background: var(--background-modifier-hover); color: var(--text-accent); } + +/* Both sidebar regions remain reachable, including empty drop targets. */ +.fluent-sidebar-content { min-height: 0; overflow-x: hidden; overscroll-behavior: contain; } +.fluent-sidebar-content > .fluent-sidebar-section { flex-shrink: 0; } +.fluent-sidebar-content .fluent-navigation-list { min-height: 28px; } +.fluent-sidebar-rail { overflow-y: auto; min-height: 0; } + +/* One flat header surface, including Obsidian's own navigation/actions. */ +.view-header:has(.tg-fluent-top-nav) { flex-wrap: nowrap; padding: 0 8px; align-items: center; } +.view-header:has(.tg-fluent-top-nav) :is(.view-header-nav-buttons, .view-actions, .panel-toggle-container, .panel-toggle-btn) { + background: transparent; border: 0; box-shadow: none; margin: 0; padding: 0; align-items: center; gap: 4px; +} +.view-header:has(.tg-fluent-top-nav) :is(.view-header-nav-buttons, .view-actions) { display: flex; flex-shrink: 0; height: 34px; } +.view-header:has(.tg-fluent-top-nav) :is(.view-header-nav-buttons, .view-actions)::before, +.view-header:has(.tg-fluent-top-nav) :is(.view-header-nav-buttons, .view-actions)::after { display: none; } +.view-header:has(.tg-fluent-top-nav) .fluent-top-navigation { flex-wrap: nowrap; border: 0; box-shadow: none; } +.view-header:has(.tg-fluent-top-nav) :is(.fluent-nav-right, .fluent-nav-custom-buttons) { display: flex; align-items: center; gap: 4px; } +.view-header:has(.tg-fluent-top-nav) .fluent-nav-left { flex-basis: 100px; min-width: 80px; } + +.fluent-sidebar-rail > .fluent-rail-btn { flex-shrink: 0; } +.view-header:has(.tg-fluent-top-nav) :is(.view-header-left, .view-header-title-container, .view-header-nav-buttons .clickable-icon) { border: 0; box-shadow: none; } + +.view-header .tg-active-filter-label { flex: 0 0 auto; max-width: none; overflow: visible; text-overflow: clip; } +.view-header .fluent-search-container { min-width: 0; flex-wrap: nowrap; } + +.view-header .fluent-search-container > .search-input-container { flex: 1; min-width: 80px; } + +.view-header:has(.tg-fluent-top-nav) .fluent-nav-left { flex: 1 1 300px; min-width: min(100%, 300px); } + +/* In-view phone toolbar with a dedicated first-row slot for the drawer button. */ +.tg-fluent-phone-toolbar { + position: relative; + flex-shrink: 0; +} + +.tg-fluent-phone-toolbar > .tg-fluent-top-nav.fluent-top-navigation { + height: auto; + min-height: 48px; + padding: 4px 8px; + gap: 4px; + flex-wrap: wrap; +} + +.tg-fluent-phone-toolbar .fluent-nav-left { + flex: 1 0 100%; + min-width: 0; + padding-inline-start: 44px; + box-sizing: border-box; +} + +.tg-fluent-phone-toolbar .fluent-search-container { + max-width: none; + min-width: 0; + flex-wrap: wrap; + gap: 4px; +} + +.tg-fluent-phone-toolbar .search-input-container { + flex: 1 1 0; + width: auto; + min-width: 0; +} + +.tg-fluent-phone-toolbar .search-input-container input { + width: 100%; + min-height: 40px; + font-size: 16px; +} + +.tg-fluent-phone-toolbar .tg-active-filter-label { + flex-basis: 100%; + white-space: normal; + overflow-wrap: anywhere; +} + +.tg-fluent-phone-toolbar :is(.fluent-nav-center, .fluent-view-tabs, .fluent-nav-right, .fluent-nav-custom-buttons) { + display: flex; + flex-wrap: wrap; + min-width: 0; + gap: 2px; +} + +.tg-fluent-phone-toolbar .fluent-nav-right { + margin-inline-start: auto; +} + +.tg-fluent-phone-toolbar .panel-toggle-container { + position: absolute; + inset: 4px auto auto 8px; +} + +.tg-fluent-phone-toolbar :is(.fluent-view-tab, .fluent-nav-icon-button, .panel-toggle-btn button, .fluent-nav-custom-button-wrapper .clickable-icon) { + box-sizing: border-box; + min-width: 40px; + min-height: 40px; + padding: 8px; + justify-content: center; +} + +.tg-fluent-phone-toolbar .fluent-view-tab > span { + display: none; +} + +@media (max-width: 520px) { + .tg-saved-filter-modal .setting-item { + flex-wrap: wrap; + } + + .tg-saved-filter-modal .setting-item-control { + flex: 1 1 100%; + min-width: 0; + flex-wrap: wrap; + } + + .tg-saved-filter-modal .setting-item-control :is(input, select, textarea) { + max-width: 100%; + min-height: 40px; + } +} + +/* Let the native header fit its controls, including when modern styling is enabled. */ +.is-phone .workspace-leaf-content[data-type="fluent-task-genius-view"] { + --tg-fluent-header-height: auto; +} + +.is-phone .workspace-leaf-content[data-type="fluent-task-genius-view"] > .view-header { + height: auto; + min-height: 0; + flex-shrink: 0; + margin-block: 0; +} + +.is-phone .workspace-leaf-content[data-type="fluent-task-genius-view"] > .task-genius-fluent-view { + flex: 1 1 0; + height: auto; + min-height: 0; +} + +.tg-fluent-main-container > .tg-fluent-phone-toolbar + .tg-fluent-content-wrapper { + flex: 1 1 0; + height: auto; + min-height: 0; +} + +.tg-fluent-phone-toolbar .fluent-top-navigation.other-view .fluent-nav-left { + flex: 1 1 0; +} diff --git a/src/styles/fluent/fluent-modern.css b/src/styles/fluent/fluent-modern.css index af1025a2f..1aec5c274 100644 --- a/src/styles/fluent/fluent-modern.css +++ b/src/styles/fluent/fluent-modern.css @@ -126,7 +126,7 @@ .workspace-leaf-content[data-type^="fluent-task-genius-view"] .view-header { background-color: var(--modern-background-primary); border-radius: var(--radius-m); - height: var(--header-height); + height: var(--tg-fluent-header-height, var(--header-height)); display: flex; z-index: 1; position: relative; @@ -142,7 +142,7 @@ } .workspace-leaf-content[data-type^="fluent-task-genius-view"] .view-header { - height: var(--view-header-height); + height: var(--tg-fluent-header-height, var(--view-header-height)); } .tg-fluent-sidebar-container.fluent-sidebar:not(.is-collapsed) { diff --git a/src/styles/gantt/gantt.css b/src/styles/gantt/gantt.css index 12311bbe5..463234008 100644 --- a/src/styles/gantt/gantt.css +++ b/src/styles/gantt/gantt.css @@ -507,3 +507,13 @@ overflow: hidden; text-overflow: ellipsis; } + +.gantt-project-controls { display: flex; align-items: center; gap: 8px; padding: 4px 8px; } +.gantt-task-item:has(.gantt-resize-handle) { cursor: grab; touch-action: none; } +.gantt-task-item:active { cursor: grabbing; } +.gantt-resize-handle { fill: var(--interactive-accent); opacity: .3; cursor: ew-resize; touch-action: none; } +.gantt-task-item:hover .gantt-resize-handle { opacity: 1; } + +.gantt-scroll-container.is-panning { cursor: grabbing; user-select: none; } + +.gantt-drag-date-hint { position: fixed; z-index: 10000; pointer-events: none; padding: 6px 10px; border-radius: 6px; background: var(--background-secondary); color: var(--text-normal); box-shadow: var(--shadow-s); border: 1px solid var(--background-modifier-border); font-variant-numeric: tabular-nums; } diff --git a/src/styles/habit.css b/src/styles/habit.css index 4dc21494f..751c12280 100644 --- a/src/styles/habit.css +++ b/src/styles/habit.css @@ -570,3 +570,32 @@ max-height: 60vh; overflow: auto; } + +.tg-habit-component-container.tg-habits-surface { border: 0; box-shadow: none; border-radius: 0; background: var(--background-primary); } +.tg-habits-surface .habits-dashboard, .tg-habits-surface .habits-compact { border: 0; box-shadow: none; border-radius: 0; background: transparent; } +.tg-native-habits { max-width: 960px; margin: 0 auto; padding: 12px; } +.tg-native-habit-nav { display: flex; align-items: center; justify-content: flex-end; gap: 8px; margin-bottom: 16px; } +.tg-native-habit-card { margin: 0 0 16px; padding: 16px; border: 1px solid var(--background-modifier-border); border-radius: var(--radius-m); } +.tg-native-habit-heading { display: flex; align-items: center; gap: 10px; margin-bottom: 16px; } +.tg-native-habit-heading strong { flex: 1; } +.tg-native-habit-body { display: flex; align-items: center; gap: 24px; } +.tg-native-habit-grid { display: grid; grid-template-columns: repeat(10, minmax(12px, 20px)); gap: 6px; flex: 1; } +.tg-native-habit-cell { width: 20px; height: 20px; padding: 0; border: 0; border-radius: 4px; background: var(--background-modifier-border); box-shadow: none; } +.tg-native-habit-cell.is-complete { background: var(--habit-accent, var(--interactive-accent)); } +.tg-native-habit-cell.is-rest { opacity: .45; } +.tg-native-habit-controls { display: flex; align-items: center; gap: 8px; } +.tg-native-habit-controls .is-complete { color: var(--habit-accent, var(--interactive-accent)); } +.tg-native-habit-period { color: var(--text-muted); font-size: var(--font-ui-small); margin-top: 10px; } +@media(max-width: 550px) { .tg-native-habit-body { flex-wrap: wrap; gap: 12px; } .tg-native-habit-grid { grid-template-columns: repeat(10, minmax(8px, 1fr)); } .tg-native-habit-cell { width: 100%; max-width: 20px; } } + +.tg-dependency-chips { display: flex; flex-wrap: wrap; gap: 6px; } +.tg-dependency-chip { display: flex; align-items: center; gap: 6px; border-radius: var(--radius-s); padding: 4px 8px; background: var(--background-secondary); } + +.tg-native-habit-cell[data-heat="0"] { background: var(--background-modifier-border); } +.tg-native-habit-cell[data-heat="1"] { background: color-mix(in srgb, var(--habit-accent, var(--interactive-accent)) 35%, var(--background-primary)); } +.tg-native-habit-cell[data-heat="2"] { background: color-mix(in srgb, var(--habit-accent, var(--interactive-accent)) 72%, var(--background-primary)); } +.tg-native-habit-cell[data-heat="3"] { background: var(--habit-accent, var(--interactive-accent)); box-shadow: inset 0 0 0 1px var(--text-accent); } +.tg-native-habit-cell.is-over-limit, .tg-native-habit-controls .is-over-limit { background: var(--background-modifier-error); color: var(--text-error); } +.tg-native-habit-goal { margin-top: 10px; color: var(--text-muted); font-size: var(--font-ui-small); } + +.tg-native-heat-legend { display: flex; gap: 12px; flex-wrap: wrap; margin: 0 0 12px; color: var(--text-muted); font-size: var(--font-ui-smaller); } diff --git a/src/styles/points-dashboard.css b/src/styles/points-dashboard.css new file mode 100644 index 000000000..3889c9835 --- /dev/null +++ b/src/styles/points-dashboard.css @@ -0,0 +1,67 @@ +.tg-points-page { + box-sizing: border-box; + width: 100%; + height: 100%; + overflow: auto; + padding: clamp(18px, 3vw, 42px); + color: var(--text-normal); + background: radial-gradient(ellipse at 85% 0%, color-mix(in srgb, var(--interactive-accent) 12%, transparent), transparent 42%); +} +.tg-points-header { display:flex; align-items:center; justify-content:space-between; gap:20px; flex-wrap:wrap; margin:0 auto 26px; max-width:none; } +.tg-points-heading { font-size:1.8em; font-weight:700; letter-spacing:-.025em; } +.tg-points-subtitle,.tg-points-date,.tg-points-label { color:var(--text-muted); } +.tg-points-summary,.tg-points-columns { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:16px; max-width:none; margin:0 auto 18px; } +.tg-points-summary { grid-template-columns: repeat(2, minmax(0, 1fr)); } +.tg-points-card,.tg-points-panel { border:1px solid var(--background-modifier-border); border-radius:16px; background:color-mix(in srgb,var(--background-secondary) 88%,transparent); box-shadow:0 10px 34px color-mix(in srgb,#000 10%,transparent); } +.tg-points-card { min-height:118px; padding:22px; } +.tg-points-card.is-primary { background:linear-gradient(130deg,color-mix(in srgb,var(--interactive-accent) 18%,var(--background-secondary)),var(--background-secondary)); } +.tg-points-balance { margin-top:10px; font-size:2.5em; font-weight:750; } +.tg-points-columns { grid-template-columns:minmax(0,1.15fr) minmax(300px,.85fr); align-items:start; } +.tg-points-panel { padding:22px; min-width:0; } +.tg-points-panel h3 { margin:0 0 18px; } +.tg-points-entry,.tg-reward-card { display:flex; justify-content:space-between; align-items:center; gap:14px; padding:14px 0; border-top:1px solid var(--background-modifier-border); } +.tg-points-delta { color:var(--color-green); font-weight:650; white-space:nowrap; } +.tg-points-delta.is-negative { color:var(--color-red); } +.tg-points-date { margin-top:4px; font-size:.82em; } +.tg-points-shop-header,.tg-reward-actions { display:flex; align-items:center; gap:8px; } +.tg-points-shop-header { justify-content:space-between; } +.tg-reward-actions button { padding:4px 8px; } +.tg-reward-name { font-weight:600; } +.tg-points-empty { padding:24px 0; color:var(--text-muted); } +@media(max-width:850px) { .tg-points-columns { grid-template-columns:1fr; } .tg-points-summary { grid-template-columns:1fr 1fr; } } +@media(max-width:520px) { .tg-points-summary { grid-template-columns:1fr; } .tg-points-header { align-items:flex-start; flex-direction:column; } .tg-points-panel { padding:16px; } } +.tg-points-page { width:100%; max-width:none; margin:0 auto; overflow-y:auto; min-height:0; } +.tg-points-page h2 { margin:0 0 8px; font-size:24px; } +.tg-points-tabs { display:flex; gap:6px; padding:5px; margin:20px 0 14px; border-radius:12px; background:var(--background-secondary); flex-wrap:wrap; } +.tg-points-tabs button { border:0; background:transparent; box-shadow:none; color:var(--text-muted); padding:9px 15px; border-radius:9px; } +.tg-points-tabs button.is-active { background:var(--background-primary); color:var(--text-normal); box-shadow:0 1px 4px var(--background-modifier-box-shadow); } +.tg-points-tools { display:flex; align-items:center; gap:12px; margin-bottom:16px; } +.tg-points-tools .search-input-container { flex:1; } +.tg-points-body { display:grid; gap:16px; } +.tg-points-body.is-actions { grid-template-columns:minmax(0,1fr) minmax(0,1fr); align-items:start; } +.tg-points-body.is-history { grid-template-columns:minmax(0,1.4fr) minmax(0,1fr); align-items:start; } +.tg-points-body .tg-points-panel { min-width:0; } +.tg-points-body .tg-reward-card { margin:10px 0; gap:16px; align-items:center; } +.tg-points-body .tg-reward-card > div:first-child { flex:1; overflow-wrap:anywhere; } +.tg-points-body .setting-item { gap:16px; } +.tg-points-body .tg-habits-surface { min-height:250px; } +.tg-quick-filter-button.is-active { color:var(--interactive-accent); background:var(--background-modifier-hover); } +@media (max-width:600px) { .tg-points-page { padding:12px; } .tg-points-tabs button { flex:1; padding:8px; } .tg-points-summary { grid-template-columns:1fr; } .tg-points-header { align-items:flex-start; } } +@media (max-width:850px) { .tg-points-body.is-actions,.tg-points-body.is-history { grid-template-columns:minmax(0,1fr); } } + +.tg-points-entry { display: grid; grid-template-columns: minmax(0, 1fr) 100px 64px; } +.tg-points-entry > :nth-child(2) { text-align: right; font-variant-numeric: tabular-nums; } +.tg-points-entry > button { grid-column: 3; } + +.tg-points-page > * { max-width: none; width: 100%; box-sizing: border-box; } +.tg-points-body.is-history { grid-template-columns: repeat(2, minmax(0, 1fr)); } +.tg-points-page .tg-points-entry { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 16px; align-items: center; } +.tg-points-page .tg-points-entry > :last-child { text-align: right; min-width: 6.5em; font-variant-numeric: tabular-nums; justify-self: end; } +@media(max-width:850px) { .tg-points-body.is-history { grid-template-columns: minmax(0, 1fr); } } + +/* Both catalog editors use the same full-width, horizontally scrollable field. */ +.modal.tg-points-list-modal { width: min(1120px, 94vw); max-width: 94vw; } +.tg-points-list-modal .tg-points-list-field { flex-direction: column; align-items: stretch; gap: 12px; } +.tg-points-list-field .setting-item-info { margin: 0; } +.tg-points-list-field .setting-item-control { width: 100%; min-width: 0; } +.tg-points-list-field textarea { box-sizing: border-box; width: 100%; min-width: 0; max-width: 100%; min-height: 300px; resize: vertical; white-space: pre; overflow: auto; line-height: 1.7; } diff --git a/src/styles/project-view.css b/src/styles/project-view.css index 2519815fc..cb1308f46 100644 --- a/src/styles/project-view.css +++ b/src/styles/project-view.css @@ -354,3 +354,8 @@ background: var(--background-modifier-hover); color: var(--text-normal); } + +.tg-project-folder-row { display:flex; align-items:center; gap:6px; width:100%; background:transparent; border:0; box-shadow:none; color:var(--text-muted); padding:8px 4px; justify-content:flex-start; text-align:left; } +.tg-project-folder-row svg { width:15px; height:15px; } +.tg-project-folder-children { padding-left:14px; } +.tg-project-folder-children[hidden] { display:none; } diff --git a/src/styles/quadrant/quadrant.css b/src/styles/quadrant/quadrant.css index 40fba0f58..fbf87749b 100644 --- a/src/styles/quadrant/quadrant.css +++ b/src/styles/quadrant/quadrant.css @@ -980,3 +980,9 @@ background: linear-gradient(to top, var(--background-primary), transparent); z-index: 1; } + +.tg-quadrant-card-header { display: flex; align-items: flex-start; gap: 8px; } +.tg-quadrant-card-header .tg-quadrant-card-checkbox { flex: 0 0 auto; padding-top: 2px; } +.tg-quadrant-card-header .tg-quadrant-card-content { flex: 1; min-width: 0; margin: 0; padding: 0; } +.tg-quadrant-card-title p { margin: 0; } +.tg-quadrant-card-header .tg-quadrant-card-actions { flex: 0 0 auto; } diff --git a/src/styles/quick-capture.css b/src/styles/quick-capture.css index 8b29ccbaf..ca3efc651 100644 --- a/src/styles/quick-capture.css +++ b/src/styles/quick-capture.css @@ -595,27 +595,6 @@ margin-top: 8px; } -/* Mobile optimization */ -@media (max-width: 768px) { - .quick-capture-modal.full { - width: 95vw; - } - - .quick-capture-layout { - flex-direction: column; - } - - .quick-capture-config-panel { - max-width: 100%; - border-right: none; - border-bottom: 1px solid var(--background-modifier-border); - padding-right: 0; - padding-bottom: 16px; - margin-bottom: 16px; - max-height: 40%; - } -} - .quick-capture-config-panel .details-status-selector { display: flex; flex-direction: row; @@ -636,3 +615,135 @@ .quick-capture-modal .setting-item-control input[type="datetime-local"] { width: 10rem; } + +.tg-date-time-picker { display: flex; gap: 5px; flex-wrap: nowrap; min-width: 0; } +.tg-date-time-picker input[type=date] { min-width: 125px; width: 130px; } +.tg-date-time-picker input[type=time] { width: 100px; } +.calendar-current-date[role=button] { cursor: pointer; } +.calendar-current-date[role=button]:hover { color: var(--text-accent); } + +.tg-active-filter-label { max-width: none; flex-shrink: 0; white-space: nowrap; font-size: var(--font-ui-small); color: var(--text-accent); } +.tg-active-filter-label[hidden] { display:none; } + +.quick-capture-modal.full { width: min(1120px, 96vw); max-width: 1120px; min-height: 0; } +.quick-capture-modal .quick-capture-config-panel { flex: 0 0 420px; max-width: 46%; min-width: 0; } +.quick-capture-modal .quick-capture-config-panel .setting-item { gap: 8px; } +.quick-capture-modal .quick-capture-config-panel .setting-item-info { flex: 0 0 104px; margin-right: 0; } +.quick-capture-modal .quick-capture-config-panel .setting-item-name { white-space: nowrap; } +.quick-capture-modal .quick-capture-config-panel .setting-item-control { min-width: 0; flex: 1; justify-content: flex-end; } +.quick-capture-modal input[hidden] { display: none !important; } +.tg-date-time-picker input[type=date] { flex: 0 0 138px; width: 138px; } +.tg-date-time-picker input[type=time] { flex: 0 0 100px; width: 100px; } +.tg-date-time-picker .tg-clear-time { flex: 0 0 24px; width: 24px; min-width: 24px; padding: 0; } +@media (max-width: 800px) { + .quick-capture-modal.full { + display: flex; + flex-direction: column; + } + + .quick-capture-modal.full > .modal-content { + display: flex; + flex-direction: column; + min-height: 0; + overflow: hidden; + } + + .quick-capture-modal.full .quick-capture-content { + min-height: 0; + overflow: auto; + } + + .quick-capture-modal.full .quick-capture-layout { + flex-direction: column; + height: auto; + } + + .quick-capture-modal.full .quick-capture-config-panel { + flex-basis: auto; + max-width: 100%; + border-right: 0; + border-bottom: 1px solid var(--background-modifier-border); + padding: 0 0 12px; + overflow: visible; + } + + .quick-capture-modal.full .quick-capture-footer { + flex-shrink: 0; + } +} + +.quick-capture-additional > summary { cursor: pointer; color: var(--text-muted); padding: 12px 0; } + +@media (max-width: 520px) { + .quick-capture-modal { + box-sizing: border-box; + min-width: 0; + min-height: 0; + max-width: calc(100vw - 16px); + } + + .quick-capture-modal.full { + width: calc(100vw - 16px); + max-width: calc(100vw - 16px); + max-height: calc(100vh - 24px); + max-height: calc(100dvh - 24px); + padding: 12px; + } + + .quick-capture-modal.full .quick-capture-content { + padding: 8px 0; + } + + .quick-capture-modal .details-status-selector { + flex-wrap: wrap; + gap: 4px; + } + + .quick-capture-modal .quick-capture-config-panel .setting-item { + flex-wrap: wrap; + } + + .quick-capture-modal .quick-capture-config-panel :is(.setting-item-info, .setting-item-control) { + flex: 1 1 100%; + } + + .quick-capture-modal .quick-capture-config-panel .setting-item-name { + white-space: normal; + } + + .quick-capture-modal .setting-item-control { + flex-wrap: wrap; + } + + .quick-capture-modal :is(input, select, textarea) { + max-width: 100%; + } + + .quick-capture-modal .tg-date-time-picker { + display: grid; + grid-template-columns: minmax(0, 1.4fr) minmax(0, 1fr) 40px; + width: 100%; + } + + .quick-capture-modal .tg-date-time-picker :is(input[type=date], input[type=time], .tg-clear-time) { + box-sizing: border-box; + min-width: 0; + width: 100%; + min-height: 40px; + } + + .quick-capture-modal .quick-capture-footer { + flex-shrink: 0; + flex-wrap: wrap; + gap: 4px; + padding-inline: 0; + } + + .quick-capture-modal .quick-capture-footer-right { + margin-inline-start: auto; + } + + .quick-capture-modal .quick-capture-footer button { + min-height: 40px; + } +} diff --git a/src/styles/table.css b/src/styles/table.css index e96b39726..b236f9486 100644 --- a/src/styles/table.css +++ b/src/styles/table.css @@ -987,3 +987,7 @@ .task-table-row-level-5 .task-table-cell:first-child { padding-left: 12px; /* Reset to normal padding, let tree structure handle indentation */ } + +.task-table-status { min-width: 84px; width: max-content; gap: 6px; } +.task-table-status-text { white-space: nowrap; overflow: visible; text-overflow: clip; flex-shrink: 0; } +.task-table-status-icon { flex: 0 0 16px; } diff --git a/src/styles/task-planner.css b/src/styles/task-planner.css new file mode 100644 index 000000000..5076be217 --- /dev/null +++ b/src/styles/task-planner.css @@ -0,0 +1,42 @@ +.tg-task-planner { padding: 18px; height: 100%; overflow: auto; } +.tg-planner-nav { display: flex; gap: 8px; align-items: center; margin-bottom: 16px; } +.tg-planner-nav strong { margin-left: auto; } +.tg-planner-layout { display: grid; grid-template-columns: minmax(170px, 240px) minmax(500px, 1fr); gap: 16px; } +.tg-planner-unscheduled { min-height: 200px; border: 1px solid var(--background-modifier-border); padding: 12px; border-radius: var(--radius-m); } +.tg-planner-calendar { display: grid; grid-template-columns: repeat(7,minmax(0,1fr)); gap: 4px; } +.tg-planner-day { min-height: 110px; padding: 6px; border: 1px solid var(--background-modifier-border); border-radius: var(--radius-s); } +.tg-planner-day.is-today { border-color: var(--interactive-accent); } +.tg-planner-day.is-other-month { background: var(--background-secondary); color: var(--text-muted); } +.tg-planner-card { border-radius: var(--radius-s); background: var(--background-modifier-hover); margin-top: 6px; padding: 6px; cursor: grab; overflow-wrap: anywhere; } +.tg-planner-day-label { font-size: var(--font-ui-small); } + +/* Both panes scroll independently, so a long backlog cannot stretch calendar rows. */ +.tg-task-planner { box-sizing: border-box; display: flex; flex-direction: column; min-height: 0; overflow: hidden; } +.tg-planner-nav { flex-shrink: 0; flex-wrap: wrap; } +.tg-planner-layout { flex: 1; min-height: 0; grid-template-columns: minmax(160px, 240px) minmax(0, 1fr); overflow: hidden; align-items: stretch; } +.tg-planner-unscheduled { min-height: 0; overflow-y: auto; box-sizing: border-box; } +.tg-planner-unscheduled h3 { margin: 0 0 12px; font-size: var(--font-ui-medium); color: var(--text-normal); } +.tg-planner-calendar { min-height: 0; overflow: auto; align-content: start; grid-template-rows: 28px repeat(6, minmax(110px, 1fr)); } +.tg-planner-weekday { position: sticky; top: 0; background: var(--background-primary); z-index: 1; } +.tg-planner-day { min-width: 0; box-sizing: border-box; } +@media(max-width: 650px) { .tg-planner-layout { grid-template-columns: minmax(120px, 30%) minmax(0, 1fr); gap: 8px; } .tg-planner-day { padding: 3px; } } + +@media (max-width: 520px) { + .tg-task-planner { + padding: 8px; + } + + .tg-planner-layout { + grid-template-columns: minmax(0, 1fr); + grid-template-rows: minmax(60px, min(25%, 140px)) minmax(0, 1fr); + } + + .tg-planner-calendar { + grid-template-columns: repeat(7, minmax(64px, 1fr)); + overscroll-behavior: contain; + } + + .tg-planner-nav button { + min-height: 40px; + } +} diff --git a/src/styles/taskgenius-calendar.css b/src/styles/taskgenius-calendar.css index 401a3e62b..d237244f4 100644 --- a/src/styles/taskgenius-calendar.css +++ b/src/styles/taskgenius-calendar.css @@ -67,7 +67,7 @@ border-radius: 4px; padding: 2px 6px; font-size: var(--tg-font-event); - color: var(--text-on-accnet); + color: var(--text-normal); background-color: var(--background-secondary-alt) !important; cursor: grab; z-index: 10; @@ -77,7 +77,7 @@ box-shadow: var(--shadow-s); transition: opacity 0.2s, - transform 0.1s; + box-shadow 0.1s; } .tg-event-base:active { @@ -86,7 +86,6 @@ .tg-event-base:hover { opacity: 0.9; - transform: translateY(-1px); box-shadow: var(--shadow-l); color: var(--text-on-accent); background-color: var(--interactive-accent) !important; @@ -681,3 +680,18 @@ transform: scale(1); } } + +/* Geometry belongs to the calendar engine; theme styling must not stretch it. */ +.full-calendar-container .tg-time-grid-container { display: block; height: auto; min-height: 0; } +.full-calendar-container .tg-time-body { flex-shrink: 0; } +.full-calendar-container .tg-day-column { flex: 1 1 0; min-width: 0; box-sizing: border-box; } +.full-calendar-container .tg-time-header { padding-right: 0; } +.full-calendar-container .tg-time-header-cell { flex: 1 1 0; min-width: 0; box-sizing: border-box; } +.full-calendar-container .tg-event-base { box-sizing: border-box; } +.full-calendar-container .tg-event-block .task-list-item-checkbox { flex-shrink: 0; align-self: flex-start; width: 16px; height: 16px; margin: 0 0 2px; } +.full-calendar-container .tg-now-line { position: absolute; left: 0; right: 0; height: 2px; background: var(--color-red, #e5484d); z-index: 70; pointer-events: none; } +.full-calendar-container .tg-now-line::before { content: ""; position: absolute; left: -4px; top: -3px; width: 8px; height: 8px; border-radius: 50%; background: inherit; } + +.full-calendar-container .calendar-header { flex-wrap: wrap; gap: 8px; } + +.full-calendar-container .tg-view-container { min-height: 0; } diff --git a/src/translations/locale/en-gb.ts b/src/translations/locale/en-gb.ts index 0bc4e27ef..4a618d6f3 100644 --- a/src/translations/locale/en-gb.ts +++ b/src/translations/locale/en-gb.ts @@ -1539,8 +1539,6 @@ const translations = { "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 default display mode for all views. This affects how tasks are displayed when you first open a view or create a new view.", "List View": "List View", "Tree View": "Tree View", - "Global Filter Configuration": "Global Filter Configuration", - "Configure global filter rules that apply to all Views by default. Individual Views can override these settings.": "Configure global filter rules that apply to all Views by default. Individual Views can override these settings.", "Cancelled Date": "Cancelled Date", "Configuration is valid": "Configuration is valid", "Action to execute on completion": "Action to execute on completion", diff --git a/src/translations/locale/en.ts b/src/translations/locale/en.ts index 0cedf5156..4cab29be1 100644 --- a/src/translations/locale/en.ts +++ b/src/translations/locale/en.ts @@ -1,5 +1,8 @@ // English translations const translations = { + "Move project tasks into note": "Move project tasks into note", + "Enter a project name.": "Enter a project name.", + "New project": "New project", "Search settings...": "Search settings...", "Clear search": "Clear search", "No settings found": "No settings found", @@ -504,6 +507,7 @@ const translations = { About: "About", "Core Settings": "Core Settings", "Display & Progress": "Display & Progress", + "Views & Display": "Views & Display", "Workflow & Automation": "Workflow & Automation", Gamification: "Gamification", Integration: "Integration", @@ -2054,9 +2058,6 @@ const translations = { "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.", "List View": "List View", "Tree View": "Tree View", - "Global Filter Configuration": "Global Filter Configuration", - "Configure global filter rules that apply to all Views by default. Individual Views can override these settings.": - "Configure global filter rules that apply to all Views by default. Individual Views can override these settings.", "Cancelled Date": "Cancelled Date", "Depends On": "Depends On", "Task IDs separated by commas": "Task IDs separated by commas", @@ -2630,6 +2631,770 @@ const translations = { "Automatically start the timer when creating a new task via quick capture (checkbox mode only)": "Automatically start the timer when creating a new task via quick capture (checkbox mode only)", "Timer started for new task": "Timer started for new task", + + " (truncated)": " (truncated)", + "(Copy)": "(Copy)", + "(space)": "(space)", + "+ Add Custom Cycle": "+ Add Custom Cycle", + "+ Add Status": "+ Add Status", + ", Replacement: ": ", Replacement: ", + "0.0.0.0 (All interfaces - for external access)": "0.0.0.0 (All interfaces - for external access)", + "1 → 2 → 3 → 4 → 5": "1 → 2 → 3 → 4 → 5", + "1) Initialize": "1) Initialize", + "127.0.0.1 (Local only)": "127.0.0.1 (Local only)", + "2) Call tool with session id": "2) Call tool with session id", + "A descriptive name for the workspace": "A descriptive name for the workspace", + "Active strategies: ": "Active strategies: ", + "Add Custom Mapping": "Add Custom Mapping", + "Add Cycle": "Add Cycle", + "Add Detailed Cycle": "Add Detailed Cycle", + "Add Detection Method": "Add Detection Method", + "Add File": "Add File", + "Add Folder": "Add Folder", + "Add Number Cycle": "Add Number Cycle", + "Add Pattern": "Add Pattern", + "Add Simple Cycle": "Add Simple Cycle", + "Add custom status mappings for your workflow.": "Add custom status mappings for your workflow.", + "Add metadata fields that indicate a file should be treated as a task (e.g., dueDate, status, priority)": "Add metadata fields that indicate a file should be treated as a task (e.g., dueDate, status, priority)", + "Add paths that contain task files (e.g., Projects/, Tasks/2024/, Work/TODO/)": "Add paths that contain task files (e.g., Projects/, Tasks/2024/, Work/TODO/)", + "Add progress bar to Projects view": "Add progress bar to Projects view", + "Add tags that indicate a file should be treated as a task (e.g., #task, #todo, #actionable)": "Add tags that indicate a file should be treated as a task (e.g., #task, #todo, #actionable)", + "Add {{value0}} Theme as New Cycle?": "Add {{value0}} Theme as New Cycle?", + "Agenda View": "Agenda View", + "All Workspaces": "All Workspaces", + "All history": "All history", + "All settings have been reset to their default values": "All settings have been reset to their default values", + "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 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.", + "Applied recommended configuration: ": "Applied recommended configuration: ", + "Apply {{value0}} Theme?": "Apply {{value0}} Theme?", + "Are you sure you want to delete \"{{name}}\"? This action cannot be undone.": "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 '{{value0}}' workflow?", + "Are you sure you want to delete the habit ": "Are you sure you want to delete the habit ", + "Are you sure you want to reset all settings to their default values?\n\nThis action cannot be undone.": "Are you sure you want to reset all settings to their default values?\n\nThis action cannot be undone.", + "Arguments:": "Arguments:", + "Auto-detect Status Mappings": "Auto-detect Status Mappings", + "Automatically convert between metadata status values and task symbols": "Automatically convert between metadata status values and task symbols", + "Automatically sync with task status configuration": "Automatically sync with task status configuration", + "Base View Type": "Base View Type", + "Based on: ": "Based on: ", + "Bases Support": "Bases Support", + "Basic": "Basic", + "Blacklist": "Blacklist", + "Block References": "Block References", + "Block reference prefix": "Block reference prefix", + "Both": "Both", + "Bottom Section": "Bottom Section", + "Built-in View Templates": "Built-in View Templates", + "Cache TTL": "Cache TTL", + "Calendar View Configuration": "Calendar View Configuration", + "Calendar Views": "Calendar Views", + "Calendar view created: ": "Calendar view created: ", + "Calendar view updated: ": "Calendar view updated: ", + "Cannot enable views without indexer. Please enable the indexer first in Index & Sources settings.": "Cannot enable views without indexer. Please enable the indexer first in Index & Sources settings.", + "Capture as:": "Capture as:", + "Capture to:": "Capture to:", + "Case Sensitive Matching": "Case Sensitive Matching", + "Changelog": "Changelog", + "Choose a color for this workspace": "Choose a color for this workspace", + "Choose a preset or customize the time range": "Choose a preset or customize the time range", + "Choose an icon for this view": "Choose an icon for this view", + "Choose an icon for this workspace": "Choose an icon for this workspace", + "Choose the note that should be copied; {{CONTENT}} placeholders are replaced, otherwise the captured text is appended.": "Choose the note that should be copied; {{CONTENT}} placeholders are replaced, otherwise the captured text is appended.", + "Choose where this view appears in the sidebar. Views in the bottom section are visually separated from top section views.": "Choose where this view appears in the sidebar. Views in the bottom section are visually separated from top section views.", + "Choose your preferred interface style and configure how Task Genius displays in your workspace.": "Choose your preferred interface style and configure how Task Genius displays in your workspace.", + "Classic": "Classic", + "Classic & Familiar": "Classic & Familiar", + "Clear Logs": "Clear Logs", + "Click the button below to automatically add this MCP server to Cursor:": "Click the button below to automatically add this MCP server to Cursor:", + "Collapse/Expand": "Collapse/Expand", + "Comma-separated list of folder paths where task timer should be enabled": "Comma-separated list of folder paths where task timer should be enabled", + "Comma-separated list of tags that enable task timer": "Comma-separated list of tags that enable task timer", + "Common Mappings": "Common Mappings", + "Completed Tasks": "Completed Tasks", + "Config File-based Project Detection": "Config File-based Project Detection", + "Configure Symbols": "Configure Symbols", + "Configure Task Fields": "Configure Task Fields", + "Configure Task Paths": "Configure Task Paths", + "Configure Task Tags": "Configure Task Tags", + "Configure additional methods to detect project files": "Configure additional methods to detect project files", + "Configure file filtering to improve indexing performance and focus on relevant content": "Configure file filtering to improve indexing performance and focus on relevant content", + "Configure hidden modules": "Configure hidden modules", + "Configure how dates and times are displayed in views.": "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 files are recognized as tasks. At least one strategy must be enabled.", + "Configure inline editing and metadata positioning.": "Configure inline editing and metadata positioning.", + "Configure keywords for date parsing": "Configure keywords for date parsing", + "Configure metadata fields that indicate a file should be treated as a task (e.g., dueDate, status, priority)": "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 multiple status cycles with different workflows. You can apply preset themes or create custom cycles.", + "Configure options specific to the Fluent interface.": "Configure options specific to the Fluent interface.", + "Configure paths that contain task files (e.g., Projects/, Tasks/2024/, Work/TODO/)": "Configure paths that contain task files (e.g., Projects/, Tasks/2024/, Work/TODO/)", + "Configure project detection from project configuration files": "Configure project detection from project configuration files", + "Configure project display, organization and metadata mappings": "Configure project display, organization and metadata mappings", + "Configure symbols that represent abandoned tasks in square brackets": "Configure symbols that represent abandoned tasks in square brackets", + "Configure symbols that represent completed 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 not started tasks in square brackets. Default is space \" \"", + "Configure symbols that represent planned tasks in square brackets": "Configure symbols that represent planned tasks in square brackets", + "Configure symbols that represent tasks in progress in square brackets": "Configure symbols that represent tasks in progress in square brackets", + "Configure system tray, notifications, and desktop features": "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 tags that indicate a file should be treated as a task (e.g., #task, #todo, #actionable)", + "Configure the format of time expressions": "Configure the format of time expressions", + "Configure which files, folders, or patterns are included during 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 modules should be hidden in this workspace. Hidden views will not appear in the sidebar.", + "Contains match": "Contains match", + "Control which days are displayed in the calendar": "Control which days are displayed in the calendar", + "Copy Install Link": "Copy Install Link", + "Copy Settings From": "Copy Settings From", + "Copy settings from an existing workspace": "Copy settings from an existing workspace", + "Copy this cycle": "Copy this cycle", + "Create": "Create", + "Create Calendar View": "Create Calendar View", + "Create New Calendar View": "Create New Calendar View", + "Create New Workspace": "Create New Workspace", + "Create a backup of active timers": "Create a backup of active timers", + "Create a custom view from the templates above to get started.": "Create a custom view from the templates above to get started.", + "Create a new workspace with custom settings": "Create a new workspace with custom settings", + "Create custom calendar views based on Month, Week, or Day views. Each custom view can have its own display settings.": "Create custom calendar views based on Month, Week, or Day views. Each custom view can have its own display settings.", + "Create task timer backup": "Create task timer backup", + "Current Workspace": "Current Workspace", + "Custom Calendar Views": "Custom Calendar Views", + "Custom Content Field": "Custom Content Field", + "Custom Cycle": "Custom Cycle", + "Custom Date Formats": "Custom Date Formats", + "Custom Mappings": "Custom Mappings", + "Custom Project Detection Methods": "Custom Project Detection Methods", + "Custom Range": "Custom Range", + "Custom Selection": "Custom Selection", + "Custom days": "Custom days", + "Custom marker": "Custom marker", + "Custom metadata field": "Custom metadata field", + "Customize how dates are displayed in headers": "Customize how dates are displayed in headers", + "Daily summary": "Daily summary", + "Data Management": "Data Management", + "Date Filter": "Date Filter", + "Date and Time Display": "Date and Time Display", + "Date marker": "Date marker", + "Day Filter": "Day Filter", + "Day Header Format": "Day Header Format", + "Day View": "Day View", + "Days to Show": "Days to Show", + "Default": "Default", + "Default Cycle": "Default Cycle", + "Default Task Status": "Default Task Status", + "Default file name template": "Default file name template", + "Default folder for new files": "Default folder for new files", + "Default settings": "Default settings", + "Default status for newly created file tasks": "Default status for newly created file tasks", + "Default workspace": "Default workspace", + "Default workspace cannot be deleted": "Default workspace cannot be deleted", + "Define the statuses in cycling order": "Define the statuses in cycling order", + "Delete Workspace": "Delete Workspace", + "Delete this cycle": "Delete this cycle", + "Desktop Integration": "Desktop Integration", + "Desktop integration features are only available in the desktop app": "Desktop integration features are only available in the desktop app", + "Desktop only": "Desktop only", + "Detailed": "Detailed", + "Display": "Display", + "Display a full year with 12 mini-month calendars": "Display a full year with 12 mini-month calendars", + "Display days with no events": "Display days with no events", + "Display event count badges on date cells": "Display event count badges on date cells", + "Display name for this calendar view": "Display name for this calendar view", + "Display tasks for a single day with detailed time slots": "Display tasks for a single day with detailed time slots", + "Display tasks in a monthly calendar grid": "Display tasks in a monthly calendar grid", + "Display tasks in a weekly time grid with hourly slots": "Display tasks in a weekly time grid with hourly slots", + "Display timer usage statistics": "Display timer usage statistics", + "Display upcoming tasks in a list format grouped by day": "Display upcoming tasks in a list format grouped by day", + "Display week numbers in the month view": "Display week numbers in the month view", + "Drag to reorder": "Drag to reorder", + "Drag views between sections or within sections to reorder them. Toggle visibility with the eye icon.": "Drag views between sections or within sections to reorder them. Toggle visibility with the eye icon.", + "Edit Calendar View": "Edit Calendar View", + "Edit File Filter Rules": "Edit File Filter Rules", + "Editor Configuration": "Editor Configuration", + "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.", + "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 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 File Task": "Enable File Task", + "Enable Task Genius Views": "Enable Task Genius Views", + "Enable Task Genius Views above to configure view settings.": "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 Genius sidebar views to display and manage tasks. Requires the indexer to be enabled.", + "Enable Task Timer": "Enable Task Timer", + "Enable Time Filter": "Enable Time Filter", + "Enable case-sensitive matching for status values": "Enable case-sensitive matching for status values", + "Enable notifications": "Enable notifications", + "Enable project features": "Enable project features", + "Enable task timer functionality for tracking time spent on tasks": "Enable task timer functionality for tracking time spent on tasks", + "Enable/disable this cycle": "Enable/disable this cycle", + "End Hour": "End Hour", + "Enhanced": "Enhanced", + "Enter details for {{value0}}...": "Enter details for {{value0}}...", + "Enter metadata field name": "Enter metadata field name", + "Enter metadata value and symbol (e.g., 'done:x')": "Enter metadata value and symbol (e.g., 'done:x')", + "Enter new name": "Enter new name", + "Enter path (e.g., Projects/, Tasks/**/*.md)": "Enter path (e.g., Projects/, Tasks/**/*.md)", + "Enter tag (e.g., #task)": "Enter tag (e.g., #task)", + "Enter workspace name": "Enter workspace name", + "Error rendering format": "Error rendering format", + "Error:": "Error:", + "Exact match": "Exact match", + "Examples of time expressions": "Examples of time expressions", + "Examples:": "Examples:", + "Exclude Archive Folder": "Exclude Archive Folder", + "Exclude Temporary Files": "Exclude Temporary Files", + "Export all timer data to JSON": "Export all timer data to JSON", + "Export task timer data": "Export task timer data", + "Export task timer data (YAML)": "Export task timer data (YAML)", + "Export to YAML format": "Export to YAML format", + "Failed to sync mapping": "Failed to sync mapping", + "Features to be enabled": "Features to be enabled", + "Field name in frontmatter to check for enabling task timer (e.g., 'task-timer: true')": "Field name in frontmatter to check for enabling task timer (e.g., 'task-timer: true')", + "File Content": "File Content", + "File Creation Mode": "File Creation Mode", + "File Task is disabled": "File Task is disabled", + "File Task is enabled and monitoring files": "File Task is enabled and monitoring files", + "File filtering helps you focus on relevant content while improving performance, especially in large vaults.": "File filtering helps you focus on relevant content while improving performance, especially in large vaults.", + "FileSource status mapping synced": "FileSource status mapping synced", + "Filename": "Filename", + "Filter files during task indexing to improve performance": "Filter files during task indexing to improve performance", + "First H1 heading": "First H1 heading", + "First hour to display (0-23)": "First hour to display (0-23)", + "Fluent Interface Settings": "Fluent Interface Settings", + "Focus on Projects": "Focus on Projects", + "Folder paths": "Folder paths", + "Folder that contains Quick Capture templates for File mode.": "Folder that contains Quick Capture templates for File mode.", + "Format for day headers (e.g., dddd, MMMM D)": "Format for day headers (e.g., dddd, MMMM D)", + "Format for day view header (e.g., yyyy'年'M'月'd'日')": "Format for day view header (e.g., yyyy'年'M'月'd'日')", + "Format for month view header (e.g., yyyy M)": "Format for month view header (e.g., yyyy M)", + "Friday": "Friday", + "Frontmatter field": "Frontmatter field", + "Frontmatter title": "Frontmatter title", + "Full project workflow": "Full project workflow", + "Full year": "Full year", + "Glob pattern (e.g., Projects/**/*.md)": "Glob pattern (e.g., Projects/**/*.md)", + "Hidden Days": "Hidden Days", + "Hidden Modules Configuration": "Hidden Modules Configuration", + "Hide Weekends": "Hide Weekends", + "Hide from sidebar": "Hide from sidebar", + "How paths should be matched": "How paths should be matched", + "How tags should be matched against file tags": "How tags should be matched against file tags", + "If enabled, #tags in the editor content are written into YAML frontmatter tags (merged and deduplicated)": "If enabled, #tags in the editor content are written into YAML frontmatter tags (merged and deduplicated)", + "Ignore system and temporary files": "Ignore system and temporary files", + "Import task timer data": "Import task timer data", + "Import timer data from JSON file": "Import timer data from JSON file", + "Incomplete Tasks": "Incomplete Tasks", + "Index & Sources": "Index & Sources", + "Index only specific project folders": "Index only specific project folders", + "Inline": "Inline", + "Input: ": "Input: ", + "Interface": "Interface", + "Interface Mode": "Interface Mode", + "Interface Style": "Interface Style", + "Keep open after capture": "Keep open after capture", + "Keep the familiar interface and interaction style you know": "Keep the familiar interface and interaction style you know", + "Keep the modal open after capturing content": "Keep the modal open after capturing content", + "Last hour to display (0-23)": "Last hour to display (0-23)", + "Last month": "Last month", + "Last updated: {{date}}": "Last updated: {{date}}", + "Last week": "Last week", + "Last year": "Last year", + "Legacy": "Legacy", + "Link Filter": "Link Filter", + "Linked Note": "Linked Note", + "MCP Server Logs": "MCP Server Logs", + "MCP server is not running": "MCP server is not running", + "Manage Workspaces...": "Manage Workspaces...", + "Manage workspaces to organize different contexts with their own settings and filters.": "Manage workspaces to organize different contexts with their own settings and filters.", + "Manual Configuration": "Manual Configuration", + "Map between human-readable metadata values (e.g., 'completed') and task symbols (e.g., 'x').": "Map between human-readable metadata values (e.g., 'completed') and task symbols (e.g., 'x').", + "Mark": "Mark", + "Max Events Per Row": "Max Events Per Row", + "Max other views before overflow": "Max other views before overflow", + "Maximum events to show per day cell before showing '+N more'": "Maximum events to show per day cell before showing '+N more'", + "Meeting": "Meeting", + "Metadata": "Metadata", + "Metadata Detection": "Metadata Detection", + "Metadata Property": "Metadata Property", + "Metadata Value": "Metadata Value", + "Metadata-based Project Detection": "Metadata-based Project Detection", + "Metadata-based Recognition": "Metadata-based Recognition", + "Method": "Method", + "Method A (Custom Header):": "Method A (Custom Header):", + "Method B (Combined Bearer):": "Method B (Combined Bearer):", + "Migrated from legacy settings": "Migrated from legacy settings", + "Missed": "Missed", + "Modern": "Modern", + "Modern & Sleek": "Modern & Sleek", + "Mon first": "Mon first", + "Monday": "Monday", + "Month Header Format": "Month Header Format", + "Month View": "Month View", + "My Custom View": "My Custom View", + "Name of the metadata field to use as task content": "Name of the metadata field to use as task content", + "New Calendar View": "New Calendar View", + "New Name": "New Name", + "New visual design with elegant animations and modern interactions": "New visual design with elegant animations and modern interactions", + "No custom calendar views yet": "No custom calendar views yet", + "No filter rules configured yet": "No filter rules configured yet", + "No logs match your search.": "No logs match your search.", + "No logs yet. Tool calls will appear here.": "No logs yet. Tool calls will appear here.", + "No markdown notes were found in the selected folder.": "No markdown notes were found in the selected folder.", + "No weekends": "No weekends", + "Note:": "Note:", + "Notes": "Notes", + "Notify shortly before each task's due time": "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 'Other Views' to show before grouping the rest into an overflow menu (ellipsis)", + "Number of days to display in the agenda": "Number of days to display in the agenda", + "Numeric progress tracking": "Numeric progress tracking", + "Only show certain hours of the day": "Only show certain hours of the day", + "Open in external browser": "Open in external browser", + "Optimize Performance": "Optimize Performance", + "Optional: Only match links containing this text": "Optional: Only match links containing this text", + "Other Views": "Other Views", + "Path Matching Mode": "Path Matching Mode", + "Path-based Recognition": "Path-based Recognition", + "Paths": "Paths", + "Pattern: ": "Pattern: ", + "Per-task reminders": "Per-task reminders", + "Performance": "Performance", + "Please enter a name": "Please enter a name", + "Please enter a workspace name": "Please enter a workspace name", + "Populate FileSource status mapping from your checkbox status configuration": "Populate FileSource status mapping from your checkbox status configuration", + "Prefer Frontmatter Title": "Prefer Frontmatter Title", + "Prefix (e.g., Projects/ matches Projects/App.md)": "Prefix (e.g., Projects/ matches Projects/App.md)", + "Prefix for generated block reference IDs (e.g., 'timer' creates ^timer-123456-7890)": "Prefix for generated block reference IDs (e.g., 'timer' creates ^timer-123456-7890)", + "Prefix match": "Prefix match", + "Progress Tracker": "Progress Tracker", + "Projects List": "Projects List", + "Quick Add Rules": "Quick Add Rules", + "Quick Install": "Quick Install", + "Quick TODO/DONE cycle": "Quick TODO/DONE cycle", + "Quick Templates": "Quick Templates", + "Quickly add common workflow patterns": "Quickly add common workflow patterns", + "Recognition Strategies": "Recognition Strategies", + "Recognize files as tasks based on their file path": "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 frontmatter fields", + "Recognize files as tasks if they have specific tags": "Recognize files as tasks if they have specific tags", + "Recommended Configurations": "Recommended Configurations", + "Record Details for {{value0}}": "Record Details for {{value0}}", + "Regular expression (advanced)": "Regular expression (advanced)", + "Remember last mode": "Remember last mode", + "Remember the last used quick capture mode": "Remember the last used quick capture mode", + "Remove the .md extension from filename when using as task content": "Remove the .md extension from filename when using as task content", + "Remove this status": "Remove this status", + "Rename": "Rename", + "Rename Workspace": "Rename Workspace", + "Require All Fields": "Require All Fields", + "Require all specified fields to be present (otherwise any field is sufficient)": "Require all specified fields to be present (otherwise any field is sufficient)", + "Reset All Settings": "Reset All Settings", + "Reset Settings": "Reset Settings", + "Reset all settings to their default values": "Reset all settings to their default values", + "Result:": "Result:", + "Review Your Configuration": "Review Your Configuration", + "Rule {{value0}}": "Rule {{value0}}", + "Sat first": "Sat first", + "Saturday": "Saturday", + "Saved. Reopen the view to apply.": "Saved. Reopen the view to apply.", + "Scan now": "Scan now", + "Scope:": "Scope:", + "Search logs...": "Search logs...", + "Select a template folder above to enable the dropdown.": "Select a template folder above to enable the dropdown.", + "Select between the modern Fluent interface or the classic Legacy interface.": "Select between the modern Fluent interface or the classic Legacy interface.", + "Select the interface style to use.": "Select the interface style to use.", + "Select which days to hide from the calendar": "Select which days to hide from the calendar", + "Selected folder was not found in the vault.": "Selected folder was not found in the vault.", + "Send now": "Send now", + "Send one notification for today's due tasks at a specific time (HH:mm)": "Send one notification for today's due tasks at a specific time (HH:mm)", + "Set value": "Set value", + "Show All Days": "Show All Days", + "Show Empty Days": "Show Empty Days", + "Show Event Counts": "Show Event Counts", + "Show Week Numbers": "Show Week Numbers", + "Show a bell with count in system tray, status bar, or both": "Show a bell with count in system tray, status bar, or both", + "Show changelog after plugin updates": "Show changelog after plugin updates", + "Show indicator with checkbox": "Show indicator with checkbox", + "Show project progress in Projects header": "Show project progress in Projects header", + "Show task timer statistics": "Show task timer statistics", + "Show the status indicator directly next to the checkbox. When enabled, a indicator will be shown next to the checkbox.": "Show the status indicator directly next to the checkbox. When enabled, a indicator will be shown next to the checkbox.", + "Sidebar Components": "Sidebar Components", + "Sidebar Position": "Sidebar Position", + "Simple": "Simple", + "Skip archived content": "Skip archived content", + "Standard task lifecycle with all states": "Standard task lifecycle with all states", + "Start Hour": "Start Hour", + "Statistics": "Statistics", + "Status Cycles Management": "Status Cycles Management", + "Status bar": "Status bar", + "Status mappings work with your Task Status Settings. ": "Status mappings work with your Task Status Settings. ", + "Status sequence": "Status sequence", + "Strip File Extension": "Strip File Extension", + "Submit": "Submit", + "Sunday": "Sunday", + "Switch": "Switch", + "Switch Workspace": "Switch Workspace", + "Sync from Task Status Settings": "Sync from Task Status Settings", + "System Default": "System Default", + "System tray": "System tray", + "TODO → PLAN → IN PROGRESS → DONE": "TODO → PLAN → IN PROGRESS → DONE", + "TODO ↔ DONE": "TODO ↔ DONE", + "TODO.md in any direct subfolder of Work": "TODO.md in any direct subfolder of Work", + "Tag Matching Mode": "Tag Matching Mode", + "Tag-based Recognition": "Tag-based Recognition", + "Task Fields": "Task Fields", + "Task Paths": "Task Paths", + "Task Properties for Files": "Task Properties for Files", + "Task Symbol": "Task Symbol", + "Task Tags": "Task Tags", + "Task Timer": "Task Timer", + "Task Title Source": "Task Title Source", + "Task fields updated. Rebuild the task index to apply to existing files.": "Task fields updated. Rebuild the task index to apply to existing files.", + "Task paths updated. Rebuild the task index to apply to existing files.": "Task paths updated. Rebuild the task index to apply to existing files.", + "Task tags updated. Rebuild the task index to apply to existing files.": "Task tags updated. Rebuild the task index to apply to existing files.", + "Template folder": "Template folder", + "Template folder is invalid; update the folder to continue.": "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 for displaying completed task time. Use {h} for hours, {m} for minutes, {s} for seconds", + "Template note": "Template note", + "Templates": "Templates", + "Templates/Quick Capture": "Templates/Quick Capture", + "The calendar layout this view is based on": "The calendar layout this view is based on", + "The symbols defined here should match those in your checkbox status configuration.": "The symbols defined here should match those in your checkbox status configuration.", + "This will add a new status cycle based on the {{value0}} theme.": "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 override your current checkbox status settings with the {{value0}} theme. Do you want to continue?", + "Thursday": "Thursday", + "Time Filter": "Time Filter", + "Time Format": "Time Format", + "Time Range Preset": "Time Range Preset", + "Time filter is only available for Week and Day views": "Time filter is only available for Week and Day views", + "Time filter is only available for Week and Day views.": "Time filter is only available for Week and Day views.", + "Time format template": "Time format template", + "Time-to-live for cached results in milliseconds (default: 300000 = 5 minutes)": "Time-to-live for cached results in milliseconds (default: 300000 = 5 minutes)", + "Top Section": "Top Section", + "Total: {{value0}} | Success: {{value1}} | Errors: {{value2}}": "Total: {{value0}} | Success: {{value1}} | Errors: {{value2}}", + "Tray indicator": "Tray indicator", + "Tuesday": "Tuesday", + "URL: ": "URL: ", + "Untitled View": "Untitled View", + "Update now": "Update now", + "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 left/right workspace side leaves for Sidebar and Details. When enabled, the main fluent view won't render in-view sidebar or details.", + "Use system notifications when possible": "Use system notifications when possible", + "Use template for new files": "Use template for new files", + "Use the command palette to access timer data management:": "Use the command palette to access timer data management:", + "Use these templates as a starting point to create your own custom calendar views.": "Use these templates as a starting point to create your own custom calendar views.", + "Use workspace side leaves": "Use workspace side leaves", + "Used by File mode (requires FileSource). Leave empty for vault root.": "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}})": "Used by File mode to prefill the file name input (supports date templates like {{DATE:YYYY-MM-DD}})", + "User Interface": "User Interface", + "Value cannot be empty": "Value cannot be empty", + "Version marker": "Version marker", + "View Icon": "View Icon", + "View Logs": "View Logs", + "View Server Logs": "View Server Logs", + "View all MCP server tool calls and their results": "View all MCP server tool calls and their results", + "View deleted: ": "View deleted: ", + "View duplicated: ": "View duplicated: ", + "Views": "Views", + "Views are disabled": "Views are disabled", + "Wednesday": "Wednesday", + "Week View": "Week View", + "Weekends Only": "Weekends Only", + "Weekends only": "Weekends only", + "What should be used as the task title when a file becomes a task": "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 File mode is used, create the new note from a template and then insert the captured content.", + "When updating task content, prefer updating frontmatter title over renaming the file. This protects the original filename.": "When updating task content, prefer updating frontmatter title over renaming the file. This protects the original filename.", + "Which day should the week start on": "Which day should the week start on", + "Whitelist": "Whitelist", + "Whitelist: Include only specified paths | Blacklist: Exclude specified paths": "Whitelist: Include only specified paths | Blacklist: Exclude specified paths", + "Whitelist: include only specified paths. Blacklist: exclude specified paths.": "Whitelist: include only specified paths. Blacklist: exclude specified paths.", + "Why File Filtering?": "Why File Filtering?", + "Working Hours (9:00-18:00)": "Working Hours (9:00-18:00)", + "Workspace \"{{name}}\" created": "Workspace \"{{name}}\" created", + "Workspace \"{{name}}\" deleted": "Workspace \"{{name}}\" deleted", + "Workspace Color": "Workspace Color", + "Workspace Icon": "Workspace Icon", + "Workspace Management": "Workspace Management", + "Workspace Name": "Workspace Name", + "Workspace manager is not available.": "Workspace manager is not available.", + "Workspace updated": "Workspace updated", + "Workspaces": "Workspaces", + "Write content tags to frontmatter": "Write content tags to frontmatter", + "Year View": "Year View", + "Year view displays 12 mini-month calendars. Use the Date Filter tab to hide weekends if needed.": "Year view displays 12 mini-month calendars. Use the Date Filter tab to hide weekends if needed.", + "You can customize any of these settings later in the plugin settings": "You can customize any of these settings later in the plugin settings", + "Your custom calendar views. Drag to reorder, toggle visibility, or edit settings.": "Your custom calendar views. Drag to reorder, toggle visibility, or edit settings.", + "all .md files in Projects and subfolders": "all .md files in Projects and subfolders", + "all .md files in Projects folder": "all .md files in Projects folder", + "archived on {{date}}": "archived on {{date}}", + "files ending with .task.md in Tasks folder": "files ending with .task.md in Tasks folder", + "files starting with date in Tasks": "files starting with date in Tasks", + "matches all files under Projects folder": "matches all files under Projects folder", + "matches all files under Tasks/2024 folder": "matches all files under Tasks/2024 folder", + "moved on {{date}}": "moved on {{date}}", + "version 1.0": "version 1.0", + "{title} ({count} days)": "{title} ({count} days)", + "{{count}} field(s) configured": "{{count}} field(s) configured", + "{{count}} path(s) configured": "{{count}} path(s) configured", + "{{count}} symbol(s) configured": "{{count}} symbol(s) configured", + "{{count}} tag(s) configured": "{{count}} tag(s) configured", + "{{hidden}}/{{total}} hidden": "{{hidden}}/{{total}} hidden", + "{{status}} Task Symbols": "{{status}} Task Symbols", + "{{value0}} theme workflow": "{{value0}} theme workflow", + "{{value0}} · Heatmap": "{{value0}} · Heatmap", + "{{value0}}: Error": "{{value0}}: Error", + "{{value0}}ms": "{{value0}}ms", + "Index & Task Source Configuration": "Index & Task Source Configuration", + "Configure how Task Genius discovers and indexes tasks from various sources including inline tasks, file metadata, and projects.": "Configure how Task Genius discovers and indexes tasks from various sources including inline tasks, file metadata, and projects.", + "Enable Indexer": "Enable Indexer", + "Please restart Obsidian for the Indexer change to take effect.": "Please restart Obsidian for the Indexer change to take effect.", + "Checkbox Tasks": "Checkbox Tasks", + "File Tasks": "File Tasks", + "Enable checkbox tasks": "Enable checkbox tasks", + "Index markdown checkbox tasks. Disable this if you only want to use file-based or external task sources.": "Index markdown checkbox tasks. Disable this if you only want to use file-based or external task sources.", + "Checkbox task indexing disabled. The index will prune inline tasks shortly.": "Checkbox task indexing disabled. The index will prune inline tasks shortly.", + "Inline task parsing": "Inline task parsing", + "Configure how tasks are parsed from markdown content.": "Configure how tasks are parsed from markdown content.", + "Enable custom date formats": "Enable custom date formats", + "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 format patterns for parsing dates. When enabled, the parser will try your custom formats before falling back to default formats.", + "Custom date formats": "Custom date formats", + "Configure custom date format patterns.": "Configure custom date format patterns.", + "Configure Date Formats": "Configure Date Formats", + "{{count}} format(s) configured": "{{count}} format(s) configured", + "Configure Custom Date Formats": "Configure Custom Date Formats", + "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 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).", + "Enter date format (e.g., yyyy-MM-dd or yyyyMMdd_HHmmss)": "Enter date format (e.g., yyyy-MM-dd or yyyyMMdd_HHmmss)", + "Date formats updated. The parser will now recognize these custom formats.": "Date formats updated. The parser will now recognize these custom formats.", + "Format Pattern": "Format Pattern", + "Example": "Example", + "Configure headings to ignore. Tasks under these headings will be excluded from indexing.": "Configure headings to ignore. Tasks under these headings will be excluded from indexing.", + "Heading filters updated. Rebuild the task index to apply to existing tasks.": "Heading filters updated. Rebuild the task index to apply to existing tasks.", + "Configure headings to focus on. Only tasks under these headings will be included in indexing.": "Configure headings to focus on. Only tasks under these headings will be included in indexing.", + "This change affects how tasks inherit metadata from files. Rebuild the index now so changes take effect immediately?": "This change affects how tasks inherit metadata from files. Rebuild the index now so changes take effect immediately?", + "Failed to reindex tasks": "Failed to reindex tasks", + "Enable file tasks": "Enable file tasks", + "Allow Task Genius to recognize files as tasks using metadata, tags, or templates.": "Allow Task Genius to recognize files as tasks using metadata, tags, or templates.", + "File task recognition disabled. Existing file tasks will be pruned shortly.": "File task recognition disabled. Existing file tasks will be pruned shortly.", + "File tasks are disabled. Enable them to configure recognition strategies.": "File tasks are disabled. Enable them to configure recognition strategies.", + "Performance Configuration": "Performance Configuration", + "Configure performance-related indexing settings": "Configure performance-related indexing settings", + "Index Maintenance": "Index Maintenance", + "Tools for managing and rebuilding the task index": "Tools for managing and rebuilding the task index", + "Force a complete rebuild of the task index. Use this if you notice missing or incorrect tasks.": "Force a complete rebuild of the task index. Use this if you notice missing or incorrect tasks.", + "How to use": "How to use", + + + + "Fluent": "Fluent", + + + 'Points and rewards': 'Points and rewards', + 'Open project note': 'Open project note', + 'Create project note and move tasks': 'Create project note and move tasks', + 'Project note created; tasks moved': 'Project note created; tasks moved', + 'Moved to project': 'Moved to project', + 'Failed to move project tasks': 'Failed to move project tasks', + 'Project notes': 'Project notes', + 'Legacy project marker prefix': 'Legacy project marker prefix', + 'Used only to recognize existing project markers while migrating old tasks. New project assignments use project notes.': 'Used only to recognize existing project markers while migrating old tasks. New project assignments use project notes.', + 'Create, edit and archive project Markdown notes from the Projects page. New tasks assigned to a project are moved into its note.': 'Create, edit and archive project Markdown notes from the Projects page. New tasks assigned to a project are moved into its note.', + 'Legacy project detection settings': 'Legacy project detection settings', + 'Additional project detection': 'Additional project detection', + 'Compatibility options for existing path, tag and config-file project setups. These do not affect new project notes.': 'Compatibility options for existing path, tag and config-file project setups. These do not affect new project notes.', + 'Edit project details': 'Edit project details', + 'Archive project': 'Archive project', + 'Restore project': 'Restore project', + 'Add task to project': 'Add task to project', + 'Task moved to project': 'Task moved to project', + 'Could not create project note': 'Could not create project note', + 'Canvas tasks must be moved through Task Genius.': 'Canvas tasks must be moved through Task Genius.', + 'Could not move task to project note': 'Could not move task to project note', + 'Quick filters': 'Quick filters', + 'Clear quick filter': 'Clear quick filter', + 'No saved filters': 'No saved filters', + 'Earn points from tasks, add points manually, and redeem rewards.': 'Earn points from tasks, add points manually, and redeem rewards.', + 'Add points': 'Add points', + 'Available points': 'Available points', + 'ledger entries': 'ledger entries', + 'Complete tasks to start earning points.': 'Complete tasks to start earning points.', + 'Points history': 'Points history', + 'Reward shop': 'Reward shop', + 'Add reward': 'Add reward', + 'Add rewards to redeem them with points.': 'Add rewards to redeem them with points.', + 'points': 'points', + 'Set a point cost to enable redemption': 'Set a point cost to enable redemption', + 'Redeem': 'Redeem', + 'Manual points': 'Manual points', + 'Redeemed': 'Redeemed', + 'Reward redeemed': 'Reward redeemed', + 'Enter a non-zero number': 'Enter a non-zero number', + 'Name': 'Name', + 'Point cost': 'Point cost', + 'Inventory': 'Inventory', + 'Check the reward details': 'Check the reward details', + 'Default task points': 'Default task points', + 'points per task': 'points per task', + 'Task points': 'Task points', + 'Interval window days key': 'Interval window days key', + "Check in, earn points, and choose your rewards.": "Check in, earn points, and choose your rewards.", + "Search habits, rewards, and records": "Search habits, rewards, and records", + "Points earned": "Points earned", + "Points spent": "Points spent", + "Today's points": "Today's points", + "Habits / check-ins": "Habits / check-ins", + "Daily check-in": "Daily check-in", + "Bonuses and rewards": "Bonuses and rewards", + "Points rules": "Points rules", + "Bonus actions": "Bonus actions", + "Edit bonus actions": "Edit bonus actions", + "Record points": "Record points", + "Edit reward wishes": "Edit reward wishes", + "Reward wishes": "Reward wishes", + "Delete this points record?": "Delete this points record?", + "No matching records": "No matching records", + "Habit points": "Habit points", + "check-ins": "check-ins", + "Points data file": "Points data file", + "Choose a Markdown file.": "Choose a Markdown file.", + "Default habit points": "Default habit points", + "Habit-specific points override the default. Negative values deduct points above the habit allowance.": "Habit-specific points override the default. Negative values deduct points above the habit allowance.", + "Default rule": "Default rule", + "Points per unit": "Points per unit", + "Enter a positive point cost.": "Enter a positive point cost.", + "Enter a description and a valid point amount.": "Enter a description and a valid point amount.", + "One item per line": "One item per line", + "Habits and points": "Habits and points", + "Archived projects": "Archived projects", + "No archived projects": "No archived projects", + "A project with that name already exists.": "A project with that name already exists.", + "Each project is a Markdown note. Its project property owns task membership, and assigned tasks are moved into that note.": "Each project is a Markdown note. Its project property owns task membership, and assigned tasks are moved into that note.", + "New project folder": "New project folder", + "Archive finished projects and restore them when needed. Notes and task history stay available.": "Archive finished projects and restore them when needed. Notes and task history stay available.", + "Manage archives": "Manage archives", + "Existing project tags": "Existing project tags", + "Existing tags can still be read. Use Create project note and move tasks to consolidate a legacy project into its note.": "Existing tags can still be read. Use Create project note and move tasks to consolidate a legacy project into its note.", + "New saved filter": "New saved filter", + "Edit saved filter": "Edit saved filter", + "Delete saved filter": "Delete saved filter", + "Combine fields with AND, OR, NOT and parentheses. Example: project:\"Writing\" AND priority:>=3": "Combine fields with AND, OR, NOT and parentheses. Example: project:\"Writing\" AND priority:>=3", + "Include matches": "Include matches", + "Exclude matches": "Exclude matches", + "Enter a filter name.": "Enter a filter name.", + "Search habits": "Search habits", + "Filter mode": "Filter mode", + "Change": "Change", + "File path": "File path", + "Confirm": "Confirm", + "Delete this reward?": "Delete this reward?", + "Use default rule": "Use default rule", + "Use 0 to award task points only when a task has its own point value.": "Use 0 to award task points only when a task has its own point value.", + "Combine conditions": "Combine conditions", + "Match all conditions": "Match all conditions", + "Match any condition": "Match any condition", + "Text": "Text", + "Contains": "Contains", + "Equals": "Equals", + "Does not equal": "Does not equal", + "At least / on or after": "At least / on or after", + "At most / on or before": "At most / on or before", + "Remove condition": "Remove condition", + "Add condition": "Add condition", + "Choose a Markdown file inside the vault.": "Choose a Markdown file inside the vault.", + "The points data path is occupied by a folder.": "The points data path is occupied by a folder.", + "Enter a description, a valid date, and a non-zero amount.": "Enter a description, a valid date, and a non-zero amount.", + "Habit note not found.": "Habit note not found.", + "Not enough points.": "Not enough points.", + "This reward is out of stock.": "This reward is out of stock.", + "Open": "Open", + "Points": "Points", + "A project file already exists at that path.": "A project file already exists at that path.", + "The task file could not be found.": "The task file could not be found.", + "The task changed before it could be moved.": "The task changed before it could be moved.", + "The project folder path is occupied by a file.": "The project folder path is occupied by a file.", + "Create project": "Create project", + "Add task": "Add task", + "Delete project": "Delete project", + "Move the project note and its tasks to the trash.": "Move the project note and its tasks to the trash.", + "Habit layout": "Habit layout", + "Task Genius cards": "Task Genius cards", + "Dashboard layout": "Dashboard layout", + "Check in": "Check in", + "Period progress": "Period progress", + "Decrease": "Decrease", + "Increase": "Increase", + "To do": "To do", + "This month's tasks": "This month's tasks", + "Saved filters": "Saved filters", + "Any task date": "Any task date", + "Select a value": "Select a value", + "Choose date": "Choose date", + "Advanced query (optional)": "Advanced query (optional)", + "Use advanced query": "Use advanced query", + "Choose a value for every condition.": "Choose a value for every condition.", + "Where tasks come from": "Where tasks come from", + "Task Genius reads checkboxes in your notes. You can also use an entire note as a task.": "Task Genius reads checkboxes in your notes. You can also use an entire note as a task.", + "Tasks in notes": "Tasks in notes", + "Whole-note tasks": "Whole-note tasks", + "Task writing format": "Task writing format", + "Existing task dates and priorities are read automatically.": "Existing task dates and priorities are read automatically.", + "Save dates and priorities as": "Save dates and priorities as", + "Choose how new dates and priorities appear in your notes. Existing tasks do not need conversion.": "Choose how new dates and priorities appear in your notes. Existing tasks do not need conversion.", + "Inline properties": "Inline properties", + "Task icons (recommended)": "Task icons (recommended)", + "Exclude tasks in these sections": "Exclude tasks in these sections", + "Only include tasks in these sections": "Only include tasks in these sections", + "For example, exclude tasks below an Archive heading. Leave blank to include all sections.": "For example, exclude tasks below an Archive heading. Leave blank to include all sections.", + "Optional: only read tasks below the selected headings. Leave blank to include all sections.": "Optional: only read tasks below the selected headings. Leave blank to include all sections.", + "Use the journal date for tasks": "Use the journal date for tasks", + "Use the date in the journal filename when arranging its tasks.": "Use the date in the journal filename when arranging its tasks.", + "Search for a task to depend on": "Search for a task to depend on", + "These tasks would depend on each other.": "These tasks would depend on each other.", + "Task no longer available": "Task no longer available", + "Remove dependency": "Remove dependency", + "Search and select task": "Search and select task", + "Project Gantt": "Project Gantt", + "Zoom out": "Zoom out", + "Zoom in": "Zoom in", + "Project not found": "Project not found", + "Choose a reward and redeem it with your points.": "Choose a reward and redeem it with your points.", + "Manage points, bonuses and history.": "Manage points, bonuses and history.", + "Search rewards": "Search rewards", + "Search bonuses and records": "Search bonuses and records", + "Previous day": "Previous day", + "Next day": "Next day", + "Open note": "Open note", + "Add habit": "Add habit", + "This week": "This week", + "This month": "This month", + "Next 7 days": "Next 7 days", + "Choose a saved filter beside search. Edit its rules here using dropdowns.": "Choose a saved filter beside search. Edit its rules here using dropdowns.", + "Reset filter preset": "Reset filter preset", + + "Earn points and redeem rewards in one place.": "Earn points and redeem rewards in one place.", + "Search bonuses, rewards and records": "Search bonuses, rewards and records", + + "Completed checkbox tasks earn points by completion date. Existing daily task check-ins are deducted to prevent double counting.": "Completed checkbox tasks earn points by completion date. Existing daily task check-ins are deducted to prevent double counting.", + "Task scheduling": "Task scheduling", + "Unscheduled tasks": "Unscheduled tasks", + "Previous month": "Previous month", + "Task content": "Task content", + "This task no longer exists. Refresh the task list.": "This task no longer exists. Refresh the task list.", + "Enter a valid date, optionally followed by HH:mm.": "Enter a valid date, optionally followed by HH:mm.", + "Task writer is unavailable": "Task writer is unavailable", + "Project color": "Project color", + "Manual order": "Manual order", + "Daily note date": "Daily note date", + "Weekly note": "Weekly note", + "Monthly note": "Monthly note", + "Yearly note": "Yearly note", + "Ignore all past missed habits": "Ignore all past missed habits", + "Dismiss reminders before today. Habit records and points stay unchanged.": "Dismiss reminders before today. Habit records and points stay unchanged.", + "Ignore past misses": "Ignore past misses", + "Past missed habit reminders ignored.": "Past missed habit reminders ignored.", + "Parent folder": "Parent folder", + "Projects root": "Projects root", + "New parent folder (optional)": "New parent folder (optional)", + "Folder name": "Folder name", + "Enter a valid folder name.": "Enter a valid folder name.", + "View filter": "View filter", + "Clear time": "Clear time", + "More properties": "More properties", + "Edit reward shop": "Edit reward shop", + "One reward per line: name -100. Optional stock: name -100 | 3. Use -1 for unlimited stock. Remove a line to delete the item.": "One reward per line: name -100. Optional stock: name -100 | 3. Use -1 for unlimited stock. Remove a line to delete the item.", + "Rewards changed while editing. Reopen the editor and try again.": "Rewards changed while editing. Reopen the editor and try again.", + "One bonus per line: name +10. Remove a line to delete the item.": "One bonus per line: name +10. Remove a line to delete the item.", }; export default translations; diff --git a/src/translations/locale/ja.ts b/src/translations/locale/ja.ts index f3032d0a0..d0527e81f 100644 --- a/src/translations/locale/ja.ts +++ b/src/translations/locale/ja.ts @@ -1947,9 +1947,6 @@ const translations = { "すべてのビューのデフォルト表示モードを選択してください。これはビューを初めて開いたり新しいビューを作成したりするときのタスクの表示方法に影響します。", "List View": "リストビュー", "Tree View": "ツリービュー", - "Global Filter Configuration": "グローバルフィルター設定", - "Configure global filter rules that apply to all Views by default. Individual Views can override these settings.": - "デフォルトですべてのビューに適用されるグローバルフィルタールールを設定します。個別のビューでこれらの設定を上書きできます。", "Cancelled Date": "キャンセル日", "Configuration is valid": "設定が有効です", "Action to execute on completion": "完了時に実行するアクション", diff --git a/src/translations/locale/pt-br.ts b/src/translations/locale/pt-br.ts index 7d6df224c..f6f0cf0d5 100644 --- a/src/translations/locale/pt-br.ts +++ b/src/translations/locale/pt-br.ts @@ -1539,8 +1539,6 @@ const translations = { "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 default display mode for all views. This affects how tasks are displayed when you first open a view or create a new view.", "List View": "List View", "Tree View": "Tree View", - "Global Filter Configuration": "Global Filter Configuration", - "Configure global filter rules that apply to all Views by default. Individual Views can override these settings.": "Configure global filter rules that apply to all Views by default. Individual Views can override these settings.", "Cancelled Date": "Cancelled Date", "Configuration is valid": "Configuration is valid", "Action to execute on completion": "Action to execute on completion", diff --git a/src/translations/locale/ru.ts b/src/translations/locale/ru.ts index 46d8cff40..bfe39e41e 100644 --- a/src/translations/locale/ru.ts +++ b/src/translations/locale/ru.ts @@ -1539,8 +1539,6 @@ const translations = { "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 default display mode for all views. This affects how tasks are displayed when you first open a view or create a new view.", "List View": "List View", "Tree View": "Tree View", - "Global Filter Configuration": "Global Filter Configuration", - "Configure global filter rules that apply to all Views by default. Individual Views can override these settings.": "Configure global filter rules that apply to all Views by default. Individual Views can override these settings.", "Cancelled Date": "Cancelled Date", "Configuration is valid": "Configuration is valid", "Action to execute on completion": "Action to execute on completion", diff --git a/src/translations/locale/uk.ts b/src/translations/locale/uk.ts index ed7f2cc19..37e62f80b 100644 --- a/src/translations/locale/uk.ts +++ b/src/translations/locale/uk.ts @@ -1539,8 +1539,6 @@ const translations = { "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 default display mode for all views. This affects how tasks are displayed when you first open a view or create a new view.", "List View": "List View", "Tree View": "Tree View", - "Global Filter Configuration": "Global Filter Configuration", - "Configure global filter rules that apply to all Views by default. Individual Views can override these settings.": "Configure global filter rules that apply to all Views by default. Individual Views can override these settings.", "Cancelled Date": "Cancelled Date", "Configuration is valid": "Configuration is valid", "Action to execute on completion": "Action to execute on completion", diff --git a/src/translations/locale/zh-cn.ts b/src/translations/locale/zh-cn.ts index 4957132c3..bf596ab7c 100644 --- a/src/translations/locale/zh-cn.ts +++ b/src/translations/locale/zh-cn.ts @@ -1,5 +1,8 @@ // Simplified Chinese translations const translations = { + "Move project tasks into note": "将项目任务统一移入笔记", + "Enter a project name.": "请输入项目名称。", + "New project": "新建项目", "File Metadata Inheritance": "文件元数据继承", "Configure how tasks inherit metadata from file frontmatter": "配置任务如何从文件前置元数据继承属性", @@ -255,9 +258,9 @@ const translations = { "No priority": "无优先级", "Low priority": "低优先级", "Lowest priority": "最低优先级", - "Priority A": "优先级A", - "Priority B": "优先级B", - "Priority C": "优先级C", + "Priority A": "优先级 A", + "Priority B": "优先级 B", + "Priority C": "优先级 C", "Task Priority": "任务优先级", "Remove Priority": "移除优先级", "Cycle task status forward": "向前循环任务状态", @@ -424,6 +427,7 @@ const translations = { About: "关于", "Core Settings": "核心设置", "Display & Progress": "显示与进度", + "Views & Display": "视图与显示", "Workflow & Automation": "工作流与自动化", Gamification: "游戏化", Integration: "集成", @@ -483,7 +487,7 @@ const translations = { "Incomplete tasks": "未完成的任务", "In progress tasks": "进行中的任务", "Completed tasks": "已完成的任务", - "All tasks": "所有任务", + "All tasks": "全部任务", "After heading": "标题之后", "End of section": "章节结尾", "Enable text mark in source mode": "在源码模式中启用文本标记", @@ -584,7 +588,7 @@ const translations = { "Task Title": "任务标题", Tags: "标签", "e.g. every day, every 2 weeks": "例如:每天,每两周", - Forecast: "预测", + Forecast: "展望", "0 actions, 0 projects": "0 个行动,0 个项目", "Toggle list/tree view": "切换列表/树形视图", "Focusing on Work": "专注工作", @@ -841,13 +845,13 @@ const translations = { "Move to": "移动到", Settings: "设置", "Just started": "刚刚开始", - "Making progress": "正在进行中", - "Half way": "完成一半", - "Good progress": "进展良好", + "Making progress": "正在推进", + "Half way": "已完成一半", + "Good progress": "进展顺利", "Almost there": "即将完成", "archived on": "归档于", moved: "已移动", - "Capture your thoughts...": "记录你的想法...", + "Capture your thoughts...": "记录你的想法……", "Project Workflow": "项目工作流", "Standard project management workflow": "标准项目管理工作流", Planning: "规划中", @@ -856,12 +860,12 @@ const translations = { Cancelled: "已取消", Habit: "习惯", "Drink a cup of good tea": "喝一杯好茶", - "Watch an episode of a favorite series": "观看一集喜欢的剧集", - "Play a game": "玩一局游戏", + "Watch an episode of a favorite series": "看一集喜欢的剧集", + "Play a game": "玩一会游戏", "Eat a piece of chocolate": "吃一块巧克力", common: "普通", rare: "稀有", - legendary: "传奇", + legendary: "传说", "No Habits Yet": "暂无习惯", "Click the open habit button to create a new habit.": "点击打开习惯按钮创建新习惯。", @@ -1044,7 +1048,7 @@ const translations = { "Reset to Defaults": "重置为默认值", "Has due date": "有截止日期", "Has date": "有日期", - "No date": "无日期", + "No date": "没有日期", Any: "任意", "Has start date": "有开始日期", "Has scheduled date": "有计划日期", @@ -1784,14 +1788,14 @@ const translations = { "消除或最小化。这些任务可能是时间浪费。", "Review and categorize these tasks appropriately.": "适当地审查和分类这些任务。", - "Urgent & Important": "紧急 & 重要", - "Do First - Crisis & emergencies": "优先处理 - 危机与紧急情况", - "Not Urgent & Important": "不紧急 & 重要", - "Schedule - Planning & development": "安排 - 规划与发展", - "Urgent & Not Important": "紧急 & 不重要", - "Delegate - Interruptions & distractions": "委托 - 干扰与分心", - "Not Urgent & Not Important": "不紧急 & 不重要", - "Eliminate - Time wasters": "消除 - 时间浪费", + "Urgent & Important": "紧急且重要", + "Do First - Crisis & emergencies": "优先处理:危机和紧急事务", + "Not Urgent & Important": "重要但不紧急", + "Schedule - Planning & development": "安排计划:规划与发展", + "Urgent & Not Important": "紧急但不重要", + "Delegate - Interruptions & distractions": "委派处理:干扰与打断", + "Not Urgent & Not Important": "不紧急也不重要", + "Eliminate - Time wasters": "减少投入:消耗时间的事务", "Task Priority Matrix": "任务优先级矩阵", "Created Date (Newest First)": "创建日期(最新优先)", "Created Date (Oldest First)": "创建日期(最早优先)", @@ -1896,9 +1900,6 @@ const translations = { "选择所有视图的默认显示模式。这影响您第一次打开视图或创建新视图时任务的显示方式。", "List View": "列表视图", "Tree View": "树状视图", - "Global Filter Configuration": "全局筛选配置", - "Configure global filter rules that apply to all Views by default. Individual Views can override these settings.": - "配置默认应用于所有视图的全局筛选规则。单个视图可以覆盖这些设定。", "Cancelled Date": "取消日期", "Depends On": "依赖于", "Task IDs separated by commas": "用逗号分隔的任务 ID", @@ -2171,7 +2172,7 @@ const translations = { "Common Metadata Symbols": "常用元数据符号", "Due date": "截止日期", "Start date": "开始日期", - "Scheduled date": "计划日期", + "Scheduled date": "安排日期", "Higher priority": "较高优先级", "Lower priority": "较低优先级", "Recurring task": "重复任务", @@ -2420,6 +2421,797 @@ const translations = { "Automatically start the timer when creating a new task via quick capture (checkbox mode only)": "通过快速捕获创建新任务时自动启动计时器(仅限复选框模式)", "Timer started for new task": "已为新任务启动计时器", + + " (truncated)": "(截断)", + "(Copy)": "(复制)", + "(space)": "(空格)", + "+ Add Custom Cycle": "+ 添加自定义循环", + "+ Add Status": "+ 添加状态", + ", Replacement: ": ",替换为:", + "0.0.0.0 (All interfaces - for external access)": "0.0.0.0(监听所有网络接口,允许外部访问)", + "1 → 2 → 3 → 4 → 5": "1 → 2 → 3 → 4 → 5", + "1) Initialize": "1)初始化", + "12-hour format (1:30 PM)": "12 小时格式 (1:30 PM)", + "127.0.0.1 (Local only)": "127.0.0.1(仅限本地)", + "2) Call tool with session id": "2)使用会话 ID 调用工具", + "24-hour format (13:30)": "24 小时格式 (13:30)", + "A descriptive name for the workspace": "工作区的描述性名称", + "AM (Morning)": "AM(上午)", + "Active strategies: ": "已启用的识别规则:", + "Add Custom Mapping": "添加自定义映射", + "Add Cycle": "添加循环", + "Add Detailed Cycle": "添加详细状态循环", + "Add Detection Method": "添加检测方法", + "Add File": "添加文件", + "Add Folder": "添加文件夹", + "Add Item": "添加条目", + "Add Number Cycle": "添加数字循环", + "Add Pattern": "添加匹配规则", + "Add Simple Cycle": "添加简单循环", + "Add custom status mappings for your workflow.": "为您的工作流添加自定义状态映射。", + "Add metadata fields that indicate a file should be treated as a task (e.g., dueDate, status, priority)": "添加用于将文件识别为任务的元数据字段,例如 dueDate、status、priority。", + "Add paths that contain task files (e.g., Projects/, Tasks/2024/, Work/TODO/)": "添加包含任务文件的路径(例如,Projects/、Tasks/2024/、Work/TODO/)", + "Add progress bar to Projects view": "将进度条添加到项目视图", + "Add tags that indicate a file should be treated as a task (e.g., #task, #todo, #actionable)": "添加指示文件应被视为任务的标签(例如,#task、#todo、#actionable)", + "Add {{value0}} Theme as New Cycle?": "将 {{value0}} 主题添加为新的状态循环?", + "Agenda View": "日程视图", + "All Workspaces": "所有工作区", + "All history": "所有历史", + "All settings have been reset to their default values": "所有设置已重置为默认值", + "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.": "允许根据文件的元数据、标签或文件路径来识别文件并将其视为任务。这提供了超越简单元数据解析的高级识别策略。", + "Applied recommended configuration: ": "应用推荐配置:", + "Apply {{value0}} Theme?": "应用 {{value0}} 主题?", + "Are you sure you want to delete \"{{name}}\"? This action cannot be undone.": "您确定要删除“{{name}}”吗?此操作无法撤消。", + "Are you sure you want to delete the '{{value0}}' workflow?": "确定删除工作流“{{value0}}”吗?", + "Are you sure you want to delete the habit ": "您确定要删除该习惯吗", + "Are you sure you want to reset all settings to their default values?\n\nThis action cannot be undone.": "您确定要将所有设置重置为默认值吗?\n\n此操作无法撤消。", + "Arguments:": "参数:", + "Auto-detect Status Mappings": "自动检测状态映射", + "Automatically convert between metadata status values and task symbols": "自动在元数据状态值和任务符号之间转换", + "Automatically parse natural language time expressions and specific times (12:00, 1:30 PM, 12:00-13:00)": "自动解析自然语言时间表达式和具体时间(12:00、1:30 PM、12:00-13:00)", + "Automatically sync with task status configuration": "自动与任务状态配置同步", + "Base View Type": "基础视图类型", + "Based on: ": "基于:", + "Bases Support": "Bases 支持", + "Basic": "基础", + "Blacklist": "黑名单", + "Block References": "块引用", + "Block reference prefix": "块引用前缀", + "Both": "两处同时显示", + "Bottom Section": "底部", + "Built-in View Templates": "内置视图模板", + "Cache TTL": "缓存生存时间", + "Calendar View Configuration": "日历视图配置", + "Calendar Views": "日历视图", + "Calendar view created: ": "已创建日历视图:", + "Calendar view updated: ": "已更新日历视图:", + "Cannot enable views without indexer. Please enable the indexer first in Index & Sources settings.": "无法启用没有索引器的视图。请首先在“索引和来源”设置中启用索引器。", + "Capture as:": "捕获方式:", + "Capture to:": "保存位置:", + "Case Sensitive Matching": "区分大小写的匹配", + "Changelog": "变更日志", + "Characters used to separate time ranges (comma-separated)": "用于分隔时间范围的字符(逗号分隔)", + "Choose a color for this workspace": "为此工作区选择颜色", + "Choose a preset or customize the time range": "选择预设或自定义时间范围", + "Choose an icon for this view": "为此视图选择一个图标", + "Choose an icon for this workspace": "为此工作区选择一个图标", + "Choose the note that should be copied; {{CONTENT}} placeholders are replaced, otherwise the captured text is appended.": "选择要复制的笔记; {{CONTENT}} 占位符将被替换,否则将附加捕获的文本。", + "Choose where this view appears in the sidebar. Views in the bottom section are visually separated from top section views.": "选择此视图在侧栏中的显示位置。底部视图在视觉上与顶部视图分开。", + "Choose your preferred interface style and configure how Task Genius displays in your workspace.": "选择您喜欢的界面风格并配置 Task Genius 在工作区中的显示方式。", + "Classic": "经典", + "Classic & Familiar": "经典又熟悉", + "Clear Logs": "清除日志", + "Click the button below to automatically add this MCP server to Cursor:": "单击下面的按钮自动将此 MCP 服务器添加到 Cursor:", + "Collapse/Expand": "折叠/展开", + "Comma-separated list of folder paths where task timer should be enabled": "在哪些文件夹中启用任务计时器;多个路径用英文逗号分隔。", + "Comma-separated list of tags that enable task timer": "哪些标签可以启用任务计时器;多个标签用英文逗号分隔。", + "Common Mappings": "常用映射", + "Completed Tasks": "已完成的任务", + "Config File-based Project Detection": "基于配置文件的项目检测", + "Configure Symbols": "配置符号", + "Configure Task Fields": "配置任务字段", + "Configure Task Paths": "配置任务路径", + "Configure Task Tags": "配置任务标签", + "Configure additional methods to detect project files": "配置其他方法来检测项目文件", + "Configure file filtering to improve indexing performance and focus on relevant content": "配置文件过滤以提高索引性能并专注于相关内容", + "Configure hidden modules": "配置隐藏模块", + "Configure how dates and times are displayed in views.": "配置日期和时间在视图中的显示方式。", + "Configure how files are recognized as tasks. At least one strategy must be enabled.": "配置如何将文件识别为任务。必须至少启用一项策略。", + "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)": "配置用于将文件识别为任务的元数据字段,例如 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.": "配置特定于 Fluent 界面的选项。", + "Configure paths that contain task files (e.g., Projects/, Tasks/2024/, Work/TODO/)": "配置包含任务文件的路径(例如,Projects/、Tasks/2024/、Work/TODO/)", + "Configure project detection from project configuration files": "从项目配置文件配置项目检测", + "Configure project display, organization and metadata mappings": "配置项目显示、组织和元数据映射", + "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)": "配置指示文件应被视为任务的标签(例如,#task、#todo、#actionable)", + "Configure the format of time expressions": "配置时间表达式的格式", + "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.": "配置应在此工作区中隐藏哪些模块。隐藏视图不会出现在侧边栏中。", + "Contains match": "包含匹配项", + "Control which days are displayed in the calendar": "控制日历中显示的日期", + "Copy Install Link": "复制安装链接", + "Copy Settings From": "从工作区复制设置", + "Copy settings from an existing workspace": "从现有工作区复制设置", + "Copy this cycle": "复制这个循环", + "Create": "创建", + "Create Calendar View": "创建日历视图", + "Create New Calendar View": "创建新的日历视图", + "Create New Workspace": "创建新工作区", + "Create a backup of active timers": "创建活动计时器的备份", + "Create a custom view from the templates above to get started.": "从上面的模板创建自定义视图以开始使用。", + "Create a new workspace with custom settings": "使用自定义设置创建新工作区", + "Create custom calendar views based on Month, Week, or Day views. Each custom view can have its own display settings.": "基于月、周或日视图创建自定义日历视图。每个自定义视图都可以有自己的显示设置。", + "Create task timer backup": "创建任务计时器备份", + "Current Workspace": "当前工作区", + "Custom Calendar Views": "自定义日历视图", + "Custom Content Field": "自定义任务内容字段", + "Custom Cycle": "自定义循环", + "Custom Date Formats": "自定义日期格式", + "Custom Mappings": "自定义映射", + "Custom Project Detection Methods": "自定义项目识别方式", + "Custom Range": "自定义范围", + "Custom Selection": "自定义选择", + "Custom days": "自定义日期", + "Custom marker": "自定义标记", + "Custom metadata field": "自定义元数据字段", + "Customize how dates are displayed in headers": "自定义日期在标题中的显示方式", + "Daily summary": "每日总结", + "Data Management": "数据管理", + "Date Filter": "日期过滤器", + "Date and Time Display": "日期和时间显示", + "Date marker": "日期标记", + "Day Filter": "显示日期筛选", + "Day Header Format": "日期标题格式", + "Day View": "日视图", + "Days to Show": "显示天数", + "Default": "默认", + "Default AM/PM Period": "默认上午/下午时段", + "Default Cycle": "默认循环", + "Default Task Status": "默认任务状态", + "Default file name template": "默认文件名模板", + "Default folder for new files": "新文件的默认文件夹", + "Default format preference for ambiguous time expressions": "不明确的时间表达式的默认格式首选项", + "Default period when AM/PM is ambiguous in 12-hour format": "当 AM/PM 不明确时的默认时间段(12 小时格式)", + "Default settings": "默认设置", + "Default status for newly created file tasks": "新建文件任务的默认状态", + "Default workspace": "默认工作区", + "Default workspace cannot be deleted": "默认工作区无法删除", + "Define the statuses in cycling order": "按循环顺序定义状态", + "Delete Workspace": "删除工作区", + "Delete item": "删除条目", + "Delete this cycle": "删除这个循环", + "Delete this item": "删除此项", + "Desktop Integration": "桌面集成", + "Desktop integration features are only available in the desktop app": "桌面集成功能仅在桌面应用程序中可用", + "Desktop only": "仅限桌面版", + "Detailed": "详细", + "Display": "显示", + "Display a full year with 12 mini-month calendars": "用 12 个月的小日历展示全年任务。", + "Display days with no events": "显示没有事件的日期", + "Display event count badges on date cells": "在日期单元格上显示事件计数徽章", + "Display name for this calendar view": "此日历视图的显示名称", + "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": "在月视图中显示周序号", + "Drag to reorder": "拖动以重新排序", + "Drag views between sections or within sections to reorder them. Toggle visibility with the eye icon.": "在部分之间或部分内拖动视图以重新排序。使用眼睛图标切换可见性。", + "Edit Calendar View": "编辑日历视图", + "Edit File Filter Rules": "编辑文件过滤规则", + "Editor Configuration": "编辑器配置", + "Enable Base View functionality. This feature provides enhanced view management capabilities but may be affected by future Obsidian API changes.": "启用基本视图功能。此功能提供增强的视图管理功能,但可能会受到未来 Obsidian API 更改的影响。", + "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.": "启用基本视图功能。此功能提供增强的视图管理功能,但可能会受到未来 Obsidian API 更改的影响。您可能需要重新启动 Obsidian 才能看到更改。", + "Enable File Task": "启用文件任务", + "Enable Task Genius Views": "启用 Task Genius 视图", + "Enable Task Genius Views above to configure view settings.": "启用上面的 Task Genius 视图来配置视图设置。", + "Enable Task Genius sidebar views to display and manage tasks. Requires the indexer to be enabled.": "启用 Task Genius 侧边栏视图来显示和管理任务。需要启用索引器。", + "Enable Task Timer": "启用任务计时器", + "Enable Time Filter": "启用时间过滤器", + "Enable case-sensitive matching for status values": "为状态值启用区分大小写的匹配", + "Enable notifications": "启用通知", + "Enable project features": "启用项目功能", + "Enable task timer functionality for tracking time spent on tasks": "启用任务计时器功能以跟踪任务所花费的时间", + "Enable/disable this cycle": "启用/停用此循环", + "End Hour": "结束小时", + "Enhanced": "增强型", + "Enter details for {{value0}}...": "输入“{{value0}}”的详细信息……", + "Enter metadata field name": "输入元数据字段名称", + "Enter metadata value and symbol (e.g., 'done:x')": "输入元数据值和符号(例如“done:x”)", + "Enter new name": "输入新名称", + "Enter path (e.g., Projects/, Tasks/**/*.md)": "输入路径(例如,Projects/、Tasks/**/*.md)", + "Enter tag (e.g., #task)": "输入标签(例如,#task)", + "Enter value": "输入值", + "Enter workspace name": "输入工作区名称", + "Error rendering format": "渲染格式错误", + "Error:": "错误:", + "Exact match": "精确匹配", + "Examples of time expressions": "时间表达示例", + "Examples:": "示例:", + "Exclude Archive Folder": "排除存档文件夹", + "Exclude Temporary Files": "排除临时文件", + "Export all timer data to JSON": "将所有计时器数据导出到JSON", + "Export task timer data": "导出任务计时器数据", + "Export task timer data (YAML)": "导出任务计时器数据(YAML)", + "Export to YAML format": "导出为 YAML 格式", + "Failed to sync mapping": "同步映射失败", + "Features to be enabled": "要启用的功能", + "Field name in frontmatter to check for enabling task timer (e.g., 'task-timer: true')": "文件属性区 中用于检查是否启用任务计时器的字段名称(例如“task-timer:true”)", + "File Content": "文件内容", + "File Creation Mode": "文件创建模式", + "File Task is disabled": "文件任务已禁用", + "File Task is enabled and monitoring files": "文件任务已启用并监视文件", + "File filtering helps you focus on relevant content while improving performance, especially in large vaults.": "文件过滤可帮助您专注于相关内容,同时提高性能,尤其是在大型仓库中。", + "FileSource status mapping synced": "文件任务的状态映射已同步", + "Filename": "文件名", + "Filter files during task indexing to improve performance": "在任务索引期间过滤文件以提高性能", + "First H1 heading": "第一个 H1 标题", + "First hour to display (0-23)": "显示的第一个小时 (0-23)", + "Fluent Interface Settings": "Fluent 界面设置", + "Focus on Projects": "聚焦项目", + "Folder paths": "文件夹路径", + "Folder that contains Quick Capture templates for File mode.": "包含文件模式的快速捕获模板的文件夹。", + "Format for day headers (e.g., dddd, MMMM D)": "日期标题的格式(例如 dddd、MMMM D)", + "Format for day view header (e.g., yyyy'年'M'月'd'日')": "日视图标题的格式(例如,yyyy'年'M'月'd'日')", + "Format for month view header (e.g., yyyy M)": "月视图标题的格式(例如,yyyy M)", + "Friday": "周五", + "Frontmatter field": "文件属性字段", + "Frontmatter title": "文件属性中的标题", + "Full project workflow": "完整的项目工作流", + "Full year": "全年", + "Glob pattern (e.g., Projects/**/*.md)": "Glob 通配符规则,例如 Projects/**/*.md", + "Hidden Days": "隐藏的日期", + "Hidden Modules Configuration": "隐藏模块配置", + "Hide Weekends": "隐藏周末", + "Hide from sidebar": "从侧边栏隐藏", + "How paths should be matched": "路径应该如何匹配", + "How tags should be matched against file tags": "标签应如何与文件标签匹配", + "How to handle time ranges that cross midnight (e.g., 23:00-01:00)": "如何处理跨越午夜的时间范围(例如 23:00-01:00)", + "If enabled, #tags in the editor content are written into YAML frontmatter tags (merged and deduplicated)": "如果启用,编辑器内容中的#tags将写入YAML 文件属性区标签(合并和去重)", + "Ignore system and temporary files": "忽略系统和临时文件", + "Import task timer data": "导入任务计时器数据", + "Import timer data from JSON file": "从 JSON 文件导入计时器数据", + "Incomplete Tasks": "未完成的任务", + "Index & Sources": "索引与来源", + "Index only specific project folders": "仅索引特定项目文件夹", + "Inline": "内联", + "Input: ": "输入:", + "Interface": "界面", + "Interface Mode": "界面模式", + "Interface Style": "界面风格", + "Keep open after capture": "捕获后保持打开状态", + "Keep the familiar interface and interaction style you know": "保持您熟悉的界面和交互风格", + "Keep the modal open after capturing content": "捕获内容后保持弹窗打开。", + "Last hour to display (0-23)": "最后一小时显示 (0-23)", + "Last month": "上个月", + "Last updated: {{date}}": "最后更新:{{date}}", + "Last week": "上周", + "Last year": "去年", + "Legacy": "经典界面", + "Link Filter": "链接过滤器", + "Linked Note": "关联笔记", + "MCP Server Logs": "MCP 服务器日志", + "MCP server is not running": "MCP 服务器未运行", + "Manage Workspaces...": "管理工作区...", + "Manage workspaces to organize different contexts with their own settings and filters.": "管理工作区以使用自己的设置和过滤器组织不同的上下文。", + "Manual Configuration": "手动配置", + "Map between human-readable metadata values (e.g., 'completed') and task symbols (e.g., 'x').": "人类可读的元数据值(例如“已完成”)和任务符号(例如“x”)之间的映射。", + "Mark": "符号", + "Max Events Per Row": "每行最大事件数", + "Max other views before overflow": "“其他视图”直接显示的数量上限", + "Maximum events to show per day cell before showing '+N more'": "在显示“+N 更多”之前每天单元格显示的最大事件数", + "Meeting": "会议", + "Metadata": "元数据", + "Metadata Detection": "元数据识别", + "Metadata Property": "元数据属性", + "Metadata Value": "元数据值", + "Metadata-based Project Detection": "基于元数据的项目检测", + "Metadata-based Recognition": "通过元数据识别", + "Method": "方法", + "Method A (Custom Header):": "方式 A(自定义请求头):", + "Method B (Combined Bearer):": "方式 B(组合 Bearer 凭据):", + "Midnight Crossing Behavior": "跨午夜处理方式", + "Migrated from legacy settings": "从旧设置迁移", + "Missed": "未完成", + "Modern": "现代", + "Modern & Sleek": "现代时尚", + "Mon first": "周一为一周起点", + "Monday": "星期一", + "Month Header Format": "月份标题格式", + "Month View": "月视图", + "My Custom View": "我的自定义视图", + "Name of the metadata field to use as task content": "用作任务内容的元数据字段的名称", + "New Calendar View": "新日历视图", + "New Name": "新名称", + "New visual design with elegant animations and modern interactions": "新的视觉设计,优雅的动画和现代互动", + "Next day (23:00 today - 01:00 tomorrow)": "第二天(今天 23:00 - 明天 01:00)", + "No custom calendar views yet": "尚无自定义日历视图", + "No filter rules configured yet": "尚未配置过滤规则", + "No items configured. Click 'Add Item' to get started.": "没有配置任何项目。单击“添加项目”即可开始。", + "No logs match your search.": "没有与搜索内容匹配的日志。", + "No logs yet. Tool calls will appear here.": "暂无日志,工具调用记录会显示在这里。", + "No markdown notes were found in the selected folder.": "在所选文件夹中未找到 Markdown 笔记。", + "No weekends": "排除周末", + "Note:": "注意:", + "Notes": "笔记", + "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": "数字进度跟踪", + "Only show certain hours of the day": "只显示一天中的某些时段", + "Open in external browser": "在外部浏览器中打开", + "Optimize Performance": "优化性能", + "Optional: Only match links containing this text": "可选:仅匹配包含此文本的链接", + "Other Views": "其他视图", + "PM (Afternoon/Evening)": "PM(下午/晚上)", + "Path Matching Mode": "路径匹配模式", + "Path-based Recognition": "通过路径识别", + "Paths": "路径", + "Pattern: ": "匹配规则:", + "Per-task reminders": "每个任务提醒", + "Performance": "性能", + "Please enter a name": "请输入名称", + "Please enter a workspace name": "请输入工作区名称", + "Populate FileSource status mapping from your checkbox status configuration": "从复选框状态配置填充 FileSource 状态映射", + "Prefer Frontmatter Title": "优先使用文件属性中的标题", + "Preferred Time Format": "首选时间格式", + "Prefix (e.g., Projects/ matches Projects/App.md)": "前缀(例如,Projects/ 匹配 Projects/App.md)", + "Prefix for generated block reference IDs (e.g., 'timer' creates ^timer-123456-7890)": "生成的块引用 ID 的前缀(例如,“timer”创建 ^timer-123456-7890)", + "Prefix match": "前缀匹配", + "Progress Tracker": "进度追踪器", + "Projects List": "项目清单", + "Quick Add Rules": "快速添加规则", + "Quick Install": "快速安装", + "Quick TODO/DONE cycle": "未开始/已完成简易循环", + "Quick Templates": "快速模板", + "Quickly add common workflow patterns": "快速添加常用工作流模式", + "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}}": "记录“{{value0}}”的详细信息", + "Regular expression (advanced)": "正则表达式(高级)", + "Remember last mode": "记住最后的模式", + "Remember the last used quick capture mode": "记住上次使用的快速捕获模式。", + "Remove the .md extension from filename when using as task content": "用作任务内容时从文件名中删除 .md 扩展名", + "Remove this status": "删除此状态", + "Rename": "重命名", + "Rename Workspace": "重命名工作区", + "Require All Fields": "必须包含所有字段", + "Require all specified fields to be present (otherwise any field is sufficient)": "要求所有指定字段都存在(否则任何字段就足够了)", + "Reset All Settings": "重置所有设置", + "Reset Settings": "重置设置", + "Reset all settings to their default values": "将所有设置重置为默认值", + "Result:": "结果:", + "Review Your Configuration": "检查您的配置", + "Rule {{value0}}": "规则 {{value0}}", + "Same day (treat as error)": "同一天(视为错误)", + "Sat first": "周六为一周起点", + "Saturday": "星期六", + "Saved. Reopen the view to apply.": "已保存。重新打开视图以应用。", + "Scan now": "立即扫描", + "Scope:": "范围:", + "Search logs...": "搜索日志...", + "Select a template folder above to enable the dropdown.": "选择上面的模板文件夹以启用下拉列表。", + "Select between the modern Fluent interface or the classic Legacy interface.": "在现代 Fluent 界面或经典 Legacy 界面之间进行选择。", + "Select the interface style to use.": "选择要使用的界面风格。", + "Select which days to hide from the calendar": "选择要从日历中隐藏的日期", + "Selected folder was not found in the vault.": "在当前仓库中找不到所选文件夹。", + "Send now": "立即发送", + "Send one notification for today's due tasks at a specific time (HH:mm)": "在特定时间发送一份有关今天到期任务的通知 (HH:mm)", + "Set value": "设定值", + "Show All Days": "显示所有日期", + "Show Empty Days": "显示没有事件的日期", + "Show Event Counts": "显示事件计数", + "Show Week Numbers": "显示周序号", + "Show a bell with count in system tray, status bar, or both": "在系统托盘、状态栏或两处同时显示带任务数量的铃铛图标。", + "Show changelog after plugin updates": "插件更新后显示更改日志", + "Show error": "显示错误", + "Show indicator with checkbox": "显示带有复选框的指示器", + "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.": "在复选框旁边显示状态指示器。启用后,复选框旁边将显示一个指示器。", + "Sidebar Components": "侧边栏组件", + "Sidebar Position": "侧边栏位置", + "Simple": "简单", + "Skip archived content": "跳过存档内容", + "Standard task lifecycle with all states": "包含全部状态的标准任务流程", + "Start Hour": "起始小时", + "Statistics": "统计数据", + "Status Cycles Management": "状态循环管理", + "Status bar": "状态栏", + "Status mappings work with your Task Status Settings. ": "状态映射与您的任务状态设置一起使用。", + "Status sequence": "状态序列", + "Strip File Extension": "移除文件扩展名", + "Submit": "提交", + "Sunday": "周日", + "Switch": "切换", + "Switch Workspace": "切换工作区", + "Sync from Task Status Settings": "从任务状态设置同步", + "System Default": "系统默认值", + "System tray": "系统托盘", + "TODO → PLAN → IN PROGRESS → DONE": "未开始 → 计划 → 进行中 → 已完成", + "TODO ↔ DONE": "未开始 ↔ 已完成", + "TODO.md in any direct subfolder of Work": "Work 的任意直接子文件夹中的 TODO.md", + "Tag Matching Mode": "标签匹配模式", + "Tag-based Recognition": "通过标签识别", + "Task Fields": "任务字段", + "Task Paths": "任务路径", + "Task Properties for Files": "文件的任务属性", + "Task Symbol": "任务符号", + "Task Tags": "任务标签", + "Task Timer": "任务计时器", + "Task Title Source": "任务标题来源", + "Task fields updated. Rebuild the task index to apply to existing files.": "任务字段已更新。重建任务索引以应用于现有文件。", + "Task paths updated. Rebuild the task index to apply to existing files.": "任务路径已更新。重建任务索引以应用于现有文件。", + "Task tags updated. Rebuild the task index to apply to existing files.": "任务标签已更新。重建任务索引以应用于现有文件。", + "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": "用于显示已完成任务时间的模板。使用 {h} 表示小时,{m} 表示分钟,{s} 表示秒", + "Template note": "模板笔记", + "Templates": "模板", + "Templates/Quick Capture": "Templates/Quick Capture", + "The calendar layout this view is based on": "此视图所基于的日历布局", + "The symbols defined here should match those in your checkbox status configuration.": "此处定义的符号应与复选框状态配置中的符号相匹配。", + "This will add a new status cycle based on the {{value0}} theme.": "将根据 {{value0}} 主题新增一个状态循环。", + "This will override your current checkbox status settings with the {{value0}} theme. Do you want to continue?": "这会用 {{value0}} 主题覆盖当前的复选框状态设置。是否继续?", + "Thursday": "星期四", + "Time Filter": "时间过滤器", + "Time Format": "时间格式", + "Time Format Configuration": "时间格式配置", + "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)": "缓存结果的生存时间(以毫秒为单位)(默认值:300000 = 5 分钟)", + "Top Section": "顶部", + "Total: {{value0}} | Success: {{value1}} | Errors: {{value2}}": "总计:{{value0}} | 成功:{{value1}} | 错误:{{value2}}", + "Tray indicator": "托盘指示灯", + "Tuesday": "星期二", + "URL: ": "网址:", + "Untitled View": "无标题视图", + "Update now": "立即更新", + "Use left/right workspace side leaves for Sidebar and Details. When enabled, the main fluent view won't render in-view sidebar or details.": "将侧栏和任务详情放到工作区左右侧边面板。启用后,Fluent 主视图内部不再显示侧栏和详情面板。", + "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 workspace side leaves": "使用工作区侧边面板", + "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}})": "由文件模式用于预填充文件名输入(支持 {{DATE:YYYY-MM-DD}} 等日期模板)", + "User Interface": "用户界面", + "Value cannot be empty": "值不能为空", + "Version marker": "版本标记", + "View Icon": "视图图标", + "View Logs": "查看日志", + "View Server Logs": "查看服务器日志", + "View all MCP server tool calls and their results": "查看所有 MCP 服务器工具调用及其结果", + "View deleted: ": "已删除视图:", + "View duplicated: ": "已复制视图:", + "Views": "视图", + "Views are disabled": "视图已禁用", + "Wednesday": "星期三", + "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 updating task content, prefer updating frontmatter title over renaming the file. This protects the original filename.": "更新任务内容时,优先更新 文件属性区 标题而不是重命名文件。这可以保护原始文件名。", + "Which day should the week start on": "一周应该从哪一天开始", + "Whitelist": "白名单", + "Whitelist: Include only specified paths | Blacklist: Exclude specified paths": "白名单:仅包含指定路径 |黑名单:排除指定路径", + "Whitelist: include only specified paths. Blacklist: exclude specified paths.": "白名单:仅包含指定路径。黑名单:排除指定路径。", + "Why File Filtering?": "为什么要进行文件过滤?", + "Working Hours (9:00-18:00)": "工作时间(9:00-18:00)", + "Workspace \"{{name}}\" created": "工作区“{{name}}”已创建", + "Workspace \"{{name}}\" deleted": "工作区“{{name}}”已删除", + "Workspace Color": "工作区颜色", + "Workspace Icon": "工作区图标", + "Workspace Management": "工作区管理", + "Workspace Name": "工作区名称", + "Workspace manager is not available.": "工作区管理器不可用。", + "Workspace updated": "工作区已更新", + "Workspaces": "工作区", + "Write content tags to frontmatter": "将内容标签写入文件属性区", + "Year View": "年视图", + "Year view displays 12 mini-month calendars. Use the Date Filter tab to hide weekends if needed.": "年视图显示 12 个迷你月历。如果需要,可以使用“日期过滤器”选项卡隐藏周末。", + "You can customize any of these settings later in the plugin settings": "您可以稍后在插件设置中自定义任何这些设置", + "Your custom calendar views. Drag to reorder, toggle visibility, or edit settings.": "您的自定义日历视图。拖动即可重新排序、切换可见性或编辑设置。", + "all .md files in Projects and subfolders": "Projects 及其子文件夹中的所有 .md 文件", + "all .md files in Projects folder": "Projects 文件夹中的所有 .md 文件", + "archived on {{date}}": "存档于 {{date}}", + "files ending with .task.md in Tasks folder": "Tasks 文件夹中以 .task.md 结尾的文件", + "files starting with date in Tasks": "Tasks 文件夹中以日期开头的文件", + "matches all files under Projects folder": "匹配 Projects 文件夹下的所有文件", + "matches all files under Tasks/2024 folder": "匹配Tasks/2024文件夹下的所有文件", + "moved on {{date}}": "移至{{date}}", + "version 1.0": "1.0版", + "{title} ({count} days)": "{title}({count}天)", + "{{count}} field(s) configured": "已配置 {{count}} 个字段", + "{{count}} path(s) configured": "已配置 {{count}} 条路径", + "{{count}} symbol(s) configured": "已配置 {{count}} 个符号", + "{{count}} tag(s) configured": "已配置 {{count}} 个标签", + "{{hidden}}/{{total}} hidden": "已隐藏 {{hidden}}/{{total}} 项", + "{{status}} Task Symbols": "{{status}} 任务符号", + "{{value0}} theme workflow": "{{value0}} 主题工作流", + "{{value0}} · Heatmap": "{{value0}} · 热力图", + "{{value0}}: Error": "{{value0}}:出错了", + "{{value0}}ms": "{{value0}} 毫秒", + "Index & Task Source Configuration": "索引与任务来源配置", + "Configure how Task Genius discovers and indexes tasks from various sources including inline tasks, file metadata, and projects.": "配置 Task Genius 如何从行内任务、文件元数据和项目等来源发现任务并建立索引。", + "Enable Indexer": "启用索引器", + "Please restart Obsidian for the Indexer change to take effect.": "请重启 Obsidian,使索引器设置生效。", + "Checkbox Tasks": "复选框任务", + "File Tasks": "文件任务", + "Enable checkbox tasks": "启用复选框任务", + "Index markdown checkbox tasks. Disable this if you only want to use file-based or external task sources.": "为 Markdown 中的复选框任务建立索引。如果只使用文件任务或外部任务来源,可以关闭此项。", + "Checkbox task indexing disabled. The index will prune inline tasks shortly.": "已关闭复选框任务索引,现有行内任务将从索引中移除。", + "Inline task parsing": "行内任务解析", + "Configure how tasks are parsed from markdown content.": "配置如何从 Markdown 内容中解析任务。", + "Enable custom date formats": "启用自定义日期格式", + "Enable custom date format patterns for parsing dates. When enabled, the parser will try your custom formats before falling back to default formats.": "启用自定义日期解析格式。启用后,解析器会优先尝试自定义格式,再尝试默认格式。", + "Custom date formats": "自定义日期格式", + "Configure custom date format patterns.": "配置自定义日期格式。", + "Configure Date Formats": "配置日期格式", + "{{count}} format(s) configured": "已配置 {{count}} 种格式", + "Configure Custom Date Formats": "配置自定义日期格式", + "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).": "添加自定义日期格式。日期标记:yyyy(四位年份)、yy(两位年份)、MM(两位月份)、M(一至两位月份)、dd(两位日期)、d(一至两位日期)、MMM(月份简称)、MMMM(月份全称)。时间标记:HH(两位小时)、mm(两位分钟)、ss(两位秒数)。固定文字请用单引号包围,例如 ISO 格式中的 'T'。", + "Enter date format (e.g., yyyy-MM-dd or yyyyMMdd_HHmmss)": "输入日期格式,例如 yyyy-MM-dd 或 yyyyMMdd_HHmmss", + "Date formats updated. The parser will now recognize these custom formats.": "日期格式已更新,解析器现在可以识别这些自定义格式。", + "Format Pattern": "格式", + "Example": "示例", + "Configure headings to ignore. Tasks under these headings will be excluded from indexing.": "配置需要忽略的标题,这些标题下的任务不会进入索引。", + "Configure Ignore Headings": "配置忽略的标题", + "{{count}} heading(s) configured": "已配置 {{count}} 个标题", + "Add headings to ignore. Tasks under these headings will be excluded from indexing. Examples: '## Project', '## Inbox', '# Archive'": "添加需要忽略的标题,其下的任务不会进入索引。例如:'## Project'、'## Inbox'、'# Archive'。", + "Enter heading (e.g., ## Inbox)": "输入标题,例如 ## Inbox", + "Heading filters updated. Rebuild the task index to apply to existing tasks.": "标题过滤设置已更新。重建任务索引后即可应用到现有任务。", + "Configure headings to focus on. Only tasks under these headings will be included in indexing.": "配置要关注的标题,仅将这些标题下的任务纳入索引。", + "Configure Focus Headings": "配置关注的标题", + "Add headings to focus on. Only tasks under these headings will be included in indexing. Examples: '## Project', '## Inbox', '# Tasks'": "添加要关注的标题,仅将其下的任务纳入索引。例如:'## Project'、'## Inbox'、'# Tasks'。", + "Enter heading (e.g., ## Tasks)": "输入标题,例如 ## Tasks", + "This change affects how tasks inherit metadata from files. Rebuild the index now so changes take effect immediately?": "此更改会影响任务从文件继承元数据的方式。是否立即重建索引,使更改生效?", + "Failed to reindex tasks": "任务索引重建失败", + "Enable file tasks": "启用文件任务", + "Allow Task Genius to recognize files as tasks using metadata, tags, or templates.": "允许 Task Genius 根据元数据、标签或模板将整个文件识别为任务。", + "File task recognition disabled. Existing file tasks will be pruned shortly.": "已关闭文件任务识别,现有文件任务将从索引中移除。", + "File tasks are disabled. Enable them to configure recognition strategies.": "文件任务已关闭,启用后可以配置识别规则。", + "Performance Configuration": "性能配置", + "Configure performance-related indexing settings": "配置与索引性能有关的设置。", + "Index Maintenance": "索引维护", + "Tools for managing and rebuilding the task index": "用于管理和重建任务索引的工具。", + "Force a complete rebuild of the task index. Use this if you notice missing or incorrect tasks.": "强制完整重建任务索引。当任务缺失或索引信息不正确时,可以使用此功能。", + "How to use": "使用说明", + + "Fluent": "Fluent", + + + 'Points and rewards': '积分与奖励', + 'Open project note': '打开项目笔记', + 'Create project note and move tasks': '创建项目笔记并迁移任务', + 'Project note created; tasks moved': '项目笔记已创建,任务已迁移', + 'Moved to project': '已移入项目', + 'Failed to move project tasks': '迁移项目任务失败', + 'Project notes': '项目笔记', + 'Legacy project marker prefix': '旧版项目标记前缀', + 'Used only to recognize existing project markers while migrating old tasks. New project assignments use project notes.': '仅用于迁移旧任务时识别已有项目标记。新项目归属使用项目笔记。', + 'Create, edit and archive project Markdown notes from the Projects page. New tasks assigned to a project are moved into its note.': '在“项目”页面创建、编辑和归档项目 Markdown 笔记。新归属到项目的任务会移动到对应笔记中。', + 'Legacy project detection settings': '旧版项目识别设置', + 'Additional project detection': '其他项目识别方式', + 'Compatibility options for existing path, tag and config-file project setups. These do not affect new project notes.': '为现有路径、标签和配置文件项目保留的兼容选项,不影响新建的项目笔记。', + 'Edit project details': '编辑项目信息', + 'Archive project': '归档项目', + 'Restore project': '恢复项目', + 'Add task to project': '向项目添加任务', + 'Task moved to project': '任务已移入项目', + 'Could not create project note': '无法创建项目笔记', + 'Canvas tasks must be moved through Task Genius.': 'Canvas 任务请通过 Task Genius 移动', + 'Could not move task to project note': '无法将任务移入项目笔记', + 'Quick filters': '快速筛选', + 'Clear quick filter': '清除快速筛选', + 'No saved filters': '没有已保存的筛选器', + 'Earn points from tasks, add points manually, and redeem rewards.': '完成任务获得积分,手动加减积分,并兑换奖励。', + 'Add points': '记一笔积分', + 'Available points': '可用积分', + 'ledger entries': '条积分记录', + 'Complete tasks to start earning points.': '完成任务即可开始获得积分。', + 'Points history': '积分明细', + 'Reward shop': '奖励商店', + 'Add reward': '添加奖励', + 'Add rewards to redeem them with points.': '添加奖励后即可使用积分兑换。', + 'points': '积分', + 'Set a point cost to enable redemption': '设置积分价格后即可兑换', + 'Redeem': '兑换', + 'Manual points': '手动积分', + 'Redeemed': '已兑换', + 'Reward redeemed': '奖励兑换成功', + 'Enter a non-zero number': '请输入非零数值', + 'Name': '名称', + 'Point cost': '所需积分', + 'Inventory': '库存', + 'Check the reward details': '请检查奖励信息', + 'Default task points': '默认任务积分', + 'points per task': '每个任务积分', + 'Task points': '任务积分', + 'Interval window days key': '间隔签到窗口天数属性名', + "Check in, earn points, and choose your rewards.": "签到、积累积分,再兑换你想要的奖励。", + "Search habits, rewards, and records": "搜索习惯、奖励和流水", + "Points earned": "加分", + "Points spent": "扣分", + "Today's points": "今日积分", + "Habits / check-ins": "习惯 / 打卡记录", + "Daily check-in": "每日打卡", + "Bonuses and rewards": "加分与奖励", + "Points rules": "积分规则", + "Bonus actions": "加分项", + "Edit bonus actions": "编辑加分项", + "Record points": "记录积分", + "Edit reward wishes": "编辑奖励愿望", + "Reward wishes": "奖励愿望", + "Delete this points record?": "删除这条积分流水?", + "No matching records": "没有匹配的记录", + "Habit points": "习惯积分", + "check-ins": "次打卡", + "Points data file": "积分数据文件", + "Choose a Markdown file.": "请选择 Markdown 文件。", + "Default habit points": "默认习惯积分", + "Habit-specific points override the default. Negative values deduct points above the habit allowance.": "单个习惯的积分优先于默认规则;负分习惯只对超过允许额度的部分扣分。", + "Default rule": "默认规则", + "Points per unit": "每单位积分", + "Enter a positive point cost.": "请输入大于零的积分费用。", + "Enter a description and a valid point amount.": "请填写说明和有效分值。", + "One item per line": "每行一项", + "Habits and points": "习惯与积分", + "Archived projects": "已归档项目", + "No archived projects": "暂无归档项目", + "A project with that name already exists.": "已存在同名项目。", + "Each project is a Markdown note. Its project property owns task membership, and assigned tasks are moved into that note.": "每个项目对应一个 Markdown 笔记,由 project 属性管理归属;分配给项目的任务会移入该笔记。", + "New project folder": "新项目保存目录", + "Archive finished projects and restore them when needed. Notes and task history stay available.": "完成的项目可以归档,也能随时恢复;项目笔记和任务历史会保留。", + "Manage archives": "管理归档", + "Existing project tags": "原有项目标签", + "Existing tags can still be read. Use Create project note and move tasks to consolidate a legacy project into its note.": "仍可读取原有标签;使用“创建项目笔记并迁移任务”即可把旧项目统一到笔记中。", + "New saved filter": "新建预设筛选器", + "Edit saved filter": "编辑预设筛选器", + "Delete saved filter": "删除预设筛选器", + "Combine fields with AND, OR, NOT and parentheses. Example: project:\"Writing\" AND priority:>=3": "可用 AND、OR、NOT 和括号组合条件。例如:project:\"写作\" AND priority:>=3", + "Include matches": "包含符合条件的任务", + "Exclude matches": "排除符合条件的任务", + "Enter a filter name.": "请输入筛选器名称。", + "Search habits": "搜索习惯", + "Filter mode": "筛选模式", + "Change": "更改", + "File path": "文件路径", + "Confirm": "确认", + "Delete this reward?": "删除这个奖励?", + "Use default rule": "使用默认规则", + "Use 0 to award task points only when a task has its own point value.": "设为 0 时,只有明确设置了积分的任务才会自动加分。", + "Combine conditions": "条件组合方式", + "Match all conditions": "符合全部条件", + "Match any condition": "符合任一条件", + "Text": "文字", + "Contains": "包含", + "Equals": "等于", + "Does not equal": "不等于", + "At least / on or after": "不小于 / 日期不早于", + "At most / on or before": "不大于 / 日期不晚于", + "Remove condition": "移除条件", + "Add condition": "添加条件", + "Choose a Markdown file inside the vault.": "请选择库内的 Markdown 文件。", + "The points data path is occupied by a folder.": "积分数据文件路径被一个文件夹占用了。", + "Enter a description, a valid date, and a non-zero amount.": "请填写说明、有效日期和非零分值。", + "Habit note not found.": "找不到习惯笔记。", + "Not enough points.": "积分不足。", + "This reward is out of stock.": "这个奖励的库存已用完。", + "Open": "打开", + "Points": "积分", + "A project file already exists at that path.": "该路径已存在项目文件。", + "The task file could not be found.": "找不到任务所在的文件。", + "The task changed before it could be moved.": "任务已发生变化,请刷新后再移动。", + "The project folder path is occupied by a file.": "项目目录路径被一个文件占用了。", + "Create project": "创建项目", + "Add task": "添加任务", + "Delete project": "删除项目", + "Move the project note and its tasks to the trash.": "将项目笔记及其中的任务移入回收站。", + "Habit layout": "习惯布局", + "Task Genius cards": "原生卡片布局", + "Dashboard layout": "仪表盘布局", + "Check in": "签到", + "Period progress": "本周期进度", + "Decrease": "减少", + "Increase": "增加", + "To do": "待办", + "This month's tasks": "本月任务", + "Saved filters": "预设筛选", + "Any task date": "任意任务日期", + "Select a value": "请选择条件值", + "Choose date": "指定日期", + "Advanced query (optional)": "高级查询(可选)", + "Use advanced query": "使用高级查询", + "Choose a value for every condition.": "请为每条规则选择条件值。", + "Where tasks come from": "任务来源", + "Task Genius reads checkboxes in your notes. You can also use an entire note as a task.": "自动读取笔记中的待办事项;也可以把整篇笔记作为一个任务。", + "Tasks in notes": "笔记中的待办", + "Whole-note tasks": "整页任务", + "Task writing format": "任务保存方式", + "Existing task dates and priorities are read automatically.": "已有任务的日期和优先级会自动识别。", + "Save dates and priorities as": "日期与优先级的写入格式", + "Choose how new dates and priorities appear in your notes. Existing tasks do not need conversion.": "选择新写入的日期和优先级如何显示。已有任务无需转换。", + "Inline properties": "行内属性(如 [due:: 日期])", + "Task icons (recommended)": "任务图标(推荐,如 📅 日期)", + "Exclude tasks in these sections": "忽略这些章节下的任务", + "Only include tasks in these sections": "只收录这些章节下的任务", + "For example, exclude tasks below an Archive heading. Leave blank to include all sections.": "例如忽略“归档”标题下的任务。留空表示不排除任何章节。", + "Optional: only read tasks below the selected headings. Leave blank to include all sections.": "只管理指定标题下的任务。留空表示收录所有章节。", + "Use the journal date for tasks": "使用日记日期安排任务", + "Use the date in the journal filename when arranging its tasks.": "根据日记文件名中的日期,安排其中的任务。", + "Search for a task to depend on": "搜索要依赖的任务", + "These tasks would depend on each other.": "这会形成循环依赖,请选择其他任务。", + "Task no longer available": "此任务已无法找到", + "Remove dependency": "移除依赖", + "Search and select task": "搜索并选择任务", + "Project Gantt": "项目甘特图", + "Zoom out": "缩小", + "Zoom in": "放大", + "Project not found": "未找到项目", + "Choose a reward and redeem it with your points.": "选择奖励,使用积分兑换。", + "Manage points, bonuses and history.": "管理积分、加分项和积分流水。", + "Search rewards": "搜索奖励", + "Search bonuses and records": "搜索加分项和流水", + "Previous day": "前一天", + "Next day": "后一天", + "Open note": "打开笔记", + "Add habit": "新增习惯", + "This week": "本周", + "This month": "本月", + "Next 7 days": "未来七天", + "Choose a saved filter beside search. Edit its rules here using dropdowns.": "在搜索框旁直接选择预设;在这里通过下拉选项编辑规则。", + "Reset filter preset": "恢复默认预设", + + "Earn points and redeem rewards in one place.": "统一记录积分与加分,并兑换奖励。", + "Search bonuses, rewards and records": "搜索加分项、奖励和流水", + + "Completed checkbox tasks earn points by completion date. Existing daily task check-ins are deducted to prevent double counting.": "按完成日期统计复选框任务积分,自动抵扣已有的完成任务打卡积分,避免重复计分。", + "Task scheduling": "任务排期", + "Unscheduled tasks": "未安排任务", + "Previous month": "上个月", + "Task content": "任务内容", + "This task no longer exists. Refresh the task list.": "此任务已不存在,请刷新任务列表。", + "Enter a valid date, optionally followed by HH:mm.": "请输入有效日期,可在后面填写时:分,例如 2026-11-12 09:30。", + "Task writer is unavailable": "任务保存服务尚未就绪", + "Project color": "项目颜色", + "Manual order": "手动排序", + "Daily note date": "日记日期", + "Weekly note": "周记", + "Monthly note": "月记", + "Yearly note": "年记", + "Ignore all past missed habits": "忽略所有过去漏打卡的习惯", + "Dismiss reminders before today. Habit records and points stay unchanged.": "忽略今天之前的漏打卡提醒,保留所有习惯记录和积分。", + "Ignore past misses": "忽略过去的漏打卡", + "Past missed habit reminders ignored.": "已忽略过去的漏打卡提醒。", + "Parent folder": "父级文件夹", + "Projects root": "项目根目录", + "New parent folder (optional)": "新建父级文件夹(可选)", + "Folder name": "文件夹名称", + "Enter a valid folder name.": "请输入有效的文件夹名称。", + "View filter": "视图筛选", + "Clear time": "清除时间", + "More properties": "更多属性", + "Edit reward shop": "编辑奖励商店", + "One reward per line: name -100. Optional stock: name -100 | 3. Use -1 for unlimited stock. Remove a line to delete the item.": "每行一个奖励:名称 -100。可选库存:名称 -100 | 3;-1 表示不限库存。删除整行即可移除条目。", + "Rewards changed while editing. Reopen the editor and try again.": "编辑期间奖励已变化,请重新打开编辑器后再试。", + "One bonus per line: name +10. Remove a line to delete the item.": "每行一个加分项:名称 +10。删除整行即可移除条目。", }; export default translations; diff --git a/src/translations/locale/zh-tw.ts b/src/translations/locale/zh-tw.ts index 31354620e..691e08d51 100644 --- a/src/translations/locale/zh-tw.ts +++ b/src/translations/locale/zh-tw.ts @@ -1849,9 +1849,6 @@ const translations = { "選擇所有檢視的預設顯示模式。這影響您第一次開啟檢視或建立新檢視時任務的顯示方式。", "List View": "列表檢視", "Tree View": "樹狀檢視", - "Global Filter Configuration": "全域篩選配置", - "Configure global filter rules that apply to all Views by default. Individual Views can override these settings.": - "配置預設應用於所有檢視的全域篩選規則。個別檢視可以覆蓋這些設定。", "Cancelled Date": "取消日期", "Configuration is valid": "配置有效", "Action to execute on completion": "完成時執行的操作", @@ -2311,6 +2308,24 @@ const translations = { "Workflow settings enabled": "已啟用工作流程設定", "Advanced features enabled": "已啟用進階功能", "File parsing customized": "已自訂檔案解析", + "Project color": "项目颜色", + "Manual order": "手动排序", + "Daily note date": "日记日期", + "Weekly note": "周记", + "Monthly note": "月记", + "Yearly note": "年记", + "Ignore all past missed habits": "忽略所有过去漏打卡的习惯", + "Dismiss reminders before today. Habit records and points stay unchanged.": "忽略今天之前的漏打卡提醒,保留所有习惯记录和积分。", + "Ignore past misses": "忽略过去的漏打卡", + "Past missed habit reminders ignored.": "已忽略过去的漏打卡提醒。", + "Parent folder": "父级文件夹", + "Projects root": "项目根目录", + "New parent folder (optional)": "新建父级文件夹(可选)", + "Folder name": "文件夹名称", + "Enter a valid folder name.": "请输入有效的文件夹名称。", + "View filter": "视图筛选", + "Clear time": "清除時間", + "More properties": "更多屬性", }; export default translations; diff --git a/src/types/obsidian-ex.d.ts b/src/types/obsidian-ex.d.ts index 9fdae19f6..2a5bf319d 100644 --- a/src/types/obsidian-ex.d.ts +++ b/src/types/obsidian-ex.d.ts @@ -398,6 +398,8 @@ declare module "obsidian" { callback: () => void, ): EventRef; + on(event: "task-genius:points-updated", callback: () => void): EventRef; + on( event: "task-genius:task-completed", callback: (task: Task) => void, @@ -442,6 +444,8 @@ declare module "obsidian" { trigger(event: "task-genius:ics-cache-updated"): void; + trigger(event: "task-genius:points-updated"): void; + trigger( event: "task-genius:habit-index-updated", habits: HabitProps[], diff --git a/src/types/task.d.ts b/src/types/task.d.ts index 6429e27cc..0b8d0e486 100644 --- a/src/types/task.d.ts +++ b/src/types/task.d.ts @@ -24,6 +24,7 @@ export interface BaseTask { /** Standard task metadata interface */ export interface StandardTaskMetadata { + datePrecision?: Record; /** Creation date (optional) */ createdDate?: number; /** Start date for the task (Tasks plugin compatible) */ @@ -55,6 +56,7 @@ export interface StandardTaskMetadata { area?: string; /** Priority level (1-5, higher is more important) */ priority?: number; + points?: number; /** Parent task ID for hierarchical tasks */ parent?: string; diff --git a/src/utils/date/calendar-week.ts b/src/utils/date/calendar-week.ts new file mode 100644 index 000000000..31a182f5f --- /dev/null +++ b/src/utils/date/calendar-week.ts @@ -0,0 +1,7 @@ +/** January 1 always belongs to week 1; weeks start on the configured weekday. */ +export function calendarWeekNumber(date: Date, firstDay = 1): number { + const year = date.getFullYear(); + const day = Math.floor((Date.UTC(year, date.getMonth(), date.getDate()) - Date.UTC(year, 0, 1)) / 86400000); + const offset = (new Date(year, 0, 1).getDay() - firstDay + 7) % 7; + return Math.floor((day + offset) / 7) + 1; +} diff --git a/src/utils/date/date-helper.ts b/src/utils/date/date-helper.ts index 1481d2c98..b6c54b885 100644 --- a/src/utils/date/date-helper.ts +++ b/src/utils/date/date-helper.ts @@ -1,3 +1,4 @@ +import { calendarWeekNumber } from "./calendar-week"; export class DateHelper { public dateToX(date: Date, startDate: Date, dayWidth: number): number { if (!startDate) return 0; @@ -51,14 +52,5 @@ export class DateHelper { return result; } - // ISO 8601 week number calculation - public getWeekNumber(d: Date): number { - d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate())); - d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7)); // Set to Thursday of the week - const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1)); - const weekNo = Math.ceil( - ((d.getTime() - yearStart.getTime()) / 86400000 + 1) / 7 - ); - return weekNo; - } + public getWeekNumber(date: Date): number { return calendarWeekNumber(date); } } diff --git a/src/utils/date/date-time-picker.ts b/src/utils/date/date-time-picker.ts new file mode 100644 index 000000000..f0b855cb5 --- /dev/null +++ b/src/utils/date/date-time-picker.ts @@ -0,0 +1,14 @@ +import { t } from "@/translations/helper"; +/** Native date and optional time controls share the validated text model used by parsers. */ +export function attachDateTimePicker(input: HTMLInputElement, label: string): void { + const wrapper = input.ownerDocument.createElement("div"); wrapper.className = "tg-date-time-picker"; + input.after(wrapper); input.hidden = true; + const date = input.ownerDocument.createElement("input"); date.type = "date"; date.setAttribute("aria-label", label); wrapper.appendChild(date); + const time = input.ownerDocument.createElement("input"); time.type = "time"; time.setAttribute("aria-label", label + " (HH:mm)"); wrapper.appendChild(time); + const clear = input.ownerDocument.createElement("button"); clear.type = "button"; clear.className = "tg-clear-time"; clear.textContent = "×"; clear.setAttribute("aria-label", t("Clear time")); clear.title = t("Clear time"); wrapper.appendChild(clear); + const sync = () => { const match = input.value.match(/^(\d{4}-\d{2}-\d{2})(?:[ T](\d{2}:\d{2}))?/); date.value = match?.[1] || ""; time.value = match?.[2] || ""; time.disabled = !date.value; clear.disabled = !time.value; }; + const update = () => { if (!date.value) time.value = ""; input.value = date.value ? date.value + (time.value ? " " + time.value : "") : ""; input.dispatchEvent(new (input.ownerDocument.defaultView!.Event)("input", { bubbles: true })); input.dispatchEvent(new (input.ownerDocument.defaultView!.Event)("change", { bubbles: true })); sync(); }; + clear.addEventListener("click", event => { event.preventDefault(); event.stopPropagation(); time.value = ""; update(); }); + date.addEventListener("change", update); time.addEventListener("change", update); + input.addEventListener("change", sync); input.addEventListener("tg-date-updated", sync); sync(); +} diff --git a/src/utils/date/optional-date-time.ts b/src/utils/date/optional-date-time.ts new file mode 100644 index 000000000..a84278ade --- /dev/null +++ b/src/utils/date/optional-date-time.ts @@ -0,0 +1,26 @@ +export type DatePrecision = "date" | "datetime"; +export function parseOptionalDateTime(value: string): { timestamp: number; precision: DatePrecision } | null { + const match = value.trim().match(/^(\d{4})[-/](\d{1,2})[-/](\d{1,2})(?:[ T](\d{1,2}):(\d{2}))?$/); + if (!match) return null; + const [,y,m,d,h,min] = match, date = new Date(+y,+m-1,+d,+(h||0),+(min||0)); + if (date.getFullYear()!==+y || date.getMonth()!==+m-1 || date.getDate()!==+d || date.getHours()!==+(h||0) || date.getMinutes()!==+(min||0)) return null; + return { timestamp: date.getTime(), precision: h === undefined ? "date" : "datetime" }; +} +export function formatOptionalDateTime(value: number | string | Date | undefined, precision?: DatePrecision): string { + if (value == null || value === "") return ""; + const date = value instanceof Date ? value : typeof value === "string" && parseOptionalDateTime(value) ? new Date(parseOptionalDateTime(value)!.timestamp) : new Date(value); + if (!Number.isFinite(date.getTime())) return ""; + const pad = (n: number) => String(n).padStart(2,"0"); + const day = `${date.getFullYear()}-${pad(date.getMonth()+1)}-${pad(date.getDate())}`; + return precision === "datetime" || precision !== "date" && (date.getHours()!==0 || date.getMinutes()!==0) ? `${day} ${pad(date.getHours())}:${pad(date.getMinutes())}` : day; +} + +export function taskDatePrecisions(task: { originalMarkdown?: string; metadata?: { datePrecision?: Record } }): Record { + const result = { ...task.metadata?.datePrecision }; + const raw = task.originalMarkdown || ""; + for (const [field, marker, key] of [["dueDate","📅","due"],["startDate","🛫|🚀","start"],["scheduledDate","⏳","scheduled"],["completedDate","✅","completion"],["cancelledDate","❌","cancelled"]]) { + const match = raw.match(new RegExp(`(?:${marker}|\\[${key}::)\\s*(\\d{4}-\\d{2}-\\d{2}(?:[ T]\\d{1,2}:\\d{2})?)`)); + if (match) result[field] = /\d{1,2}:\d{2}/.test(match[1]) ? "datetime" : "date"; + } + return result; +} diff --git a/src/utils/file/file-operations.ts b/src/utils/file/file-operations.ts index e3e6b6953..8a59431e1 100644 --- a/src/utils/file/file-operations.ts +++ b/src/utils/file/file-operations.ts @@ -1,6 +1,7 @@ import { App, getFrontMatterInfo, TFile } from "obsidian"; import { QuickCaptureOptions } from "@/editor-extensions/core/quick-capture-panel"; import { moment } from "obsidian"; +import { ProjectFileManager } from "@/managers/project-file-manager"; /** * Get template file with automatic .md extension detection @@ -100,8 +101,14 @@ export function processDateTemplates(filePath: string): string { export async function saveCapture( app: App, content: string, - options: QuickCaptureOptions + options: QuickCaptureOptions & { project?: string; projectTagPrefixes?: string[] } ): Promise { + if (options.project?.trim() && /^\s*[-*+]\s+\[[^\]]*\]/.test(content)) { + const manager = new ProjectFileManager(app, options.projectTagPrefixes || ["project"]); + const project = await manager.create(options.project); + if (!project || !await manager.appendTaskBlock(project.name, content.split(/\r?\n/))) throw new Error("Could not save task to project note"); + return; + } const { targetFile, appendToFile, @@ -115,7 +122,7 @@ export async function saveCapture( // Determine the target file path based on target type if (targetType === "daily-note" && dailyNoteSettings) { // Generate daily note file path - const dateStr = moment().format(dailyNoteSettings.format); + const dateStr = moment(options.dailyNoteDate || undefined).format(dailyNoteSettings.format); // For daily notes, the format might include path separators (e.g., YYYY-MM/YYYY-MM-DD) // We need to preserve the path structure and only sanitize the final filename const pathWithDate = dailyNoteSettings.folder diff --git a/src/utils/grouping/groupByStorage.ts b/src/utils/grouping/groupByStorage.ts index 18594258c..74c9e7a2a 100644 --- a/src/utils/grouping/groupByStorage.ts +++ b/src/utils/grouping/groupByStorage.ts @@ -77,7 +77,7 @@ export function getAllGroupByConfigs(): Record { * Get the expanded state for a specific group * @param viewId - View identifier * @param groupKey - Unique key for the group - * @returns true if expanded, false if collapsed (default: false) + * @returns true if expanded, false if collapsed (default: true) */ export function getGroupExpandedState( viewId: string, @@ -87,7 +87,7 @@ export function getGroupExpandedState( const stored = localStorage.getItem(key); if (stored === null) { - return false; // Default: collapsed + return true; // Default: expanded } return stored === "true"; diff --git a/src/utils/status-cycle-resolver.ts b/src/utils/status-cycle-resolver.ts index 6daf4505e..f9e0483ca 100644 --- a/src/utils/status-cycle-resolver.ts +++ b/src/utils/status-cycle-resolver.ts @@ -6,7 +6,7 @@ * priority-based cycle selection. */ -import type { StatusCycle } from "@/common/setting-definition"; +import type { StatusCycle, TaskProgressBarSettings } from "@/common/setting-definition"; /** * Result of finding the next status in a cycle @@ -448,3 +448,84 @@ export function getAllStatusMarks(settings: { return uniqueStatuses; } + +export type TaskStatusGroup = "notStarted" | "planned" | "inProgress" | "completed" | "archived" | "abandoned"; + +type StatusSettings = Pick; + +function statusGroup(name: string): TaskStatusGroup | undefined { + const key = name.toLowerCase().replace(/[\s_-]/g, ""); + const groups: Record = { + notstarted: "notStarted", planned: "planned", inprogress: "inProgress", + completed: "completed", done: "completed", finished: "completed", + paused: "archived", pause: "archived", archived: "archived", + abandoned: "abandoned", cancelled: "abandoned", canceled: "abandoned", + 未开始: "notStarted", 计划: "planned", 进行中: "inProgress", + 已完成: "completed", 暂停: "archived", 已暂停: "archived", 已放弃: "abandoned", + }; + return groups[key]; +} + +/** Resolve the workflow mark first, then accept marks from older task files. */ +export function getTaskStatusGroup(mark: string, settings: StatusSettings): TaskStatusGroup | undefined { + const cycle = findPrimaryCycle(mark, settings.statusCycles); + if (cycle) { + const name = cycle.cycle.find(name => cycle.marks[name] === mark); + const group = name && statusGroup(name); + if (group) return group; + } + for (const [name, marks] of Object.entries(settings.taskStatuses || {})) { + if (marks.split("|").includes(mark)) return statusGroup(name); + } + for (const [name, value] of Object.entries(settings.taskStatusMarks || {})) { + if (value === mark) return statusGroup(name); + } + const defaults: Record = { + " ": "notStarted", "?": "planned", "/": "inProgress", ">": "inProgress", + x: "completed", X: "completed", a: "archived", "-": "abandoned", + }; + return statusGroup(mark) || defaults[mark]; +} + +/** Use the same primary workflow as source-mode checkboxes. */ +export function getNextTaskStatusMark(mark: string, settings: StatusSettings): string { + const next = getNextStatusPrimary(mark, settings.statusCycles); + if (next?.mark?.length === 1) return next.mark; + // Older notes can use a different mark for the same status, such as a + // for pause while the current workflow uses =. + const group = getTaskStatusGroup(mark, settings); + if (group) { + const cycles = (settings.statusCycles || []).filter(cycle => cycle.enabled) + .sort((a, b) => a.priority - b.priority); + for (const cycle of cycles) { + const name = cycle.cycle.find(name => statusGroup(name) === group); + if (!name) continue; + const compatible = getNextStatus(cycle.marks[name], cycle); + if (compatible?.mark?.length === 1) return compatible.mark; + } + } + const names = (settings.taskStatusCycle || []).filter(name => + !(settings.excludeMarksFromCycle || []).includes(name) + && settings.taskStatusMarks?.[name]?.length === 1); + if (names.length) { + const index = names.findIndex(name => settings.taskStatusMarks[name] === mark); + return settings.taskStatusMarks[names[(index + 1) % names.length]]; + } + return getTaskStatusGroup(mark, settings) === "completed" + ? (settings.taskStatuses?.notStarted || " ").split("|")[0] + : (settings.taskStatuses?.completed || "x").split("|")[0]; +} + +export function getPausedTaskMarks(settings: StatusSettings): string[] { + const marks = new Set(); + for (const variants of Object.values(settings.taskStatuses || {})) { + for (const mark of variants.split("|")) marks.add(mark); + } + for (const cycle of settings.statusCycles || []) { + if (cycle.enabled) for (const name of cycle.cycle) marks.add(cycle.marks[name]); + } + for (const mark of Object.values(settings.taskStatusMarks || {})) marks.add(mark); + return [...marks].filter(mark => mark?.length === 1 && mark !== " " + && getTaskStatusGroup(mark, settings) === "archived"); +} diff --git a/src/utils/task/__tests__/filter-compatibility.test.ts b/src/utils/task/__tests__/filter-compatibility.test.ts new file mode 100644 index 000000000..28ec9a70a --- /dev/null +++ b/src/utils/task/__tests__/filter-compatibility.test.ts @@ -0,0 +1,49 @@ +import { evaluateFilterNode, parseAdvancedFilterQuery } from "../filter-compatibility"; + +describe("advanced task filters", () => { + const task = { content: "Write weekly report", status: " ", completed: false, metadata: { tags: ["#work"], project: "Alpha", priority: 4, dueDate: new Date("2026-11-20T00:00:00").getTime() } }; + const matches = (query: string) => evaluateFilterNode(parseAdvancedFilterQuery(query), task); + + test("supports field filters, boolean precedence, grouping, and negation", () => { + expect(matches("PROJECT:Alpha AND #work")).toBe(true); + expect(matches("PROJECT:Beta OR PRIORITY:>=#B")).toBe(true); + expect(matches("PROJECT:Beta AND PRIORITY:>=#B")).toBe(false); + expect(matches("NOT PROJECT:Beta")).toBe(true); + expect(matches("(PROJECT:Beta OR #work) AND TEXT:report")).toBe(true); + }); + + test("supports priority and date comparisons", () => { + expect(matches("PRIORITY:>=#B")).toBe(true); + expect(matches("PRIORITY:<#B")).toBe(false); + expect(matches("DATE:<2026-11-30")).toBe(true); + expect(matches("DATE:>2026-11-30")).toBe(false); + expect(matches("DUE:<2026-11-30")).toBe(true); + expect(evaluateFilterNode(parseAdvancedFilterQuery("STATUS:in-progress"), { ...task, statusName: "in-progress" })).toBe(true); + }); + test("relative dates match the full local day and missing-date filters remain useful", () => { + const now = new Date(), noon = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 12).getTime(); + const dated = { ...task, metadata: { ...task.metadata, dueDate: noon } }; + expect(evaluateFilterNode(parseAdvancedFilterQuery("due:today"), dated)).toBe(true); + expect(evaluateFilterNode(parseAdvancedFilterQuery("due:>today"), dated)).toBe(false); + expect(evaluateFilterNode(parseAdvancedFilterQuery("due:<=today"), dated)).toBe(true); + expect(evaluateFilterNode(parseAdvancedFilterQuery("due:none"), { metadata: {} })).toBe(true); + expect(evaluateFilterNode(parseAdvancedFilterQuery("status:completed"), { completed: true, metadata: {} })).toBe(true); + }); + test("any-date emptiness means all date fields are empty", () => { + const match = (query: string, metadata: any) => evaluateFilterNode(parseAdvancedFilterQuery(query), { metadata }); + expect(match("date:none", {})).toBe(true); + expect(match("date:none", { dueDate: Date.now() })).toBe(false); + expect(match("date:!=none", { startDate: Date.now() })).toBe(true); + }); + test("tag equality checks membership and ignores the leading hash", () => { + expect(matches("tag:=work")).toBe(true); + expect(matches("tag:=#work")).toBe(true); + expect(matches("tag:!=work")).toBe(false); + expect(evaluateFilterNode(parseAdvancedFilterQuery("tag:=work"), { metadata: { tags: ["personal", "work"] } })).toBe(true); + }); + test("dropdown-generated project queries support numeric names and escaped quotes", () => { + for (const name of ["123", 'Writing "weekly" reports', "A (new) project"]) { + expect(evaluateFilterNode(parseAdvancedFilterQuery(`project:=${JSON.stringify(name)}`), { metadata: { project: name } })).toBe(true); + } + }); +}); diff --git a/src/utils/task/filter-compatibility.ts b/src/utils/task/filter-compatibility.ts index e41ef0f38..58fe89ce3 100644 --- a/src/utils/task/filter-compatibility.ts +++ b/src/utils/task/filter-compatibility.ts @@ -1,42 +1,133 @@ -// Compatibility shim for advanced filter utilities removed in dataflow refactor -// Provides minimal API used by editor-ext/filterTasks.ts and utils/RewardManager.ts +export type FilterNode = + | { type: "term"; value: string } + | { type: "not"; child: FilterNode } + | { type: "and" | "or"; left: FilterNode; right: FilterNode }; -export type FilterNode = any; - -// Very minimal parser: returns the raw string; real implementation lives elsewhere in the codebase. -// This keeps build passing without changing editor-ext consumers. You can replace later with full parser. +/** Parse boolean task filters with parentheses, field terms, and implicit AND. */ export function parseAdvancedFilterQuery(query: string): FilterNode { - return query; + const tokens = query.match(/(?:[A-Za-z_][\w-]*\s*:\s*(?:(?:>=|<=|!=|>|<|=)\s*)?(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\s()]+)|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\(|\)|\bAND\b|\bOR\b|\bNOT\b|[^\s()]+)/gi) || []; + let index = 0; + const peek = () => tokens[index]?.toUpperCase(); + const take = () => tokens[index++]; + const parsePrimary = (): FilterNode | null => { + if (peek() === "NOT") { take(); const child = parsePrimary(); return child ? { type: "not", child } : null; } + if (take() === "(") { const node = parseOr(); if (take() !== ")") throw new Error("Missing closing parenthesis in filter"); return node; } + const token = tokens[index - 1] === "(" ? take() : tokens[index - 1]; + if (!token || token === ")" || /^(AND|OR)$/i.test(token)) return null; + return { type: "term", value: token }; + }; + const parseAnd = (): FilterNode | null => { + let node = parsePrimary(); + while (index < tokens.length && peek() !== "OR" && peek() !== ")") { + if (peek() === "AND") take(); + const right = parsePrimary(); + if (!right) break; + node = node ? { type: "and", left: node, right } : right; + } + return node; + }; + const parseOr = (): FilterNode | null => { + let node = parseAnd(); + while (peek() === "OR") { take(); const right = parseAnd(); if (right) node = node ? { type: "or", left: node, right } : right; } + return node; + }; + if (!tokens.length) return { type: "term", value: "" }; + const result = parseOr(); + if (index < tokens.length) throw new Error("Unexpected token in filter: " + tokens[index]); + return result || { type: "term", value: "" }; } -// Very permissive evaluator: if query is empty -> true; otherwise do a simple substring match on content/tags/project/context when possible. -// This is a temporary shim to satisfy type-check; views already have rich filtering via TaskFilterUtils. -export function evaluateFilterNode(node: FilterNode, task: any): boolean { - if (!node || (typeof node === 'string' && node.trim() === '')) return true; - const q = typeof node === 'string' ? node.toLowerCase() : ''; - if (!q) return true; - try { - const haystacks: string[] = []; - if (task.content) haystacks.push(String(task.content).toLowerCase()); - const tags = task.metadata?.tags || task.tags; - if (Array.isArray(tags)) haystacks.push(tags.join(' ').toLowerCase()); - const project = task.metadata?.project || task.project || task.metadata?.tgProject?.name || task.tgProject; - if (project) haystacks.push(String(project).toLowerCase()); - const context = task.metadata?.context || task.context; - if (context) haystacks.push(String(context).toLowerCase()); - return haystacks.some(h => h.includes(q)); - } catch { - return true; +function compareFilterValue(actual: unknown, operator: string, expected: string, isDate = false): boolean { + if (Array.isArray(actual)) { + if (["none", "empty"].includes(expected.toLowerCase())) return operator === "!=" ? actual.length > 0 : actual.length === 0; + return operator === "!=" ? actual.every(value => compareFilterValue(value, operator, expected, isDate)) : actual.some(value => compareFilterValue(value, operator, expected, isDate)); + } + if (["none", "empty"].includes(expected.toLowerCase())) return operator === "!=" ? actual != null && actual !== "" : actual == null || actual === ""; + if (actual === undefined || actual === null) return false; + if (isDate) { + const key = expected.toLowerCase(); + const now = new Date(); + if (["this-month", "this-week", "next-7-days"].includes(key)) { + const start = key === "this-month" ? new Date(now.getFullYear(), now.getMonth(), 1) : new Date(now.getFullYear(), now.getMonth(), now.getDate() - (key === "this-week" ? (now.getDay() + 6) % 7 : 0)); + const end = key === "this-month" ? new Date(now.getFullYear(), now.getMonth() + 1, 1) : new Date(start.getFullYear(), start.getMonth(), start.getDate() + 7); + const value = typeof actual === "number" ? actual : new Date(String(actual)).getTime(); + const match = value >= start.getTime() && value < end.getTime(); + return operator === ">" ? value >= end.getTime() : operator === ">=" ? value >= start.getTime() : operator === "<" ? value < start.getTime() : operator === "<=" ? value < end.getTime() : operator === "!=" ? !match : match; + } + const offset = key === "tomorrow" ? 1 : key === "yesterday" ? -1 : 0; + const date = ["today", "tomorrow", "yesterday"].includes(key) ? new Date(now.getFullYear(), now.getMonth(), now.getDate() + offset) : /^\d{4}-\d{2}-\d{2}$/.test(expected) ? new Date(Number(expected.slice(0, 4)), Number(expected.slice(5, 7)) - 1, Number(expected.slice(8, 10))) : new Date(expected); + const start = date.getTime(), end = new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1).getTime(); + const value = typeof actual === "number" ? actual : new Date(String(actual)).getTime(); + if (!Number.isFinite(start) || !Number.isFinite(value)) return false; + return operator === ">" ? value >= end : operator === ">=" ? value >= start : operator === "<" ? value < start : operator === "<=" ? value < end : operator === "!=" ? value < start || value >= end : value >= start && value < end; + } + const text = String(actual).toLowerCase(); + const target = expected.toLowerCase(); + if (operator === "=") return text === target; + if (operator === "!=") return text !== target; + const actualNumber = Number(actual); + const expectedNumber = parsePriorityFilterValue(expected); + if ([">", "<", ">=", "<=", "!=", "="].includes(operator)) { + const a = Number.isFinite(actualNumber) ? actualNumber : Date.parse(text); + const b = isDate ? Date.parse(expected) : (expectedNumber !== null && Number.isFinite(expectedNumber) ? expectedNumber : Date.parse(expected)); + if (!Number.isFinite(a) || !Number.isFinite(b)) return operator === "!=" ? text !== target : operator === "=" && text === target; + return operator === ">" ? a > b : operator === "<" ? a < b : operator === ">=" ? a >= b : operator === "<=" ? a <= b : operator === "!=" ? a !== b : a === b; } + return Array.isArray(actual) ? actual.some(value => String(value).toLowerCase().includes(target)) : text.includes(target); +} + +function unquote(value: string): string { + if (value.startsWith('"') && value.endsWith('"')) { try { return JSON.parse(value); } catch { return value.slice(1, -1); } } + return value.startsWith("'") && value.endsWith("'") ? value.slice(1, -1).replace(/\\'/g, "'") : value; +} + +function evaluateTerm(raw: string, task: any): boolean { + const term = unquote(raw).trim(); + if (!term) return true; + const field = term.match(/^([A-Za-z_][\w-]*)\s*:\s*(?:(>=|<=|!=|>|<|=)\s*)?(.*)$/); + if (field) { + const key = field[1].toLowerCase(); const op = field[2] || ""; const value = unquote(field[3]); + const meta = task.metadata || {}; + const status = task.statusName ?? (task.completed ? "completed" : ({ " ": "not-started", "?": "planned", "/": "in-progress", ">": "in-progress", "-": "abandoned", "~": "paused", "=": "paused" } as Record)[task.status] ?? task.status); + const actual = key === "priority" ? (meta.priority ?? task.priority) : key === "path" || key === "file" ? task.filePath : key === "date" ? (meta.dueDate ?? meta.scheduledDate) : key === "due" || key === "duedate" ? meta.dueDate : key === "scheduled" || key === "scheduleddate" ? meta.scheduledDate : key === "start" || key === "startdate" ? meta.startDate : key === "tag" || key === "tags" ? (meta.tags ?? task.tags) : key === "project" ? (meta.project ?? task.project ?? meta.tgProject?.name) : key === "context" ? (meta.context ?? task.context) : key === "status" ? status : key === "text" || key === "content" ? task.content : meta[key] ?? task[key]; + if (key === "priority" && value.startsWith("#")) { + const priority = parsePriorityFilterValue(value); + if (priority !== null) return compareFilterValue(actual, op || "=", String(priority)); + } + if (key === "status" && !op) { + const normalize = (status: unknown) => String(status ?? "").toLowerCase().replace(/[\s_-]/g, ""); + return normalize(actual).includes(normalize(value)); + } + if (key === "date") { + const dates = [meta.dueDate, meta.scheduledDate, meta.startDate].filter(date => date != null && date !== ""); + if (["none", "empty"].includes(value.toLowerCase())) return op === "!=" ? dates.length > 0 : dates.length === 0; + if (!dates.length) return false; + return op === "!=" ? dates.every(date => compareFilterValue(date, op, value, true)) : dates.some(date => compareFilterValue(date, op, value, true)); + } + if (key === "tag" || key === "tags") return compareFilterValue((Array.isArray(actual) ? actual : actual == null ? [] : [actual]).map(tag => String(tag).replace(/^#/, "")), op, value.replace(/^#/, "")); + return compareFilterValue(actual, op, value, ["date", "due", "scheduled", "start", "duedate", "scheduleddate", "startdate"].includes(key)); + } + const needle = term.replace(/^[#@]/, "").toLowerCase(); + const haystacks = [task.content, task.metadata?.tags, task.tags, task.metadata?.project, task.metadata?.tgProject?.name, task.metadata?.context].flatMap(value => Array.isArray(value) ? value : [value]).filter(value => value != null).map(value => String(value).toLowerCase()); + return haystacks.some(value => value.includes(needle)); +} + +export function evaluateFilterNode(node: FilterNode | null, task: any): boolean { + if (!node) return true; + if (node.type === "term") return evaluateTerm(node.value, task); + if (node.type === "not") return !evaluateFilterNode(node.child, task); + if (node.type === "and") return evaluateFilterNode(node.left, task) && evaluateFilterNode(node.right, task); + return evaluateFilterNode(node.left, task) || evaluateFilterNode(node.right, task); } // Parse priority expressions used by filter UI, returning a numeric 1..5 if recognized; otherwise null. export function parsePriorityFilterValue(input: string | number | undefined | null): number | null { if (input == null) return null; if (typeof input === 'number') return input; - const s = String(input).trim().toLowerCase(); + const s = String(input).trim().toLowerCase().replace(/^#/, ""); if (!s) return null; const map: Record = { + a: 5, b: 4, c: 3, d: 2, e: 1, highest: 5, high: 4, medium: 3, @@ -51,7 +142,7 @@ export function parsePriorityFilterValue(input: string | number | undefined | nu trivial: 1, }; if (s in map) return map[s]; - const n = parseInt(s.replace(/^#/, ''), 10); + const n = parseInt(s, 10); return Number.isFinite(n) ? n : null; } diff --git a/src/utils/task/project-calendar.ts b/src/utils/task/project-calendar.ts new file mode 100644 index 000000000..a3ef0d9e4 --- /dev/null +++ b/src/utils/task/project-calendar.ts @@ -0,0 +1,12 @@ +import type { App } from "obsidian"; +import type { Task } from "@/types/task"; + +/** A project note is a Gantt row; the checkbox tasks inside it remain calendar tasks. */ +export function isProjectCalendarEntry(app: App, task: Task): boolean { + if (task.metadata?.projectPlan || task.id.startsWith("project-plan:")) return true; + const fileTask = (task as any).isFileTask || task.id.startsWith("file-source:") || task.metadata?.source === "file-source" || task.metadata?.sourceType === "file"; + if (!fileTask) return false; + const file = app.vault.getFileByPath(task.filePath); + const project = file ? app.metadataCache.getFileCache(file)?.frontmatter?.project : undefined; + return typeof project === "string" && !!project.trim(); +} diff --git a/src/utils/task/removeBlankTasks.ts b/src/utils/task/removeBlankTasks.ts new file mode 100644 index 000000000..1cb7900d5 --- /dev/null +++ b/src/utils/task/removeBlankTasks.ts @@ -0,0 +1,23 @@ +import type { Task } from "@/types/task"; + +/** Empty Markdown placeholders must not become indexed tasks or orphan children. */ +export function removeBlankTasks(tasks: Task[]): Task[] { + const removed = new Map(tasks.filter(task => !String(task.content ?? "").replace(/\u200b/g, "").trim()).map(task => [task.id, task])); + if (!removed.size) return tasks; + const kept = tasks.filter(task => !removed.has(task.id)).map(task => { + let parent = task.metadata.parent; + const visited = new Set(); + while (parent && removed.has(parent)) { + if (visited.has(parent)) { parent = undefined; break; } + visited.add(parent); + parent = removed.get(parent)!.metadata.parent; + } + return { ...task, metadata: { ...task.metadata, parent, children: (task.metadata.children || []).filter(id => !removed.has(id)) } }; + }); + const byId = new Map(kept.map(task => [task.id, task])); + for (const task of kept) { + const parent = task.metadata.parent && byId.get(task.metadata.parent); + if (parent && !parent.metadata.children.includes(task.id)) parent.metadata.children.push(task.id); + } + return kept; +} diff --git a/src/utils/task/saved-task-filters.ts b/src/utils/task/saved-task-filters.ts new file mode 100644 index 000000000..e13042e65 --- /dev/null +++ b/src/utils/task/saved-task-filters.ts @@ -0,0 +1,27 @@ +import type { PresetTaskFilter } from "@/common/setting-definition"; +import { t } from "@/translations/helper"; + +export type FilterCondition = { field: string; operator: string; value: string }; +export function savedTaskFilters(custom: PresetTaskFilter[] = []): PresetTaskFilter[] { + const merged = new Map(defaultSavedFilters().map(filter => [filter.id, filter])); + for (const filter of custom) merged.set(filter.id, filter); + return [...merged.values()]; +} +export function conditionsQuery(conditions: FilterCondition[], relation: "AND" | "OR"): string { + return conditions.filter(row => row.value.trim()).map(row => { + const value = row.value.trim(); + return `${row.field}:${row.operator === "contains" ? "" : row.operator}${/^[^\s"]+$/.test(value) ? value : JSON.stringify(value)}`; + }).join(` ${relation} `); +} +export function defaultSavedFilters(): PresetTaskFilter[] { + return [["todo", "To do", "status", "!=", "completed", "status", "!=", "abandoned"], + ["completed", "Completed", "status", "=", "completed"], + ["abandoned", "Abandoned", "status", "=", "abandoned"], + ["month", "This month's tasks", "date", "=", "this-month"]].map(([id, name, field, operator, value, field2, operator2, value2]) => { + const conditions: FilterCondition[] = [{ field, operator, value }]; + if (field2) conditions.push({ field: field2, operator: operator2, value: value2 }); + return { id: `builtin-${id}`, name: t(name), options: { includeCompleted: true, includeInProgress: true, includeAbandoned: true, includeNotStarted: true, includePlanned: true, + includeParentTasks: false, includeChildTasks: false, includeSiblingTasks: false, + conditions, relation: "AND", advancedFilterQuery: conditionsQuery(conditions, "AND"), filterMode: "INCLUDE" } }; + }); +} diff --git a/src/utils/task/task-filter-utils.ts b/src/utils/task/task-filter-utils.ts index 675380404..668b6bd4f 100644 --- a/src/utils/task/task-filter-utils.ts +++ b/src/utils/task/task-filter-utils.ts @@ -11,11 +11,12 @@ import { FilterGroup, RootFilterState, } from "@/components/features/task/filter/ViewTaskFilter"; -import { hasProject } from "./task-operations"; +import { hasProject, getEffectiveProject } from "./task-operations"; // 从ViewTaskFilter.ts导入相关接口 interface FilterOptions { + includeClosedTasks?: boolean; textQuery?: string; selectedDate?: Date; // For forecast-like filtering // Add other potential options needed by specific views later @@ -502,9 +503,15 @@ export function filterTasks( options: FilterOptions = {}, ): Task[] { let filtered = [...allTasks]; + if (plugin.app?.vault?.getMarkdownFiles && plugin.app.metadataCache?.getFileCache) { + const archivedProjects = new Set(plugin.app.vault.getMarkdownFiles().flatMap(file => { + const fm = plugin.app.metadataCache.getFileCache(file)?.frontmatter; + return fm && (fm.archived === true || fm.status === "archived") && typeof fm.project === "string" ? [fm.project.toLocaleLowerCase()] : []; + })); + filtered = filtered.filter(task => !archivedProjects.has((getEffectiveProject(task) || "").toLocaleLowerCase())); + } const viewConfig = getViewSettingOrDefault(plugin, viewId); const filterRules = viewConfig.filterRules || {}; - const globalFilterRules = plugin.settings.globalFilterRules || {}; // --- 过滤 ICS 事件在不应展示的视图中(例如 inbox)--- // ICS 事件应仅在日历/日程类视图(calendar/forecast)中展示 @@ -531,7 +538,7 @@ export function filterTasks( // 注意:这些是基础过滤条件,始终应用 if (viewConfig.hideCompletedAndAbandonedTasks) { filtered = filtered.filter((task) => - isNotCompleted(plugin, task, viewId), + options.includeClosedTasks || isNotCompleted(plugin, task, viewId), ); } @@ -539,17 +546,6 @@ export function filterTasks( filtered = filtered.filter((task) => task.content.trim() !== ""); } - // --- 应用全局筛选器(如果存在) --- - if ( - globalFilterRules.advancedFilter && - globalFilterRules.advancedFilter.filterGroups?.length > 0 - ) { - console.log("应用全局筛选器:", globalFilterRules.advancedFilter); - filtered = filtered.filter((task) => - applyAdvancedFilter(task, globalFilterRules.advancedFilter!), - ); - } - // --- 应用视图配置中的基础高级过滤器(如果存在) --- if ( filterRules.advancedFilter && @@ -577,7 +573,7 @@ export function filterTasks( // 如果有实时高级过滤器,应用基本规则后直接返回 // 应用 isNotCompleted 过滤器(基于视图配置的 hideCompletedAndAbandonedTasks) filtered = filtered.filter((task) => - isNotCompleted(plugin, task, viewId), + options.includeClosedTasks || isNotCompleted(plugin, task, viewId), ); // 应用 isBlank 过滤器(基于视图配置的 filterBlanks) @@ -789,7 +785,7 @@ export function filterTasks( // --- Apply `isNotCompleted` Filter --- // This uses the hideCompletedAndAbandonedTasks setting from the viewConfig - filtered = filtered.filter((task) => isNotCompleted(plugin, task, viewId)); + filtered = filtered.filter((task) => options.includeClosedTasks || isNotCompleted(plugin, task, viewId)); // --- Apply `isBlank` Filter --- // This uses the filterBlanks setting from the viewConfig diff --git a/src/utils/ui/tree-view-utils.ts b/src/utils/ui/tree-view-utils.ts index 682db4740..5a09ae4be 100644 --- a/src/utils/ui/tree-view-utils.ts +++ b/src/utils/ui/tree-view-utils.ts @@ -1,67 +1,29 @@ -import { Task } from "../../types/task"; - -/** - * Convert a flat list of tasks to a hierarchical tree structure - * @param tasks Flat list of tasks - * @returns List of root tasks with children populated recursively - */ -export function tasksToTree(tasks: Task[]): Task[] { - // Create a map for quick task lookup - const taskMap = new Map(); - tasks.forEach((task) => { - taskMap.set(task.id, { ...task }); - }); - - // Find root tasks and build hierarchy - const rootTasks: Task[] = []; - - // First pass: connect children to parents - tasks.forEach((task) => { - const taskWithChildren = taskMap.get(task.id)!; - - if (task.metadata.parent && taskMap.has(task.metadata.parent)) { - // This task has a parent, add it to parent's children - const parent = taskMap.get(task.metadata.parent)!; - if (!parent.metadata.children.includes(task.id)) { - parent.metadata.children.push(task.id); - } - } else { - // No parent or parent not in current set, treat as root - rootTasks.push(taskWithChildren); +import type { Task } from "../../types/task"; + +/** Filtered results form their own safe tree. Missing parents become roots. */ +export function buildVisibleTaskTree(tasks: Task[]): { roots: Task[]; taskMap: Map } { + const taskMap = new Map(tasks.map(task => [task.id, { ...task, metadata: { ...task.metadata, children: [] as string[] } }])); + for (const task of taskMap.values()) { + const parent = task.metadata.parent; + if (!parent || parent === task.id || !taskMap.has(parent)) { task.metadata.parent = undefined; continue; } + const seen = new Set([task.id]); let cursor: string | undefined = parent; + while (cursor && taskMap.has(cursor)) { + if (seen.has(cursor)) { task.metadata.parent = undefined; break; } + seen.add(cursor); cursor = taskMap.get(cursor)?.metadata.parent; } - }); - - return rootTasks; -} - -/** - * Flatten a tree of tasks back to a list, with child tasks following their parents - * @param rootTasks List of root tasks with populated children - * @param taskMap Map of all tasks by ID for lookup - * @returns Flattened list of tasks in hierarchical order - */ -export function flattenTaskTree( - rootTasks: Task[], - taskMap: Map -): Task[] { - const result: Task[] = []; - - function addTaskAndChildren(task: Task) { - result.push(task); - - // Add all children recursively - task.metadata.children.forEach((childId) => { - const childTask = taskMap.get(childId); - if (childTask) { - addTaskAndChildren(childTask); - } - }); } + const roots: Task[] = []; + for (const task of taskMap.values()) { + const parent = task.metadata.parent ? taskMap.get(task.metadata.parent) : undefined; + if (parent) parent.metadata.children!.push(task.id); else roots.push(task); + } + return { roots, taskMap }; +} - // Process all root tasks - rootTasks.forEach((task) => { - addTaskAndChildren(task); - }); +export function tasksToTree(tasks: Task[]): Task[] { return buildVisibleTaskTree(tasks).roots; } - return result; +export function flattenTaskTree(roots: Task[], taskMap: Map): Task[] { + const result: Task[] = [], seen = new Set(); + const visit = (task: Task) => { if (seen.has(task.id)) return; seen.add(task.id); result.push(task); for (const id of task.metadata?.children || []) { const child = taskMap.get(id); if (child) visit(child); } }; + roots.forEach(visit); return result; } diff --git a/tests/habits/compact.test.mjs b/tests/habits/compact.test.mjs new file mode 100644 index 000000000..461fabe45 --- /dev/null +++ b/tests/habits/compact.test.mjs @@ -0,0 +1,357 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { build } from 'esbuild'; + +// A minimal Obsidian surface lets us exercise the actual render/write code +// without a running desktop vault. Stats and date utilities remain real. +const result = await build({ + stdin: { contents: 'export { HabitsCompact } from "./src/integrations/habits/ui/habits-compact"; export { HabitsBlock } from "./src/integrations/habits/ui/habits-block";', resolveDir: process.cwd(), loader: 'ts' }, bundle: true, write: false, format: 'esm', platform: 'node', + plugins: [{ name: 'obsidian-test-surface', setup(build) { + build.onResolve({ filter: /^obsidian$/ }, () => ({ path: 'obsidian', namespace: 'mock' })); + build.onLoad({ filter: /.*/, namespace: 'mock' }, () => ({ contents: ` + export class Component { + children = []; cleanups = []; + addChild(c) { this.children.push(c); c.onload?.(); return c; } + removeChild(c) { c.unload(); this.children = this.children.filter(x => x !== c); } + registerDomEvent(el, type, fn) { el.handlers[type] = fn; this.cleanups.push(() => delete el.handlers[type]); } + registerEvent() {} + register(fn) { this.cleanups.push(fn); } + unload() { this.onunload?.(); this.children.forEach(c => c.unload()); this.cleanups.forEach(f => f()); } + } + export class MarkdownRenderChild extends Component { constructor(root) { super(); this.containerEl = root; } } + export class App {} export class TFile {} export class Notice { constructor(message) { globalThis.lastNotice = message; } } + export class Modal { constructor(app) { this.app = app; this.modalEl = {addClass() {}}; } open() { globalThis.lastModal = this; } close() {} } + export class Setting {} + export class Menu { + items = []; separators = 0; + addSeparator() { this.separators++; return this; } + addItem(fn) { const item = { setTitle(title) { this.title = title; return this; }, setIcon(icon) { this.icon = icon; return this; }, onClick(fn) { this.click = fn; return this; } }; fn(item); this.items.push(item); return this; } + showAtPosition(position) { this.position = position; globalThis.lastMenu = this; globalThis.menuCount = (globalThis.menuCount ?? 0) + 1; } + } + export const debounce = fn => fn; + export const normalizePath = s => s; + export const setIcon = (el, icon) => { el.icon = icon; }; + export const setTooltip = () => {}; + export const moment = {}; + ` })); + build.onLoad({ filter: /i18n[\\/]index\.ts$/ }, () => ({ contents: 'export const t = (s, vars = {}) => s.replace(/\\{(.*?)\\}/g, (_, k) => vars[k]);' })); + build.onLoad({ filter: /ui[\\/]habit-modal\.ts$/ }, () => ({ contents: 'export class HabitModal { constructor(...args) { this.args = args; } open() { globalThis.lastHabitModal = this; } }' })); + build.onLoad({ filter: /ui[\\/]confirm-modal\.ts$/ }, () => ({ contents: 'export class ConfirmModal { constructor(app, options) { this.options = options; } open() { globalThis.lastConfirmation = this.options; } }' })); + build.onLoad({ filter: /ui[\\/]dashboard\.ts$/ }, () => ({ contents: 'import { MarkdownRenderChild } from "obsidian"; export class HabitsDashboard extends MarkdownRenderChild { constructor(a, s, g, e, p, root) { super(root); } onload() { this.containerEl.createSpan({ text: "Card dashboard" }); } }' })); + build.onLoad({ filter: /ui[\\/]icon-suggest-modal\.ts$/ }, () => ({ contents: 'export const applyHabitIcon = (el, icon) => { el.icon = icon; };' })); + build.onLoad({ filter: /ui[\\/]stats-view\.ts$/ }, () => ({ contents: 'export const renderStatsView = () => {};' })); + build.onLoad({ filter: /[\\/]note-habit\.ts$/ }, () => ({ contents: 'export const notePathForDate = (h, k) => `${h.noteFolder}/${k}.md`; export const createNoteHabitEntry = async () => null;' })); + } }], +}); +const { HabitsCompact, HabitsBlock } = await import(`data:text/javascript;base64,${Buffer.from(result.outputFiles[0].text).toString('base64')}`); +class Element { + children = []; handlers = {}; attrs = {}; dataset = {}; classes = new Set(); + win = { timers: new Map(), setTimeout(fn) { const id = this.timers.size + 1; this.timers.set(id, fn); return id; }, clearTimeout(id) { this.timers.delete(id); } }; + constructor(tag = 'div', options = {}) { this.tag = tag; this.text = options.text ?? ''; this.attrs = options.attr ?? {}; this.className = options.cls ?? ''; } + createEl(tag, options) { const el = new Element(tag, options); this.children.push(el); return el; } + createDiv(options) { return this.createEl('div', options); } + createSpan(options) { return this.createEl('span', options); } + addClass(cls) { this.classes.add(cls); } + toggleClass(cls, active) { if (active) this.classes.add(cls); else this.classes.delete(cls); } + setCssProps() {} setAttribute(key, value) { this.attrs[key] = value; } + empty() { this.children = []; } + all() { return [this, ...this.children.flatMap(el => el.all())]; } +} +function fixture(overrides = {}, write = async () => {}, extra = {}) { + const habit = { path: 'Habits/Test.md', name: 'Test', type: 'repetition', frequency: 'daily', target: 5, unit: 'cups', goalDirection: 'min', startDate: '2020-01-01', records: {}, pauses: [], reschedules: [], failed: [], skipped: [], times: [], group: '', ...overrides }; + const events = {}; + const app = { metadataCache: { on: (name, fn) => { events[name] = fn; } }, vault: { on() {}, getAbstractFileByPath() {} }, workspace: { openLinkText() {} } }; + const snoozes = {}; + const store = { + isHabitFile: path => path.startsWith("Habits/"), + getHabits: () => structuredClone([habit, ...(extra.habits ?? [])]), setRecord: write, dayCalls: [], snoozes, + snoozedUntil: (h, now = Date.now()) => (snoozes[h.path] > now ? snoozes[h.path] : null), + snoozeHabit: async (h, until) => { snoozes[h.path] = until; }, + clearSnooze: async h => { delete snoozes[h.path]; }, + // Mirrors the real store: the passed habit's lists change, the cached copy doesn't. + setDayStatus: async (h, key, status) => { + store.dayCalls.push([h.path, key, status]); + h.failed = (h.failed ?? []).filter(d => d !== key); h.skipped = (h.skipped ?? []).filter(d => d !== key); + if (status) h[status].push(key); + }, + }; + const settings = { habitsFolder: 'Habits', sortMode: 'name', manualOrder: [], groups: {}, groupOrder: [], experimental: {}, statusOrdering: true, ...extra.settings }; + const root = new Element(); + const view = new HabitsCompact(app, store, () => settings, { on(name, fn) { events[name] = fn; } }, 'Dashboard.md', root); + view.selectedDate = new Date(2026, 9, 12); view.onload(); + const button = label => root.all().find(el => el.attrs['aria-label'] === label); + const text = () => root.all().map(el => el.text).join(''); + return { view, root, habit, events, button, text, app, store, settings }; +} + +const rowNames = root => root.all().filter(el => el.className === 'habits-compact-row').map(row => row.children.find(el => el.className === 'habits-compact-name').children.at(-1).text); + +test('completed rows move down after saving and return when undone', async () => { + const second = { path: 'Habits/Zebra.md', name: 'Zebra', type: 'binary', frequency: 'daily', target: 1, goalDirection: 'min', startDate: '2020-01-01', records: {}, pauses: [], reschedules: [], times: [], group: '' }; + const f = fixture({ name: 'Alpha', type: 'binary', target: 1 }, async () => {}, { habits: [second] }); + assert.deepEqual(rowNames(f.root), ['Alpha', 'Zebra']); + f.button('Mark as done').handlers.click(); await new Promise(setImmediate); + assert.deepEqual(rowNames(f.root), ['Zebra', 'Alpha']); + const completed = f.root.all().find(el => el.className === 'habits-compact-row' && el.classes.has('is-done')); + assert.ok(completed, 'completed row exposes its visual state'); + assert.ok(completed.all().some(el => el.attrs['aria-label'] === 'Mark as not done'), 'completed row remains interactive'); + f.button('Mark as not done').handlers.click(); await new Promise(setImmediate); + assert.deepEqual(rowNames(f.root), ['Alpha', 'Zebra']); + assert.equal(f.root.all().some(el => el.className === 'habits-compact-row' && el.classes.has('is-done')), false); +}); + +test('status order respects settings, selected date and paused rows', () => { + const base = { type: 'binary', frequency: 'daily', target: 1, goalDirection: 'min', startDate: '2020-01-01', pauses: [], reschedules: [], times: [], group: '' }; + const f = fixture({ ...base, name: 'Alpha', records: { '2026-10-12': 1 } }, async () => {}, { habits: [ + { ...base, path: 'Habits/Beta.md', name: 'Beta', records: {} }, + { ...base, path: 'Habits/Gamma.md', name: 'Gamma', records: {}, pauses: [{ start: '2026-10-01', end: '' }] }, + ] }); + assert.deepEqual(rowNames(f.root), ['Beta', 'Alpha', 'Gamma']); + f.button('Next day').handlers.click(); + assert.deepEqual(rowNames(f.root), ['Alpha', 'Beta', 'Gamma']); + f.button('Previous day').handlers.click(); + f.settings.statusOrdering = false; f.events['settings-changed'](); + assert.deepEqual(rowNames(f.root), ['Alpha', 'Beta', 'Gamma']); +}); + +test('completed rows stay within their group', () => { + const base = { type: 'binary', frequency: 'daily', target: 1, goalDirection: 'min', startDate: '2020-01-01', pauses: [], reschedules: [], times: [] }; + const f = fixture({ ...base, name: 'Alpha', group: 'First', records: { '2026-10-12': 1 } }, async () => {}, { + habits: [ + { ...base, path: 'Habits/Beta.md', name: 'Beta', group: 'First', records: {} }, + { ...base, path: 'Habits/Gamma.md', name: 'Gamma', group: 'Second', records: {} }, + ], + settings: { groupsEnabled: true, sortMode: 'group', groupOrder: ['First', 'Second'] }, + }); + assert.deepEqual(rowNames(f.root), ['Beta', 'Alpha', 'Gamma']); +}); + +test('date label opens the picker and a selected date changes the logged day', async () => { + const writes = []; + const f = fixture({}, async (...args) => writes.push(args)); + const input = f.root.all().find(el => el.className === 'habits-compact-date-input'); + const nav = f.root.all().find(el => el.className === 'habits-compact-nav'); + assert.deepEqual(nav.children.map(el => el.attrs['aria-label']), ['Previous day', 'Choose a date', 'Next day', 'Today']); + assert.ok(f.root.children.includes(input), 'date picker must not occupy navigation space'); + let opened = false; + input.showPicker = () => { opened = true; }; + f.button('Choose a date').handlers.click(); + assert.equal(opened, true); + assert.equal(input.value, '2026-10-12'); + input.value = '2026-09-05'; input.handlers.change(); + f.button('Increase by 1').handlers.click(); await new Promise(setImmediate); + assert.equal(writes[0][1], '2026-09-05'); + f.button('Today').handlers.click(); + const now=new Date();const today=`${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,'0')}-${String(now.getDate()).padStart(2,'0')}`; + assert.equal(f.root.all().find(el=>el.className==='habits-compact-date-input').value,today); +}); + +test('successful writes bridge stale metadata, then accept external changes', async () => { + const writes = []; + const f = fixture({}, async (...args) => writes.push(args)); + f.button('Increase by 1').handlers.click(); + await new Promise(setImmediate); + assert.match(f.text(), /1 \/ 5 cups/); + f.button('Increase by 1').handlers.click(); + await new Promise(setImmediate); + assert.equal(writes[1][2], 2); + f.habit.records['2026-10-12'] = 4; + f.events.changed({ path: f.habit.path }); + assert.match(f.text(), /4 \/ 5 cups/); +}); + +test('double clicks are serialized and changing dates cannot redirect a write', async () => { + let release; const writes = []; + const f = fixture({}, (...args) => { writes.push(args); return new Promise(r => { release = r; }); }); + const click = f.button('Increase by 1').handlers.click; click(); click(); + assert.equal(writes.length, 1); + assert.equal(f.button('Increase by 1').disabled, true); + f.button('Next day').handlers.click(); release(); + await new Promise(setImmediate); + assert.equal(writes[0][1], '2026-10-12'); + assert.match(f.text(), /0 \/ 5 cups/); + f.button('Previous day').handlers.click(); + assert.match(f.text(), /1 \/ 5 cups/); +}); + +test('failed saves preserve the count and restore controls', async () => { + const f = fixture({}, async () => { throw new Error('disk full'); }); + f.button('Increase by 1').handlers.click(); await new Promise(setImmediate); + assert.match(f.text(), /0 \/ 5 cups/); + assert.equal(f.button('Increase by 1').disabled, false); + assert.equal(globalThis.lastNotice, 'Could not save habit record.'); +}); + +test('flexible totals span the week while steppers write only the selected day', async () => { + const writes = []; + const f = fixture({ frequency: 'flexibleWeekly', records: { '2026-10-12': 2, '2026-10-13': 1 } }, async (...args) => writes.push(args)); + f.button('Next day').handlers.click(); + assert.match(f.text(), /3 \/ 5 cups This week/); + f.button('Increase by 1').handlers.click(); await new Promise(setImmediate); + assert.equal(writes[0][2], 2); + assert.match(f.text(), /4 \/ 5 cups This week/); +}); + +test('binary limits, paused habits, timed steps and listener cleanup', () => { + const limit = fixture({ type: 'binary', goalDirection: 'max', target: 0 }); + assert.ok(limit.button('Mark as slipped')); + const paused = fixture({ pauses: [{ start: '2026-10-01', end: '' }] }); + assert.match(paused.text(), /Paused/); assert.equal(paused.button('Increase by 1'), undefined); + const timed = fixture({ type: 'timed' }); assert.ok(timed.button('Increase by 5')); assert.ok(timed.button('Decrease by 5')); + const old = timed.button('Increase by 5'); timed.button('Next day').handlers.click(); + assert.equal(old.handlers.click, undefined); + timed.view.unload(); assert.equal(timed.button('Increase by 5').handlers.click, undefined); +}); + +test('existing habits block switches layouts immediately and unloads old controls', () => { + const root = new Element(); + const settings = { dashboardLayout: 'carousel', habitsFolder: 'Habits', sortMode: 'name', manualOrder: [], groups: {}, groupOrder: [], experimental: {} }; + const listeners = []; + const events = { on: (_, fn) => { listeners.push(fn); } }; + const app = { metadataCache: { on() {} }, vault: { on() {} } }; + const block = new HabitsBlock(app, { getHabits: () => [] }, () => settings, events, 'Dashboard.md', root); + block.onload(); + assert.ok(root.all().some(el => el.text === 'Card dashboard')); + settings.dashboardLayout = 'compact'; listeners[0](); + assert.ok(root.all().some(el => el.className === 'habits-compact-header')); + assert.equal(root.all().some(el => el.text === 'Card dashboard'), false); + const plus = root.all().find(el => el.attrs['aria-label'] === 'Add habit'); + settings.dashboardLayout = 'grid'; listeners[0](); + assert.equal(plus.handlers.click, undefined); + assert.ok(root.all().some(el => el.text === 'Card dashboard')); + assert.equal(block.children.length, 1); +}); + +const item = (menu, title) => menu.items.find(i => i.title === title); + +function openMenu(f) { + const row = f.root.all().find(el => el.className === 'habits-compact-row'); + let prevented = false, stopped = false; + row.handlers.contextmenu({ clientX: 100, clientY: 200, preventDefault() { prevented = true; }, stopPropagation() { stopped = true; } }); + assert.equal(prevented, true); assert.equal(stopped, true); + assert.deepEqual(globalThis.lastMenu.position, { x: 100, y: 200 }); + openMenu.last = { row, menu: globalThis.lastMenu }; + return openMenu.last; +} + +test('right-click offers working open, edit and pause actions', async () => { + const f = fixture(); let opened, paused; + f.app.workspace.openLinkText = (...args) => { opened = args; }; + f.store.pauseHabit = async h => { paused = h.path; }; + const { menu } = openMenu(f); + assert.deepEqual(menu.items.map(i => i.title), ['Fail this day', 'Skip this day', 'Open note', 'Edit habit', 'Pause habit', 'Stop tracking', 'Remove habit']); + assert.equal(menu.separators, 1, 'day actions are set apart from the rest'); + item(menu, 'Open note').click(); assert.deepEqual(opened, [f.habit.path, 'Dashboard.md', false]); + item(menu, 'Edit habit').click(); assert.equal(globalThis.lastHabitModal.args[3].path, f.habit.path); + assert.equal(globalThis.lastHabitModal.args.length, 5, 'modal takes no limit-habit flag any more'); + await item(menu, 'Pause habit').click(); assert.equal(paused, f.habit.path); +}); + +test('paused rows retain their menu and offer resume instead of pause', async () => { + const f = fixture({ paused: true, pauses: [{ start: '2026-10-01', end: '' }] }); let resumed; + f.store.resumeHabit = async h => { resumed = h.path; }; + const { menu } = openMenu(f); + assert.equal(item(menu, 'Fail this day'), undefined, 'a paused day has nothing to fail or skip'); + await item(menu, 'Resume habit').click(); assert.equal(resumed, f.habit.path); +}); + +test('stop and remove are deferred until confirmation', async () => { + const f = fixture(); const calls = []; + f.store.stopHabit = async h => calls.push(['stop', h.path]); + f.store.deleteHabit = async h => calls.push(['delete', h.path]); + const { menu } = openMenu(f); + item(menu, 'Stop tracking').click(); assert.deepEqual(calls, []); + assert.equal(globalThis.lastConfirmation.title, 'Stop tracking'); + await globalThis.lastConfirmation.onConfirm(); + item(menu, 'Remove habit').click(); assert.equal(calls.length, 1); + assert.equal(globalThis.lastConfirmation.danger, true); + await globalThis.lastConfirmation.onConfirm(); + assert.deepEqual(calls, [['stop', f.habit.path], ['delete', f.habit.path]]); +}); + +test('long-press opens once, movement cancels it, and redraw removes timers', () => { + const f = fixture(); const row = f.root.all().find(el => el.className === 'habits-compact-row'); + const count = globalThis.menuCount ?? 0; + row.handlers.touchstart({ touches: [{ clientX: 100, clientY: 200 }] }); + const fn = [...row.win.timers.values()][0]; row.win.timers.clear(); fn(); + assert.equal(globalThis.menuCount, count + 1); + row.handlers.contextmenu({ clientX: 100, clientY: 200, preventDefault() {}, stopPropagation() {} }); + assert.equal(globalThis.menuCount, count + 1); + row.handlers.touchstart({ touches: [{ clientX: 100, clientY: 200 }] }); + row.handlers.touchmove({ touches: [{ clientX: 120, clientY: 200 }] }); + assert.equal(row.win.timers.size, 0); + row.handlers.touchstart({ touches: [{ clientX: 100, clientY: 200 }] }); + f.button('Next day').handlers.click(); + assert.equal(row.win.timers.size, 0); assert.equal(row.handlers.contextmenu, undefined); +}); + +const hiddenToggle = root => root.all().find(el => el.className === 'habits-closed-toggle'); +const toggleText = root => hiddenToggle(root)?.children.at(-1).text; + +test('fail hides the row, lists it underneath, and undo brings it back', async () => { + const zebra = { path: 'Habits/Zebra.md', name: 'Zebra', type: 'binary', frequency: 'daily', target: 1, goalDirection: 'min', startDate: '2020-01-01', records: {}, pauses: [], reschedules: [], failed: [], skipped: [], times: [], group: '' }; + const f = fixture({ name: 'Alpha', type: 'binary', target: 1 }, async () => {}, { habits: [zebra] }); + assert.deepEqual(rowNames(f.root), ['Alpha', 'Zebra']); + assert.equal(hiddenToggle(f.root), undefined, 'nothing hidden yet'); + const { menu } = openMenu(f); + await item(menu, 'Fail this day').click(); + assert.deepEqual(f.store.dayCalls, [[f.habit.path, '2026-10-12', 'failed']]); + assert.deepEqual(rowNames(f.root), ['Zebra'], 'failed habit leaves the list before the cache catches up'); + assert.equal(toggleText(f.root), '1 hidden for this day'); + hiddenToggle(f.root).handlers.click(); + const hidden = f.root.all().find(el => el.className === 'habits-closed-row is-failed'); + assert.ok(hidden, 'listed as failed'); + assert.ok(hidden.all().some(el => el.text === 'Failed')); + await hidden.all().find(el => el.text === 'Undo').handlers.click(); + assert.deepEqual(f.store.dayCalls.at(-1), [f.habit.path, '2026-10-12', null]); + assert.deepEqual(rowNames(f.root), ['Alpha', 'Zebra']); + assert.equal(hiddenToggle(f.root), undefined); +}); + +test('skipping works the same way, and the list reads as nothing left', async () => { + const f = fixture({ type: 'binary', target: 1 }); + await item(openMenu(f).menu, 'Skip this day').click(); + assert.deepEqual(rowNames(f.root), []); + assert.match(f.text(), /Nothing left on this day's list\./); + hiddenToggle(f.root).handlers.click(); + assert.ok(f.root.all().some(el => el.className === 'habits-closed-row is-skipped')); +}); + +test('a completed habit cannot be failed, but a limit habit always can', () => { + const done = fixture({ type: 'binary', target: 1, records: { '2026-10-12': 1 } }); + assert.equal(item(openMenu(done).menu, 'Fail this day'), undefined); + const limit = fixture({ type: 'binary', target: 0, goalDirection: 'max' }); + assert.ok(item(openMenu(limit).menu, 'Fail this day')); +}); + +test('snooze is offered for today only, hides the row and schedules its return', async () => { + const f = fixture({ type: 'binary', target: 1 }); + assert.equal(item(openMenu(f).menu, 'Snooze…'), undefined, 'not for another day'); + f.view.selectedDate = new Date(); f.view.render(); + f.view.lastMenuAt = -Infinity; + const snooze = item(openMenu(f).menu, 'Snooze…'); + assert.ok(snooze); assert.ok(item(openMenu.last.menu, 'Fail for today')); + snooze.click(); + assert.equal(globalThis.lastModal.constructor.name, 'SnoozeModal'); + await f.store.snoozeHabit(f.habit, Date.now() + 60_000); f.view.render(); + assert.deepEqual(rowNames(f.root), []); + assert.equal(toggleText(f.root), '1 hidden for today'); + assert.equal(f.root.win.timers.size, 1, 'refresh scheduled for when the snooze ends'); + hiddenToggle(f.root).handlers.click(); + assert.ok(f.root.all().some(el => /^Snoozed until /.test(el.text))); + await f.root.all().find(el => el.text === 'Undo').handlers.click(); + assert.deepEqual(rowNames(f.root), ['Test']); + f.view.unload(); + assert.equal(f.root.win.timers.size, 0, 'pending refresh cancelled on unload'); +}); + +test('counted habits step by their own decimal step size', async () => { + const writes = []; + const f = fixture({ step: 0.1, target: 1.5, unit: 'L' }, async (...args) => writes.push(args)); + assert.ok(f.button('Increase by 0.1') && f.button('Decrease by 0.1')); + for (let i = 0; i < 3; i++) { f.button('Increase by 0.1').handlers.click(); await new Promise(setImmediate); } + assert.deepEqual(writes.map(w => w[2]), [0.1, 0.2, 0.3], 'no floating-point drift'); + assert.match(f.text(), /0\.3 \/ 1\.5 L/); + f.button('Decrease by 0.1').handlers.click(); await new Promise(setImmediate); + assert.equal(writes.at(-1)[2], 0.2); +}); diff --git a/tests/habits/dom-fixture.mjs b/tests/habits/dom-fixture.mjs new file mode 100644 index 000000000..f3a18a6ed --- /dev/null +++ b/tests/habits/dom-fixture.mjs @@ -0,0 +1,33 @@ +/** Minimal Obsidian DOM extensions on a real jsdom document. */ +export function installObsidianDom(window) { + const proto=window.HTMLElement.prototype; + window.Element.prototype.createSvg=function(tag,options={}){const child=this.ownerDocument.createElementNS('http://www.w3.org/2000/svg',tag);if(options.cls)child.setAttribute('class',options.cls);for(const[key,value]of Object.entries(options.attr||{}))child.setAttribute(key,value);this.append(child);return child;}; + window.SVGElement.prototype.empty=function(){this.replaceChildren();}; + + Object.defineProperties(proto,{doc:{get(){return this.ownerDocument;}},win:{get(){return this.ownerDocument.defaultView;}}}); + proto.createEl=function(tag,options={},callback) { + if(typeof options==='string') options={cls:options}; + const child=this.ownerDocument.createElement(tag); + if(options.cls) child.className=Array.isArray(options.cls)?options.cls.join(' '):options.cls; + if(options.text!==undefined) child.textContent=options.text; + if(options.value!==undefined) child.value=options.value; + if(options.type!==undefined) child.type=options.type; + for(const [key,value] of Object.entries(options.attr??{})) child.setAttribute(key,value); + this.append(child); callback?.(child); return child; + }; + proto.createDiv=function(options,callback){return this.createEl('div',options,callback);}; + proto.createSpan=function(options,callback){return this.createEl('span',options,callback);}; + proto.empty=function(){this.replaceChildren();}; + proto.addClass=function(...names){this.classList.add(...names);}; + proto.addClasses=function(names){this.classList.add(...names);}; + proto.removeClass=function(...names){this.classList.remove(...names);}; + proto.toggleClass=function(name,enabled){this.classList.toggle(name,enabled);}; + proto.toggle=function(enabled){this.hidden=!enabled;}; + proto.show=function(){this.style.display="";}; + proto.hide=function(){this.style.display="none";}; + proto.isShown=function(){return this.style.display!=="none";}; + proto.setText=function(value){this.textContent=value;}; + proto.setCssProps=function(values){for(const [key,value]of Object.entries(values))this.style.setProperty(key,value);}; + proto.setAttr=function(key,value){this.setAttribute(key,value);}; + proto.onClickEvent=function(callback){this.addEventListener('click',callback);}; +} diff --git a/tests/habits/integration.test.mjs b/tests/habits/integration.test.mjs new file mode 100644 index 000000000..2aa36d1a3 --- /dev/null +++ b/tests/habits/integration.test.mjs @@ -0,0 +1,530 @@ +import assert from 'node:assert/strict'; +import {test, after} from 'node:test'; +import {build} from 'esbuild'; +import {mkdtemp, rm} from 'node:fs/promises'; +import {tmpdir} from 'node:os'; +import path from 'node:path'; +import {pathToFileURL} from 'node:url'; +import {createRequire} from 'node:module'; +import {installObsidianDom} from './dom-fixture.mjs'; +const require = createRequire(import.meta.url); +const {JSDOM} = createRequire(require.resolve('jest-environment-jsdom'))('jsdom'); +const directory = await mkdtemp(path.join(tmpdir(), 'tg-habits-tests-')); +after(() => rm(directory, {recursive: true, force: true})); +await build({ + stdin: {contents: `export {TaskGeniusHabits} from './src/integrations/habits/task-genius-host'; + export {HabitStore} from './src/integrations/habits/habit-store'; + export {MissedHabitsModal} from './src/integrations/habits/ui/missed-habits-modal'; + export {ConfirmModal} from './src/integrations/habits/ui/confirm-modal'; + export {NativeHabitCards} from './src/integrations/habits/ui/native-cards'; + export {nativeCardHeat} from './src/integrations/habits/ui/native-card-state'; + export {DEFAULT_SETTINGS, DEFAULT_FRONTMATTER_KEYS} from './src/integrations/habits/settings'; + export {planLegacyHabits, importLegacyHabits} from './src/integrations/habits/legacy-import'; + export {isDue, isActive, isComplete, isDailyComplete, habitStats, missedInstances, isRescheduleTargetOpen} from './src/integrations/habits/stats'; + export {resolveTaskPoints, taskCompletionTransactionId} from './src/managers/points-utils'; + export {t} from './src/integrations/habits/i18n'; + export {ReminderSync} from './src/integrations/habits/reminders'; + export {NoteHabitSync, computeNoteValue} from './src/integrations/habits/note-habit'; + export {applyCommentLog, parseCommentLog} from './src/integrations/habits/comment-log'; + export {generateSummary} from './src/integrations/habits/ai-summary'; + export {ExportModal} from './src/integrations/habits/ui/export-modal'; + export * from './tests/habits/obsidian-fixture.mjs';`, resolveDir: process.cwd(), loader: 'ts'}, + bundle: true, format: 'esm', platform: 'node', outfile: path.join(directory, 'integration.mjs'), + loader: {'.css': 'empty'}, logLevel: 'silent', + plugins: [{name: 'obsidian-fixture', setup(builder) { + builder.onResolve({filter: /^obsidian$/}, () => ({path: path.resolve('tests/habits/obsidian-fixture.mjs')})); + }}], +}); +const {TaskGeniusHabits, ConfirmModal, Menu, HabitStore, NativeHabitCards, MissedHabitsModal, nativeCardHeat, Events, DEFAULT_SETTINGS, DEFAULT_FRONTMATTER_KEYS, + planLegacyHabits, importLegacyHabits, isDue, isActive, isComplete, isDailyComplete, habitStats, missedInstances, isRescheduleTargetOpen, t, vaultFixture, + ReminderSync, NoteHabitSync, computeNoteValue, applyCommentLog, parseCommentLog, generateSummary, ExportModal, resolveTaskPoints, taskCompletionTransactionId} = await import(pathToFileURL(path.join(directory, 'integration.mjs'))); +const settings = extra => ({...structuredClone(DEFAULT_SETTINGS), ...extra}); +const date = value => {const [year, month, day] = value.split('-').map(Number); return new Date(year, month - 1, day);}; +const habit = extra => ({type:'binary', goalDirection:'min', frequency:'interval', intervalMode:'completion', intervalDays:2, startDate:'2026-11-01', records:{}, pauses:[], reschedules:[], failed:[], skipped:[], target:1, ...extra}); + +test('three active days in a four-day cycle require three independent check-ins', () => { + const h = habit({intervalMode:'cycle', intervalDays:4, cycleActiveDays:3, records:{'2026-11-01':1}}); + for (const [key, expected] of [['2026-11-01',true],['2026-11-02',true],['2026-11-03',true],['2026-11-04',false],['2026-11-05',true]]) assert.equal(isDue(h,date(key)),expected,key); + assert.equal(isComplete(h,'2026-11-01'),true); + assert.equal(isComplete(h,'2026-11-02'),false); +}); +test('restarting a cycle changes future days without changing earlier schedules', () => { + const h=habit({intervalMode:'cycle',intervalDays:4,cycleActiveDays:3,cycleRestarts:['2026-11-07']}); + assert.equal(isDue(h,date('2026-11-04')),false); + assert.equal(isDue(h,date('2026-11-07')),true); + assert.equal(isDue(h,date('2026-11-10')),false); + assert.equal(isDue(h,date('2026-11-11')),true); +}); +test('one creation completes the daily card while the weekly quota remains three', () => { + const h=habit({frequency:'flexibleWeekly',type:'repetition',target:3,dailyTarget:1,records:{'2026-11-02':1}}); + assert.equal(isDailyComplete(h,'2026-11-02'),true); + assert.equal(isComplete(h,'2026-11-02'),false); + assert.equal(isDailyComplete(h,'2026-11-03'),false); +}); +test('rolling intervals remain due after a miss, then restart from the actual completion', () => { + const h = habit({records:{'2026-11-01':1, '2026-11-04':1}}); + for (const [key, expected] of [['2026-10-31',false],['2026-11-01',true],['2026-11-02',false],['2026-11-03',true],['2026-11-04',true],['2026-11-05',false],['2026-11-06',true]]) assert.equal(isDue(h, date(key)), expected, key); + assert.equal(isComplete(h, '2026-11-04'), true); + assert.equal(isActive(h, date('2026-11-05')), false); +}); + +test('interval habits offer a multi-day check-in window and score one completion per cycle', () => { + const h = habit({intervalMode:'fixed', intervalDays:4, intervalWindowDays:3, startDate:'2026-11-01', records:{'2026-11-02':1}}); + for (const day of ['2026-11-01','2026-11-02','2026-11-03']) assert.equal(isActive(h,date(day)),true,day); + assert.equal(isDue(h,date('2026-11-03')),true); + assert.equal(isComplete(h,'2026-11-03'),true); + assert.equal(isActive(h,date('2026-11-04')),false); + assert.equal(isActive(h,date('2026-11-05')),true); + assert.equal(isDue(h,date('2026-11-07')),true); + assert.equal(isComplete(h,'2026-11-07'),false); +}); + +test('completion-anchored windows restart after a late check-in', () => { + const h = habit({intervalMode:'completion', intervalDays:4, intervalWindowDays:3, startDate:'2026-11-01', records:{'2026-11-03':1}}); + assert.equal(isActive(h,date('2026-11-03')),true); + assert.equal(isDue(h,date('2026-11-03')),true); + assert.equal(isComplete(h,'2026-11-03'),true); + assert.equal(isActive(h,date('2026-11-04')),false); + assert.equal(isActive(h,date('2026-11-07')),true); + assert.equal(isDue(h,date('2026-11-09')),true); +}); + +test('task points use per-task values, then configured defaults, and dedupe completion records', () => { + assert.equal(resolveTaskPoints({metadata:{points:25},originalMarkdown:'- [x] task [points:: 4]'},10),25); + assert.equal(resolveTaskPoints({originalMarkdown:'- [x] task [points:: 4]'},10),4); + assert.equal(resolveTaskPoints({originalMarkdown:'- [x] task [积分:: 6]'},10),6); + assert.equal(resolveTaskPoints({},10),10); + assert.equal(resolveTaskPoints({metadata:{points:-4}},10),0); + assert.equal(taskCompletionTransactionId({id:'task-1',metadata:{completedDate:'2026-11-08'}}), 'task:task-1:2026-11-08'); +}); +test('partial, failed, skipped and future records cannot shift earlier rolling due dates', () => { + const h = habit({type:'repetition',target:3,records:{'2026-11-01':3,'2026-11-03':2,'2026-11-04':3,'2026-11-09':3}, failed:['2026-11-04']}); + assert.equal(isDue(h,date('2026-11-04')),true); + assert.equal(isDue(h,date('2026-11-05')),true); + delete h.records['2026-11-09']; + assert.equal(isDue(h,date('2026-11-05')),true); + h.failed=[]; h.skipped=['2026-11-04']; + assert.equal(isDue(h,date('2026-11-05')),true); +}); +test('fixed intervals and maximum limits retain the original start-date schedule', () => { + const h = habit({intervalMode:'fixed',records:{'2026-11-04':1}}); + assert.equal(isDue(h,date('2026-11-05')),true); + assert.equal(isDue(h,date('2026-11-06')),false); + h.intervalMode='completion'; h.goalDirection='max'; + assert.equal(isDue(h,date('2026-11-05')),true); +}); +test('legacy conversion retains zero mapping scores, fractional counts, details and event presence', () => { + const source = [ + {id:'daily',name:'Read',icon:'book',type:'daily',completions:{'2026-11-01':'done','2026-11-02':false}}, + {id:'count',name:'Water',icon:'glass-water',type:'count',min:2,countUnit:'L',completions:{'2026-11-01':1.25}}, + {id:'mood',name:'Mood',icon:'smile',type:'mapping',mapping:{0:'Neutral',1:'Happy'},completions:{'2026-11-01':0}}, + {id:'schedule',name:'Routine',icon:'sun',type:'scheduled',events:[{name:'Morning',details:[]},{name:'Evening',details:[]}],completions:{'2026-11-01':{Morning:'',Evening:'Walked'}}}, + ]; + const plans = planLegacyHabits(source); + assert.equal(plans.length,5); + assert.equal(plans[0].records['2026-11-01'],1); + assert.equal(plans[1].records['2026-11-01'],1.25); + assert.equal(plans[2].records['2026-11-01'],0); + assert.equal(plans[3].records['2026-11-01'],1); + assert.deepEqual(plans[4].source,source[3]); + assert.deepEqual(source[3].completions['2026-11-01'],{Morning:'',Evening:'Walked'}); +}); +test('legacy import uses configurable folders and keys, preserves source data and is idempotent', async () => { + const fixture = vaultFixture(); + const config = settings({habitsFolder:'Tracking/习惯',frontmatterKeys:{...DEFAULT_FRONTMATTER_KEYS,records:'日志'}}); + const plans = planLegacyHabits([{id:'old',name:'健身',icon:'dumbbell',type:'daily',completions:{'2026-11-04':true}}]); + assert.deepEqual(await importLegacyHabits(fixture.app,config,plans),{created:1,skipped:0}); + assert.deepEqual(await importLegacyHabits(fixture.app,config,plans),{created:0,skipped:1}); + const file = fixture.app.vault.getMarkdownFiles()[0]; + const fm = fixture.metadata.get(file.path).frontmatter; + assert.ok(file.path.startsWith('Tracking/习惯/')); + assert.deepEqual(fm['日志'],{'2026-11-04':1}); + assert.deepEqual(fm.taskGeniusLegacy.source,plans[0].source); + const store = new HabitStore(fixture.app,()=>config,async()=>{}); + assert.equal(store.getHabits()[0].records['2026-11-04'],1); + await store.setRecord(store.getHabits()[0],'2026-11-06',1); + assert.deepEqual(fm['日志'],['2026-11-04','2026-11-06']); +}); +test('import detects path conflicts and never overwrites an unrelated existing note', async () => { + const fixture = vaultFixture(), config = settings(); + const plans = planLegacyHabits([{id:'old',name:'Read',icon:'book',type:'daily',completions:{}}]); + await importLegacyHabits(fixture.app,config,plans); + const file = fixture.app.vault.getMarkdownFiles()[0]; fixture.text.set(file.path,'Important unrelated content'); + await assert.rejects(importLegacyHabits(fixture.app,config,plans),/Import conflict/); + assert.equal(fixture.text.get(file.path),'Important unrelated content'); + await assert.rejects(importLegacyHabits(fixture.app,{...config,habitsFolder:'../outside'},plans),/Invalid habits folder/); +}); +test('habit store follows folder changes immediately and writes fractional values through the file API', async () => { + const fixture = vaultFixture(), config = settings({habitsFolder:'One'}); + for (const folder of ['One','Two']) { + await fixture.app.vault.createFolder(folder); + await fixture.app.vault.create(`${folder}/Water.md`,`---\n${JSON.stringify({habit:true,type:'repetition',target:2,step:0.25,records:{'2026-11-01':0.5}})}\n---\n`); + } + const store = new HabitStore(fixture.app,()=>config,async()=>{}); + assert.equal(store.getHabits()[0].path,'One/Water.md'); + config.habitsFolder='Two'; + const h = store.getHabits()[0]; assert.equal(h.path,'Two/Water.md'); + await store.setRecord(h,'2026-11-02',0.1+0.2); + assert.equal(fixture.metadata.get(h.path).frontmatter.records['2026-11-02'],0.3); + assert.equal(fixture.metadata.get('One/Water.md').frontmatter.records['2026-11-02'],undefined); +}); +test('saving a chosen cycle restart preserves the original start date and every historical record', async () => { + const fixture=vaultFixture(),config=settings(); + await fixture.app.vault.createFolder('Habits'); + await fixture.app.vault.create('Habits/Exercise.md','---\n'+JSON.stringify({habit:true,type:'binary',frequency:'interval',intervalMode:'cycle',intervalDays:4,cycleActiveDays:3,startDate:'2026-11-01',records:{'2026-11-01':1,'2026-11-02':1},bravoPoints:2})+'\n---\nOriginal notes'); + const store=new HabitStore(fixture.app,()=>config,async()=>{}),h=store.getHabits()[0]; + await store.updateHabit(h,{...h,name:h.name,restartCycleDate:'2026-11-07'}); + const fm=fixture.metadata.get(h.path).frontmatter; + assert.equal(fm.startDate,'2026-11-01');assert.deepEqual(fm.records,{'2026-11-01':1,'2026-11-02':1});assert.deepEqual(fm.cycleRestarts,['2026-11-07']);assert.equal(fm.bravoPoints,2); +}); +test('host imports compatible Habits settings without copying API keys or enabling external writes', async () => { + const fixture = vaultFixture(); + fixture.text.set('.obsidian/plugins/habits/data.json', JSON.stringify({habitsFolder:'Existing',cardsPerView:2,frontmatterKeys:{records:'done'},aiSummary:{apiKey:'secret'},reminders:{enabled:true}})); + const host = {app:fixture.app,manifest:{id:'task-genius'},settings:{habit:{enableHabits:true}},saveSettings:async()=>{}}; + const plugin = new TaskGeniusHabits(host); await plugin.loadSettings(); + assert.equal(plugin.settings.habitsFolder,'Existing'); + assert.equal(plugin.settings.frontmatterKeys.records,'done'); + assert.equal(plugin.settings.aiSummary.apiKey,''); + assert.equal(plugin.settings.reminders.enabled,false); + await plugin.saveSettings(); + assert.equal(host.settings.habitsIntegration.habitsFolder,'Existing'); + assert.ok(!JSON.stringify(host.settings).includes('secret')); +}); +test('full host registration namespaces commands, views and blocks and avoids standalone collisions', async () => { + globalThis.window=globalThis; + for (const standalone of [false,true]) { + const fixture = vaultFixture(); if (standalone) fixture.app.plugins.enabledPlugins.add('habits'); + const host={app:fixture.app,manifest:{id:'task-genius'},settings:{habit:{enableHabits:true},habitsIntegration:settings()},saveSettings:async()=>{}}; + const plugin=new TaskGeniusHabits(host); await plugin.onload(); await plugin.ready; + for (const language of ['habits','habit-metrics','habits-table','habits-heatmap']) { + assert.ok(plugin.blocks.has(`tg-${language}`)); assert.equal(plugin.blocks.has(language),!standalone); + } + assert.ok(plugin.views.has('tg-habits-panel')); + assert.equal(plugin.manifest.id,'task-genius-habits'); + const inserted=[]; plugin.commands.find(command=>command.id==='insert-dashboard').editorCallback({replaceSelection:value=>inserted.push(value)}); + assert.ok(inserted[0].startsWith('```tg-habits')); + assert.ok(plugin.embeddedSettings); + plugin.unload(); + assert.equal([...fixture.app.vault.handlers.values()].reduce((sum,set)=>sum+set.size,0),0); + } +}); +test('English and Chinese use separate complete strings and preserve zero placeholders', () => { + globalThis.testLanguage='zh-cn'; assert.equal(t('Create habit'),'创建习惯'); + assert.equal(t('Imported {created} habits; skipped {skipped} existing imports.',{created:0,skipped:2}),'已导入 0 个习惯,跳过 2 个已导入习惯。'); + globalThis.testLanguage='en'; assert.equal(t('Create habit'),'Create habit'); +}); + +test('background synchronization has one owner and stops after disabling or unloading', async () => { + globalThis.window=globalThis; + const originalPrime=NoteHabitSync.prototype.primeAll, originalUpdate=ReminderSync.prototype.update; + let primes=0, updates=0; + NoteHabitSync.prototype.primeAll=async()=>{primes++;}; + ReminderSync.prototype.update=async()=>{updates++;}; + try { + const fixture=vaultFixture(); fixture.app.plugins.enabledPlugins.add('habits'); + const host={app:fixture.app,manifest:{id:'task-genius'},settings:{habit:{enableHabits:true},habitsIntegration:settings()},saveSettings:async()=>{}}; + const plugin=new TaskGeniusHabits(host); await plugin.onload(); + assert.deepEqual([primes,updates],[0,0]); + fixture.app.plugins.enabledPlugins.delete('habits'); plugin.events.trigger('settings-changed'); + assert.deepEqual([primes,updates],[1,1]); + host.settings.habit.enableHabits=false; plugin.events.trigger('settings-changed'); + assert.deepEqual([primes,updates],[1,1]); + plugin.unload(); host.settings.habit.enableHabits=true; plugin.events.trigger('settings-changed'); + assert.deepEqual([primes,updates],[1,1]); + } finally { NoteHabitSync.prototype.primeAll=originalPrime; ReminderSync.prototype.update=originalUpdate; } +}); +test('unloading during asynchronous settings loading does not register late listeners', async () => { + const fixture=vaultFixture(); + let release; + fixture.app.vault.adapter.read=()=>new Promise(resolve=>{release=resolve;}); + const host={app:fixture.app,manifest:{id:'task-genius'},settings:{habit:{enableHabits:true}},saveSettings:async()=>{}}; + const plugin=new TaskGeniusHabits(host), loading=plugin.onload(); plugin.unload(); release('{}'); await loading; await plugin.ready; + assert.equal(plugin.commands.length,0); assert.equal(plugin.blocks.size,0); assert.equal(fixture.app.vault.handlers.size,0); +}); +test('reminder checkboxes and counted records synchronize in both directions', async () => { + const fixture=vaultFixture(), config=settings({reminders:{enabled:true,target:'fixed-note',notePath:'Reminders.md'}}); + await fixture.app.vault.createFolder('Habits'); + await fixture.app.vault.create('Habits/Water.md',`---\n${JSON.stringify({type:'repetition',target:2,times:['09:00','18:00'],startDate:'2026-11-01',records:{}})}\n---\n`); + const store=new HabitStore(fixture.app,()=>config,async()=>{}), sync=new ReminderSync(fixture.app,store,()=>config); + await sync.update(date('2026-11-08')); + const first=fixture.text.get('Reminders.md'); assert.equal((first.match(/- \[ \]/g)??[]).length,2); + fixture.text.set('Reminders.md',first.replace('- [ ]','- [x]')); + await sync.update(date('2026-11-08')); assert.equal(store.getHabits()[0].records['2026-11-08'],1); + fixture.text.set('Reminders.md',fixture.text.get('Reminders.md').replace('- [x]','- [ ]')); + await sync.update(date('2026-11-08')); assert.equal(store.getHabits()[0].records['2026-11-08'],undefined); +}); +test('note habits support character, all-checklist, counted-checklist and failure rules', () => { + const h={noteCompletionMode:'chars',noteChecklistRequirement:'all',noteChecklistMin:2,noteFailKeyword:'failed',target:10}; + assert.equal(computeNoteValue(h,'---\ntitle: ignored\n---\nhello'),5); + h.noteCompletionMode='checklist'; + assert.equal(computeNoteValue(h,'- [x] one\n- [ ] two'),50); + h.noteChecklistRequirement='count'; assert.equal(computeNoteValue(h,'- [x] one\n- [x] two\n- [ ] three'),2); + assert.equal(computeNoteValue(h,'- [x] failed'),0); +}); +test('day comments preserve unrelated Markdown, tags, links and multiline text', () => { + const comments={'2026-11-08':'Gym #fitness [[Training]]\nSecond line','2026-11-06':'Rest'}; + const original='# Notes\n\nKeep this paragraph.\n'; + const result=applyCommentLog(original,comments); + assert.ok(result.startsWith(original.trimEnd())); assert.deepEqual(parseCommentLog(result),comments); + assert.equal(applyCommentLog(result,comments),result); +}); +test('AI summary requests are opt-in, configurable, cached, and report endpoint errors', async () => { + let count=0; + globalThis.mockHabitRequest=async request=>{count++; assert.equal(request.url,'https://example.invalid/v1/chat/completions'); assert.equal(request.headers.Authorization,'Bearer test-key'); return {status:200,json:{choices:[{message:{content:'Summary'}}]}};}; + const config={baseUrl:'https://example.invalid/v1/',apiKey:'test-key',model:'local-test'}; + try { + assert.equal(await generateSummary(config,'weekly','rolling','test-digest'),'Summary'); + assert.equal(await generateSummary(config,'weekly','rolling','test-digest'),'Summary'); assert.equal(count,1); + globalThis.mockHabitRequest=async()=>({status:429,json:{error:{message:'Rate limited'}}}); + await assert.rejects(generateSummary(config,'weekly','rolling','test-digest',true),/Rate limited/); + } finally { delete globalThis.mockHabitRequest; } +}); +test('PDF export produces a real PDF in the vault without overwriting previous exports', async () => { + const fixture=vaultFixture(), config=settings(); await fixture.app.vault.createFolder('Habits'); + await fixture.app.vault.create('Habits/Read.md',`---\n${JSON.stringify({type:'binary',startDate:'2026-11-01',records:{'2026-11-08':1}})}\n---\n`); + const store=new HabitStore(fixture.app,()=>config,async()=>{}); + const dom=new JSDOM(''); + dom.window.document.body.createSpan=()=>{ + const span=dom.window.document.createElement('span'); + Object.defineProperty(span,'win',{value:dom.window}); dom.window.document.body.append(span); return span; + }; + for(let index=0;index<2;index++) { + const modal=new ExportModal(fixture.app,store.getHabits()); modal.contentEl.doc=dom.window.document; + modal.options.includeTrend=false; await modal.exportPdf(); + } + const pdfs=[...fixture.text].filter(([name])=>name.endsWith('.pdf')); assert.equal(pdfs.length,2); + for (const [,data] of pdfs) { const bytes=Buffer.from(data); assert.equal(bytes.subarray(0,5).toString(),'%PDF-'); assert.ok(bytes.length>1000); } + dom.window.close(); +}); +test('all embedded settings tabs render in English and Chinese; folder input saves into Task Genius', async () => { + for (const language of ['en','zh-cn']) { + globalThis.testLanguage=language; + const dom=new JSDOM(''); installObsidianDom(dom.window); + const fixture=vaultFixture(); let saves=0; + const host={app:fixture.app,manifest:{id:'task-genius'},settings:{habit:{enableHabits:true},habitsIntegration:settings()},saveSettings:async()=>{saves++;}}; + const plugin=new TaskGeniusHabits(host); await plugin.onload(); + const root=dom.window.document.body.createDiv(); plugin.renderSettings(root); + const tabs=[...root.querySelectorAll('.habits-settings-tab')]; assert.equal(tabs.length,3); + assert.equal(tabs[0].textContent,language==='en'?'General':'常规'); + const input=root.querySelector('input'); input.value='Tracking/自定义'; input.dispatchEvent(new dom.window.Event('input')); await globalThis.lastSettingSave; + assert.equal(host.settings.habitsIntegration.habitsFolder,'Tracking/自定义'); assert.ok(saves>0); + const layoutSelectors=[...root.querySelectorAll('select')].filter(select=>[...select.options].some(option=>option.value==='cards')); + assert.equal(layoutSelectors.length,1);assert.deepEqual([...layoutSelectors[0].options].map(option=>option.value),['cards','compact','grid','carousel','vertical']); + layoutSelectors[0].value='compact';layoutSelectors[0].dispatchEvent(new dom.window.Event('change'));await globalThis.lastSettingSave;assert.equal(host.settings.habitsIntegration.dashboardLayout,'compact');assert.equal(host.settings.habitsIntegration.nativeLayout,undefined); + tabs[1].click(); assert.ok(root.querySelectorAll('input[type=checkbox]').length>=2); + tabs[2].click(); assert.ok(root.querySelectorAll('.setting-item').length>=30); + plugin.unload(); dom.window.close(); + } + globalThis.testLanguage='en'; +}); + +test('AI summary cache separates endpoints even when model and statistics are identical',async()=>{ + let requests=0;globalThis.mockHabitRequest=async request=>{requests++;return {status:200,json:{choices:[{message:{content:request.url}}]}};}; + try{const first={baseUrl:'https://first.invalid',apiKey:'',model:'same-model'},second={...first,baseUrl:'https://second.invalid'}; + assert.equal(await generateSummary(first,'weekly','rolling','endpoint-digest'),'https://first.invalid/chat/completions'); + assert.equal(await generateSummary(second,'weekly','rolling','endpoint-digest'),'https://second.invalid/chat/completions');assert.equal(requests,2); + }finally{delete globalThis.mockHabitRequest;} +}); + +test('native habit cards show existing Markdown records and save catch-up without replacing history',async()=>{ + globalThis.testLanguage='en'; + const dom=new JSDOM('');installObsidianDom(dom.window);globalThis.document=dom.window.document;globalThis.window=dom.window; + const fixture=vaultFixture(),config=settings();await fixture.app.vault.createFolder('Habits'); + await fixture.app.vault.create('Habits/Exercise.md','---\n'+JSON.stringify({habit:true,type:'binary',startDate:'2026-11-01',frequency:'daily',records:{'2026-11-07':1}})+'\n---\n'); + const store=new HabitStore(fixture.app,()=>config,async()=>{}),root=document.body.createDiv(); + const cards=new NativeHabitCards(fixture.app,store,config,new Events(),root); + cards.selectedDate=date('2026-11-08');cards.onload(); + assert.equal(root.querySelectorAll('.tg-native-habit-cell').length,30);assert.equal(root.querySelectorAll('.is-complete').length,1); + root.querySelector('[aria-label="Check in"]').click();await new Promise(resolve=>setTimeout(resolve,0)); + assert.deepEqual(fixture.metadata.get('Habits/Exercise.md').frontmatter.records,{'2026-11-07':1,'2026-11-08':1}); + assert.equal(fixture.metadata.get('Habits/Exercise.md').frontmatter.startDate,'2026-11-01'); + cards.setSearchQuery('missing');assert.equal(root.querySelectorAll('.tg-native-habit-card').length,0); + cards.unload();dom.window.close();delete globalThis.document;delete globalThis.window; +}); + +test('native heatmap has four progress levels and never rewards breaking a maximum limit',()=>{ + const base=habit({type:'repetition',frequency:'daily',intervalMode:'fixed',target:10}); + for(const [value,level] of [[0,0],[4,1],[10,2],[20,3]])assert.equal(nativeCardHeat({...base,records:{'2026-11-08':value}},'2026-11-08').level,level); + assert.deepEqual(nativeCardHeat({...base,goalDirection:'max',records:{'2026-11-08':20}},'2026-11-08'),{level:1,overLimit:true}); + assert.equal(nativeCardHeat({...base,goalDirection:'max',records:{'2026-11-08':4}},'2026-11-08').level,2); +}); + +test('native cards show minimum and maximum goals and put completed habits after pending habits',async()=>{ + globalThis.testLanguage='en';const dom=new JSDOM('');installObsidianDom(dom.window);globalThis.document=dom.window.document;globalThis.window=dom.window; + const f=vaultFixture(),config=settings();await f.app.vault.createFolder('Habits'); + for(const[name,goalDirection,target,value]of [['A Counter','min',2,0],['B Done','min',2,2],['C Limit','max',1,2],['D Within limit','max',1,0]])await f.app.vault.create('Habits/'+name+'.md','---\n'+JSON.stringify({habit:true,type:'repetition',frequency:'daily',startDate:'2026-11-01',goalDirection,target,records:{'2026-11-08':value}})+'\n---\n'); + const store=new HabitStore(f.app,()=>config,async()=>{}),root=document.body.createDiv(),cards=new NativeHabitCards(f.app,store,config,new Events(),root);cards.selectedDate=date('2026-11-08');cards.onload(); + assert.deepEqual([...root.querySelectorAll('.tg-native-habit-heading strong')].map(el=>el.textContent),['A Counter','C Limit','B Done','D Within limit']); + assert.match(root.textContent,/At least: 0 \/ 2/);assert.match(root.textContent,/At most: 2 \/ 1/);assert.ok(root.querySelector('.is-over-limit'));assert.equal(root.querySelector('select'),null); + cards.unload();dom.window.close();delete globalThis.document;delete globalThis.window; +}); + + +test('native cards change the selected day, show goals, fade completed cards and return to today',async()=>{ + globalThis.testLanguage='en';const dom=new JSDOM('');installObsidianDom(dom.window);globalThis.document=dom.window.document;globalThis.window=dom.window; + const f=vaultFixture(),config=settings();await f.app.vault.createFolder('Habits'); + await f.app.vault.create('Habits/Exercise.md','---\n'+JSON.stringify({habit:true,type:'repetition',frequency:'daily',target:2,startDate:'2026-11-01',records:{'2026-11-07':1,'2026-11-08':2}})+'\n---\n'); + const root=document.body.createDiv(),cards=new NativeHabitCards(f.app,new HabitStore(f.app,()=>config,async()=>{}),config,new Events(),root);cards.selectedDate=date('2026-11-08');cards.onload(); + assert.ok(root.querySelector('.tg-native-habit-cards > .tg-native-habit-card.is-done'));assert.match(root.querySelector('.tg-native-habit-goal').textContent,/2 \/ 2/); + root.querySelector('[aria-label="Previous day"]').click();assert.equal(root.querySelector('input[type=date]').value,'2026-11-07');assert.equal(root.querySelector('.tg-native-habit-card.is-done'),null);assert.match(root.querySelector('.tg-native-habit-goal').textContent,/1 \/ 2/); + root.querySelector('.tg-native-habit-date-label').click();assert.equal(root.querySelector('.tg-native-habit-date-label').textContent,'Today'); + cards.unload();dom.window.close();delete globalThis.document;delete globalThis.window; +}); + +test('the two old layout settings merge into one selector without losing the selected page layout',async()=>{ + for(const [nativeLayout,dashboardLayout,expected] of [['cards','compact','cards'],['dashboard','compact','compact'],[undefined,'grid','cards']]){ + const f=vaultFixture(),host={app:f.app,manifest:{id:'test',name:'Task Genius'},settings:{habitsIntegration:{...settings(),nativeLayout,dashboardLayout}},saveSettings:async()=>{}}; + const integration=new TaskGeniusHabits(host);const result=await integration.loadData();assert.equal(result.dashboardLayout,expected);assert.equal(result.nativeLayout,undefined);assert.equal(result.layoutUnified,true); + host.settings.habitsIntegration={...result,dashboardLayout:'grid'};assert.equal((await integration.loadData()).dashboardLayout,'grid'); + } +}); + + +test('ignored missed days stay ignored without changing recorded values or future schedules',async()=>{ + const f=vaultFixture(),config=settings();await f.app.vault.createFolder('Habits'); + await f.app.vault.create('Habits/Exercise.md','---\n'+JSON.stringify({habit:true,type:'binary',frequency:'interval',intervalDays:2,startDate:'2026-11-01',records:{'2026-11-01':1}})+'\n---\n'); + const store=new HabitStore(f.app,()=>config,async()=>{});let h=store.getHabits()[0]; + assert.ok(missedInstances([h],date('2026-11-09')).some(item=>item.dateKey==='2026-11-07')); + await store.ignoreMissedDay(h,'2026-11-07');h=store.getHabits()[0]; + assert.equal(missedInstances([h],date('2026-11-09')).some(item=>item.dateKey==='2026-11-07'),false);assert.deepEqual(h.records,{'2026-11-01':1});assert.equal(h.startDate,'2026-11-01');assert.deepEqual(h.ignoredMisses,['2026-11-07']); +}); + +test('rescheduling rejects originally due days, existing records and concurrent claims at save time',async()=>{ + const f=vaultFixture(),config=settings();await f.app.vault.createFolder('Habits'); + await f.app.vault.create('Habits/Exercise.md','---\n'+JSON.stringify({habit:true,type:'binary',frequency:'interval',intervalDays:2,startDate:'2026-11-01',records:{'2026-11-01':1,'2026-11-06':1}})+'\n---\n'); + const store=new HabitStore(f.app,()=>config,async()=>{}),h=store.getHabits()[0]; + assert.equal(isRescheduleTargetOpen(h,'2026-11-09'),false);assert.equal(isRescheduleTargetOpen(h,'2026-11-06'),false); + await assert.rejects(()=>store.rescheduleHabit(h,'2026-11-03','2026-11-09')); + await assert.rejects(()=>store.rescheduleHabit(h,'2026-11-03','2026-11-06')); + await store.rescheduleHabit(h,'2026-11-03','2026-11-10'); + await assert.rejects(()=>store.rescheduleHabit(h,'2026-11-05','2026-11-10')); + const current=store.getHabits()[0];assert.deepEqual(current.reschedules,[{from:'2026-11-03',to:'2026-11-10'}]);assert.deepEqual(current.records,{'2026-11-01':1,'2026-11-06':1}); +}); + +test('daily habits expose missed-day review and ignore without offering an overlapping reschedule',()=>{ + const h=habit({frequency:'daily',startDate:'2026-11-01',records:{},ignoredMisses:['2026-11-07']}); + assert.equal(missedInstances([h],date('2026-11-09')).some(item=>item.dateKey==='2026-11-08'),true); + assert.equal(missedInstances([h],date('2026-11-09')).some(item=>item.dateKey==='2026-11-07'),false); + assert.equal(isRescheduleTargetOpen(h,'2026-11-10'),false); +}); + +test('native habit cards hide the duplicate date and legend, show habit icons and apply column settings',async()=>{ + globalThis.testLanguage='en';const dom=new JSDOM('');installObsidianDom(dom.window);globalThis.document=dom.window.document;globalThis.window=dom.window; + const f=vaultFixture(),config=settings({habitColumns:'3'});await f.app.vault.createFolder('Habits');await f.app.vault.create('Habits/Exercise.md','---\n'+JSON.stringify({habit:true,type:'binary',frequency:'daily',icon:'💪',startDate:'2026-11-01',records:{}})+'\n---\n'); + const root=document.body.createDiv(),cards=new NativeHabitCards(f.app,new HabitStore(f.app,()=>config,async()=>{}),config,new Events(),root);cards.onload(); + assert.equal(root.querySelector('.tg-native-habit-cards').dataset.columns,'3');assert.match(root.querySelector('.tg-native-habit-icon').textContent,/💪/);assert.equal(root.querySelector('.tg-native-heat-legend'),null);assert.equal(root.querySelector('.tg-native-habit-nav input[type=date]'),null);assert.ok(root.querySelector('.tg-habit-add'));assert.ok(root.querySelector('[aria-label="Missed habits"]')); + cards.unload();dom.window.close();delete globalThis.document;delete globalThis.window; +}); + + +test('ignore all past misses dismisses old notifications without changing records, scores or future misses',async()=>{ + const f=vaultFixture(),config=settings();await f.app.vault.createFolder('Habits'); + for(const name of ['Exercise','Read'])await f.app.vault.create(`Habits/${name}.md`,'---\n'+JSON.stringify({habit:true,name,type:'binary',frequency:'daily',startDate:'2026-11-01',records:{'2026-11-01':1},bravoPoints:10})+'\n---\n'); + const store=new HabitStore(f.app,()=>config,async()=>{});assert.ok(missedInstances(store.getHabits(),date('2026-11-09')).length); + assert.equal(await store.ignoreAllPastMisses('2026-11-09'),2);assert.equal(missedInstances(store.getHabits(),date('2026-11-09')).length,0); + for(const h of store.getHabits()){assert.deepEqual(h.records,{'2026-11-01':1});assert.equal(f.metadata.get(h.path).frontmatter.bravoPoints,10);assert.equal(h.startDate,'2026-11-01');} + assert.ok(missedInstances(store.getHabits(),date('2026-11-10')).every(item=>item.dateKey==='2026-11-09'));assert.ok(missedInstances(store.getHabits(),date('2026-11-10')).length); +}); + +test('sync metadata only replaces cards when a habit record actually changes', async () => { + const dom = new JSDOM(''); + installObsidianDom(dom.window); + globalThis.document = dom.window.document; + globalThis.window = dom.window; + const f = vaultFixture(); + const config = settings(); + await f.app.vault.createFolder('Habits'); + const file = await f.app.vault.create('Habits/Read.md', '---\n{"type":"binary","startDate":"2026-11-01","records":{}}\n---\n'); + const unrelated = await f.app.vault.create('Journal.md', 'A note'); + const store = new HabitStore(f.app, () => config, async () => {}); + const root = document.body.createDiv(); + const cards = new NativeHabitCards(f.app, store, config, new Events(), root); + cards.selectedDate = date('2026-11-09'); + cards.onload(); + try { + const initial = root.querySelector('.tg-native-habit-card'); + assert.ok(initial); + f.app.metadataCache.trigger('changed', unrelated); + f.app.metadataCache.trigger('changed', file); + assert.equal(root.querySelector('.tg-native-habit-card'), initial); + const original = store.getHabits()[0]; + await store.setRecord(original, '2026-11-09', 1); + f.app.metadataCache.trigger('changed', file); + const updated = root.querySelector('.tg-native-habit-card'); + assert.notEqual(updated, initial); + assert.ok(updated.classList.contains('is-done')); + f.app.metadataCache.trigger('changed', file); + assert.equal(root.querySelector('.tg-native-habit-card'), updated); + await store.stopHabit(store.getHabits()[0]); + f.app.metadataCache.trigger('changed', file); + assert.equal(root.querySelector('.tg-native-habit-card'), null); + assert.deepEqual(store.getHabits()[0].records, {'2026-11-09': 1}); + } finally { + cards.unload(); + dom.window.close(); + delete globalThis.document; + delete globalThis.window; + } +}); + +test('the missed dialog backfills the original day and preserves a concurrent record', async () => { + const dom = new JSDOM(''); + installObsidianDom(dom.window); + globalThis.document = dom.window.document; + globalThis.testLanguage = 'en'; + const f = vaultFixture(); + const config = settings(); + await f.app.vault.createFolder('Habits'); + await f.app.vault.create('Habits/Read.md', '---\n{"type":"binary","frequency":"daily","startDate":"2026-11-01","records":{}}\n---\n'); + const store = new HabitStore(f.app, () => config, async () => {}); + const original = store.getHabits()[0]; + const modal = new MissedHabitsModal(f.app, store, [original], () => {}); + modal.contentEl = dom.window.document.body.createDiv(); + try { + modal.renderList(); + const backfill = modal.contentEl.querySelector('.habits-missed-reschedule'); + assert.equal(backfill.textContent, 'Backfill'); + assert.equal(backfill.disabled, false); + backfill.click(); + const originalDay = missedInstances([original], new Date())[0].dateKey; + const confirm = [...modal.contentEl.querySelectorAll('button')].find(button => button.textContent === 'Confirm'); + assert.ok(confirm && !confirm.disabled); + confirm.click(); + await new Promise(resolve => setImmediate(resolve)); + assert.deepEqual(store.getHabits()[0].records, {[originalDay]: 1}); + assert.deepEqual(store.getHabits()[0].reschedules, []); + await assert.rejects(() => store.setRecord(original, originalDay, 2, 0)); + assert.deepEqual(store.getHabits()[0].records, {[originalDay]: 1}); + } finally { + dom.window.close(); + delete globalThis.document; + } +}); + +test('the native card Stop habit menu stops tracking while keeping the Markdown note and records', async () => { + const dom=new JSDOM(''); + installObsidianDom(dom.window); + globalThis.document=dom.window.document;globalThis.window=dom.window;globalThis.testLanguage='en'; + const f=vaultFixture(), config=settings(); + await f.app.vault.createFolder('Habits'); + const file=await f.app.vault.create('Habits/Read.md','---\n{"type":"binary","frequency":"daily","startDate":"2026-11-01","records":{"2026-11-01":1}}\n---\nKeep the original note body'); + const store=new HabitStore(f.app,()=>config,async()=>{}); + const root=document.body.createDiv(); + const cards=new NativeHabitCards(f.app,store,config,new Events(),root); + const ask=ConfirmModal.ask; + ConfirmModal.ask=async()=>true; + try{ + cards.onload(); + root.querySelector('[aria-label="More actions"]').click(); + const stop=Menu.last.items.find(item=>item.title==='Stop habit'); + assert.ok(stop); + await stop.callback(); + assert.equal(store.getHabits()[0].stopped,true); + assert.deepEqual(store.getHabits()[0].records,{'2026-11-01':1}); + assert.ok(f.app.vault.getAbstractFileByPath(file.path)); + assert.match(await f.app.vault.read(file),/Keep the original note body/); + assert.equal(root.querySelector('.tg-native-habit-card'),null); + }finally{ + ConfirmModal.ask=ask;cards.unload();dom.window.close();delete globalThis.document;delete globalThis.window; + } +}); diff --git a/tests/habits/limit-frequency.test.mjs b/tests/habits/limit-frequency.test.mjs new file mode 100644 index 000000000..7a4ceeb18 --- /dev/null +++ b/tests/habits/limit-frequency.test.mjs @@ -0,0 +1,70 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { build } from 'esbuild'; + +const built = await build({ entryPoints: ['src/integrations/habits/stats.ts'], bundle: true, write: false, format: 'esm', platform: 'node', plugins: [{ name: 'obsidian-stubs', setup(b) { + b.onResolve({ filter: /^obsidian$/ }, () => ({ path: 'obsidian', namespace: 'stub' })); + b.onLoad({ filter: /.*/, namespace: 'stub' }, () => ({ contents: 'export const moment = {};' })); + b.onLoad({ filter: /i18n\/index\.ts$/ }, () => ({ contents: 'export const t = s => s;' })); +} }] }); +const { isActive, isDue, isComplete, flexiblePeriodTotal, currentStreak, longestStreak, habitStats } = await import(`data:text/javascript;base64,${Buffer.from(built.outputFiles[0].text).toString('base64')}`); +const date = key => { const [y,m,d] = key.split('-').map(Number); return new Date(y,m-1,d); }; +const habit = overrides => ({ type: 'repetition', goalDirection: 'max', frequency: 'daily', target: 2, startDate: '2026-10-01', records: {}, pauses: [], reschedules: [], weekdays: [1,3], monthDay: 31, intervalDays: 2, ...overrides }); + +test('daily limits preserve equality, zero allowance and existing semantics', () => { + const h = habit({ records: { '2026-10-12': 2, '2026-10-13': 3 } }); + assert.equal(isComplete(h, '2026-10-12'), true); + assert.equal(isComplete(h, '2026-10-13'), false); + assert.equal(isComplete(h, '2026-10-11'), true); + assert.equal(isComplete(h, '2026-09-30'), false); +}); +test('scheduled weekly limits only count their selected due days', () => { + const h = habit({ frequency: 'weekly', startDate: '2026-10-12', records: { '2026-10-12': 2, '2026-10-13': 99, '2026-10-14': 3 } }); + assert.equal(isActive(h, date('2026-10-13')), false); + assert.equal(isActive(h, date('2026-10-14')), true); + const s = habitStats(h, { start: date('2026-10-12'), end: date('2026-10-14') }, date('2026-10-14')); + assert.equal(s.days, 2); assert.equal(s.completed, 1); assert.equal(s.total, 5); +}); +test('monthly date clamping and interval anchors work for limits', () => { + const monthly = habit({ frequency: 'monthly', startDate: '2026-01-01' }); + assert.equal(isDue(monthly, date('2026-02-28')), true); + assert.equal(isDue(monthly, date('2026-02-27')), false); + const interval = habit({ frequency: 'interval', startDate: '2026-10-12' }); + assert.equal(isActive(interval, date('2026-10-11')), false); + assert.equal(isActive(interval, date('2026-10-13')), false); + assert.equal(isActive(interval, date('2026-10-14')), true); +}); +test('weekly totals cross days, stop at selected day, and reset on Monday', () => { + const h = habit({ frequency: 'flexibleWeekly', records: { '2026-10-12': 1, '2026-10-13': 1, '2026-10-14': 1 } }); + assert.equal(flexiblePeriodTotal(h, date('2026-10-13')), 2); + assert.equal(isComplete(h, '2026-10-13'), true); + assert.equal(isComplete(h, '2026-10-14'), false); + assert.equal(isActive(h, date('2026-10-15')), true); + assert.equal(isComplete(h, '2026-10-19'), true); +}); +test('monthly zero and binary limits reject any consumption in the period', () => { + for (const extra of [{ target: 0 }, { type: 'binary', target: 999 }]) { + const h = habit({ frequency: 'flexibleMonthly', records: { '2026-10-02': 1 }, ...extra }); + assert.equal(isComplete(h, '2026-10-01'), true); + assert.equal(isComplete(h, '2026-10-20'), false); + assert.equal(isComplete(h, '2026-11-01'), true); + assert.equal(isComplete(h, '2026-09-30'), false); + } +}); +test('exceeding an open weekly limit breaks streaks; correction restores them', () => { + const h = habit({ frequency: 'flexibleWeekly', startDate: '2026-10-05', records: { '2026-10-06': 2, '2026-10-12': 3 } }); + assert.equal(currentStreak(h, date('2026-10-13')), 0); + assert.equal(longestStreak(h, date('2026-10-13')), 1); + h.records['2026-10-12'] = 2; + assert.equal(currentStreak(h, date('2026-10-13')), 2); +}); +test('completed period statistics exclude fully paused weeks and count zero consumption', () => { + const h = habit({ frequency: 'flexibleWeekly', startDate: '2026-10-05', pauses: [{ start: '2026-10-12', end: '2026-10-18' }], records: { '2026-10-06': 3 } }); + const s = habitStats(h, { start: date('2026-10-05'), end: date('2026-10-25') }, date('2026-10-25')); + assert.equal(s.days, 2); assert.equal(s.completed, 1); assert.equal(s.total, 3); +}); +test('minimum flexible goals retain unfinished-period grace', () => { + const h = habit({ goalDirection: 'min', frequency: 'flexibleWeekly', startDate: '2026-10-05', records: { '2026-10-06': 2 } }); + assert.equal(isComplete(h, '2026-10-13'), false); + assert.equal(currentStreak(h, date('2026-10-13')), 1); +}); diff --git a/tests/habits/obsidian-fixture.mjs b/tests/habits/obsidian-fixture.mjs new file mode 100644 index 000000000..5fd78708c --- /dev/null +++ b/tests/habits/obsidian-fixture.mjs @@ -0,0 +1,137 @@ +export class Events { + handlers = new Map(); + on(name, callback) { const list = this.handlers.get(name) ?? new Set(); list.add(callback); this.handlers.set(name, list); return {emitter: this, name, callback}; } + offref(ref) { this.handlers.get(ref.name)?.delete(ref.callback); } + trigger(name, ...args) { for (const callback of this.handlers.get(name) ?? []) callback(...args); } +} +export class Component { + onload() {} + onunload() {} + children = []; cleanups = []; + addChild(child) { this.children.push(child); child.onload?.(); return child; } + removeChild(child) { child.unload(); this.children = this.children.filter(value => value !== child); } + register(callback) { this.cleanups.push(callback); } + registerEvent(ref) { this.register(() => ref?.emitter?.offref(ref)); } + registerInterval(id) { this.register(() => clearInterval(id)); } + registerDomEvent(el, name, callback) { el.addEventListener(name, callback); this.register(() => el.removeEventListener(name, callback)); } + unload() { this.onunload?.(); this.children.forEach(child => child.unload()); this.children = []; this.cleanups.splice(0).forEach(callback => callback()); } +} +export class Plugin extends Component { + blocks = new Map(); commands = []; views = new Map(); + constructor(app, manifest) { super(); this.app = app; this.manifest = manifest; } + addSettingTab() {} + addCommand(command) { this.commands.push(command); } + addRibbonIcon() {} + registerHoverLinkSource() {} + registerEditorSuggest() {} + registerMarkdownCodeBlockProcessor(language, callback) { if (this.blocks.has(language)) throw new Error(`Duplicate block: ${language}`); this.blocks.set(language, callback); return callback; } + registerView(type, callback) { this.views.set(type, callback); } +} +export class TFile { constructor(path) { this.path = path; this.extension = path.split('.').pop(); this.basename = path.split('/').pop().replace(/\.md$/, ''); } } +export class TFolder { constructor(path) { this.path = path; this.children = []; } } +export class App {} +export class PluginSettingTab { constructor(app, plugin) { this.app = app; this.plugin = plugin; } } +export class Modal extends Component { constructor(app) { super(); this.app = app; this.modalEl = {addClass() {}}; this.contentEl = {empty(){}, win:{removeEventListener(){}}}; } close() { this.onClose?.(); } } +export class SuggestModal extends Modal {} +export class FuzzySuggestModal extends Modal {} +export class EditorSuggest extends Component {} +export class AbstractInputSuggest extends Component {} +export class ButtonComponent {} +export class ColorComponent {} +export class ItemView extends Component { constructor(leaf) { super(); this.leaf = leaf; } } +export class MarkdownRenderChild extends Component { constructor(containerEl) { super(); this.containerEl = containerEl; } } +export class Setting { + constructor(root) { + this.settingEl=root.createDiv({cls:'setting-item'}); + this.infoEl=this.settingEl.createDiv({cls:'setting-item-info'}); + this.nameEl=this.infoEl.createDiv({cls:'setting-item-name'}); + this.descEl=this.infoEl.createDiv({cls:'setting-item-description'}); + this.controlEl=this.settingEl.createDiv({cls:'setting-item-control'}); + } + setName(value) { this.nameEl.textContent=value; return this; } + setDesc(value) { this.descEl.textContent=value; return this; } + setHeading() { this.settingEl.classList.add('setting-item-heading'); return this; } + addControl(type, callback) { + const element=this.controlEl.createEl(type==='dropdown'?'select':type==='button'?'button':type==='textarea'?'textarea':'input'); + if (type==='toggle') element.type='checkbox'; + const component={inputEl:element,buttonEl:element,selectEl:element, + setValue(value) { if(type==='toggle') element.checked=value; else element.value=value; return this; }, + setPlaceholder(value) {element.placeholder=value;return this;}, + setButtonText(value) {element.textContent=value;return this;}, + setCta() {return this;}, + setDisabled(value) {element.disabled=value;return this;}, + setWarning() {return this;}, + setTooltip(value) {element.title=value;return this;}, + setIcon(value) {element.dataset.icon=value;return this;}, + onChange(fn) {element.addEventListener(type==='text'?'input':'change',()=>{ const promise=fn(type==='toggle'?element.checked:element.value); globalThis.lastSettingSave=promise; });return this;}, + onClick(fn) {element.addEventListener('click',fn);return this;}, + addOption(value,label) {const option=element.createEl('option',{text:label});option.value=value;return this;}, + }; + callback(component); return this; + } + addText(callback) {return this.addControl('text',callback);} + addToggle(callback) {return this.addControl('toggle',callback);} + addDropdown(callback) {return this.addControl('dropdown',callback);} + addTextArea(callback) {return this.addControl('textarea',callback);} + addExtraButton(callback) {return this.addControl('button',callback);} + addButton(callback) {return this.addControl('button',callback);} +} +export class Notice { constructor(text) { globalThis.lastNotice = text; } } +export class Menu { + static last; + constructor() { this.items=[]; Menu.last=this; } + addItem(callback) { + const item={setTitle(value){this.title=value;return this;},setIcon(){return this;},setDisabled(){return this;},setChecked(){return this;},onClick(callback){this.callback=callback;return this;}}; + callback(item);this.items.push(item);return this; + } + addSeparator(){return this;} + showAtPosition(){return this;} +} +export const moment = Object.assign(() => ({format: () => '2026-11-08'}), {locale: () => globalThis.testLanguage ?? 'en'}); +export const debounce = callback => callback; +export const normalizePath = value => value.replace(/\\/g, '/').replace(/\/+/g, '/').replace(/^\.\//, '').replace(/\/$/, ''); +export const parseYaml = JSON.parse; +export const getFrontMatterInfo = text => { const match=text.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/); return {exists:!!match,frontmatter:match?.[1]??'',contentStart:match?.[0].length??0}; }; +export const stringifyYaml = value => JSON.stringify(value, null, 2) + '\n'; +export const setIcon = () => {}; +export const setTooltip = () => {}; +export const getIconIds = () => []; +export const getAllTags = () => []; +export const prepareFuzzySearch = () => () => null; +export const renderResults = () => {}; +export const requestUrl = request => { if (globalThis.mockHabitRequest) return globalThis.mockHabitRequest(request); throw new Error('Network calls are forbidden in tests'); }; +export const Platform = {isMobile: false}; +export const MarkdownRenderer = {render: async () => {}}; + +export function vaultFixture() { + const files = new Map(), text = new Map(), metadata = new Map(); + const vault = Object.assign(new Events(), { + configDir: '.obsidian', + getAbstractFileByPath: path => files.get(path) ?? null, + getMarkdownFiles: () => [...files.values()].filter(file => file instanceof TFile), + adapter: {exists: async path => text.has(path), read: async path => { if (!text.has(path)) throw new Error('Missing file'); return text.get(path); }}, + read: async file => text.get(file.path) ?? '', + cachedRead: async file => text.get(file.path) ?? '', + createFolder: async path => { const folder = new TFolder(path); files.set(path, folder); return folder; }, + create: async (path, content) => { + if (files.has(path)) throw new Error(`File exists: ${path}`); + const file = new TFile(path); files.set(path, file); text.set(path, content); + const folder = files.get(path.slice(0, path.lastIndexOf('/'))); folder?.children?.push(file); + const fm = /^---\r?\n([\s\S]*?)\r?\n---/.exec(content); + if (fm) metadata.set(path, {frontmatter: parseYaml(fm[1])}); + return file; + }, + createBinary: async (path, content) => { files.set(path,new TFile(path)); text.set(path,content); }, + modify: async (file, content) => { text.set(file.path, content); }, + process: async (file, callback) => { text.set(file.path, callback(text.get(file.path) ?? '')); }, + }); + const app = { + vault, metadataCache: Object.assign(new Events(), {getFileCache: file => metadata.get(file.path) ?? null}), + workspace: Object.assign(new Events(), {onLayoutReady: callback => callback()}), + plugins: {enabledPlugins: new Set()}, + fileManager: {processFrontMatter: async (file, callback) => { + const cache = metadata.get(file.path) ?? {frontmatter: {}}; callback(cache.frontmatter); metadata.set(file.path, cache); + }}, + }; + return {app, files, text, metadata}; +} diff --git a/tests/habits/styles.test.mjs b/tests/habits/styles.test.mjs new file mode 100644 index 000000000..0012888a5 --- /dev/null +++ b/tests/habits/styles.test.mjs @@ -0,0 +1,29 @@ +import assert from 'node:assert/strict'; +import {test} from 'node:test'; +import fs from 'node:fs'; +import postcss from 'postcss'; +import selectorParser from 'postcss-selector-parser'; + +function selectors(css) { + const result=[]; + postcss.parse(css).walkRules(rule=>{ + let parent=rule.parent; + while(parent) { if(parent.type==='atrule' && /keyframes$/i.test(parent.name))return; parent=parent.parent; } + result.push(rule.selector); + }); + return result; +} +test('every upstream CSS selector is scoped to Task Genius, including modal subjects and pseudo-elements',()=>{ + const directory='src/integrations/habits/'; + const original=selectors(fs.readFileSync(directory+'upstream.css','utf8')); + const scoped=selectors(fs.readFileSync(directory+'scoped.css','utf8')); + assert.equal(scoped.length,original.length); + for(const selector of scoped) { + selectorParser(root=>root.each(subject=>{ + assert.ok(subject.nodes.some(node=>node.type==='pseudo'&&node.value===':where'&&node.toString().includes('.tg-habits-surface')),selector); + const pseudoElement=subject.nodes.findIndex(node=>node.type==='pseudo'&&node.value.startsWith('::')); + const scope=subject.nodes.findIndex(node=>node.type==='pseudo'&&node.value===':where'); + if(pseudoElement>=0)assert.ok(scope{ + const directory=await fs.mkdtemp(path.join(tmpdir(),'tg-calendar-patch-')); + try{ + const patch=JSON.parse(await fs.readFile('patches/calendar-layout.json','utf8')); + await fs.mkdir(path.join(directory,'scripts'),{recursive:true});await fs.mkdir(path.join(directory,'patches'),{recursive:true}); + await fs.copyFile('scripts/patch-calendar.cjs',path.join(directory,'scripts/patch-calendar.cjs'));await fs.copyFile('patches/calendar-layout.json',path.join(directory,'patches/calendar-layout.json')); + for(const file of patch.files){let original=(await fs.readFile(path.join('packages/calendar',file.file),'utf8')).replace(/\r\n/g,'\n');for(const step of [...file.steps].reverse())original=original.replace(step.after,step.before);assert.equal(createHash('sha256').update(original).digest('hex'),file.baseline);const target=path.join(directory,'packages/calendar',file.file);await fs.mkdir(path.dirname(target),{recursive:true});await fs.writeFile(target,original);} + const run=()=>execFileSync(process.execPath,['scripts/patch-calendar.cjs'],{cwd:directory,stdio:'pipe'}).toString(); + assert.match(run(),/6 files patched/);assert.match(run(),/0 files patched/); + for(const file of patch.files){const content=await fs.readFile(path.join(directory,'packages/calendar',file.file),'utf8');assert.equal(createHash('sha256').update(content).digest('hex'),file.result);} + await fs.appendFile(path.join(directory,'packages/calendar',patch.files[0].file),'\n// unexpected upstream edit\n');assert.throws(run); + }finally{await fs.rm(directory,{recursive:true,force:true});} +}); diff --git a/tests/ui-audit/fixture.mjs b/tests/ui-audit/fixture.mjs new file mode 100644 index 000000000..793024d90 --- /dev/null +++ b/tests/ui-audit/fixture.mjs @@ -0,0 +1,74 @@ +export * from '../habits/obsidian-fixture.mjs'; +import {Component} from '../habits/obsidian-fixture.mjs'; +import actualMoment from 'moment'; +export {actualMoment as moment}; +export class ButtonComponent { + constructor(root) { this.buttonEl=root.createEl('button'); } + setClass(value) {this.buttonEl.classList.add(value);return this;} + setIcon(icon) { this.buttonEl.dataset.icon=icon; return this; } + setButtonText(text) {this.buttonEl.textContent=text;return this;} + setTooltip(text) {this.buttonEl.title=text;return this;} + setCta(){return this;} + onClick(callback){this.buttonEl.addEventListener('click',callback);return this;} +} +export class ExtraButtonComponent extends ButtonComponent {} +export class DropdownComponent { + constructor(root){this.selectEl=root.createEl('select');} + addOption(value,label){const option=this.selectEl.createEl('option',{text:label});option.value=value;return this;} + setValue(value){this.selectEl.value=value;return this;} + onChange(callback){this.selectEl.addEventListener('change',()=>callback(this.selectEl.value));return this;} +} +export class ItemView extends Component { constructor(leaf){super();this.leaf=leaf;} } +export class SearchComponent { + constructor(root){this.inputEl=root.createEl('input');} + setPlaceholder(value){this.inputEl.placeholder=value;return this;} + setValue(value){this.inputEl.value=value;return this;} + onChange(callback){this.inputEl.addEventListener('input',()=>callback(this.inputEl.value));return this;} +} +export class Scope { register(){} } +export function setTooltip() {} +export const Platform={isMobile:false,isPhone:false,isDesktopApp:true}; +export const debounce=(callback,delay)=>{ + let timer; + const debounced=function(...args){clearTimeout(timer);timer=setTimeout(()=>callback.apply(this,args),delay);}; + debounced.cancel=()=>clearTimeout(timer); + return debounced; +}; +export class StubComponent extends Component { + constructor(...args){super();this.element=document.createElement('div');this.containerEl=this.element;this.task=args[0];} + startManaging(){} + stopManaging(){} + render(value){this.element.textContent=value;} + load(){} + setTasks(){} + updateTasks(){} + setViewMode(){} + setIsTreeView(){} + setTopNavigation(){} + setActiveProject(){} + refresh(){} + destroy(){this.element.remove();} +} + +export class Modal extends Component { + constructor(app){super();this.app=app;this.containerEl=document.body.createDiv({cls:'modal-container'});this.modalEl=this.containerEl.createDiv({cls:'modal'});this.modalEl.createDiv({cls:'modal-header-button'});this.titleEl=this.modalEl.createEl('h2',{cls:'modal-title'});this.contentEl=this.modalEl.createDiv({cls:'modal-content'});} + setTitle(value){this.titleEl ||= this.modalEl.createEl("h2");this.titleEl.textContent=value;return this;} + open(){this.onOpen?.();return this;} + close(){this.onClose?.();this.containerEl.remove();} +} + +export class Menu { + static last; + constructor(){this.items=[];Menu.last=this;} + addItem(callback){const item={titleEl:document.createElement('div'),setTitle(value){this.title=value;return this;},setIcon(){return this;},setChecked(){return this;},setDisabled(){return this;},setWarning(){return this;},onClick(callback){this.callback=callback;return this;},setSubmenu(){return new Menu();}};callback(item);this.items.push(item);return this;} + addSeparator(){return this;} + showAtMouseEvent(event){Menu.shown=this;this.event=event;return this;} + showAtPosition(){return this;} +} + +export class TextComponent { + constructor(root){this.inputEl=root.createEl('input');} + setValue(value){this.inputEl.value=value??'';return this;}setPlaceholder(value){this.inputEl.placeholder=value;return this;} + setDisabled(value){this.inputEl.disabled=value;return this;}onChange(fn){this.inputEl.addEventListener('input',()=>fn(this.inputEl.value));return this;} +} +export class TextAreaComponent extends TextComponent {} diff --git a/tests/ui-audit/regressions.test.mjs b/tests/ui-audit/regressions.test.mjs new file mode 100644 index 000000000..9bfe799b3 --- /dev/null +++ b/tests/ui-audit/regressions.test.mjs @@ -0,0 +1,958 @@ +import assert from 'node:assert/strict'; +import {test,after} from 'node:test'; +import {build} from 'esbuild'; +import fs from 'node:fs'; +import {mkdtemp,rm} from 'node:fs/promises'; +import path from 'node:path'; +import {tmpdir} from 'node:os'; +import {pathToFileURL} from 'node:url'; +import {createRequire} from 'node:module'; +import {installObsidianDom} from '../habits/dom-fixture.mjs'; +const require=createRequire(import.meta.url); +const ts=require('typescript'); +const {JSDOM}=createRequire(require.resolve('jest-environment-jsdom'))('jsdom'); +const directory=await mkdtemp(path.join(tmpdir(),'tg-ui-audit-')); +after(()=>rm(directory,{recursive:true,force:true})); +const owned=[ + 'utils/status-cycle-resolver.ts', 'components/features/task/view/forecast.ts', + 'components/features/quick-capture/modals/BaseQuickCaptureModal.ts', 'components/ui/feedback/StatusIndicator.ts', 'services/time-parsing-service.ts', 'components/features/task/edit/TaskDependencyPicker.ts', 'managers/icon-manager.ts', 'components/features/quick-capture/modals/QuickCaptureModalWithSwitch.ts', 'components/features/task/view/details.ts', + + "dataflow/Orchestrator.ts", + 'components/features/planner/TaskPlanner.ts', 'components/features/gantt/gantt.ts', 'utils/date/date-helper.ts', 'utils/date/optional-date-time.ts', 'components/features/task/edit/TaskDetailsModal.ts', 'components/features/task/edit/MetadataEditor.ts', + + 'integrations/habits/ui/modal-close.ts', + 'components/features/task/view/content.ts', + 'components/features/fluent/components/FluentTopNavigation.ts', 'components/features/fluent/components/ProjectList.ts', 'components/features/fluent/components/FluentSidebar.ts', + 'components/features/fluent/managers/FluentLayoutManager.ts', + 'components/features/fluent/managers/FluentDataManager.ts', + 'components/features/fluent/managers/FluentComponentManager.ts', 'components/features/fluent/managers/FluentActionHandlers.ts', 'utils/dateOperations.ts', + 'components/features/calendar/index.ts', + 'components/features/calendar/views/tg-year-view.ts', + 'components/features/calendar/views/tg-agenda-view.ts', + 'components/ui/behavior/ViewComponentManager.ts', + 'pages/FluentTaskView.ts', 'integrations/habits/ui/habit-modal.ts', + 'mcp/auth/AuthMiddleware.ts', 'services/view-settings-signature.ts', 'integrations/habits/ui/modal-close.ts', 'dataflow/events/Events.ts', 'utils/ui/view-mode-utils.ts', + 'utils/ui/tree-view-utils.ts', + 'components/features/gantt/drag-pan.ts', 'components/features/gantt/task-renderer.ts', 'utils/task/priority-utils.ts', 'services/markdown-status-sync.ts', 'utils/task/filter-compatibility.ts', 'utils/task/saved-task-filters.ts', 'utils/task/project-calendar.ts', 'components/features/quadrant/quadrant-column.ts', 'components/features/table/TableRenderer.ts', 'components/features/fluent/components/SavedTaskFilterModal.ts', + 'components/features/rewards/PointsDashboard.ts', 'managers/points-service.ts', 'managers/daily-points.ts', 'managers/daily-task-points.ts', 'managers/points-utils.ts', 'managers/reward-catalog.ts', 'utils/adapters/TaskCalendarAdapter.ts', 'utils/date/date-utils.ts', + 'utils/date/calendar-week.ts', 'components/features/fluent/components/ProjectFolders.ts', 'utils/date/date-time-picker.ts', 'managers/project-file-manager.ts', 'managers/period-notes.ts', 'icon.ts', + 'components/features/kanban/kanban.ts', 'components/features/quadrant/quadrant.ts', 'components/features/table/TableView.ts', +].map(file=>path.resolve('src',file)); +await build({stdin:{contents:` + export {ForecastComponent} from './src/components/features/task/view/forecast'; + export {getTaskStatusGroup,getNextTaskStatusMark,getPausedTaskMarks} from './src/utils/status-cycle-resolver'; + export {TaskGeniusIconManager} from './src/managers/icon-manager'; + export {calendarWeekNumber} from './src/utils/date/calendar-week'; + export {projectFolderContainer} from './src/components/features/fluent/components/ProjectFolders'; + export {openPeriodNote} from './src/managers/period-notes'; + export {attachDateTimePicker} from './src/utils/date/date-time-picker'; + export {ProjectFileManager,ProjectEditModal,ProjectCreateModal} from './src/managers/project-file-manager'; + export {getStatusIcon} from './src/icon'; + export {ContentComponent} from './src/components/features/task/view/content'; + export {TaskRendererComponent} from './src/components/features/gantt/task-renderer'; + export {MarkdownStatusSync} from './src/services/markdown-status-sync'; + export {registerGanttPan} from './src/components/features/gantt/drag-pan'; + export {QuadrantColumnComponent} from './src/components/features/quadrant/quadrant-column'; + export {FluentSidebar} from './src/components/features/fluent/components/FluentSidebar'; + export {DataflowOrchestrator} from './src/dataflow/Orchestrator'; + export {QuickCaptureModal} from './src/components/features/quick-capture/modals/QuickCaptureModalWithSwitch'; + export {getStatusText} from './src/components/features/task/view/details'; + export {TaskPlanner} from './src/components/features/planner/TaskPlanner'; + export {GanttComponent} from './src/components/features/gantt/gantt'; + export {TaskDetailsModal} from './src/components/features/task/edit/TaskDetailsModal'; + export {TaskMetadataEditor} from './src/components/features/task/edit/MetadataEditor'; + export {KanbanComponent} from './src/components/features/kanban/kanban'; + export {QuadrantComponent,QUADRANT_DEFINITIONS} from './src/components/features/quadrant/quadrant'; + export {TableView} from './src/components/features/table/TableView'; + export {TableRenderer} from './src/components/features/table/TableRenderer'; + export {TopNavigation} from './src/components/features/fluent/components/FluentTopNavigation'; + export {SavedTaskFilterModal} from './src/components/features/fluent/components/SavedTaskFilterModal'; + export {FluentLayoutManager} from './src/components/features/fluent/managers/FluentLayoutManager'; + export {FluentDataManager} from './src/components/features/fluent/managers/FluentDataManager'; + export {FluentComponentManager} from './src/components/features/fluent/managers/FluentComponentManager'; + export {FluentActionHandlers} from './src/components/features/fluent/managers/FluentActionHandlers'; + export {CalendarComponent} from './src/components/features/calendar'; + export {ViewComponentManager} from './src/components/ui/behavior/ViewComponentManager'; + export {FluentTaskView} from './src/pages/FluentTaskView'; + export {HabitModal} from './src/integrations/habits/ui/habit-modal'; + export {PointsDashboard} from './src/components/features/rewards/PointsDashboard'; + export {snapshotViewSettings} from './src/services/view-settings-signature'; + export {AuthMiddleware} from './src/mcp/auth/AuthMiddleware'; + export {ProjectList} from './src/components/features/fluent/components/ProjectList'; + export * from './tests/ui-audit/fixture.mjs';`,resolveDir:process.cwd(),loader:'ts'}, + bundle:true,format:'esm',platform:'node',outfile:path.join(directory,'ui.mjs'),loader:{'.css':'empty'},logLevel:'silent', + alias:{'@':path.resolve('src'),'moment':createRequire(require.resolve('obsidian/package.json')).resolve('moment')}, + plugins:[{name:'isolated-ui-dependencies',setup(builder){ + builder.onResolve({filter:/^obsidian$/},()=>({path:path.resolve('tests/ui-audit/fixture.mjs')})); + builder.onLoad({filter:/\.tsx?$/},args=>{ + if(!args.path.startsWith(path.resolve('src'))||owned.includes(args.path))return; + if(args.path.endsWith(path.normalize('components/ui/suggest/index.ts')))return{contents:`import {StubComponent} from ${JSON.stringify(path.resolve('tests/ui-audit/fixture.mjs'))};export const SuggestManager=StubComponent;export const UniversalEditorSuggest=StubComponent;`}; + if(args.path.endsWith(path.normalize('editor-extensions/core/markdown-editor.ts')))return{contents:`export class EmbeddableMarkdownEditor {} +export function createEmbeddableMarkdownEditor(app,root,options){const input=root.createEl('textarea');input.setAttribute('aria-label','Markdown editor');input.value=options.value||'';const editor={get value(){return input.value;},set(value){input.value=value;},destroy(){input.remove();},editor:{focus(){input.focus();}}};input.addEventListener('input',()=>options.onChange?.({}));return editor;}`}; + if(args.path.endsWith(path.normalize('translations/helper.ts')))return{contents:'export const t = s=>s; export const settingsText = s=>s;'}; + if(args.path.endsWith(path.normalize('common/setting-definition.ts')))return{contents:'export const getViewSettingOrDefault=(p,id)=>p.settings.viewConfiguration.find(v=>v.id===id)??{id,name:id}; export const DEFAULT_SETTINGS={};'}; + if(args.path.endsWith(path.normalize('utils/task/task-filter-utils.ts')))return{contents:'export const filterTasks=tasks=>tasks;'}; + if(args.path.endsWith(path.normalize('commands/sortTaskCommands.ts')))return{contents:'export const sortTasks=tasks=>tasks;'}; + if(args.path.endsWith(path.normalize('dataflow/createDataflow.ts')))return{contents:'export const isDataflowEnabled=p=>!!p.dataflowOrchestrator;'}; + if(args.path.endsWith(path.normalize('utils/grouping/groupByStorage.ts')))return{contents:'export const getGroupByConfig=()=>"none";export const setGroupByConfig=()=>{};export const getGroupExpandedState=()=>globalThis.testGroupExpandedState??true;export const setGroupExpandedState=()=>{};'}; + const tree=ts.createSourceFile(args.path,fs.readFileSync(args.path,'utf8'),ts.ScriptTarget.Latest,true); + const exports=[];let defaultClass=false; + for(const node of tree.statements){ + if(!node.modifiers?.some(m=>m.kind===ts.SyntaxKind.ExportKeyword))continue; + if(ts.isClassDeclaration(node)){if(node.modifiers.some(m=>m.kind===ts.SyntaxKind.DefaultKeyword))defaultClass=true;else if(node.name)exports.push(`export const ${node.name.text}=StubComponent;`);} + if(ts.isFunctionDeclaration(node)&&node.name)exports.push(`export const ${node.name.text}=(...args)=>args[0];`); + if(ts.isVariableStatement(node))for(const d of node.declarationList.declarations)if(ts.isIdentifier(d.name))exports.push(`export const ${d.name.text}={};`); + } + return{contents:`import {StubComponent} from ${JSON.stringify(path.resolve('tests/ui-audit/fixture.mjs'))};\n${exports.join('\n')}\n${defaultClass?'export default StubComponent;':''}`}; + }); + }}], +}); +const {ForecastComponent,getTaskStatusGroup,getNextTaskStatusMark,getPausedTaskMarks,Component,Platform,FluentLayoutManager,TaskGeniusIconManager,calendarWeekNumber,projectFolderContainer,getStatusIcon,ProjectFileManager,ProjectEditModal,ProjectCreateModal,openPeriodNote,attachDateTimePicker,QuickCaptureModal,getStatusText,DataflowOrchestrator,TaskPlanner,GanttComponent,TaskDetailsModal,TaskMetadataEditor,KanbanComponent,QuadrantComponent,QUADRANT_DEFINITIONS,TableView,TableRenderer,FluentSidebar,Menu,QuadrantColumnComponent,registerGanttPan,MarkdownStatusSync,TaskRendererComponent,SavedTaskFilterModal,ContentComponent,TopNavigation,FluentDataManager,FluentComponentManager,FluentActionHandlers,CalendarComponent,ViewComponentManager,FluentTaskView,HabitModal,PointsDashboard,snapshotViewSettings,AuthMiddleware,ProjectList,vaultFixture,moment}=await import(pathToFileURL(path.join(directory,'ui.mjs'))); +function environment(){ + const dom=new JSDOM('',{url:'https://obsidian.invalid',pretendToBeVisual:true});installObsidianDom(dom.window); + globalThis.window=dom.window;globalThis.document=dom.window.document;globalThis.HTMLElement=dom.window.HTMLElement;globalThis.Window=dom.window.Window;globalThis.Event=dom.window.Event;globalThis.Document=dom.window.Document; + const frames=new Map();let sequence=0; + window.requestAnimationFrame=fn=>{frames.set(++sequence,fn);return sequence;};window.cancelAnimationFrame=id=>frames.delete(id); + const tick=()=>{const pending=[...frames.values()];frames.clear();pending.forEach(fn=>fn());}; + globalThis.IntersectionObserver=class{observe(){}unobserve(){}disconnect(){}}; + const f=vaultFixture(),storage=new Map();f.app.loadLocalStorage=k=>storage.get(k);f.app.saveLocalStorage=(k,v)=>storage.set(k,v); + const plugin={app:f.app,settings:{quickCapture:{targetType:'fixed',targetFile:'Tasks.md',dailyNoteSettings:{folder:'Journal',format:'YYYY-MM-DD'},rememberLastMode:false},preferMetadataFormat:'tasks',taskStatuses:{completed:'x',inProgress:'/',abandoned:'-',planned:'?',notStarted:' ',archived:'a'},viewConfiguration:[{id:'inbox',name:'Inbox'},{id:'projects',name:'Projects'},{id:'calendar',name:'Calendar',specificConfig:{viewType:'calendar',firstDayOfWeek:1}}],defaultViewMode:'list',taskTimer:{enabled:false}},preloadedTasks:[]}; + return{...f,dom,tick,frames,plugin,close:()=>dom.window.close()}; +} +// The isolated fixture initializes components through addChild/onload, and +// does not expose Obsidian's load method for this directly hosted editor. +Component.prototype.load ||= function(){this.onload?.();}; +TaskMetadataEditor.prototype.load ||= function(){this.onload();}; +const task=(id)=>({id,content:id,filePath:'Tasks.md',status:' ',completed:false,metadata:{}}); +test('old project preferences cannot resurrect deleted projects or replace canonical identifiers',()=>{ + const e=environment();e.plugin.settings.projectConfig={customProjects:[{id:'old-real-id',name:'Real',displayName:'Real',color:'#123'},{id:'ghost-id',name:'Deleted'}]}; + const list=Object.create(ProjectList.prototype);list.plugin=e.plugin;list.projects=[{id:'Real',name:'Real',filterKey:'Real'}];list.loadCustomProjects(); + assert.deepEqual(list.projects.map(project=>project.name),['Real']);assert.equal(list.projects[0].id,'Real');e.close(); +}); +test('search stays available in specialized task views and retains its text across view changes',()=>{ + const e=environment(),root=document.body.createDiv(),queries=[]; + const nav=new TopNavigation(root,e.plugin,value=>queries.push(value),()=>{},()=>{},()=>{},()=>{},[]); + const input=root.querySelector('input'); input.value='project:Writing'; input.dispatchEvent(new window.Event('input')); + nav.updateContext('gantt');nav.updateAvailableModes([]); + assert.notEqual(root.style.display,'none');assert.equal(input.value,'project:Writing');assert.deepEqual(queries,['project:Writing']); + nav.updateContext('points');assert.notEqual(root.style.display,'none');nav.updateContext('tags');assert.notEqual(root.style.display,'none');e.close(); +}); +test('structured searches and saved filters apply the same include and exclude rules',()=>{ + const e=environment();e.plugin.settings.taskStatuses={completed:'x',inProgress:'/',planned:'?',abandoned:'-',notStarted:' '}; + const state={liveFilterState:null,currentFilterState:null,viewStateFilters:{},selectedProject:undefined,searchQuery:'project:Writing AND priority:>=3',filterInputValue:'',activeTaskPreset:null}; + const manager=new FluentDataManager(e.plugin,()=> 'inbox',()=>state,()=>false); + const rows=[{...task('write'),metadata:{project:'Writing',priority:4}},{...task('low'),metadata:{project:'Writing',priority:1}},{...task('other'),metadata:{project:'Other',priority:5}}]; + assert.deepEqual(manager.applyFilters(rows).map(item=>item.id),['write']);state.searchQuery=''; + state.activeTaskPreset={includeCompleted:true,includeInProgress:true,includeAbandoned:true,includeNotStarted:true,includePlanned:true,includeParentTasks:false,includeChildTasks:false,includeSiblingTasks:false,advancedFilterQuery:'project:Writing',filterMode:'EXCLUDE'}; + assert.deepEqual(manager.applyFilters(rows).map(item=>item.id),['other']);e.close(); +}); +test('table views receive the filtered task list rather than rebuilding from all tasks',()=>{ + const e=environment(),root=document.body.createDiv();let received=null; + const manager=new FluentComponentManager(e.app,e.plugin,root,{addChild:child=>child},{}); + const table={containerEl:root.createDiv(),updateTasks:tasks=>received=tasks}; + manager.hideAllComponents=()=>{};manager.viewComponentManager={isSpecialView:()=>true,showComponent:()=>table}; + const all=[task('one'),task('two')];manager.switchView('table',all,[all[1]],null,'list'); + assert.deepEqual(received.map(item=>item.id),['two']);e.close(); +}); +test('points and rewards share one page with the original bonus list and reward wishes',async()=>{ + const e=environment();e.plugin.settings.rewards={rewardItems:[],pointsLedger:[]}; + await e.app.vault.createFolder('99_System/01_Data'); + await e.app.vault.create('99_System/01_Data/积分系统数据.md','---\n'+JSON.stringify({manualPointRecords:[{id:'old',date:'2026-11-01',text:'Original reward history',points:30}],examplePropertyLeft:['Read a book + 50'],examplePropertyRight:['A trip - 5000']})+'\n---\n'); + const root=document.body.createDiv(),page=new PointsDashboard(e.app,e.plugin,root,true);page.onload();await new Promise(resolve=>setTimeout(resolve,0)); + assert.match(root.textContent,/Read a book \+ 50/);assert.match(root.textContent,/A trip - 5000/);assert.match(root.textContent,/30/); + const rewardRoot=document.body.createDiv(),rewards=new PointsDashboard(e.app,e.plugin,rewardRoot,false,"rewards");rewards.onload();await new Promise(resolve=>setTimeout(resolve,0)); + assert.match(rewardRoot.textContent,/A trip - 5000/);assert.match(rewardRoot.textContent,/Read a book/);assert.match(rewardRoot.textContent,/30/);rewards.unload(); + const history=[...root.querySelectorAll('[role="tab"]')].find(button=>button.textContent==='Points history');history.click();assert.match(root.textContent,/Original reward history/); + const input=root.querySelector('.tg-points-tools input');input.value='no match';input.dispatchEvent(new window.Event('input'));assert.doesNotMatch(root.querySelector('.tg-points-body').textContent,/Original reward history/); + page.unload();e.close(); +}); +function contentFixture(e){ + const root=document.body.createDiv();const content=new ContentComponent(root,e.app,e.plugin);content.onload();content.isContainerVisible=()=>true;return content; +} +test('a hidden pending render keeps the newest task snapshot, then renders without a manual refresh',()=>{ + const e=environment(),c=contentFixture(e);let visible=false;c.isContainerVisible=()=>visible; + c.setTasks([task('old')],[task('old')]);e.tick();assert.equal(c.pendingForceRefresh,true); + c.setTasks([task('new')],[task('new')]);assert.equal(c.allTasks[0].id,'new'); + visible=true;e.app.workspace.trigger('active-leaf-change');e.tick(); + assert.equal(c.taskComponents[0].task.id,'new');assert.equal(c.isRendering,false);c.onunload();e.close(); +}); +test('list/tree toggles share the top navigation state and remain responsive on consecutive clicks',()=>{ + const e=environment(),c=contentFixture(e);const navRoot=document.body.createDiv(); + const modes=[];const nav=new TopNavigation(navRoot,e.plugin,()=>{},mode=>{modes.push(mode);c.setIsTreeView(mode==='tree');},()=>{},()=>{},()=>{}); + c.topNavigation=nav;c.toggleViewMode();c.toggleViewMode();c.toggleViewMode(); + assert.deepEqual(modes,['tree','list','tree']);assert.equal(c.isTreeView,true);assert.equal(nav.currentViewMode,'tree'); + c.setViewMode('inbox');assert.equal(c.isTreeView,true);c.onunload();e.close(); +}); +test('a synchronous render does not retain a delayed render lock or discard forced updates',()=>{ + const e=environment(),c=contentFixture(e); + c.setTasks([task('one')],[task('one')],true);c.setTasks([task('two')],[task('two')]);e.tick(); + assert.equal(c.taskComponents[0].task.id,'two');assert.equal(c.isRendering,false); + c.setTasks([task('three')],[task('three')]);e.tick();assert.equal(c.taskComponents[0].task.id,'three'); + c.onunload();assert.equal(e.frames.size,0);e.close(); +}); +test('a late task load cannot replace a newer load, or update a disposed view',async()=>{ + const e=environment();const pending=[];e.plugin.dataflowOrchestrator={getQueryAPI:()=>({getAllTasks:()=>new Promise(resolve=>pending.push(resolve))})}; + const manager=new FluentDataManager(e.plugin,()=> 'inbox',()=>({}),()=>false);const loaded=[];manager.setCallbacks({onTasksLoaded:tasks=>loaded.push(tasks)}); + const old=manager.loadTasks(false),recent=manager.loadTasks(false);pending[1]([task('recent')]);await recent;pending[0]([task('stale')]);await old; + assert.deepEqual(loaded.map(tasks=>tasks[0].id),['recent']);const closed=manager.loadTasks(false);manager.onunload();pending[2]([task('closed')]);await closed;assert.equal(loaded.length,1);e.close(); +}); +test('cache-ready notifications are registered before the index exists and registration is idempotent',async()=>{ + const e=environment(),m=new FluentDataManager(e.plugin,()=> 'inbox',()=>({}),()=>false);let loads=0;m.loadTasks=async()=>{loads++;}; + await m.registerDataflowListeners();await m.registerDataflowListeners();e.app.workspace.trigger('task-genius:cache-ready');await Promise.resolve();assert.equal(loads,1);m.unload();e.close(); +}); +test('calendar next/previous/today update the existing header for all built-in periods',()=>{ + const e=environment(),calendar=new CalendarComponent(e.app,e.plugin,document.body.createDiv());calendar.dateDisplayEl=document.body.createSpan(); + for(const mode of ['month','week','year','day']){ + calendar.currentViewMode=mode;calendar.currentDate=moment('2026-11-08');let engine=moment('2026-11-08'); + calendar.tgCalendar={next(){engine.add(1,mode);calendar.updateDateHeader(engine.toDate());},prev(){engine.subtract(1,mode);calendar.updateDateHeader(engine.toDate());},today(){engine=moment();calendar.updateDateHeader(engine.toDate());}}; + calendar.updateDateHeader();const before=calendar.dateDisplayEl.textContent;calendar.navigate('next');assert.notEqual(calendar.dateDisplayEl.textContent,before,mode);calendar.navigate('prev');assert.equal(calendar.dateDisplayEl.textContent,before,mode);calendar.goToToday();assert.equal(calendar.currentDate.format('YYYY-MM-DD'),moment().format('YYYY-MM-DD')); + } + e.close(); +}); +test('projects overview leaves the sidebar project shortcuts enabled and selection coherent',()=>{ + const e=environment();const view=Object.create(FluentTaskView.prototype);let enabled,selected; + Object.assign(view,{app:e.app,plugin:e.plugin,loadedFilterKey:':projects',dataManager:{applyFilters:tasks=>tasks},isInitializing:false,isLoading:false,loadError:null,currentViewId:'projects',viewState:{viewMode:'list'},tasks:[task('a')],filteredTasks:[task('a')],topNavigation:{updateAvailableModes(){},updateContext(){},setViewMode(){},setActivePreset(){}},layoutManager:{updateTaskMark(){},setSidebarActiveItem(){},setActiveProject:value=>selected=value,sidebar:{setProjectListEnabled:value=>enabled=value}},selectionManager:{updateTaskCache(){}},componentManager:{getAvailableModesForView:()=>[],switchView(){}},ensureViewModeForView:()=> 'list'}); + view.updateView();assert.equal(enabled,true);assert.equal(selected,null); + view.viewState.selectedProject='毕业设计';view.updateView();assert.equal(selected,'毕业设计');e.close(); +}); +test('an empty task cache does not replace the independent habit page with a task empty state',()=>{ + const e=environment();const view=Object.create(FluentTaskView.prototype);let switched=false,empty=false; + Object.assign(view,{app:e.app,plugin:e.plugin,loadedFilterKey:':habit',dataManager:{applyFilters:tasks=>tasks},isInitializing:false,isLoading:false,loadError:null,currentViewId:'habit',viewState:{viewMode:'list'},tasks:[],filteredTasks:[],layoutManager:{updateTaskMark(){},setSidebarActiveItem(){},setActiveProject(){},sidebar:{setProjectListEnabled(){}}},selectionManager:{updateTaskCache(){}},componentManager:{getAvailableModesForView:()=>[],isContentBasedView:()=>false,switchView(){switched=true;},renderEmptyState(){empty=true;}},ensureViewModeForView:()=> 'list'}); + view.updateView();assert.equal(switched,true);assert.equal(empty,false);e.close(); +}); +test('settings refresh preserves view state while refreshing navigation, configuration and data',async()=>{ + const view=Object.create(FluentTaskView.prototype),order=[];const state={viewMode:'tree',selectedProject:'project'}; + Object.assign(view,{isInitializing:false,viewState:state,layoutManager:{sidebar:{render:()=>order.push('sidebar')},updateActionButtons:()=>order.push('actions')},componentManager:{refreshConfiguration:()=>order.push('configuration')},dataManager:{loadTasks:async()=>order.push('data')}}); + await view.refreshSettings();assert.equal(view.viewState,state);assert.deepEqual(order,['sidebar','configuration','actions','data']); +}); + +test('both native close-control versions dismiss the habit dialog even when document click bubbling is blocked',()=>{ + const e=environment(); + for(const css of ['modal-header-button','modal-close-button']){ + const modal=new HabitModal(e.app,{},()=>{});modal.build=()=>{}; + const button=modal.modalEl.querySelector('.modal-header-button');button.className=css;modal.onOpen(); + const swallow=event=>event.stopPropagation();document.addEventListener('click',swallow,true); + button.dispatchEvent(new window.MouseEvent('pointerup',{bubbles:true,button:0})); + assert.equal(modal.containerEl.isConnected,false);assert.equal(modal.modalEl.querySelector('.tg-habit-modal-close'),null); + document.removeEventListener('click',swallow,true); + } + e.close(); +}); + +test('view settings snapshots detect in-place changes without treating navigation persistence as configuration changes',()=>{ + const settings={viewConfiguration:[{id:'a',name:'Original',visible:true}],workspaces:{activeView:'a'}}; + const initial=snapshotViewSettings(settings);settings.workspaces.activeView='b';assert.equal(snapshotViewSettings(settings),initial); + settings.viewConfiguration[0].name='Renamed';assert.notEqual(snapshotViewSettings(settings),initial); +}); +test('unchanged top-navigation modes preserve the existing tab elements during data refresh',()=>{ + const e=environment();const nav=new TopNavigation(document.body.createDiv(),e.plugin,()=>{},()=>{},()=>{},()=>{},()=>{}); + const tab=nav.containerEl.querySelector('[data-mode="list"]');nav.updateAvailableModes(['list','kanban','tree','calendar']);assert.equal(nav.containerEl.querySelector('[data-mode="list"]'),tab);e.close(); +}); +test('cached calendar configuration changes refresh the existing instance and preserve its date',()=>{ + const e=environment();const parent={addChild:c=>c,removeChild:c=>c.unload()};const manager=new ViewComponentManager(parent,e.app,e.plugin,document.body.createDiv(),{}); + const calendar=manager.getOrCreateComponent('calendar');const selected=calendar.currentDate;let refreshed=0;calendar.refreshConfiguration=()=>{refreshed++;}; + e.plugin.settings.viewConfiguration.find(v=>v.id==='calendar').specificConfig.hideWeekends=true; + assert.equal(manager.getOrCreateComponent('calendar'),calendar);assert.equal(calendar.currentDate,selected);assert.equal(refreshed,1);e.close(); +}); + +test('task updates arriving during initialization are replayed when the view becomes ready',async()=>{ + const e=environment();let initializing=true,loads=0;const manager=new FluentDataManager(e.plugin,()=> 'inbox',()=>({}),()=>initializing);manager.loadTasks=async()=>{loads++;}; + await manager.registerDataflowListeners();e.app.workspace.trigger('task-genius:task-cache-updated');await new Promise(resolve=>setTimeout(resolve,550));assert.equal(loads,0); + initializing=false;await manager.finishInitialization();assert.equal(loads,1);manager.unload();e.close(); +}); + +test('real calendar engine navigation keeps month, week, day and year headers synchronized',()=>{ + const e=environment();globalThis.getComputedStyle=window.getComputedStyle.bind(window);globalThis.requestAnimationFrame=window.requestAnimationFrame; + const calendar=new CalendarComponent(e.app,e.plugin,document.body.createDiv());calendar.currentDate=moment('2026-11-08'); + for(const mode of ['month','week','day','year']){ + calendar.currentViewMode=mode;calendar.render();const first=calendar.dateDisplayEl.textContent; + calendar.navigate('next');assert.notEqual(calendar.dateDisplayEl.textContent,first,mode); + calendar.navigate('prev');assert.equal(calendar.dateDisplayEl.textContent,first,mode); + if(mode==='year')assert.equal(calendar.containerEl.querySelectorAll('.calendar-mini-month').length,12); + } + calendar.tgCalendar?.destroy();calendar.containerEl.remove();e.close(); +}); + +test('new MCP tokens keep the existing format and do not use Math.random',()=>{ + const original=Math.random;Math.random=()=>{throw new Error('Weak randomness must not be used');}; + try{const token=AuthMiddleware.generateToken();assert.match(token,/^[A-Za-z0-9]{32}$/);}finally{Math.random=original;} +}); + +test('project names containing quotes and brackets can be selected without selector errors',()=>{ + const e=environment(),list=Object.create(ProjectList.prototype);list.containerEl=document.body.createDiv(); + const id='项目 "A" [阶段一]';const item=list.containerEl.createDiv({cls:'fluent-project-item'});item.dataset.projectId=id; + assert.doesNotThrow(()=>list.setActiveProject(id));assert.equal(item.classList.contains('is-active'),true);list.setActiveProject(null);assert.equal(item.classList.contains('is-active'),false);e.close(); +}); +test('a removed sidebar project list cannot render after its pending query completes',async()=>{ + const e=environment();let resolve;const list=Object.create(ProjectList.prototype);let renders=0; + Object.assign(list,{disposed:false,projectLoad:0,containerEl:document.body.createDiv(),plugin:{dataflowOrchestrator:{getQueryAPI:()=>({getAllTasks:()=>new Promise(done=>resolve=done)})}},render:()=>renders++}); + const load=list.loadProjects();list.onunload();resolve([]);await load;assert.equal(renders,0);e.close(); +}); + +test('custom year and agenda views use their base period for navigation and header labels',()=>{ + const e=environment();e.plugin.settings.customCalendarViews=[{id:'custom-year',enabled:true,baseViewType:'year'},{id:'custom-agenda',enabled:true,baseViewType:'agenda'}];const calendar=new CalendarComponent(e.app,e.plugin,document.body.createDiv());calendar.currentDate=moment('2026-11-08'); + calendar.currentViewMode='custom-year';assert.equal(calendar.getViewUnit(),'year');assert.equal(calendar.getCurrentDateDisplay(),'2026');calendar.currentViewMode='custom-agenda';assert.equal(calendar.getViewUnit(),'week');assert.ok(calendar.getCurrentDateDisplay().includes('2026'));e.close(); +}); + +test('header has a preset menu without a separate preset dropdown or cycle selector',()=>{ + const e=environment(),root=document.body.createDiv(); + const nav=new TopNavigation(root,e.plugin,()=>{},()=>{},()=>{},()=>{},()=>{}); + assert.equal(root.querySelector('.tg-saved-filter-select'),null);assert.ok(root.querySelector('.tg-quick-filter-button')); + nav.showCycleSelector('default');assert.equal(root.querySelector('.fluent-nav-cycle-selector-wrapper').style.display,'none'); + nav.unload();e.close(); +}); +test('the saved-filter editor provides status choices instead of a handwritten status field',()=>{ + const e=environment();e.plugin.settings.taskFilter={presetTaskFilters:[]}; + const modal=new SavedTaskFilterModal(e.app,e.plugin,'',()=>{});modal.onOpen(); + const selects=[...modal.contentEl.querySelectorAll('select')]; + assert.ok(selects.some(select=>[...select.options].some(option=>option.value==='completed'))); + assert.ok(selects.some(select=>[...select.options].some(option=>option.value==='date'))); + assert.equal([...modal.contentEl.querySelectorAll('input')].filter(input=>input.type==='text').length,1); + modal.close();e.close(); +}); +test('switching pages hides the combined points page so it cannot cover a task view',()=>{ + const e=environment(),root=document.body.createDiv(),manager=new FluentComponentManager(e.app,e.plugin,root,{addChild:child=>child},{}); + for(const key of ['contentComponent','pointsComponent','calendarComponent'])manager[key]={containerEl:root.createDiv()}; + manager.hideAllComponents(true); + for(const key of ['contentComponent','pointsComponent','calendarComponent'])assert.equal(manager[key].containerEl.style.display,'none'); + e.close(); +}); + +test('project Gantt bar drags and resize handles dispatch date changes instead of opening the note',()=>{ + const e=environment(),svg=document.createElementNS('http://www.w3.org/2000/svg','svg');document.body.append(svg); + const group=svg.createSvg('g'),renderer=new TaskRendererComponent(e.app,group),changes=[];let opened=0; + const project={...task('project'),metadata:{projectPlan:true,startDate:new Date(2026,10,8).getTime(),dueDate:new Date(2026,10,10).getTime()}}; + const params={app:e.app,taskGroupEl:group,dayWidth:50,preparedTasks:[{task:project,y:20,startX:100,width:150,isMilestone:false,level:0}],showTaskLabels:false,useMarkdownRenderer:false,parentComponent:renderer,handleTaskClick:()=>opened++,handleTaskContextMenu(){},onDateChange:(task,days,edge)=>changes.push({days,edge})}; + renderer.updateParams(params); + const pointer=(type,x)=>new window.MouseEvent(type,{bubbles:true,button:0,clientX:x}); + group.querySelector('.gantt-task-bar').dispatchEvent(pointer('pointerdown',100));document.dispatchEvent(pointer('pointermove',200));assert.match(document.querySelector('.gantt-drag-date-hint').textContent,/2026-11-10.*2026-11-12/);document.dispatchEvent(pointer('pointerup',200));assert.equal(document.querySelector('.gantt-drag-date-hint'),null); + assert.deepEqual(changes,[{days:2,edge:'move'}]);assert.equal(opened,0); + renderer.updateParams(params); + group.querySelector('[data-edge="end"]').dispatchEvent(pointer('pointerdown',250));document.dispatchEvent(pointer('pointermove',300));document.dispatchEvent(pointer('pointerup',300)); + assert.deepEqual(changes[1],{days:1,edge:'end'});renderer.unload();e.close(); +}); + +test('reading-view file changes add and remove completion dates through the vault API',async()=>{ + const e=environment(),file=await e.app.vault.create('Tasks.md','- [ ] Exercise'); + e.app.workspace.getActiveFile=()=>file;e.plugin.settings.taskStatuses={completed:'x|X'};e.plugin.settings.preferMetadataFormat='tasks'; + const sync=new MarkdownStatusSync(e.plugin);sync.onload();await new Promise(resolve=>setTimeout(resolve,0)); + e.text.set(file.path,'- [x] Exercise');e.app.vault.trigger('modify',file);await new Promise(resolve=>setTimeout(resolve,0)); + assert.match(e.text.get(file.path),/^- \[x\] Exercise ✅ \d{4}-\d{2}-\d{2}$/); + e.text.set(file.path,e.text.get(file.path).replace('[x]','[ ]'));e.app.vault.trigger('modify',file);await new Promise(resolve=>setTimeout(resolve,0)); + assert.equal(e.text.get(file.path),'- [ ] Exercise');sync.unload();e.close(); +}); +test('list and tree buttons actually change the rendered content on consecutive clicks',()=>{ + const e=environment(),c=contentFixture(e),root=document.body.createDiv(); + const manager=new FluentComponentManager(e.app,e.plugin,root,{addChild:child=>child},{}); + manager.contentComponent=c;manager.viewComponentManager={isSpecialView:()=>false,hideAllComponents(){}}; + const rows=[task('parent'),{...task('child'),metadata:{parent:'parent'}}];rows[0].metadata.children=['child']; + const nav=new TopNavigation(root,e.plugin,()=>{},mode=>manager.switchView('inbox',rows,rows,null,mode),()=>{},()=>{},()=>{});c.topNavigation=nav; + manager.switchView('inbox',rows,rows,null,'list');e.tick(); + for(const mode of ['tree','list','tree','list']){root.querySelector(`[data-mode="${mode}"]`).click();e.tick();assert.equal(c.isTreeView,mode==='tree');assert.equal(c.isRendering,false);assert.equal(c.filteredTasks.length,2);} + c.onunload();nav.unload();e.close(); +}); + +test('Gantt background dragging pans the chart without stealing bar resize gestures',()=>{ + const e=environment(),root=document.body.createDiv();let cleanup; + registerGanttPan({register:fn=>cleanup=fn,registerDomEvent:(element,type,handler)=>element.addEventListener(type,handler)},root); + root.scrollLeft=100;root.scrollTop=30; + const pointer=(type,x,y)=>new window.MouseEvent(type,{bubbles:true,button:0,clientX:x,clientY:y}); + root.dispatchEvent(pointer('pointerdown',100,80));document.dispatchEvent(pointer('pointermove',70,60));document.dispatchEvent(pointer('pointerup',70,60)); + assert.equal(root.scrollLeft,130);assert.equal(root.scrollTop,50);assert.equal(root.classList.contains('is-panning'),false); + const bar=root.createDiv({cls:'gantt-task-item'});bar.dispatchEvent(pointer('pointerdown',100,80));document.dispatchEvent(pointer('pointermove',60,60)); + assert.equal(root.scrollLeft,130);cleanup();e.close(); +}); + +test('matrix filtering to zero clears old cards and rapid filter switches discard stale batches',async()=>{ + const e=environment(),root=document.body.createDiv(); + const column=new QuadrantColumnComponent(e.app,e.plugin,root,{id:'urgent-important',title:'Important',icon:'star',className:'test-quadrant'},{});column.onload(); + column.setTasks(Array.from({length:12},(_,i)=>task('old-'+i)));column.setTasks([]); + await new Promise(resolve=>setTimeout(resolve,25));assert.equal(root.querySelectorAll('[data-task-id]').length,0);assert.equal(root.querySelectorAll('.tg-quadrant-empty-state').length,1); + column.setTasks(Array.from({length:12},(_,i)=>task('stale-'+i)));column.setTasks([task('new')]); + await new Promise(resolve=>setTimeout(resolve,25));assert.deepEqual([...root.querySelectorAll('[data-task-id]')].map(el=>el.dataset.taskId),['new']);assert.equal(root.querySelector('.tg-quadrant-empty-state'),null); + column.unload();e.close(); +}); + +test('every system view offers hide in its right-click menu',async()=>{ + const e=environment();e.plugin.saveSettings=async()=>{};e.plugin.settings.viewConfiguration.push({id:'points',name:'Points'},{id:'habit',name:'Habits'},{id:'gantt',name:'Projects Gantt'}); + const sidebar=new FluentSidebar(document.body.createDiv(),e.plugin,()=>{},()=>{});sidebar.render=()=>{}; + for(const id of ['inbox','projects','points','habit','gantt']){ + sidebar.showViewContextMenu(new window.MouseEvent('contextmenu'),id); + const hide=Menu.last.items.find(item=>item.title==='Hide in sidebar');assert.ok(hide,id);await hide.callback(); + assert.equal(e.plugin.settings.viewConfiguration.find(view=>view.id===id).visible,false); + } + e.close(); +}); + +test('search automatically reveals matching tasks inside previously collapsed groups',()=>{ + const e=environment(),c=contentFixture(e);globalThis.testGroupExpandedState=false;c.setSearchQuery('co'); + c.renderGroupContent=(group,content)=>content.setText(group.tasks.map(task=>task.content).join(' ')); + c.renderGroupRecursive({key:'Tasks.md',title:'Tasks.md',tasks:[task('co task')],children:[]},c.taskListEl,new Map(),0); + assert.match(c.taskListEl.textContent,/co task/);assert.notEqual(c.taskListEl.querySelector('.group-section-content').style.display,'none'); + delete globalThis.testGroupExpandedState;c.onunload();e.close(); +}); + +test('table status width remains readable instead of being squeezed by the whole table',()=>{ + const e=environment(),table=document.body.createEl('table'),header=table.createEl('thead'),body=table.createEl('tbody'); + const columns=[{id:'status',title:'Status',width:64,visible:true,sortable:false,resizable:false},{id:'content',title:'Task',width:420,visible:true,sortable:false,resizable:false}]; + const renderer=new TableRenderer(table,header,body,columns,{},e.app,e.plugin);renderer.onload(); + assert.equal(header.querySelector('[data-column-id="status"]').style.width,'112px');assert.equal(table.style.minWidth,'532px'); + renderer.updateColumnWidth('status',50);assert.equal(header.querySelector('[data-column-id="status"]').style.width,'112px');renderer.unload();e.close(); +}); + + +test('header controls share the host action strip and do not duplicate after rerender',()=>{ + const e=environment(),header=document.body.createDiv({cls:'view-header'}),title=header.createDiv({cls:'view-header-title-container'}),actions=header.createDiv({cls:'view-actions'}),native=actions.createEl('button',{text:'Native'}),root=title.createDiv(); + let clicks=0;native.addEventListener('click',()=>clicks++); + const nav=new TopNavigation(root,e.plugin,()=>{},()=>{},()=>{},()=>{},()=>{},[]); + assert.equal(actions.querySelectorAll('.fluent-nav-right').length,1);assert.equal(root.querySelector('.fluent-nav-right'),null); + let customClicks=0;nav.registerCustomButton({id:'test-tool',icon:'list',tooltip:'Tool',onClick:()=>customClicks++}); + nav.render();assert.equal(actions.querySelectorAll('.fluent-nav-right').length,1);actions.querySelector('.fluent-nav-custom-button-wrapper button').click();assert.equal(customClicks,1);nav.notificationCount=7;nav.updateNotificationBadge();assert.equal(actions.querySelector('.fluent-notification-badge').textContent,'7'); + native.click();assert.equal(clicks,1);nav.onunload();assert.equal(actions.querySelector('.fluent-nav-right'),null);assert.equal(native.parentElement,actions);e.close(); +}); + +test('all sidebar views stay visible and drag freely into either region including an empty one',async()=>{ + const e=environment();let saves=0;e.plugin.saveSettings=async()=>{saves++;};e.plugin.settings.changelog={lastVersion:'9.12.0'}; + e.plugin.workspaceManager={isSidebarComponentHidden:id=>id==='projects-list',getActiveWorkspace:()=>({id:'test'}),isViewHidden:()=>false}; + e.plugin.settings.viewConfiguration=[{id:'inbox',name:'Inbox',region:'bottom'},{id:'custom-top',name:'Top',region:'top'},...Array.from({length:12},(_,i)=>({id:'custom-'+i,name:'Custom '+i,region:'bottom'})),{id:'hidden',name:'Hidden',visible:false,region:'bottom'}]; + const root=document.body.createDiv(),sidebar=new FluentSidebar(root,e.plugin,()=>{},()=>{}); + sidebar.ensureSystemViews();assert.equal(e.plugin.settings.viewConfiguration.find(v=>v.id==='inbox').region,'bottom');assert.equal(e.plugin.settings.viewConfiguration.find(v=>v.id==='custom-top').region,'top');sidebar.render(); + const top=root.querySelector('[data-region="top"] .fluent-navigation-list'),bottom=root.querySelector('[data-region="bottom"] .fluent-navigation-list'); + assert.equal(bottom.children.length,13);assert.equal(root.querySelector('[aria-label="More views"]'),null); + const inbox=bottom.querySelector('[data-view-id="inbox"]');top.append(inbox);await sidebar.handleReorder({from:bottom,to:top,oldIndex:0,newIndex:top.children.length-1});assert.equal(e.plugin.settings.viewConfiguration.find(v=>v.id==='inbox').region,'top'); + const item=top.querySelector('[data-view-id="today"]');bottom.append(item);await sidebar.handleReorder({from:top,to:bottom,oldIndex:0,newIndex:bottom.children.length-1});assert.equal(e.plugin.settings.viewConfiguration.find(v=>v.id==='today').region,'bottom'); + e.plugin.settings.viewConfiguration.forEach(v=>v.region='bottom');sidebar.render();assert.equal(root.querySelector('[data-region="top"] .fluent-navigation-list').children.length,0);assert.ok(saves>=2);sidebar.destroySortables();e.close(); +}); + +test('table resizing saves widths once at release to the correct custom view and restores on reopen',()=>{ + const e=environment();let saves=0;e.plugin.saveSettings=async()=>{saves++;};const config={viewType:'table',visibleColumns:['status','content'],columnWidths:{}}; + e.plugin.settings.viewConfiguration.push({id:'custom-table',specificConfig:structuredClone(config)},{id:'table',specificConfig:structuredClone(config)}); + const view=new TableView(e.app,e.plugin,document.body.createDiv(),config,{},'custom-table');view.tableEl=document.body.createEl('table');view.headerEl=view.tableEl.createEl('thead');view.bodyEl=view.tableEl.createEl('tbody');view.initializeChildComponents(); + view.renderer.startResize(new window.MouseEvent('mousedown',{clientX:100}),'content',420);view.renderer.handleMouseMove(new window.MouseEvent('mousemove',{clientX:260}));assert.equal(saves,0);view.renderer.handleMouseUp();view.renderer.handleMouseUp();assert.equal(saves,1); + const saved=e.plugin.settings.viewConfiguration.find(v=>v.id==='custom-table').specificConfig;assert.equal(saved.columnWidths.content,580);assert.deepEqual(e.plugin.settings.viewConfiguration.find(v=>v.id==='table').specificConfig.columnWidths,{}); + const reopened=new TableView(e.app,e.plugin,document.body.createDiv(),structuredClone(saved),{},'custom-table');assert.equal(reopened.columns.find(c=>c.id==='content').width,580);view.renderer.unload();e.close(); +}); + +test('matrix dragging persists explicit placement in every quadrant without changing deadlines or the source object',async()=>{ + const e=environment(),source={...task('a'),metadata:{tags:['#keep','#urgent','#important'],dueDate:Date.now(),priority:5}},matrix=Object.create(QuadrantComponent.prototype);let saved,refreshes=0; + Object.assign(matrix,{plugin:e.plugin,tasks:[source],allTasks:[source],configOverride:{},refresh(){refreshes++;},showUpdateFeedback(){},showErrorFeedback(){throw new Error('write failed');}}); + e.plugin.writeAPI={updateTask:async args=>{saved=args;return {success:true};}}; + for(const quadrant of QUADRANT_DEFINITIONS){await matrix.updateTaskQuadrant('a',quadrant);const reindexed={...source,metadata:structuredClone(saved.updates.metadata)};assert.equal(matrix.determineTaskQuadrant(reindexed),quadrant.id);assert.equal(reindexed.metadata.dueDate,source.metadata.dueDate);assert.ok(reindexed.metadata.tags.includes('#keep'));} + assert.deepEqual(source.metadata.tags,['#keep','#urgent','#important']);assert.equal(refreshes,4);e.close(); +}); + +test('matrix and kanban failed writes keep source properties unchanged and restore their rendered data',async()=>{ + const e=environment(),source={...task('a'),metadata:{tags:['#keep'],priority:3}},matrix=Object.create(QuadrantComponent.prototype),board=Object.create(KanbanComponent.prototype);let matrixRefresh=0,boardRefresh=0; + e.plugin.writeAPI={updateTask:async()=>({success:false,error:'disk failure'})}; + Object.assign(matrix,{plugin:e.plugin,tasks:[source],allTasks:[source],configOverride:{},refresh(){matrixRefresh++;},showErrorFeedback(){}}); + Object.assign(board,{plugin:e.plugin,tasks:[source],allTasks:[source],applyFiltersAndRender(){boardRefresh++;}}); + await matrix.updateTaskQuadrant('a',QUADRANT_DEFINITIONS[0]);await board.handlePropertyUpdate('a','priority',3,'5');await board.handleStatusUpdate('a','x'); + assert.equal(source.metadata.priority,3);assert.equal(source.status,' ');assert.deepEqual(source.metadata.tags,['#keep']);assert.equal(matrixRefresh,1);assert.equal(boardRefresh,2);e.close(); +}); + +test('kanban drag uses the column value rather than its translated title and completes with a date',async()=>{ + const e=environment(),board=Object.create(KanbanComponent.prototype),source={...task('a'),metadata:{tags:[],priority:3}},root=document.body.createDiv();let saved; + Object.assign(board,{plugin:e.plugin,currentViewId:'kanban',tasks:[source],allTasks:[source],configOverride:null,applyFiltersAndRender(){this.tasks=[...this.allTasks];}});e.plugin.settings.viewConfiguration.push({id:'kanban',specificConfig:{groupBy:'priority'}});e.plugin.settings.taskStatuses={completed:'x'}; + e.plugin.writeAPI={updateTask:async args=>{saved=args;return {success:true};}}; + const from=root.createDiv({cls:'tg-kanban-column',attr:{'data-column-value':'3'}}),to=root.createDiv({cls:'tg-kanban-column',attr:{'data-column-value':'5'}});from.createSpan({cls:'tg-kanban-column-title',text:'中等'});to.createSpan({cls:'tg-kanban-column-title',text:'最高'});const a=from.createDiv(),b=to.createDiv(),card=b.createDiv({attr:{'data-task-id':'a'}}); + await board.handleSortEnd({from:a,to:b,item:card,oldIndex:0,newIndex:0});assert.equal(saved.updates.metadata.priority,5);assert.equal(board.allTasks[0].metadata.priority,5);assert.equal(source.metadata.priority,3); + await board.handleStatusUpdate('a','x');assert.equal(saved.updates.completed,true);assert.ok(Number.isFinite(saved.updates.metadata.completedDate));await board.handleStatusUpdate('a',' ');assert.equal(saved.updates.metadata.completedDate,undefined);e.close(); +}); + + +test('task editor preserves task identity and all staged fields, and cancel never writes',async()=>{ + const e=environment(),original={...task('real-id'),line:8,originalMarkdown:'- [ ] Original',content:'Original',metadata:{tags:[],children:[],context:'home',scheduledDate:new Date(2026,10,8,9,30).getTime()}};let saved; + e.plugin.writeAPI={updateTask:async args=>{saved=args;return {success:true};}}; + const modal=new TaskDetailsModal(e.app,e.plugin,original);await modal.onOpen(); + const row=name=>[...modal.contentEl.querySelectorAll('.setting-item')].find(el=>el.querySelector('.setting-item-name')?.textContent===name);const priority=row('Priority').querySelector('select');priority.value='4';priority.dispatchEvent(new window.Event('change'));const complete=modal.contentEl.querySelector('.status-option[aria-label="Completed"] input');assert.ok(complete,JSON.stringify([...modal.contentEl.querySelectorAll('.status-option')].map(el=>({label:el.getAttribute('aria-label'),html:el.innerHTML}))));complete.click();const context=row('Context').querySelector('input');context.value='work';context.dispatchEvent(new window.Event('input')); + await modal.save();assert.equal(saved.taskId,'real-id');assert.equal(saved.updates.line,8);assert.equal(saved.updates.id,'real-id');assert.equal(saved.updates.metadata.priority,4);assert.equal(saved.updates.metadata.context,'work');assert.equal(saved.updates.completed,true);assert.ok(saved.updates.metadata.completedDate); + assert.deepEqual(original.metadata,{tags:[],children:[],context:'home',scheduledDate:new Date(2026,10,8,9,30).getTime()}); + saved=null;const cancel=new TaskDetailsModal(e.app,e.plugin,original);await cancel.onOpen();cancel.taskMetadata.priority=1;cancel.close();assert.equal(saved,null);e.close(); +}); + +test('date editor keeps time until explicitly removed and accepts an optional midnight time',()=>{ + const e=environment(),root=document.body.createDiv(),editor=new TaskMetadataEditor(root,e.app,e.plugin),changes=[]; + editor.task={...task('date'),metadata:{tags:[],children:[],dueDate:new Date(2026,10,12,9,30).getTime(),datePrecision:{dueDate:'datetime'}}};editor.onMetadataChange=event=>{changes.push(event);editor.task.metadata[event.field]=event.value;};editor.createDateEditor(root,'Due Date','dueDate',''); + const input=root.querySelector('input');assert.equal(input.type,'text');assert.equal(input.value,'2026-11-12 09:30'); + input.value='2026-11-13 00:00';input.dispatchEvent(new window.Event('change'));assert.equal(editor.task.metadata.datePrecision.dueDate,'datetime');assert.equal(new Date(editor.task.metadata.dueDate).getHours(),0); + input.value='2026-11-14';input.dispatchEvent(new window.Event('change'));assert.equal(editor.task.metadata.datePrecision.dueDate,'date'); + const before=editor.task.metadata.dueDate;input.value='2026-02-31';input.dispatchEvent(new window.Event('change'));assert.equal(input.getAttribute('aria-invalid'),'true');assert.equal(editor.task.metadata.dueDate,before); + input.value='';input.dispatchEvent(new window.Event('change'));assert.equal(editor.task.metadata.dueDate,undefined);editor.unload();e.close(); +}); + +test('task editor resolves a stale gutter identifier to the indexed task before saving',async()=>{ + const e=environment(),indexed={...task('indexed'),line:3,originalMarkdown:'- [ ] Test',metadata:{tags:[],children:[]}};let saved; + e.plugin.dataflowOrchestrator={getQueryAPI:()=>({getAllTasks:async()=>[indexed]})};e.plugin.writeAPI={updateTask:async args=>{saved=args;return {success:true};}}; + const modal=new TaskDetailsModal(e.app,e.plugin,{...indexed,id:'wrong-gutter-id',line:4});await modal.onOpen();await modal.save();assert.equal(saved.taskId,'indexed');assert.equal(saved.updates.line,3);e.close(); +}); + +test('planner drag sets only the scheduled date, preserves deadline/time, and supports unscheduling',async()=>{ + const e=environment(),deadline=new Date(2026,11,1).getTime(),source={...task('schedule'),metadata:{tags:[],children:[],dueDate:deadline,scheduledDate:new Date(2026,10,10,9,45).getTime(),datePrecision:{scheduledDate:'datetime'}}};let saved; + e.plugin.writeAPI={updateTask:async args=>{saved=args;return {success:true};}}; + const planner=new TaskPlanner(e.plugin,document.body.createDiv());planner.setTasks([source]);assert.equal(planner.containerEl.querySelectorAll('.tg-planner-day').length,42); + await planner.schedule('schedule','2026-11-12');assert.equal(saved.updates.metadata.dueDate,deadline);assert.equal(new Date(saved.updates.metadata.scheduledDate).getHours(),9);assert.equal(new Date(saved.updates.metadata.scheduledDate).getMinutes(),45);assert.equal(new Date(saved.updates.metadata.scheduledDate).getDate(),12); + await planner.schedule('schedule',null);assert.equal(saved.updates.metadata.scheduledDate,undefined);assert.equal(saved.updates.metadata.dueDate,deadline);planner.unload();e.close(); +}); + +test('project Gantt week, month and year each contain exactly the previous/current/next period',()=>{ + const e=environment(),gantt=Object.create(GanttComponent.prototype);Object.assign(gantt,{viewId:'gantt',periodAnchor:new Date(2026,10,12),scrollContainerEl:{clientWidth:900},dateHelper:{daysBetween:(a,b)=>Math.round((b-a)/86400000),addDays:(a,n)=>{const d=new Date(a);d.setDate(d.getDate()+n);return d;}}}); + for(const[scale,start,end]of [['Week',[2026,10,2],[2026,10,23]],['Month',[2026,9,1],[2026,12,1]],['Year',[2025,0,1],[2028,0,1]]]){gantt.projectScale=scale;const range=gantt.calculateDateRange(true);assert.equal(+range.startDate,+new Date(...start));assert.equal(+range.endDate,+new Date(...end));} + e.close(); +}); + +test('unchanged task data repairs a cleared list instead of relying on the manual refresh button',()=>{ + const e=environment(),c=contentFixture(e);c.isTreeView=false;c.setTasks([task('visible')],[task('visible')],true,true);e.tick();assert.ok(c.taskListEl.children.length); + c.taskListEl.replaceChildren();c.setTasks([task('visible')],[task('visible')],false,true);e.tick();assert.ok(c.taskListEl.children.length);c.onunload();e.close(); +}); + + +test('every completed file write, including one with a task id, forces fresh indexing',async()=>{ + const e=environment(),orchestrator=Object.create(DataflowOrchestrator.prototype),calls=[];const file={path:'Tasks.md'}; + Object.assign(orchestrator,{app:e.app,eventRefs:[],processingQueue:new Map(),vault:{getAbstractFileByPath:()=>file},processFileImmediate:async(f,force)=>calls.push([f,force])});orchestrator.subscribeToEvents(); + const listeners=e.app.workspace.handlers.get('task-genius:write-operation-complete');assert.ok(listeners?.size); + for(const listener of listeners)await listener({path:'Tasks.md',taskId:'real-id'}); + assert.deepEqual(calls,[[file,true]]);e.close(); +}); + +test('same-file indexing is serialized so a slow old parse cannot overwrite the final edit',async()=>{ + const e=environment(),orchestrator=Object.create(DataflowOrchestrator.prototype);let release;const old=new Promise(resolve=>release=resolve),events=[]; + Object.assign(orchestrator,{disposed:false,fileProcessing:new Map(),processFileSnapshot:async(file,forced)=>{events.push(forced?'new-start':'old-start');if(!forced)await old;events.push(forced?'new-end':'old-end');}}); + const a=orchestrator.processFileImmediate({path:'Tasks.md'},false),b=orchestrator.processFileImmediate({path:'Tasks.md'},true);await Promise.resolve();await Promise.resolve();assert.deepEqual(events,['old-start']);release();await Promise.all([a,b]);assert.deepEqual(events,['old-start','old-end','new-start','new-end']);e.close(); +}); + + +test('new-task dates infer optional time independently without an include-time toggle',()=>{ + const e=environment(),quick=Object.create(QuickCaptureModal.prototype),root=document.body.createDiv();Object.assign(quick,{taskMetadata:{},updatePreview(){}});quick.createDateInputs(root); + assert.equal(root.querySelector('input[type=checkbox]'),null);assert.equal(quick.startDateInput.type,'text'); + quick.startDateInput.value='2026-11-12';quick.startDateInput.dispatchEvent(new window.Event('input'));quick.dueDateInput.value='2026-11-13 00:00';quick.dueDateInput.dispatchEvent(new window.Event('input')); + assert.equal(quick.formatDate(quick.taskMetadata.startDate),'2026-11-12');assert.equal(quick.formatDate(quick.taskMetadata.dueDate),'2026-11-13 00:00'); + quick.dueDateInput.value='invalid';quick.dueDateInput.dispatchEvent(new window.Event('input'));assert.equal(quick.dueDateInput.getAttribute('aria-invalid'),'true'); + quick.dueDateInput.value='';quick.dueDateInput.dispatchEvent(new window.Event('input'));assert.equal(quick.taskMetadata.dueDate,undefined);assert.equal(quick.taskMetadata.datePrecision.dueDate,undefined);e.close(); +}); + +test('configured legacy pause group and unknown-status fallback both display pause instead of no status',()=>{ + const e=environment();assert.equal(getStatusText('archived',e.plugin.settings),'Paused');assert.equal(getStatusText('paused',e.plugin.settings),'Paused');assert.equal(getStatusText('unmapped',e.plugin.settings),'Paused');e.close(); +}); + + +test('completion points stay in the habit total and are excluded from the points ledger list',()=>{ + const e=environment(),dashboard=Object.create(PointsDashboard.prototype),root=document.body.createDiv(); + Object.assign(dashboard,{app:e.app,plugin:e.plugin,bodyEl:root,query:'',historyFilter:'all',snapshot:{manual:[{id:'manual',date:'2026-11-08',text:'Bonus',points:10}],ledger:[{id:'task:t:2026-11-08',source:'task',createdAt:Date.now(),label:'Task award',delta:2}],automaticTasks:{habitPaths:['Habits/Tasks.md'],days:[{date:'2026-11-08',supplement:3}]},summaries:[{path:'Habits/Tasks.md',name:'Completed task habit',entries:4,points:4,todayPoints:4}]}}); + dashboard.renderHistory();const panels=root.querySelectorAll('.tg-points-panel');assert.match(panels[0].textContent,/Bonus/);assert.doesNotMatch(panels[0].textContent,/Task award|Completed task habit/); + assert.match(panels[1].textContent,/Completed task habit/);assert.equal(panels[1].querySelector('.tg-points-entry').children[1].textContent,'9');e.close(); +}); + + +test('project color and manual order persist in canonical notes without rewriting tasks', async () => { + const e=environment(); + for(const name of ['Alpha','Beta','Gamma']) await e.app.vault.create(`Projects/${name}.md`,'---\n'+JSON.stringify({project:name})+'\n---\n- [ ] Keep original '+name); + const manager=new ProjectFileManager(e.app),before=[...e.text.entries()]; + await manager.update('Beta',{color:'#abcdef'});await manager.reorder(['Gamma','Alpha','Beta']); + const reloaded=new ProjectFileManager(e.app);assert.equal(reloaded.find('Beta').color,'#abcdef'); + assert.deepEqual(['Alpha','Beta','Gamma'].sort((a,b)=>reloaded.compareNames(a,b)),['Gamma','Alpha','Beta']); + assert.deepEqual([...e.text.entries()],before);await assert.rejects(()=>manager.update('Alpha',{color:'invalid'}));e.close(); +}); + +test('dragging a project persists its drop order rather than assigning a task project tag', async()=>{ + const e=environment();for(const name of ['A','B','C']){const file=await e.app.vault.create(`Projects/${name}.md`,'');e.metadata.set(file.path,{frontmatter:{project:name}});} + const manager=new ProjectFileManager(e.app),el=document.body.createDiv();let changed=false;manager.bindReorder(el,'A',()=>['A','B','C'],()=>changed=true); + el.getBoundingClientRect=()=>({top:0,height:40});const event=new window.Event('drop',{bubbles:true,cancelable:true});Object.defineProperties(event,{dataTransfer:{value:{getData:type=>type==='application/x-taskgenius-project'?'C':''}},clientY:{value:5}});el.dispatchEvent(event);await new Promise(resolve=>setTimeout(resolve,0)); + assert.equal(changed,true);assert.deepEqual(manager.list().sort((a,b)=>a.order-b.order).map(p=>p.name),['C','A','B']);e.close(); +}); + +test('view filters restore independent presets, advanced rules and workspace scope after reopening',()=>{ + const e=environment(),view=Object.create(FluentTaskView.prototype);Object.assign(view,{app:e.app,plugin:e.plugin,workspaceId:'one',currentViewId:'inbox',isInitializing:false,viewState:{filters:{}},activeTaskPreset:null,topNavigation:{setActivePreset(id){this.id=id;}}}); + view.restoreViewFilters();view.activeTaskPresetId='builtin-completed';view.liveFilterState={rootCondition:'all',filterGroups:[{id:'due',filters:[]}]};view.saveViewFilters(); + view.currentViewId='calendar';view.restoreViewFilters();assert.equal(view.activeTaskPresetId,null);assert.equal(view.liveFilterState,null);view.activeTaskPresetId='builtin-todo';view.saveViewFilters(); + view.currentViewId='inbox';view.restoreViewFilters();assert.equal(view.activeTaskPresetId,'builtin-completed');assert.equal(view.liveFilterState.filterGroups[0].id,'due'); + view.workspaceId='two';view.restoreViewFilters();assert.equal(view.activeTaskPresetId,null);view.workspaceId='one';view.loadedFilterKey='';view.restoreViewFilters();assert.equal(view.topNavigation.id,'builtin-completed');e.close(); +}); + +test('native date/time selectors support a date only, explicit midnight, and clearing',()=>{ + const e=environment(),root=document.body.createDiv(),input=root.createEl('input');input.value='2026-11-09 08:15';let changed=0;input.addEventListener('change',()=>changed++);attachDateTimePicker(input,'Due date'); + const date=root.querySelector('input[type=date]'),time=root.querySelector('input[type=time]');assert.equal(time.value,'08:15'); + date.value='2026-11-12';date.dispatchEvent(new window.Event('change'));assert.equal(input.value,'2026-11-12 08:15'); + time.value='00:00';time.dispatchEvent(new window.Event('change'));assert.equal(input.value,'2026-11-12 00:00');time.value='';time.dispatchEvent(new window.Event('change'));assert.equal(input.value,'2026-11-12'); + date.value='';date.dispatchEvent(new window.Event('change'));assert.equal(input.value,'');assert.equal(time.disabled,true);assert.equal(changed,4);e.close(); +}); + +test('daily-note destination is selected with a date picker and forwarded to capture options',()=>{ + const e=environment();e.plugin.settings.quickCapture={targetType:'daily-note',dailyNoteSettings:{folder:'Journal',format:'YYYY-MM-DD'}};const capture=new QuickCaptureModal(e.app,e.plugin);capture.plugin=e.plugin;capture.taskMetadata={};capture.sanitizeFilePath=value=>value;capture.tempTargetFilePath='Journal/2026-11-09.md';const root=document.body.createDiv();capture.createTargetFileSelector(root); + const date=root.querySelector('input[type=date]');assert.ok(date);date.value='2026-10-31';date.dispatchEvent(new window.Event('change'));assert.equal(capture.taskMetadata.dailyNoteDate,'2026-10-31');assert.equal(capture.tempTargetFilePath,'Journal/2026-10-31.md');e.close(); +}); + +test('periodic notes reuse existing folders, templates and ISO week years, creating once without overwriting',async()=>{ + const e=environment(),opened=[];e.app.workspace.getLeaf=()=>({openFile:async file=>opened.push(file.path)}); + const settings={};for(const [period,format] of [['daily','YYYY-MM-DD'],['weekly','GGGG-[W]WW'],['monthly','YYYY-MM'],['yearly','YYYY']])settings[period]={enabled:true,folder:`Journal/${period}`,format,template:'Templates/Period'}; + e.text.set('.obsidian/plugins/periodic-notes/data.json',JSON.stringify(settings));await e.app.vault.create('Templates/Period.md','# {{title}}\n{{date:YYYY-MM-DD}}\nKeep original template'); + const date=new Date(2027,0,1,12);for(const period of Object.keys(settings))await openPeriodNote(e.app,period,date); + assert.ok(e.files.has('Journal/weekly/2026-W53.md'));assert.match(e.text.get('Journal/daily/2027-01-01.md'),/# 2027-01-01/); + const file=e.files.get('Journal/daily/2027-01-01.md');e.text.set(file.path,'Existing diary');await Promise.all([openPeriodNote(e.app,'daily',date),openPeriodNote(e.app,'daily',date)]);assert.equal(e.text.get(file.path),'Existing diary'); + assert.equal([...e.files.keys()].filter(path=>path==='Journal/weekly/2026-W53.md').length,1);assert.equal(opened.length,6);e.close(); +}); + +test('calendar week title includes its week number and keeps period-note navigation in the title',()=>{ + const e=environment(),calendar=new CalendarComponent(e.app,e.plugin,document.body.createDiv());calendar.currentDate=moment('2026-11-09');calendar.currentViewMode='week';calendar.renderHeader();assert.match(calendar.dateDisplayEl.textContent,/Week 46/);assert.equal(calendar.headerEl.querySelectorAll('.calendar-period-notes button').length,0);calendar.containerEl.remove();e.close(); +}); + +test('the legacy pause mark and pause names all resolve to the same pause icon',()=>{ + assert.equal(getStatusIcon('archived'),getStatusIcon('paused'));assert.equal(getStatusIcon('pause'),getStatusIcon('paused'));assert.match(getStatusIcon('pause'),/M9 4H5/); +}); + + +test('export actual planner DOM for the optional independent browser geometry check',async()=>{ + if(!process.env.TG_LAYOUT_DIR)return; + const e=environment(),planner=new TaskPlanner(e.plugin,document.body.createDiv());planner.setTasks(Array.from({length:100},(_,index)=>task(`Backlog task ${index+1}`))); + const target=process.env.TG_LAYOUT_DIR;fs.mkdirSync(target,{recursive:true});fs.writeFileSync(path.join(target,'planner.html'),planner.containerEl.outerHTML);planner.unload(); + e.plugin.settings.rewards={rewardItems:[],pointsLedger:[]};const points=new PointsDashboard(e.app,e.plugin,document.body.createDiv());points.onload();await new Promise(resolve=>setTimeout(resolve,0)); + const date=moment().format('YYYY-MM-DD');points.snapshot={...points.snapshot,manual:[{id:'one',date,text:'Example bonus',points:10},{id:'two',date,text:'Example redemption',points:-20}],ledger:[],automaticTasks:{days:[],habitPaths:[]},summaries:[{path:'habit',name:'Example habit',points:30,todayPoints:10,entries:3,dailyPoints:{[date]:10}}]};points.activeTab='history';points.renderTabs();points.renderBody();fs.writeFileSync(path.join(target,'points.html'),points.containerEl.outerHTML);points.unload();e.close(); +}); + + +test('calendar weeks reset at January 1 and respect Monday-based boundaries',()=>{ + assert.equal(calendarWeekNumber(new Date(2027,0,1)),1);assert.equal(calendarWeekNumber(new Date(2027,0,4)),2);assert.equal(calendarWeekNumber(new Date(2026,10,9)),46);assert.equal(calendarWeekNumber(new Date(2028,0,1)),1); +}); + +test('project folders move the same canonical note and preserve its task content and name',async()=>{ + const e=environment(),file=await e.app.vault.create('Projects/Research.md','Keep all tasks');e.metadata.set(file.path,{frontmatter:{project:'Research'}});let moved; + e.app.fileManager.renameFile=async(note,path)=>{moved={from:note.path,to:path};const old=note.path,content=e.text.get(old),meta=e.metadata.get(old);e.files.delete(old);e.text.delete(old);e.metadata.delete(old);note.path=path;e.files.set(path,note);e.text.set(path,content);e.metadata.set(path,meta);}; + const manager=new ProjectFileManager(e.app);await manager.update('Research',{folder:'Work/Study'});assert.deepEqual(moved,{from:'Projects/Research.md',to:'Projects/Work/Study/Research.md'});assert.equal(manager.find('Research').folder,'Work/Study');assert.equal(e.text.get(file.path),'Keep all tasks');await assert.rejects(()=>manager.update('Research',{folder:'../outside'}));e.close(); +}); + +test('folder navigation expands and collapses without creating a project or changing task membership',()=>{ + const e=environment(),root=document.body.createDiv(),folder=projectFolderContainer(root,e.app);folder('Work/Study').createSpan({text:'Research'});assert.equal(root.querySelectorAll('.tg-project-folder-row').length,2);const header=root.querySelector('button');header.click();assert.equal(header.getAttribute('aria-expanded'),'false');header.click();assert.equal(header.getAttribute('aria-expanded'),'true');assert.equal(e.files.size,0);e.close(); +}); + +test('choosing a project shows its existing note as the task destination',async()=>{ + const e=environment();const file=await e.app.vault.create('Projects/Work/Research.md','');e.metadata.set(file.path,{frontmatter:{project:'Research'}});const capture=new QuickCaptureModal(e.app,e.plugin);Object.assign(capture,{app:e.app,plugin:e.plugin,currentMode:'checkbox',taskMetadata:{project:'Research'}});const root=document.body.createDiv();capture.createTargetFileSelector(root);assert.equal(capture.tempTargetFilePath,file.path);assert.match(root.textContent,/Projects\/Work\/Research.md/);assert.equal(root.querySelector('[contenteditable=true]'),null);e.close(); +}); + +test('points history date filters use inclusive last 7 or 30 local days and exclude future entries',()=>{ + const e=environment(),page=new PointsDashboard(e.app,e.plugin,document.body.createDiv()),today=new Date();const date=delta=>{const d=new Date(today);d.setDate(d.getDate()+delta);return moment(d).format('YYYY-MM-DD');};page.historyFilter='week';assert.equal(page.historyDateMatches(date(-6)),true);assert.equal(page.historyDateMatches(date(-7)),false);assert.equal(page.historyDateMatches(date(1)),false);page.historyFilter='month';assert.equal(page.historyDateMatches(date(-29)),true);assert.equal(page.historyDateMatches(date(-30)),false);e.close(); +}); + + +test('zero habit points stay hidden and recent range filters sum daily contributions',()=>{ + const e=environment();e.plugin.settings.rewards={rewardItems:[],pointsLedger:[]};const page=new PointsDashboard(e.app,e.plugin,document.body.createDiv());page.bodyEl=document.body.createDiv();page.scope=page.addChild(new (class {unload(){}})());page.activeTab='history';const today=moment().format('YYYY-MM-DD'); + page.snapshot={manual:[],ledger:[],automaticTasks:{days:[],habitPaths:[]},summaries:[{name:'Zero habit',path:'zero',points:0,todayPoints:0,entries:1,dailyPoints:{}},{name:'Paid habit',path:'paid',points:100,todayPoints:10,entries:3,dailyPoints:{[today]:10,'2020-01-01':90}}]}; + page.historyFilter='week';page.renderHistory();assert.doesNotMatch(page.bodyEl.textContent,/Zero habit/);assert.match(page.bodyEl.textContent,/Paid habit/);assert.doesNotMatch(page.bodyEl.textContent,/100/);assert.match(page.bodyEl.textContent,/10/);e.close(); +}); + + +test('calendar cells create tasks without opening notes, while only the period title opens a note',()=>{ + const e=environment();globalThis.getComputedStyle=window.getComputedStyle.bind(window);globalThis.requestAnimationFrame=window.requestAnimationFrame; + const page=new CalendarComponent(e.app,e.plugin,document.body.createDiv()),notes=[];let created=0;const open=QuickCaptureModal.prototype.open;QuickCaptureModal.prototype.open=function(){created++;return this;};page.openNote=async(...args)=>notes.push(args); + try{page.onload();const date=page.containerEl.querySelector('.tg-date-number');assert.ok(date);date.dispatchEvent(new window.MouseEvent('click',{bubbles:true}));date.dispatchEvent(new window.MouseEvent('click',{bubbles:true}));date.dispatchEvent(new window.MouseEvent('dblclick',{bubbles:true}));assert.equal(notes.length,0);assert.equal(created,1);page.dateDisplayEl.click();assert.equal(notes.length,1);assert.equal(created,1);assert.equal(page.headerEl.querySelector('.calendar-period-notes'),null);}finally{QuickCaptureModal.prototype.open=open;page.unload();e.close();} +}); + +test('editing uses the capture form and shared field layout, and cancel does not save capture preferences',async()=>{ + const e=environment();let saves=0;e.plugin.saveSettings=async()=>saves++;e.plugin.settings.quickCapture.rememberLastMode=true; + const create=new QuickCaptureModal(e.app,e.plugin);create.onOpen();const edit=new TaskDetailsModal(e.app,e.plugin,{...task('edit'),metadata:{tags:[],children:[],context:'home'}});await edit.onOpen(); + const fields=modal=>[...modal.contentEl.querySelectorAll('.quick-capture-config-panel .setting-item-name')].map(el=>el.textContent); + assert.deepEqual(fields(edit),fields(create));assert.ok(edit.contentEl.querySelector('.quick-capture-editor-panel .quick-capture-modal-editor'));assert.ok(edit.contentEl.querySelector('.preview-markdown'));assert.equal(edit.contentEl.querySelector('.tg-task-editor-layout'),null);assert.equal(edit.contentEl.querySelector('.quick-capture-footer .mod-cta').textContent,'Save');edit.close();assert.equal(saves,0);create.close();e.close(); +}); + +test('the clear-time button removes time while retaining the day in a staged task edit',async()=>{ + const e=environment();let saved;e.plugin.writeAPI={updateTask:async args=>{saved=args;return {success:true};}}; + const modal=new TaskDetailsModal(e.app,e.plugin,{...task('date-clear'),originalMarkdown:'- [ ] Test 📅 2026-11-12 09:35',metadata:{tags:[],children:[],dueDate:new Date(2026,10,12,9,35).getTime(),datePrecision:{dueDate:'datetime'}}});await modal.onOpen(); + const row=[...modal.contentEl.querySelectorAll('.setting-item')].find(el=>el.querySelector('.setting-item-name')?.textContent==='Due Date');assert.equal(row.querySelector('input[type=time]').value,'09:35');row.querySelector('.tg-clear-time').click();assert.equal(row.querySelector('input[type=time]').value,'');assert.equal(row.querySelector('input[type=date]').value,'2026-11-12');await modal.save();assert.equal(saved.updates.metadata.datePrecision.dueDate,'date');assert.equal(new Date(saved.updates.metadata.dueDate).getHours(),0);e.close(); +}); + +test('pause checkboxes keep the pause icon even with optional Task Genius icons disabled',async()=>{ + const e=environment();e.plugin.settings.enableTaskGeniusIcons=false;const icons=new TaskGeniusIconManager(e.plugin);await icons.onload();const style=document.getElementById('task-genius-pause-icons');assert.ok(style);assert.match(style.textContent,/data-task="a"/);assert.doesNotMatch(style.textContent,/data-task="x"/);assert.ok(document.body.classList.contains('task-genius-pause-icons'));assert.equal(document.getElementById('task-genius-icons-styles'),null);assert.equal(e.plugin.settings.enableTaskGeniusIcons,false);icons.unload();assert.equal(document.getElementById('task-genius-pause-icons'),null);e.close(); +}); + +test('habit check-in counts follow the same date range as their point contributions',()=>{ + const e=environment(),page=new PointsDashboard(e.app,e.plugin,document.body.createDiv());page.bodyEl=document.body.createDiv();const today=moment().format('YYYY-MM-DD');page.historyFilter='week';page.snapshot={manual:[],ledger:[],automaticTasks:{days:[],habitPaths:[]},summaries:[{name:'Fitness',path:'fitness',points:30,todayPoints:10,entries:3,dailyPoints:{[today]:10,'2020-01-01':20},dailyEntries:{[today]:1,'2020-01-01':2}}]};page.renderHistory();assert.match(page.bodyEl.textContent,/Fitness · 1 check-ins/);assert.doesNotMatch(page.bodyEl.textContent,/3 check-ins/);e.close(); +}); + +test('project-bound capture metadata never repeats project tags or inline fields in the task preview',()=>{ + const e=environment(),capture=new QuickCaptureModal(e.app,e.plugin,{project:'Research'});capture.taskMetadata.project='Research';const text=capture.processContentWithMetadata('Write notes');assert.match(text,/Write notes/);assert.doesNotMatch(text,/#project\/|\[project::/);capture.onClose();e.close(); +}); + + +test('capture fields serialize explicit points, dependency ids and tags without repeating project ownership',()=>{ + const e=environment(),capture=new QuickCaptureModal(e.app,e.plugin,{project:'Research'});capture.taskMetadata={project:'Research',points:5,dependsOn:['target-id'],tags:['writing','project/Research']};const output=capture.processContentWithMetadata('Write #writing #project/Research');assert.match(output,/\[points:: 5\]/);assert.match(output,/⛔ target-id/);assert.equal((output.match(/#writing/g)||[]).length,1);assert.doesNotMatch(output,/#project\/|\[project::/);capture.onClose();e.close(); +}); + +test('export shared capture and edit forms for the independent browser layout check',async()=>{ + if(!process.env.TG_LAYOUT_DIR)return;const e=environment(),target=process.env.TG_LAYOUT_DIR;fs.mkdirSync(target,{recursive:true}); + const capture=new QuickCaptureModal(e.app,e.plugin);capture.onOpen();const edit=new TaskDetailsModal(e.app,e.plugin,{...task('Example task'),metadata:{tags:[],children:[],startDate:new Date(2026,10,9,9,30).getTime(),datePrecision:{startDate:'datetime'}}});await edit.onOpen();await new Promise(resolve=>setTimeout(resolve,65));for(const modal of [capture,edit]){for(const input of modal.modalEl.querySelectorAll('input'))input.defaultValue=input.value;for(const textarea of modal.modalEl.querySelectorAll('textarea'))textarea.defaultValue=textarea.value;}fs.writeFileSync(path.join(target,'capture.html'),capture.modalEl.outerHTML);fs.writeFileSync(path.join(target,'edit.html'),edit.modalEl.outerHTML); + const header=document.body.createDiv({cls:'view-header'}),root=header.createDiv({cls:'tg-fluent-top-nav'}),nav=new TopNavigation(root,e.plugin,()=>{},()=>{},()=>{},()=>{},()=>{});e.plugin.settings.taskFilter={presetTaskFilters:[{id:'layout-label',name:'本月尚未完成的任务',options:{}}]};nav.setActivePreset('layout-label');fs.writeFileSync(path.join(target,'filter.html'),header.outerHTML);const icons=new TaskGeniusIconManager(e.plugin);await icons.onload();fs.writeFileSync(path.join(target,'pause.css'),document.getElementById('task-genius-pause-icons').textContent);icons.unload();capture.close();edit.close();nav.unload();e.close(); +}); + + +test('clearing a parsed time remains authoritative over the original natural-language time',()=>{ + const e=environment(),due=new Date(2026,10,12,9,35),capture=new QuickCaptureModal(e.app,e.plugin,{dueDate:due,datePrecision:{dueDate:'datetime'}});capture.onOpen();capture.capturedContent='Review tomorrow at 09:35';capture.timeParsingService.parseTimeExpressionsForLine=()=>({cleanedLine:'Review',dueDate:due}); + const row=[...capture.contentEl.querySelectorAll('.setting-item')].find(el=>el.querySelector('.setting-item-name')?.textContent==='Due Date');row.querySelector('.tg-clear-time').click();const output=capture.processContentWithMetadata(capture.capturedContent);assert.match(output,/📅 2026-11-12/);assert.doesNotMatch(output,/09:35/);assert.equal(capture.taskMetadata.manuallySet.dueDate,true);capture.close();e.close(); +}); + +test('clearing the capture form synchronizes the visible native date and time pickers',()=>{ + const e=environment(),capture=new QuickCaptureModal(e.app,e.plugin,{dueDate:new Date(2026,10,12,9,35),datePrecision:{dueDate:'datetime'}});capture.onOpen();capture.handleClear();for(const input of capture.contentEl.querySelectorAll('input[type=date],input[type=time]'))assert.equal(input.value,'');capture.close();e.close(); +}); + + +test('the phone toolbar keeps its drawer toggle and closes on repeated backdrop taps', () => { + const e = environment(); + const originalPhone = Platform.isPhone; + Platform.isPhone = true; + try { + const root = document.body.createDiv({cls: 'tg-fluent-container'}); + const frame = root.createDiv({cls: 'tg-fluent-layout'}); + const main = frame.createDiv({cls: 'tg-fluent-main-container'}); + const toolbar = main.createDiv({cls: 'tg-fluent-phone-toolbar'}); + const top = toolbar.createDiv({cls: 'tg-fluent-top-nav'}); + const nav = new TopNavigation(top, e.plugin, () => {}, () => {}, () => {}, () => {}, () => {}, ['list', 'tree', 'kanban', 'calendar']); + e.plugin.settings.taskFilter = {presetTaskFilters: [{id: 'phone', name: '本月尚未完成的任务', options: {}}]}; + nav.setActivePreset('phone'); + const header = document.body.createDiv({cls: 'view-header'}); + const layout = new FluentLayoutManager(e.app, e.plugin, {leaf: {}}, root, header, header, () => 0); + // Exercise native event options so a once-only listener fails the second tap. + layout.registerDomEvent = (el, name, handler, options) => el.addEventListener(name, handler, options); + layout.createSidebarToggle(); + layout.setupDrawerOverlay(frame); + const toggle = toolbar.querySelector('button[aria-label="Toggle Sidebar"]'); + const backdrop = frame.querySelector('.drawer-overlay'); + assert.ok(toggle); + for (let attempt = 0; attempt < 2; attempt++) { + toggle.click(); + assert.ok(root.classList.contains('drawer-open')); + backdrop.click(); + assert.ok(!root.classList.contains('drawer-open')); + } + if (process.env.TG_LAYOUT_DIR) { + const searchInput = top.querySelector('.fluent-search-container input'); + const wrapper = document.createElement('div'); + wrapper.className = 'search-input-container'; + searchInput.replaceWith(wrapper); + wrapper.append(searchInput); + fs.mkdirSync(process.env.TG_LAYOUT_DIR, {recursive: true}); + fs.writeFileSync(path.join(process.env.TG_LAYOUT_DIR, 'phone.html'), root.outerHTML); + } + nav.unload(); + } finally { + Platform.isPhone = originalPhone; + e.close(); + } +}); + +test('duplicate background task snapshots retain the rendered view and a real change arrives once', async () => { + const e = environment(); + let current = [task('Read')]; + e.plugin.dataflowOrchestrator = {getQueryAPI: () => ({getAllTasks: async () => structuredClone(current)})}; + const manager = new FluentDataManager(e.plugin, () => 'inbox', () => ({}), () => false); + const renders = []; + const loading = []; + manager.setCallbacks({onTasksLoaded: tasks => renders.push(tasks[0].content), onLoadingStateChanged: state => loading.push(state)}); + try { + await manager.registerDataflowListeners(); + await manager.loadTasks(false); + for (let n = 0; n < 5; n++) e.app.workspace.trigger('task-genius:task-cache-updated', {}); + await new Promise(resolve => setTimeout(resolve, 550)); + assert.deepEqual(renders, ['Read']); + current = [{...current[0], content: 'Read the next chapter'}]; + for (let n = 0; n < 5; n++) e.app.workspace.trigger('task-genius:task-cache-updated', {}); + await new Promise(resolve => setTimeout(resolve, 550)); + assert.deepEqual(renders, ['Read', 'Read the next chapter']); + assert.ok(!loading.includes(true)); + // A background result can supersede an explicit refresh. It must still + // paint the view if that refresh has already shown a loading overlay. + await Promise.all([manager.loadTasks(true), manager.loadTasks(false, true)]); + assert.deepEqual(renders, ['Read', 'Read the next chapter', 'Read the next chapter']); + } finally { + manager.unload(); + e.close(); + } +}); + +const workflowSettings = () => ({ + taskStatuses: {completed:'x',inProgress:'/',abandoned:'-',planned:'?',notStarted:' ',archived:'a'}, + taskStatusCycle: ['Not Started','Planned','In Progress','Completed','Paused','Abandoned'], + taskStatusMarks: {'Not Started':' ','Planned':'?','In Progress':'/','Completed':'x','Paused':'=','Abandoned':'-'}, + statusCycles: [{id:'default',enabled:true,priority:0,cycle:['Not Started','Planned','In Progress','Completed','Paused','Abandoned'],marks:{'Not Started':' ','Planned':'?','In Progress':'/','Completed':'x','Paused':'=','Abandoned':'-'}}], + excludeMarksFromCycle: [], +}); + +test('calendar checkboxes follow the configured workflow and complete only at the completed step', async () => { + const e = environment(); + Object.assign(e.plugin.settings, workflowSettings()); + const original = {...task('Calendar workflow'), metadata:{tags:[]}}; + const calendar = new CalendarComponent(e.app,e.plugin,document.body.createDiv(),[original]); + const writes = []; + calendar.processTasks = async () => {}; + calendar.renderCurrentView = () => {}; + e.plugin.writeAPI = {updateTask: async args => { + writes.push(args); + return {success:true}; + }}; + try { + for (const expected of ['?','/','x','=','-',' ']) { + const current = calendar.tasks[0]; + await calendar.cycleTaskStatus(current); + assert.equal(calendar.tasks[0].status, expected); + assert.equal(writes.at(-1).updates.completed, expected === 'x'); + assert.equal(!!writes.at(-1).updates.metadata.completedDate, expected === 'x'); + } + assert.equal(original.status, ' '); + assert.equal(original.metadata.completedDate, undefined); + e.plugin.writeAPI.updateTask = async () => ({success:false,error:'disk busy'}); + await calendar.cycleTaskStatus(calendar.tasks[0]); + assert.equal(calendar.tasks[0].status, ' '); + } finally {calendar.unload();e.close();} +}); + +test('the current calendar event render entry uses the workflow writer and serializes repeat taps', async () => { + const e = environment(); + Object.assign(e.plugin.settings, workflowSettings()); + const original = task('Event'); + const calendar = new CalendarComponent(e.app,e.plugin,document.body.createDiv(),[original]); + calendar.processTasks = async () => {}; + calendar.renderCurrentView = () => {}; + let save, count = 0; + e.plugin.writeAPI = {updateTask: args => { + count++; + assert.equal(args.updates.status,'?'); + return new Promise(resolve => save = resolve); + }}; + const event = document.body.createDiv(); + calendar.handleTGRenderEvent({event:{id:original.id,metadata:{originalTask:original}},el:event,defaultRender(){}}); + const checkbox = event.querySelector('input[type=checkbox]'); + assert.ok(checkbox); + checkbox.click(); + assert.equal(count,1); + await calendar.cycleTaskStatus(original); + assert.equal(count,1); + save({success:true}); + await new Promise(resolve => setImmediate(resolve)); + assert.equal(calendar.tasks[0].status,'?'); + assert.equal(calendar.tasks[0].completed,false); + calendar.unload(); e.close(); +}); + +test('pause styles include legacy and workflow marks and override checked completion artwork', async () => { + const e = environment(); + Object.assign(e.plugin.settings,workflowSettings(),{enableTaskGeniusIcons:false}); + assert.deepEqual(getPausedTaskMarks(e.plugin.settings).sort(),['=','a']); + for(const mark of ['a','=']) { + assert.equal(getTaskStatusGroup(mark,e.plugin.settings),'archived'); + assert.equal(getNextTaskStatusMark(mark,e.plugin.settings),'-'); + } + assert.equal(getTaskStatusGroup('x',e.plugin.settings),'completed'); + assert.equal(getTaskStatusGroup('X',e.plugin.settings),'completed'); + assert.equal(getTaskStatusGroup('>',e.plugin.settings),'inProgress'); + assert.equal(getNextTaskStatusMark('X',e.plugin.settings),'='); + assert.equal(getNextTaskStatusMark('>',e.plugin.settings),'x'); + const icons = new TaskGeniusIconManager(e.plugin); + await icons.onload(); + const css = document.getElementById('task-genius-pause-icons').textContent; + assert.match(css,/data-task="="/); + assert.match(css,/data-task="a"/); + assert.match(css,/mask:.*!important/); + assert.doesNotMatch(css,/data-task="x"/); + if(process.env.TG_LAYOUT_DIR){ + fs.mkdirSync(process.env.TG_LAYOUT_DIR,{recursive:true}); + fs.writeFileSync(path.join(process.env.TG_LAYOUT_DIR,'pause.css'),css); + } + icons.unload(); e.close(); +}); + +test('forecast renders every future date expanded, including dates beyond the current year', () => { + const component = Object.create(ForecastComponent.prototype); + component.plugin = {settings:{viewConfiguration:[]}}; + component.currentDate = new Date(2026,10,15); + component.todayTasks = []; + component.pastTasks = []; + component.futureTasks = [task('Far future'), task('Next year')]; + component.getRelevantDate = task => new Date(task.id === 'Far future' ? 2026 : 2027,11,20).getTime(); + component.calculateDateSections(); + assert.equal(component.dateSections.length,2); + assert.ok(component.dateSections.every(section => section.isExpanded)); +}); + + +test('bonus and reward catalog editors share a wide multiline field and save the full shop', async () => { + const e=environment();e.plugin.settings.rewards={rewardItems:[{id:'stock',name:'Tea',pointCost:20,inventory:3,occurrence:'rare',imageUrl:'keep.png',condition:'#milestone'}],pointsLedger:[]};e.plugin.saveSettings=async()=>{}; + const pointsFile=await e.app.vault.create('99_System/01_Data/积分系统数据.md','---\n'+JSON.stringify({manualPointRecords:[],examplePropertyLeft:['Read +10'],examplePropertyRight:['Trip -100']})+'\n---\n'); + e.app.fileManager.processFrontMatter=async(file,change)=>{const data=JSON.parse((await e.app.vault.read(file)).split('---')[1]);change(data);await e.app.vault.modify(file,'---\n'+JSON.stringify(data)+'\n---\n');}; + const root=document.body.createDiv(),page=new PointsDashboard(e.app,e.plugin,root,true);page.onload();await new Promise(resolve=>setImmediate(resolve)); + for (const [label,expected] of [['Edit bonus actions','Read +10'],['Edit reward shop','Trip -100\nTea -20 | 3']]) { + [...root.querySelectorAll('button')].find(button=>button.textContent===label).click(); + const modal=document.querySelector('.tg-points-list-modal'),input=modal.querySelector('textarea'); + if(process.env.TG_LAYOUT_DIR) { fs.mkdirSync(process.env.TG_LAYOUT_DIR,{recursive:true});fs.writeFileSync(path.join(process.env.TG_LAYOUT_DIR,label==='Edit bonus actions'?'bonus-editor.html':'shop-editor.html'),''+modal.outerHTML);} + assert.ok(modal);assert.equal(input.value,expected);assert.equal(input.wrap,'off');assert.equal(modal.querySelectorAll('input').length,0); + if(label==='Edit reward shop') { + input.value='Trip -120\nTea -25 | 2\nWalk -10';input.dispatchEvent(new window.Event('change',{bubbles:true})); + [...modal.querySelectorAll('button')].find(button=>button.textContent==='Save').click();await new Promise(resolve=>setImmediate(resolve)); + assert.equal(document.querySelector('.tg-points-list-modal'),null); + assert.deepEqual(e.plugin.settings.rewards.rewardItems,[{id:'stock',name:'Tea',pointCost:25,inventory:2,occurrence:'rare',imageUrl:'keep.png',condition:'#milestone'}]); + assert.deepEqual(JSON.parse((await e.app.vault.read(pointsFile)).split('---')[1]).examplePropertyRight,['Trip -120','Walk -10']); + } else document.querySelector('.modal-container').remove(); + } + page.unload();e.close(); +}); + +test('calendar task titles and checkboxes open the shared menu exactly once with the current task', () => { + const e=environment(),original=task('calendar-task'),calls=[]; + const page=new CalendarComponent(e.app,e.plugin,document.body.createDiv(),[original],{onEventContextMenu:(event,task)=>calls.push({event,task})}); + const el=page.containerEl.createDiv({cls:'tg-event-bar'}),adapter={id:original.id,metadata:{originalTask:original}}; + const title=el.createSpan({text:original.content}); + let bubbled=0;page.containerEl.addEventListener('contextmenu',()=>bubbled++); + page.handleTGRenderEvent({event:adapter,el,defaultRender(){}});page.handleTGRenderEvent({event:adapter,el,defaultRender(){}}); + const current={...original,status:'?',filePath:'Projects/Current.md',line:42};page.tasks=[current]; + for(const target of [title,el.querySelector('input')]) { + const event=new window.MouseEvent('contextmenu',{bubbles:true,cancelable:true,clientX:123,clientY:234});target.dispatchEvent(event); + assert.equal(event.defaultPrevented,true);assert.equal(calls.at(-1).task,current);assert.equal(calls.at(-1).event,event); + } + assert.equal(calls.length,2);assert.equal(bubbled,0);assert.equal(calls[0].event.clientX,123); + page.unload();e.close(); +}); + +test('real month, week and day calendar engines route task right-clicks to the menu', () => { + const e=environment(),current={...task('dated-task'),line:3,metadata:{scheduledDate:new Date(2026,10,28,9).getTime()}}; + const calls=[],page=new CalendarComponent(e.app,e.plugin,document.body.createDiv(),[current],{onEventContextMenu:(event,task)=>calls.push(task)}); + page.currentDate=moment('2026-11-28'); + for(const mode of ['month','week','day']) { + page.currentViewMode=mode;page.render(); + const event=page.containerEl.querySelector('.tg-event-bar,.tg-event-block');assert.ok(event,mode); + const before=calls.length;event.dispatchEvent(new window.MouseEvent('contextmenu',{bubbles:true,cancelable:true})); + assert.equal(calls.length,before+1,mode);assert.equal(calls.at(-1).filePath,'Tasks.md');assert.equal(calls.at(-1).line,3); + } + page.unload();e.close(); +}); + + +test('managed calendars connect the task context-menu handler through the actual page factory', () => { + const e=environment(),owner=new Component(),selected=[]; + const actionHandlers=new FluentActionHandlers(e.app,e.plugin,()=>'',()=>false); + actionHandlers.setCallbacks({onTaskSelectionChanged:task=>selected.push(task)}); + const calls=[],handlers={onTaskContextMenu:(event,task)=>{calls.push(task);actionHandlers.handleTaskContextMenu(event,task);}}; + e.plugin.settings.viewConfiguration.push({id:'custom-calendar',name:'Custom calendar',specificConfig:{viewType:'calendar'}}); + const manager=new ViewComponentManager(owner,e.app,e.plugin,document.body.createDiv(),handlers); + const current={...task('context-menu-task'),line:12,filePath:'Projects/Current.md',metadata:{scheduledDate:new Date(2026,10,28,9).getTime()}}; + for (const id of ['calendar','custom-calendar']) { + const calendar=manager.getOrCreateComponent(id);calendar.tasks=[current];calendar.currentDate=moment('2026-11-28'); + for (const mode of ['month','week','day']) { + calendar.currentViewMode=mode;calendar.render(); + const card=calendar.containerEl.querySelector('.tg-event-bar,.tg-event-block');assert.ok(card,`${id} ${mode}`); + for (const target of [card,card.querySelector('input')]) { + Menu.shown=null;const before=calls.length; + const event=new window.MouseEvent('contextmenu',{bubbles:true,cancelable:true,clientX:120,clientY:160});target.dispatchEvent(event); + assert.equal(calls.length,before+1,`${id} ${mode}: menu callback connected`); + assert.equal(calls.at(-1),current);assert.ok(Menu.shown,`${id} ${mode}: actual menu shown`); + assert.equal(Menu.shown.event,event); + const edit=Menu.shown.items.find(item=>item.title==='Edit');assert.ok(edit);edit.callback();assert.equal(selected.at(-1),current); + assert.ok(Menu.shown.items.some(item=>item.title==='Delete Task'));assert.ok(Menu.shown.items.some(item=>item.title==='Switch status')); + } + } + calendar.unload(); + } + manager.unload();e.close(); +}); + +test('managed calendars retain an explicitly supplied calendar context-menu callback', () => { + const e=environment(),calls=[],owner=new Component(); + const manager=new ViewComponentManager(owner,e.app,e.plugin,document.body.createDiv(),{onTaskContextMenu:()=>calls.push('task'),onEventContextMenu:()=>calls.push('calendar')}); + const calendar=manager.getOrCreateComponent('calendar'),original=task('explicit-handler');calendar.tasks=[original]; + calendar.onEventContextMenu(new window.MouseEvent('contextmenu'),original); + assert.deepEqual(calls,['calendar']);calendar.unload();manager.unload();e.close(); +}); diff --git a/versions.json b/versions.json index c885ce360..f4a219b5f 100644 --- a/versions.json +++ b/versions.json @@ -179,5 +179,19 @@ "9.12.5": "0.15.2", "9.12.6": "0.15.2", "9.13.0": "0.15.2", - "9.13.1": "0.15.2" -} \ No newline at end of file + "9.13.1": "0.15.2", + "9.13.2": "0.15.2", + "9.13.3": "0.15.2", + "9.13.4": "0.15.2", + "9.13.5": "0.15.2", + "9.13.6": "0.15.2", + "9.13.7": "0.15.2", + "9.13.8": "0.15.2", + "9.13.9": "0.15.2", + "9.13.10": "0.15.2", + "9.13.11": "0.15.2", + "9.13.12": "0.15.2", + "9.13.13": "0.15.2", + "9.13.14": "0.15.2", + "9.13.15": "0.15.2" +}