generated from pengx17/logseq-plugin-template-react
-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
useTaskManager.ts
70 lines (60 loc) · 2.09 KB
/
useTaskManager.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import dayjs from 'dayjs';
import { useCallback, useMemo } from 'react';
import { TaskEntityObject, TaskMarker } from '../models/TaskEntity';
import useAppState from './useAppState';
const useTaskManager = (task: TaskEntityObject) => {
const { uuid, marker, scheduled, completed } = task;
const { userConfigs, refresh } = useAppState();
const { preferredTodo } = userConfigs;
const isToday = useMemo(() => {
if (!scheduled) return false;
return dayjs(new Date()).format('YYYYMMDD') === scheduled.toString();
}, [scheduled]);
const toggle = useCallback(async () => {
const nextMarker = completed ? preferredTodo : TaskMarker.DONE;
await window.logseq.Editor.updateBlock(
uuid,
task.rawContent.replace(marker, nextMarker),
);
refresh();
}, [completed, preferredTodo, task, refresh]);
const openTask = useCallback(async () => {
window.logseq.Editor.scrollToBlockInPage(task.page.uuid, uuid);
}, [uuid]);
const setMarker = useCallback(async (newMarker: TaskMarker) => {
const nextContent = task.rawContent.replace(new RegExp(`^${marker}`), newMarker);
await window.logseq.Editor.updateBlock(uuid, nextContent);
refresh();
}, [uuid])
const setScheduled = useCallback(async (date: Date | null) => {
let nextContent = task.rawContent;
if (date === null) {
nextContent = task.rawContent.replace(/SCHEDULED: <[^>]+>/, '');
await window.logseq.Editor.updateBlock(uuid, nextContent);
refresh();
return;
}
const scheduledString = `SCHEDULED: <${dayjs(date).format('YYYY-MM-DD ddd')}>`;
if (task.rawContent.includes('SCHEDULED')) {
nextContent = task.rawContent.replace(
/SCHEDULED: <[^>]+>/,
scheduledString,
);
} else {
const lines = task.rawContent.split('\n');
lines.splice(1, 0, scheduledString);
nextContent = lines.join('\n');
}
await window.logseq.Editor.updateBlock(uuid, nextContent);
refresh();
}, [task, refresh]);
return {
...task,
isToday,
toggle,
openTask,
setMarker,
setScheduled,
};
};
export default useTaskManager;