Repository: obsidian-tasks-group/obsidian-tasks
Pull request #2300 (2023-09-26 08:10:32)

refactor: move code for task counts text to QueryResult
<!--- Provide a general summary of your changes in the Title above -->

# Description

Refactor `QueryRenderer.addTaskCount()` code - move it to `QueryResult` and add tests.

## Motivation and Context

This is preparation for #2294

## How has this been tested?

- Adding new tests
- Testing the rendering of task results in the Tasks-Demo vault still shows counts

<!--- Please describe in detail how you tested your changes. -->
<!--- Include details of your testing environment, tests ran to see how -->
<!--- your change affects other areas of the code, etc. -->

## Screenshots (if appropriate)

## Types of changes

<!--- What types of changes does your code introduce? Put an `x` in all the boxes that apply: -->

Internal changes:

- [x] **Refactor** (prefix: `refactor` - non-breaking change which only improves the design or structure of existing code, and making no changes to its external behaviour)
- [x] **Tests** (prefix: `test` - additions and improvements to unit tests and the smoke tests)

## Checklist

<!--- Go over all the following points, and put an `x` in all the boxes that apply. -->
<!--- If you're unsure about any of these, don't hesitate to ask. We're here to help! -->

- [x] My code follows the code style of this project and passes `yarn run lint`.
- [ ] My change requires a change to the documentation.
- [ ] I have [updated the documentation](https://publish.obsidian.md/tasks-contributing/Documentation/About+Documentation) accordingly.
- [x] My change has adequate [Unit Test coverage](https://publish.obsidian.md/tasks-contributing/Testing/About+Testing).

## Terms

<!--
By submitting this pull request, you must agree to follow our
[contributing guide](https://publish.obsidian.md/tasks-contributing) and
[Code of Conduct](https://github.com/obsidian-tasks-group/obsidian-tasks/blob/main/CODE_OF_CONDUCT.md).
Put an x in the boxes to confirm you agree.
-->

- [x] My contribution follow this project's [contributing guide](https://publish.obsidian.md/tasks-contributing)
- [x] I agree to follow this project's [Code of Conduct](https://github.com/obsidian-tasks-group/obsidian-tasks/blob/main/CODE_OF_CONDUCT.md)



Patch:
diff --git a/src/Query/QueryResult.ts b/src/Query/QueryResult.ts
index acf8746a..b0f36d6a 100644
--- a/src/Query/QueryResult.ts
+++ b/src/Query/QueryResult.ts
@@ -21,6 +21,11 @@ export class QueryResult {
         return this.taskGroups.totalTasksCount();
     }
 
+    public totalTasksCountDisplayText() {
+        const tasksCount = this.totalTasksCount;
+        return `${tasksCount} task${tasksCount !== 1 ? 's' : ''}`;
+    }
+
     public get groups(): TaskGroup[] {
         return this.taskGroups.groups;
     }
diff --git a/src/QueryRenderer.ts b/src/QueryRenderer.ts
index 3c33153d..c1fc0dee 100644
--- a/src/QueryRenderer.ts
+++ b/src/QueryRenderer.ts
@@ -14,6 +14,7 @@ import type { Task } from './Task';
 import { DateFallback } from './DateFallback';
 import { TaskLayout } from './TaskLayout';
 import { explainResults, getQueryForQueryRenderer } from './lib/QueryRendererHelper';
+import type { QueryResult } from './Query/QueryResult';
 import type { TaskGroups } from './Query/TaskGroups';
 
 export class QueryRenderer {
@@ -188,7 +189,7 @@ class QueryRenderChild extends MarkdownRenderChild {
         if (debug) {
             console.debug(`${totalTasksCount} of ${tasks.length} tasks displayed in a block in "${this.filePath}"`);
         }
-        this.addTaskCount(content, totalTasksCount);
+        this.addTaskCount(content, queryResult);
     }
 
     private renderErrorMessage(content: HTMLDivElement, errorMessage: string) {
@@ -388,10 +389,10 @@ class QueryRenderChild extends MarkdownRenderChild {
         }
     }
 
-    private addTaskCount(content: HTMLDivElement, tasksCount: number) {
+    private addTaskCount(content: HTMLDivElement, queryResult: QueryResult) {
         if (!this.query.layoutOptions.hideTaskCount) {
             content.createDiv({
-                text: `${tasksCount} task${tasksCount !== 1 ? 's' : ''}`,
+                text: queryResult.totalTasksCountDisplayText(),
                 cls: 'tasks-count',
             });
         }


Test patch:
diff --git a/tests/Query/QueryResult.test.ts b/tests/Query/QueryResult.test.ts
index 3e924121..02962054 100644
--- a/tests/Query/QueryResult.test.ts
+++ b/tests/Query/QueryResult.test.ts
@@ -2,8 +2,15 @@ import { TaskGroups } from '../../src/Query/TaskGroups';
 import type { Grouper } from '../../src/Query/Grouper';
 import type { Task } from '../../src/Task';
 import { QueryResult } from '../../src/Query/QueryResult';
+import { fromLine } from '../TestHelpers';
 
 describe('QueryResult', () => {
+    function createUngroupedQueryResult(tasks: Task[]) {
+        const groupers: Grouper[] = [];
+        const groups = new TaskGroups(groupers, tasks);
+        return new QueryResult(groups);
+    }
+
     it('should create a QueryResult from TaskGroups', () => {
         // Arrange
         const groupers: Grouper[] = [];
@@ -28,4 +35,27 @@ describe('QueryResult', () => {
         expect(result.searchErrorMessage).toEqual(message);
         expect(result.taskGroups.totalTasksCount()).toEqual(0);
     });
+
+    describe('Text representation of tasks count', () => {
+        it('should pluralise "tasks" if 0 matches', () => {
+            const tasks: Task[] = [];
+            const queryResult = createUngroupedQueryResult(tasks);
+            expect(queryResult.totalTasksCountDisplayText()).toEqual('0 tasks');
+        });
+
+        it('should not pluralise "task" if only 1 match', () => {
+            const tasks = [fromLine({ line: '- [ ] Do something' })];
+            const queryResult = createUngroupedQueryResult(tasks);
+            expect(queryResult.totalTasksCountDisplayText()).toEqual('1 task');
+        });
+
+        it('should pluralise "tasks" if 2 matches', () => {
+            const tasks = [
+                fromLine({ line: '- [ ] Do something more complicated 1' }),
+                fromLine({ line: '- [ ] Do something more complicated 2' }),
+            ];
+            const queryResult = createUngroupedQueryResult(tasks);
+            expect(queryResult.totalTasksCountDisplayText()).toEqual('2 tasks');
+        });
+    });
 });