Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Display task counter in the card title #911

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
48 changes: 48 additions & 0 deletions src/Settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ export interface KanbanSettings {
'hide-date-in-title'?: boolean;
'hide-tags-display'?: boolean;
'hide-tags-in-title'?: boolean;
'hide-task-count'?: boolean;
'lane-width'?: number;
'link-date-to-daily-note'?: boolean;
'max-archive-size'?: number;
Expand Down Expand Up @@ -103,6 +104,7 @@ export const settingKeyLookup: Record<keyof KanbanSettings, true> = {
'hide-date-in-title': true,
'hide-tags-display': true,
'hide-tags-in-title': true,
'hide-task-count': true,
'lane-width': true,
'link-date-to-daily-note': true,
'max-archive-size': true,
Expand Down Expand Up @@ -458,6 +460,52 @@ export class SettingsManager {
});
});

new Setting(contentEl)
.setName(t('Hide task counter in card titles'))
.setDesc(t('When toggled, this will hide the number of tasks total and completed in the card.'))
.then((setting) => {
let toggleComponent: ToggleComponent;

setting
.addToggle((toggle) => {
toggleComponent = toggle;

const [value, globalValue] = this.getSetting(
'hide-task-count',
local
);

if (value !== undefined) {
toggle.setValue(value as boolean);
} else if (globalValue !== undefined) {
toggle.setValue(globalValue as boolean);
}

toggle.onChange((newValue) => {
this.applySettingsUpdate({
'hide-task-count': {
$set: newValue,
},
});
});
})
.addExtraButton((b) => {
b.setIcon('lucide-rotate-ccw')
.setTooltip(t('Reset to default'))
.onClick(() => {
const [, globalValue] = this.getSetting(
'hide-task-count',
local
);
toggleComponent.setValue(!!globalValue);

this.applySettingsUpdate({
$unset: ['hide-task-count'],
});
});
});
});

