-
Notifications
You must be signed in to change notification settings - Fork 443
Expand file tree
/
Copy pathhelpers.ts
More file actions
409 lines (343 loc) · 11.8 KB
/
Copy pathhelpers.ts
File metadata and controls
409 lines (343 loc) · 11.8 KB
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
import update from 'immutability-helper';
import { App, MarkdownView, TFile, moment } from 'obsidian';
import Preact, { Dispatch, RefObject, useEffect } from 'preact/compat';
import { StateUpdater, useMemo } from 'preact/hooks';
import { StateManager } from 'src/StateManager';
import { Path } from 'src/dnd/types';
import { getEntityFromPath } from 'src/dnd/util/data';
import {
InlineField,
getTaskStatusDone,
getTaskStatusPreDone,
toggleTask,
} from 'src/parsers/helpers/inlineMetadata';
import { updateItemForQuery } from 'src/parsers/helpers/taskQuery';
import { SearchContextProps } from './context';
import { Board, DataKey, DateColor, Item, Lane, PageData, TagColor } from './types';
export const baseClassName = 'kanban-plugin';
export function noop() {}
const classCache = new Map<string, string>();
export function c(className: string) {
if (classCache.has(className)) return classCache.get(className);
const cls = `${baseClassName}__${className}`;
classCache.set(className, cls);
return cls;
}
export function generateInstanceId(len: number = 9): string {
return Math.random()
.toString(36)
.slice(2, 2 + len);
}
export function maybeCompleteForMove(
sourceStateManager: StateManager,
sourceBoard: Board,
sourcePath: Path,
destinationStateManager: StateManager,
destinationBoard: Board,
destinationPath: Path,
item: Item
): { next: Item; replacement?: Item } {
const sourceParent = getEntityFromPath(sourceBoard, sourcePath.slice(0, -1)) as Lane;
const destinationParent = getEntityFromPath(destinationBoard, destinationPath.slice(0, -1)) as Lane;
const oldShouldComplete = sourceParent?.data?.shouldMarkItemsComplete;
const newShouldComplete = destinationParent?.data?.shouldMarkItemsComplete;
// Check if moving to a query lane and update item for query if needed
if (destinationParent?.data?.query) {
item = updateItemForQuery(item, destinationParent.data.query);
}
// If neither the old or new lane set it complete, leave it alone
if (!oldShouldComplete && !newShouldComplete) return { next: item };
const isComplete = item.data.checked && item.data.checkChar === getTaskStatusDone();
// If it already matches the new lane, leave it alone
if (newShouldComplete === isComplete) return { next: item };
if (newShouldComplete) {
item = update(item, { data: { checkChar: { $set: getTaskStatusPreDone() } } });
}
const updates = toggleTask(item, destinationStateManager.file);
if (updates) {
const [itemStrings, checkChars, thisIndex] = updates;
let next: Item;
let replacement: Item;
itemStrings.forEach((str, i) => {
if (i === thisIndex) {
next = destinationStateManager.getNewItem(str, checkChars[i]);
} else {
replacement = destinationStateManager.getNewItem(str, checkChars[i]);
}
});
return { next, replacement };
}
// It's different, update it
return {
next: update(item, {
data: {
checked: {
$set: newShouldComplete,
},
checkChar: {
$set: newShouldComplete ? getTaskStatusDone() : ' ',
},
},
}),
};
}
export function useIMEInputProps() {
const isComposingRef = Preact.useRef<boolean>(false);
return {
// Note: these are lowercased because we use preact
// See: https://github.com/preactjs/preact/issues/3003
oncompositionstart: () => {
isComposingRef.current = true;
},
oncompositionend: () => {
isComposingRef.current = false;
},
getShouldIMEBlockAction: () => {
return isComposingRef.current;
},
};
}
export const templaterDetectRegex = /<%/;
export async function applyTemplate(stateManager: StateManager, templatePath?: string) {
const templateFile = templatePath
? stateManager.app.vault.getAbstractFileByPath(templatePath)
: null;
if (templateFile && templateFile instanceof TFile) {
const activeView = app.workspace.getActiveViewOfType(MarkdownView);
try {
// Force the view to source mode, if needed
if (activeView?.getMode() !== 'source') {
await activeView.setState(
{
...activeView.getState(),
mode: 'source',
},
{ history: false }
);
}
const { templatesEnabled, templaterEnabled, templatesPlugin, templaterPlugin } =
getTemplatePlugins(stateManager.app);
const templateContent = await stateManager.app.vault.read(templateFile);
// If both plugins are enabled, attempt to detect templater first
if (templatesEnabled && templaterEnabled) {
if (templaterDetectRegex.test(templateContent)) {
return await templaterPlugin.append_template_to_active_file(templateFile);
}
return await templatesPlugin.instance.insertTemplate(templateFile);
}
if (templatesEnabled) {
return await templatesPlugin.instance.insertTemplate(templateFile);
}
if (templaterEnabled) {
return await templaterPlugin.append_template_to_active_file(templateFile);
}
// No template plugins enabled so we can just append the template to the doc
await stateManager.app.vault.modify(
stateManager.app.workspace.getActiveFile(),
templateContent
);
} catch (e) {
console.error(e);
stateManager.setError(e);
}
}
}
export function getDefaultDateFormat(app: App) {
const internalPlugins = (app as any).internalPlugins.plugins;
const dailyNotesEnabled = internalPlugins['daily-notes']?.enabled;
const dailyNotesValue = internalPlugins['daily-notes']?.instance.options.format;
const nlDatesValue = (app as any).plugins.plugins['nldates-obsidian']?.settings.format;
const templatesEnabled = internalPlugins.templates?.enabled;
const templatesValue = internalPlugins.templates?.instance.options.dateFormat;
return (
(dailyNotesEnabled && dailyNotesValue) ||
nlDatesValue ||
(templatesEnabled && templatesValue) ||
'YYYY-MM-DD'
);
}
export function getDefaultTimeFormat(app: App) {
const internalPlugins = (app as any).internalPlugins.plugins;
const nlDatesValue = (app as any).plugins.plugins['nldates-obsidian']?.settings.timeFormat;
const templatesEnabled = internalPlugins.templates?.enabled;
const templatesValue = internalPlugins.templates?.instance.options.timeFormat;
return nlDatesValue || (templatesEnabled && templatesValue) || 'HH:mm';
}
const reRegExChar = /[\\^$.*+?()[\]{}|]/g;
const reHasRegExChar = RegExp(reRegExChar.source);
export function escapeRegExpStr(str: string) {
return str && reHasRegExChar.test(str) ? str.replace(reRegExChar, '\\$&') : str || '';
}
export function getTemplatePlugins(app: App) {
const templatesPlugin = (app as any).internalPlugins.plugins.templates;
const templatesEnabled = templatesPlugin.enabled;
const templaterPlugin = (app as any).plugins.plugins['templater-obsidian'];
const templaterEnabled = (app as any).plugins.enabledPlugins.has('templater-obsidian');
const templaterEmptyFileTemplate =
templaterPlugin &&
(this.app as any).plugins.plugins['templater-obsidian'].settings?.empty_file_template;
const templateFolder = templatesEnabled
? templatesPlugin.instance.options.folder
: templaterPlugin
? templaterPlugin.settings.template_folder
: undefined;
return {
templatesPlugin,
templatesEnabled,
templaterPlugin: templaterPlugin?.templater,
templaterEnabled,
templaterEmptyFileTemplate,
templateFolder,
};
}
export function getTagColorFn(tagColors: TagColor[]) {
const tagMap = (tagColors || []).reduce<Record<string, TagColor>>((total, current) => {
if (!current.tagKey) return total;
total[current.tagKey] = current;
return total;
}, {});
return (tag: string) => {
if (tagMap[tag]) return tagMap[tag];
return null;
};
}
export function useGetTagColorFn(stateManager: StateManager): (tag: string) => TagColor {
const tagColors = stateManager.useSetting('tag-colors');
return useMemo(() => getTagColorFn(tagColors), [tagColors]);
}
export function getDateColorFn(dateColors: DateColor[]) {
const orders = (dateColors || []).map<[moment.Moment | 'today' | 'before' | 'after', DateColor]>(
(c) => {
if (c.isToday) {
return ['today', c];
}
if (c.isBefore) {
return ['before', c];
}
if (c.isAfter) {
return ['after', c];
}
const modifier = c.direction === 'after' ? 1 : -1;
const date = moment();
date.add(c.distance * modifier, c.unit);
return [date, c];
}
);
const now = moment();
orders.sort((a, b) => {
if (a[0] === 'today') {
return typeof b[0] === 'string' ? -1 : b[0].isSame(now, 'day') ? 1 : -1;
}
if (b[0] === 'today') {
return typeof a[0] === 'string' ? 1 : a[0].isSame(now, 'day') ? -1 : 1;
}
if (a[0] === 'after') return 1;
if (a[0] === 'before') return 1;
if (b[0] === 'after') return -1;
if (b[0] === 'before') return -1;
return a[0].isBefore(b[0]) ? -1 : 1;
});
return (date: moment.Moment) => {
const now = moment();
const result = orders.find((o) => {
const key = o[1];
if (key.isToday) return date.isSame(now, 'day');
if (key.isAfter) return date.isAfter(now);
if (key.isBefore) return date.isBefore(now);
let granularity: moment.unitOfTime.StartOf = 'days';
if (key.unit === 'hours') {
granularity = 'hours';
}
if (key.direction === 'before') {
return date.isBetween(o[0], now, granularity, '[]');
}
return date.isBetween(now, o[0], granularity, '[]');
});
if (result) {
return result[1];
}
return null;
};
}
export function useGetDateColorFn(
stateManager: StateManager
): (date: moment.Moment) => DateColor | null {
const dateColors = stateManager.useSetting('date-colors');
return useMemo(() => getDateColorFn(dateColors), [dateColors]);
}
export function parseMetadataWithOptions(data: InlineField, metadataKeys: DataKey[]): PageData {
const options = metadataKeys.find((opts) => opts.metadataKey === data.key);
return options
? {
...options,
value: data.value,
}
: {
containsMarkdown: false,
label: data.key,
metadataKey: data.key,
shouldHideLabel: false,
value: data.value,
};
}
export function useOnMount(refs: RefObject<HTMLElement>[], cb: () => void, onUnmount?: () => void) {
useEffect(() => {
let complete = 0;
let unmounted = false;
const onDone = () => {
if (unmounted) return;
if (++complete === refs.length) {
cb();
}
};
for (const ref of refs) ref.current?.onNodeInserted(onDone, true);
return () => {
unmounted = true;
onUnmount();
};
}, []);
}
export function useSearchValue(
board: Board,
query: string,
setSearchQuery: Dispatch<StateUpdater<string>>,
setDebouncedSearchQuery: Dispatch<StateUpdater<string>>,
setIsSearching: Dispatch<StateUpdater<boolean>>
) {
return useMemo<SearchContextProps>(() => {
query = query.trim().toLocaleLowerCase();
const lanes = new Set<Lane>();
const items = new Set<Item>();
if (query) {
board.children.forEach((lane) => {
let laneMatched = false;
lane.children.forEach((item) => {
if (item.data.titleSearch.includes(query)) {
laneMatched = true;
items.add(item);
}
});
if (laneMatched) lanes.add(lane);
});
}
return {
lanes,
items,
query,
search: (query, immediate) => {
if (!query) {
setIsSearching(false);
setSearchQuery('');
setDebouncedSearchQuery('');
}
setIsSearching(true);
if (immediate) {
setSearchQuery(query);
setDebouncedSearchQuery(query);
} else {
setSearchQuery(query);
}
},
};
}, [board, query, setSearchQuery, setDebouncedSearchQuery]);
}