/
WorkspaceWatcher.ts
92 lines (87 loc) · 2.75 KB
/
WorkspaceWatcher.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
import { DNodeUtilsV2, NotePropsV2, NoteUtilsV2 } from "@dendronhq/common-all";
import { HistoryService } from "@dendronhq/engine-server";
import _ from "lodash";
import moment from "moment";
import path from "path";
import {
ExtensionContext,
Range,
TextDocumentChangeEvent,
TextDocumentWillSaveEvent,
TextEdit,
window,
workspace,
} from "vscode";
import { Logger } from "./logger";
import { DendronWorkspace } from "./workspace";
export class WorkspaceWatcher {
activate(context: ExtensionContext) {
workspace.onWillSaveTextDocument(
this.onWillSaveTextDocument,
null,
context.subscriptions
);
workspace.onDidChangeTextDocument(
this.onDidChangeTextDocument,
null,
context.subscriptions
);
}
async onDidChangeTextDocument(event: TextDocumentChangeEvent) {
const activeEditor = window.activeTextEditor;
if (activeEditor && event.document === activeEditor.document) {
DendronWorkspace.instance().windowWatcher?.triggerUpdateDecorations();
}
return;
}
async onWillSaveTextDocument(ev: TextDocumentWillSaveEvent) {
const ctx = "WorkspaceWatcher:onWillSaveTextDocument";
const uri = ev.document.uri;
const reason = ev.reason;
Logger.info({ ctx, url: uri.fsPath, reason, msg: "enter" });
const eclient = DendronWorkspace.instance().getEngine();
const fname = path.basename(uri.fsPath, ".md");
const now = moment.now();
const vault = DNodeUtilsV2.getVaultByDir({
dirPath: path.dirname(uri.fsPath),
vaults: eclient.vaultsv3,
});
const note = NoteUtilsV2.getNoteByFnameV4({
fname,
vault,
notes: eclient.notes,
}) as NotePropsV2;
// if recently changed, ignore
const recentEvents = HistoryService.instance().lookBack();
if (recentEvents[0].uri?.fsPath === uri.fsPath) {
let lastUpdated: string | number = note?.updated || now;
if (_.isString(lastUpdated)) {
lastUpdated = _.parseInt(lastUpdated);
}
if (now - lastUpdated < 1 * 3e3) {
return;
}
}
const content = ev.document.getText();
const matchFM = NoteUtilsV2.RE_FM;
const matchOuter = content.match(matchFM);
if (!matchOuter) {
return;
}
const match = NoteUtilsV2.RE_FM_UPDATED.exec(content);
if (match) {
Logger.info({ ctx, match, msg: "update activeText editor" });
const startPos = ev.document.positionAt(match.index);
const endPos = ev.document.positionAt(match.index + match[0].length);
const p = new Promise(async (resolve) => {
note.updated = now.toString();
await eclient.updateNote(note);
resolve([
TextEdit.replace(new Range(startPos, endPos), `updated: ${now}`),
]);
});
ev.waitUntil(p);
}
return;
}
}