new Setting(contentEl)
.setName(t('Hide tags in card titles'))
.setDesc(
Expand Down
5 changes: 5 additions & 0 deletions src/components/Item/ItemContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { c } from '../helpers';
import { MarkdownDomRenderer } from '../MarkdownRenderer';
import { Item } from '../types';
import { DateAndTime, RelativeDate } from './DateAndTime';
import { TaskCounter } from './TaskCounter';
import {
constructDatePicker,
constructMenuDatePickerOnChange,
Expand Down Expand Up @@ -238,6 +239,10 @@ export const ItemContent = Preact.memo(function ItemContent({

return (
<div className={c('item-title')}>
<TaskCounter
item={item}
stateManager={stateManager}
/>
<MarkdownDomRenderer
className={c('item-markdown')}
dom={item.data.dom}
Expand Down
23 changes: 23 additions & 0 deletions src/components/Item/TaskCounter.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { StateManager } from 'src/StateManager';

import { c } from '../helpers';
import { Item } from '../types';

export interface TaskCounterProps {
item: Item;
stateManager: StateManager;
}

export function TaskCounter({ item, stateManager }: TaskCounterProps) {
const hideTaskCount = stateManager.useSetting('hide-task-count');

if (hideTaskCount || !item.data.metadata.tasks) {
return null;
}

return (
<div className={c('item-tasks-count')}>
{item.data.metadata.tasks.completed}/{item.data.metadata.tasks.total}
</div>
);
}
6 changes: 6 additions & 0 deletions src/components/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,17 @@ export interface FileMetadata {
[k: string]: PageData;
}

export interface TasksMetadata {
total?: number;
completed?: number;
}

export interface ItemMetaData {
dateStr?: string;
date?: moment.Moment;
timeStr?: string;
time?: moment.Moment;
tasks?: TasksMetadata;
tags?: string[];
fileAccessor?: FileAccessor;
file?: TFile | null;
Expand Down
3 changes: 3 additions & 0 deletions src/lang/locale/de.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,9 @@ export default {
'Linked Page Metadata': 'Metadaten für verknüpfte (verlinkte) Notizen',
'Display metadata for the first note linked within a card. Specify which metadata keys to display below. An optional label can be provided, and labels can be hidden altogether.':
'Zeigen Sie Metadaten für die erste Notiz an, die innerhalb einer Karte verknüpft ist. Geben Sie an, welche Metadatenschlüssel unten angezeigt werden sollen. Ein optionales Label kann hinzugefügt werden, es kann aber auch vollständig ausgeblendet werden.',
'Hide task counter in card titles': 'Aufgabenzähler in Kartentiteln ausblenden',
'When toggled, this will hide the number of tasks total and completed in the card.':
'Wenn diese Option aktiviert ist, wird die Anzahl der gesamten und abgeschlossenen Aufgaben auf der Karte ausgeblendet.',

// MetadataSettings.tsx
'Metadata key': 'Metadatenschlüssel',
Expand Down
3 changes: 3 additions & 0 deletions src/lang/locale/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,9 @@ export default {
'Calendar: first day of week': 'Calendar: first day of week',
'Override which day is used as the start of the week':
'Override which day is used as the start of the week',
'Hide task counter in card titles': 'Hide task counter in card titles',
'When toggled, this will hide the number of tasks total and completed in the card.':
'When toggled, this will hide the number of tasks total and completed in the card.',
Sunday: 'Sunday',
Monday: 'Monday',
Tuesday: 'Tuesday',
Expand Down
3 changes: 3 additions & 0 deletions src/lang/locale/it.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,9 @@ export default {
"Verrà usato per separare data e ora dell'archiviazione dal titolo",
'Archive date/time format': "Formato data/ora dell'archivio",
'Kanban Plugin': 'Plugin Kanban',
'Hide task counter in card titles': 'Nascondere il contatore delle attività nei titoli delle schede',
'When toggled, this will hide the number of tasks total and completed in the card.':
'Se attivata, nasconde il numero di attività totali e completate nella scheda.',

// components/Item/Item.tsx
'More options': 'Altre opzioni',
Expand Down
4 changes: 4 additions & 0 deletions src/lang/locale/ja.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,10 @@ export default {
'Calendar: first day of week': 'カレンダー: 週の始まり',
'Override which day is used as the start of the week':
'週の始まりとして使用する曜日を変更します。',
'Hide task counter in card titles': 'カードタイトルにタスクカウンターを隠す',
'When toggled, this will hide the number of tasks total and completed in the card.':
'トグルすると、カード内のタスクの合計数と完了数が非表示になります。',

Sunday: '日曜日',
Monday: '月曜日',
Tuesday: '火曜日',
Expand Down
3 changes: 3 additions & 0 deletions src/lang/locale/ko.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,9 @@ export default {
'Calendar: first day of week': '달력: 첫 번째 요일',
'Override which day is used as the start of the week':
'한 주의 시작으로 사용되는 요일을 재정의합니다.',
'Hide task counter in card titles': '카드 제목에 작업 카운터 숨기기',
'When toggled, this will hide the number of tasks total and completed in the card.':
'이 옵션을 켜면 카드에서 총 작업 수와 완료된 작업 수가 숨겨집니다.',
Sunday: '일요일',
Monday: '월요일',
Tuesday: '화요일',
Expand Down
3 changes: 3 additions & 0 deletions src/lang/locale/pt-br.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,9 @@ export default {
'Linked Page Metadata': "Metadados de páginas 'lincadas'",
'Display metadata for the first note linked within a card. Specify which metadata keys to display below. An optional label can be provided, and labels can be hidden altogether.':
"Exibe metadados para a primeira nota 'lincada' em um cartão. Especifique abaixo quais metadados serão exibidos. Um rótulo opcional pode ser fornecido e os rótulos podem ser ocultados completamente.",
'Hide task counter in card titles': 'Ocultar o contador de tarefas nos títulos dos cartões',
'When toggled, this will hide the number of tasks total and completed in the card.':
'Quando ativada, essa opção oculta o número de tarefas totais e concluídas no cartão.',

// MetadataSettings.tsx
'Metadata key': 'Metadado',
Expand Down
35 changes: 19 additions & 16 deletions src/lang/locale/ru.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export default {
'Untitled Kanban': 'Безымянная Kanban-доска',
'Toggle between Kanban and markdown mode':
'Переключиться между Kanban и markdown режимами',

// KanbanView.tsx
'Open as markdown': 'Открыть как markdown',
'Open board settings': 'Открыть настройки доски',
Expand All @@ -25,7 +25,7 @@ export default {
'Вы можете открыть файл как markdown и проверить или отредактировать его.',
'Are you sure you want to archive all completed cards on this board?':
'Вы уверены, что хотите архивировать все завершёённые карточки в этой доске?',

// parser.ts
Complete: 'Выполнено',
Archive: 'Архивировать',
Expand All @@ -34,13 +34,13 @@ export default {
"I don't know how to interpret this line:":
"Я не знаю, как интерпретировать эту строку:",
Untitled: 'Без имени', // auto-created column

// settingHelpers.ts
'Note: No template plugins are currently enabled.':
'Примечание: В настоящее время ни один плагин шаблона не включен.',
default: 'по умолчанию',
'Search...': 'Найти...',

// Settings.ts
'New line trigger': 'Триггер новой строки',
'Select whether Enter or Shift+Enter creates a new line. The opposite of what you choose will create and complete editing of cards and lists.':
Expand Down Expand Up @@ -135,6 +135,9 @@ export default {
'Calendar: first day of week': 'Календарь: первый день недели',
'Override which day is used as the start of the week':
'Укажите, какой день должен использоваться как начало недели',
'Hide task counter in card titles': 'Скрывать счетчик задач в заголовках карточек',
'When toggled, this will hide the number of tasks total and completed in the card.':
'Когда включено, общее количество и количество выполненных задач в карточке будет скрыто.',
Sunday: 'Воскресенье',
Monday: 'Понедельник',
Tuesday: 'Вторник',
Expand All @@ -154,7 +157,7 @@ export default {
'Set colors for the date displayed below the card based on the rules below':
'Установить цвета для даты, отображаемой под карточкой, базируясь на правилах ниже',
'Add date color': 'Добавить цвет даты',

// MetadataSettings.tsx
'Metadata key': 'Ключ метаданных',
'Display label': 'Показать ярылк',
Expand All @@ -163,26 +166,26 @@ export default {
Delete: 'Удалить',
'Add key': 'Добавить ключ',
'Field contains markdown': 'Поле содержит markdown',

// TagColorSettings.tsx
'Add tag color': 'Добавить цвет метки',

// components/Item/Item.tsx
'More options': 'Больше настроек',
Cancel: 'Отмена',

// components/Item/ItemContent.tsx
today: 'сегодня',
yesterday: 'вчера',
tomorrow: 'завтра',
'Change date': 'Изменить дату',
'Change time': 'Изменить время',

// components/Item/ItemForm.tsx
'Card title...': 'Заголовок карточки...',
'Add card': 'Добавить карточку',
'Add a card': 'Добавить карточку',

// components/Item/ItemMenu.ts
'Edit card': 'Редактировать карточку',
'New note from card': 'Новая заметка из карточки',
Expand All @@ -202,17 +205,17 @@ export default {
'Add label': 'Добавить ярлык',
'Move to top': 'Переместить вверх',
'Move to bottom': 'Переместить вниз',

// components/Lane/LaneForm.tsx
'Enter list title...': 'Введите заголовок списка...',
'Mark cards in this list as complete': 'Отметить карточки в этом списке как завершённые',
'Add list': 'Добавить список',
'Add a list': 'Добавить список',

// components/Lane/LaneHeader.tsx
'Move list': 'Переместить список',
Close: 'Закрыть',

// components/Lane/LaneMenu.tsx
'Are you sure you want to delete this list and all its cards?':
'Вы уверены, что хотите удалить этот список и все его карточки?',
Expand All @@ -231,12 +234,12 @@ export default {
'Insert list after': 'Вставить список после',
'Sort by card text': 'Сортировать по тексту карточки',
'Sort by date': 'Сортировать по дате',

// components/helpers/renderMarkdown.ts
'Unable to find': 'Невозможно найти',
'Open in default app': 'Открыть в приложении по умолчанию',

// components/Editor/MarkdownEditor.tsx
Submit: 'Сохранить',
};

3 changes: 3 additions & 0 deletions src/lang/locale/zh-cn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,9 @@ export default {
'Calendar: first day of week': '日历:一周的第一天',
'Override which day is used as the start of the week':
'设置哪一天作为一周的开始',
'Hide task counter in card titles': '在卡片标题中隐藏任务计数器',
'When toggled, this will hide the number of tasks total and completed in the card.':
'切换后,将隐藏卡片中已完成任务的总数。',
Sunday: '周日',
Monday: '周一',
Tuesday: '周二',
Expand Down
6 changes: 6 additions & 0 deletions src/main.less
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,12 @@ button.kanban-plugin__new-item-button {
overflow: hidden;
}

.kanban-plugin__item-tasks-count {
font-size: 0.75rem;
color: var(--text-muted);
float: right;
}

.kanban-plugin__markdown-preview-view {
font-family: var(--font-text, var(--default-font));
font-size: 0.875rem;
Expand Down
14 changes: 14 additions & 0 deletions src/parsers/formats/list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,20 @@ export function listItemToItemData(
itemData.metadata.fileAccessor = (genericNode as FileNode).fileAccessor;
return true;
}

if (genericNode.type === 'text') {
const listItem = genericNode.value.match(/^\s*[-\*\+] \[(?<state> |x)\]\s/);

if (listItem) {
itemData.metadata.tasks ||= { total: 0, completed: 0 };
itemData.metadata.tasks.total++;

if (listItem.groups?.state === 'x') {
itemData.metadata.tasks.completed++;
}
return true;
}
}
}
);

Expand Down