-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
210 lines (176 loc) · 7.27 KB
/
main.ts
File metadata and controls
210 lines (176 loc) · 7.27 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
import {
Plugin,
MarkdownView,
Notice,
} from 'obsidian';
import { TimerSettings } from './src/types';
import { TIMER_RE, extractTimerData } from './src/editor';
import { timerViewPlugin, setWidgetApp } from './src/widget';
import { TIMER_MUTATED_EVENT, nowSec } from './src/timer';
import { DEFAULT_SETTINGS, TimerSettingTab } from './src/settings';
import { handleCommand } from './src/commands';
import { buildContextMenu } from './src/contextMenu';
import { recoverRunningTimers, saveAllRunningTimers, pauseOpenEditorsSync, stopAllRunningTimers } from './src/recovery';
import { TimerRenderChild } from './src/postProcessor';
export default class TimerPlugin extends Plugin {
settings!: TimerSettings;
private beforeUnloadRef: (() => void) | null = null;
private timerMutatedRef: ((evt: Event) => void) | null = null;
private enforcingLimit = false;
async onload() {
await this.loadSettings();
setWidgetApp(this.app);
this.registerEditorExtension(timerViewPlugin);
await recoverRunningTimers(this.app, this.settings.lastActiveTime);
// Keep lastActiveTime up to date for recovery
this.registerInterval(
window.setInterval(() => {
this.settings.lastActiveTime = nowSec();
void this.saveSettings();
}, 30_000),
);
this.beforeUnloadRef = () => {
pauseOpenEditorsSync(this.app);
};
window.addEventListener('beforeunload', this.beforeUnloadRef);
this.timerMutatedRef = () => {
void this.saveSettings();
};
window.addEventListener(TIMER_MUTATED_EVENT, this.timerMutatedRef);
this.registerMarkdownPostProcessor((el, ctx) => {
const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
const nodes: Text[] = [];
let node: Node | null;
while ((node = walker.nextNode()) !== null) {
nodes.push(node as Text);
}
for (const textNode of nodes) {
const text = textNode.textContent ?? '';
const re = new RegExp(TIMER_RE.source, 'g');
let m: RegExpExecArray | null;
let last = 0;
let changed = false;
const frag = document.createDocumentFragment();
while ((m = re.exec(text)) !== null) {
changed = true;
if (m.index > last) {
frag.append(text.slice(last, m.index));
}
const data = extractTimerData(m);
const span = document.createElement('span');
span.className = `timer-badge timer-${data.kind} timer-${data.state}`;
frag.appendChild(span);
ctx.addChild(new TimerRenderChild(span, data, this.app, ctx.sourcePath));
last = m.index + m[0].length;
}
if (!changed) continue;
if (last < text.length) {
frag.append(text.slice(last));
}
textNode.parentNode?.replaceChild(frag, textNode);
}
});
this.registerEvent(
this.app.workspace.on('editor-change', (editor) => {
if (this.enforcingLimit) return;
const line = editor.getCursor().line;
const lineText = editor.getLine(line);
const matches = [...lineText.matchAll(new RegExp(TIMER_RE.source, 'g'))];
if (matches.length > 1) {
this.enforcingLimit = true;
try {
for (let i = matches.length - 1; i > 0; i--) {
const m = matches[i];
if (m.index !== undefined) {
editor.replaceRange(
'',
{ line, ch: m.index },
{ line, ch: m.index + m[0].length },
);
}
}
} finally {
this.enforcingLimit = false;
}
}
}),
);
this.addCommand({
id: 'toggle-timer',
name: 'Toggle timer',
hotkeys: [{ modifiers: ['Alt'], key: 's' }],
editorCallback: (e, v) =>
handleCommand(this.app, this.settings, e, v as MarkdownView, 'toggle', 'stopwatch'),
});
this.addCommand({
id: 'toggle-countdown',
name: 'Start/pause countdown',
hotkeys: [{ modifiers: ['Alt'], key: 'c' }],
editorCallback: (e, v) =>
handleCommand(this.app, this.settings, e, v as MarkdownView, 'toggle', 'countdown'),
});
this.addCommand({
id: 'stop-timer',
name: 'Stop timer',
editorCallback: (e, v) =>
handleCommand(this.app, this.settings, e, v as MarkdownView, 'stop'),
});
this.addCommand({
id: 'stop-all-timers',
name: 'Stop all running timers',
callback: async () => {
const count = await stopAllRunningTimers(this.app);
new Notice(`Stopped ${count} running timer(s).`);
}
});
this.addCommand({
id: 'reset-timer',
name: 'Reset timer',
editorCallback: (e, v) =>
handleCommand(this.app, this.settings, e, v as MarkdownView, 'reset'),
});
this.addCommand({
id: 'change-timer-time',
name: 'Change timer/countdown time',
editorCallback: (e, v) =>
handleCommand(this.app, this.settings, e, v as MarkdownView, 'change'),
});
this.addCommand({
id: 'delete-timer',
name: 'Delete timer',
hotkeys: [{ modifiers: ['Alt'], key: 'd' }],
editorCallback: (e, v) =>
handleCommand(this.app, this.settings, e, v as MarkdownView, 'delete'),
});
this.registerEvent(
this.app.workspace.on('editor-menu', (menu, editor, view) => {
if (view instanceof MarkdownView) {
buildContextMenu(this.app, this.settings, menu, editor, view);
}
}),
);
this.addSettingTab(new TimerSettingTab(this.app, this));
}
async onunload() {
if (this.beforeUnloadRef) {
window.removeEventListener('beforeunload', this.beforeUnloadRef);
this.beforeUnloadRef = null;
}
if (this.timerMutatedRef) {
window.removeEventListener(TIMER_MUTATED_EVENT, this.timerMutatedRef);
this.timerMutatedRef = null;
}
await saveAllRunningTimers(this.app);
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
// Cleanup old array if it exists
if ('runningTimerFiles' in this.settings) {
delete (this.settings as any).runningTimerFiles;
await this.saveSettings();
}
}
async saveSettings() {
await this.saveData(this.settings);
}
}