forked from johannesjo/super-productivity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshort-syntax.ts
345 lines (304 loc) · 10.2 KB
/
short-syntax.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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
import { casual } from 'chrono-node';
import { Task, TaskCopy } from './task.model';
import { getWorklogStr } from '../../util/get-work-log-str';
import { stringToMs } from '../../ui/duration/string-to-ms.pipe';
import { Tag } from '../tag/tag.model';
import { Project } from '../project/project.model';
import { ShortSyntaxConfig } from '../config/global-config.model';
type ProjectChanges = {
title?: string;
projectId?: string;
};
type TagChanges = {
taskChanges?: Partial<TaskCopy>;
newTagTitlesToCreate?: string[];
};
type DueChanges = {
title?: string;
plannedAt?: number;
};
const SHORT_SYNTAX_TIME_REG_EX =
/(?:\s|^)t?((\d+(?:\.\d+)?[mhd])(?:\s*\/\s*(\d+(?:\.\d+)?[mhd]))?(?=\s|$))/i;
// NOTE: should come after the time reg ex is executed so we don't have to deal with those strings too
const CH_PRO = '+';
const CH_TAG = '#';
const CH_DUE = '@';
const ALL_SPECIAL = `(\\${CH_PRO}|\\${CH_TAG}|\\${CH_DUE})`;
const customDateParser = casual.clone();
const SHORT_SYNTAX_PROJECT_REG_EX = new RegExp(`\\${CH_PRO}[^${ALL_SPECIAL}]+`, 'gi');
const SHORT_SYNTAX_TAGS_REG_EX = new RegExp(`\\${CH_TAG}[^${ALL_SPECIAL}|\\s]+`, 'gi');
// Literal notation: /\@[^\+|\#|\@]/gi
// Match string starting with the literal @ and followed by 1 or more of the characters
// not in the ALL_SPECIAL
const SHORT_SYNTAX_DUE_REG_EX = new RegExp(`\\${CH_DUE}[^${ALL_SPECIAL}]+`, 'gi');
export const shortSyntax = (
task: Task | Partial<Task>,
config: ShortSyntaxConfig,
allTags?: Tag[],
allProjects?: Project[],
now = new Date(),
):
| {
taskChanges: Partial<Task>;
newTagTitles: string[];
remindAt: number | null;
projectId: string | undefined;
}
| undefined => {
if (!task.title) {
return;
}
if (typeof (task.title as any) !== 'string') {
throw new Error('No str');
}
// TODO clean up this mess
let taskChanges: Partial<TaskCopy> = {};
let changesForProject: ProjectChanges = {};
let changesForTag: TagChanges = {};
if (config.isEnableDue) {
// NOTE: we do this twice... :-O ...it's weird, but required to make whitespaces work as separator and not as one
taskChanges = parseTimeSpentChanges(task);
taskChanges = {
...taskChanges,
...parseScheduledDate(task, now),
};
}
if (config.isEnableProject) {
changesForProject = parseProjectChanges(
{ ...task, title: taskChanges.title || task.title },
allProjects?.filter((p) => !p.isArchived && !p.isHiddenFromMenu),
);
if (changesForProject.projectId) {
taskChanges = {
...taskChanges,
title: changesForProject.title,
};
}
}
if (config.isEnableTag) {
changesForTag = parseTagChanges(
{ ...task, title: taskChanges.title || task.title },
allTags,
);
taskChanges = {
...taskChanges,
...(changesForTag.taskChanges || {}),
};
}
if (config.isEnableDue) {
taskChanges = {
...taskChanges,
// NOTE: because we pass the new taskChanges here we need to assignments...
...parseTimeSpentChanges(taskChanges),
// title: taskChanges.title?.trim(),
};
}
// const changesForDue = parseDueChanges({...task, title: taskChanges.title || task.title});
// if (changesForDue.remindAt) {
// taskChanges = {
// ...taskChanges,
// title: changesForDue.title,
// };
// }
if (Object.keys(taskChanges).length === 0) {
return undefined;
}
return {
taskChanges,
newTagTitles: changesForTag.newTagTitlesToCreate || [],
remindAt: null,
projectId: changesForProject.projectId,
// remindAt: changesForDue.remindAt
};
};
const parseProjectChanges = (
task: Partial<TaskCopy>,
allProjects?: Project[],
): ProjectChanges => {
if (
task.issueId || // don't allow for issue tasks
!task.title ||
!Array.isArray(allProjects) ||
!allProjects ||
allProjects.length === 0
) {
return {};
}
const rr = task.title.match(SHORT_SYNTAX_PROJECT_REG_EX);
if (rr && rr[0]) {
const projectTitle: string = rr[0].trim().replace(CH_PRO, '');
const projectTitleToMatch = projectTitle.replace(' ', '').toLowerCase();
const indexBeforePlus =
task.title.toLowerCase().lastIndexOf(CH_PRO + projectTitleToMatch) - 1;
const charBeforePlus = task.title.charAt(indexBeforePlus);
// don't parse Fun title+blu as project
if (charBeforePlus && charBeforePlus !== ' ') {
return {};
}
const existingProject = allProjects.find(
(project) =>
project.title.replace(' ', '').toLowerCase().indexOf(projectTitleToMatch) === 0,
);
if (existingProject) {
return {
title: task.title?.replace(`${CH_PRO}${projectTitle}`, '').trim(),
projectId: existingProject.id,
};
}
// also try only first word after special char
const projectTitleFirstWordOnly = projectTitle.split(' ')[0];
const projectTitleToMatch2 = projectTitleFirstWordOnly.replace(' ', '').toLowerCase();
const existingProjectForFirstWordOnly = allProjects.find(
(project) =>
project.title.replace(' ', '').toLowerCase().indexOf(projectTitleToMatch2) === 0,
);
if (existingProjectForFirstWordOnly) {
return {
title: task.title
?.replace(`${CH_PRO}${projectTitleFirstWordOnly}`, '')
.trim()
// get rid of excess whitespaces
.replace(' ', ' '),
projectId: existingProjectForFirstWordOnly.id,
};
}
}
return {};
};
const parseTagChanges = (task: Partial<TaskCopy>, allTags?: Tag[]): TagChanges => {
const taskChanges: Partial<TaskCopy> = {};
const newTagTitlesToCreate: string[] = [];
// only exec if previous ones are also passed
if (Array.isArray(task.tagIds) && Array.isArray(allTags)) {
const initialTitle = task.title as string;
const regexTagTitles = initialTitle.match(SHORT_SYNTAX_TAGS_REG_EX);
if (regexTagTitles && regexTagTitles.length) {
const regexTagTitlesTrimmedAndFiltered: string[] = regexTagTitles
.map((title) => title.trim().replace(CH_TAG, ''))
.filter((newTagTitle) => {
const charBeforeTag = initialTitle.charAt(
initialTitle.lastIndexOf(CH_TAG + newTagTitle) - 1,
);
// don't parse Fun title#blu as tag
if (charBeforeTag && charBeforeTag !== ' ') {
return false;
}
return (
newTagTitle.length >= 1 &&
// NOTE: we check this to not trigger for "#123 blasfs dfasdf"
initialTitle.trim().lastIndexOf(newTagTitle) > 4
);
});
const tagIdsToAdd: string[] = [];
regexTagTitlesTrimmedAndFiltered.forEach((newTagTitle) => {
const existingTag = allTags.find(
(tag) => newTagTitle.toLowerCase() === tag.title.toLowerCase(),
);
if (existingTag) {
if (!task.tagIds?.includes(existingTag.id)) {
tagIdsToAdd.push(existingTag.id);
}
} else {
newTagTitlesToCreate.push(newTagTitle);
}
});
if (tagIdsToAdd.length) {
taskChanges.tagIds = [...(task.tagIds as string[]), ...tagIdsToAdd];
}
if (
newTagTitlesToCreate.length ||
tagIdsToAdd.length ||
regexTagTitlesTrimmedAndFiltered.length
) {
taskChanges.title = initialTitle;
regexTagTitlesTrimmedAndFiltered.forEach((tagTitle) => {
taskChanges.title = taskChanges.title?.replace(`#${tagTitle}`, '');
});
taskChanges.title = taskChanges.title.trim();
}
// console.log(task.title);
// console.log('newTagTitles', regexTagTitles);
// console.log('newTagTitlesTrimmed', regexTagTitlesTrimmedAndFiltered);
// console.log('allTags)', allTags.map(tag => `${tag.id}: ${tag.title}`));
// console.log('task.tagIds', task.tagIds);
// console.log('task.title', task.title);
}
}
// console.log(taskChanges);
return {
taskChanges,
newTagTitlesToCreate,
};
};
const parseScheduledDate = (task: Partial<TaskCopy>, now: Date): DueChanges => {
if (!task.title) {
return {};
}
const rr = task.title.match(SHORT_SYNTAX_DUE_REG_EX);
if (rr && rr[0]) {
const parsedDateArr = customDateParser.parse(task.title, now, {
forwardDate: true,
});
if (parsedDateArr.length) {
const parsedDateResult = parsedDateArr[0];
const start = parsedDateResult.start;
const plannedAt = start.date().getTime();
let hasPlannedTime = true;
// If user doesn't explicitly enter time, set the scheduled date
// to 9:00:00 of the given day
if (!start.isCertain('hour')) {
hasPlannedTime = false;
}
const inputDate = parsedDateResult.text;
return {
plannedAt,
// Strip out the short syntax for scheduled date and given date
title: task.title.replace(`@${inputDate}`, ''),
...(hasPlannedTime ? {} : { hasPlannedTime: false }),
};
}
const simpleMatch = rr[0].match(/\d+/);
if (simpleMatch && simpleMatch[0] && typeof +simpleMatch[0] === 'number') {
const nr = +simpleMatch[0];
if (nr <= 24) {
const plannedAt = new Date();
plannedAt.setHours(nr, 0, 0, 0);
return {
plannedAt: plannedAt.getTime(),
title: task.title.replace(`@${nr}`, ''),
};
}
}
}
return {};
};
const parseTimeSpentChanges = (task: Partial<TaskCopy>): Partial<Task> => {
if (!task.title) {
return {};
}
const matches = SHORT_SYNTAX_TIME_REG_EX.exec(task.title);
if (matches && matches.length >= 3) {
const full = matches[0];
const timeSpent = matches[2]; // First part (before slash)
const timeEstimate = matches[3]; // Second part (after slash)
// If no slash, use the single value as timeEstimate only
const hasSlashFormat = matches[3] !== undefined;
return {
...(hasSlashFormat && timeSpent
? {
timeSpentOnDay: {
...(task.timeSpentOnDay || {}),
[getWorklogStr()]: stringToMs(timeSpent),
},
}
: {}),
...(timeEstimate
? { timeEstimate: stringToMs(timeEstimate) }
: timeSpent
? { timeEstimate: stringToMs(timeSpent) }
: {}),
title: task.title.replace(full, '').trim(),
};
}
return {};
};