generated from hron/logseq-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
191 lines (164 loc) · 5.06 KB
/
index.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
import '@logseq/libs'
import type { BlockEntity } from '@logseq/libs/dist/LSPlugin'
import { DateTime, Duration } from 'luxon'
type TodoStyle = 'TODO' | 'LATER'
async function preferredTodoStyle(): Promise<TodoStyle> {
const userConfigs = await logseq.App.getUserConfigs()
return userConfigs.preferredTodo as TodoStyle
}
async function getChosenBlocks(): Promise<[BlockEntity[], boolean]> {
const selected = await logseq.Editor.getSelectedBlocks()
if (selected) return [selected, true]
const uuid = await logseq.Editor.checkEditing()
if (!uuid) return [[], false]
const editingBlock = (await logseq.Editor.getBlock(
uuid as string
)) as BlockEntity
// to get ahead of Logseq block content saving process
editingBlock.content = await logseq.Editor.getEditingBlockContent()
return [[editingBlock], false]
}
const todoSequences = {
TODO: ['', 'TODO', 'DOING', 'DONE'] as const,
LATER: ['', 'LATER', 'NOW', 'DONE'] as const,
} as const
type MarkerTODOStyle = (typeof todoSequences.TODO)[number]
type MarkerLATERStyle = (typeof todoSequences.LATER)[number]
type Marker = MarkerTODOStyle | MarkerLATERStyle
function getMarker(block: BlockEntity) {
let currentMarker = ''
const allPossibleMarkers = Object.values(todoSequences)
.flat()
.filter(
(marker, index, self) => marker !== '' && self.indexOf(marker) === index
)
const matchData = block.content?.match(
new RegExp(`^(${allPossibleMarkers.join('|')})`)
)
if (matchData) {
currentMarker = matchData[1]
}
return currentMarker as Marker
}
function setMarker(block: BlockEntity, newMarker: Marker) {
const content = block.content || ''
const currentMarker = getMarker(block)
if (currentMarker === '') {
return `${newMarker} ${content}`
} else {
return content
.replace(new RegExp(`^\\s*${currentMarker}`), newMarker)
.trim()
}
}
async function computeNextMarker(currentMarker: Marker) {
const userPreferredStyle = await preferredTodoStyle()
const todoSeq = todoSequences[userPreferredStyle] as readonly Marker[]
const nextMarker =
todoSeq[(todoSeq.indexOf(currentMarker) + 1) % todoSeq.length]
if (
['NOW', 'DOING'].includes(nextMarker) &&
logseq.settings!['cycleTODOdwimSkipDoing']
) {
return computeNextMarker(nextMarker)
} else {
return nextMarker
}
}
type Timestamp = {
date: DateTime
repeatingPeriod?: Duration
}
const toLongUnits = {
y: 'years',
m: 'months',
w: 'weeks',
d: 'days',
} as const
const timestampTypes = ['SCHEDULED', 'DEADLINE'] as const
function parseTimestamps(block: BlockEntity) {
return timestampTypes.map((t) => {
const matchData = block.content?.match(
new RegExp(
`${t}: <(....-..-..) ...(?: [0-9-:]+)?(?: \\.\\+([0-9]+)([ymwd]))?>`
)
)
if (!matchData) return undefined
const date = DateTime.fromFormat(matchData[1], 'yyyy-MM-dd')
let repeatingPeriod: Duration | undefined = undefined
if (matchData[2] && matchData[3])
repeatingPeriod = Duration.fromObject({
[toLongUnits[matchData[3]]]: Number.parseInt(matchData[2]),
})
return {
date,
repeatingPeriod,
}
})
}
async function startMarker() {
const todoStyle = await preferredTodoStyle()
return todoSequences[todoStyle].at(1) as Marker
}
function updateTimestamps(
content: string,
currentTimestamps: [Timestamp?, Timestamp?]
) {
for (const [i, t] of timestampTypes.entries()) {
if (!currentTimestamps[i] || !currentTimestamps[i].repeatingPeriod) continue
const updatedTimestamp = currentTimestamps[i].date.plus(
currentTimestamps[i].repeatingPeriod
)
content = content.replace(
new RegExp(`${t}: <....-..-.. ...`),
`${t}: <${updatedTimestamp.toFormat('yyyy-MM-dd EEE')}`
)
}
return content
}
async function cycleTODOdwim(): Promise<void[]> {
const [blocks] = await getChosenBlocks()
if (blocks.length === 0) return []
return Promise.all(
blocks.map(async (b) => {
const currentMarker = getMarker(b)
const [scheduled, deadline] = parseTimestamps(b)
const nextMarker = await computeNextMarker(currentMarker)
let newContent = setMarker(b, nextMarker)
if (
nextMarker === 'DONE' &&
(scheduled?.repeatingPeriod || deadline?.repeatingPeriod)
) {
newContent = setMarker(b, await startMarker())
newContent = updateTimestamps(newContent, [scheduled, deadline])
}
return logseq.Editor.updateBlock(b.uuid, newContent)
})
)
}
async function main() {
logseq.useSettingsSchema([
{
key: 'cycleTODOdwimSkipDoing',
type: 'boolean',
title: 'Skip NOW/DOING State',
description:
'<p>Determines whether the Cycle TODO (Do What I Mean) feature skips the NOW/DOING state</p>',
default: false,
},
])
logseq.App.registerCommandPalette(
{
label: 'Cycle TODO (Do What I Mean)',
key: 'cycle-todo-dwim',
keybinding: {
mac: 'mod+shift+enter',
binding: 'ctrl+shift+enter',
mode: 'global',
},
},
cycleTODOdwim
)
}
// bootstrap
logseq.ready(main).catch(console.error)