generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmain.ts
454 lines (370 loc) · 18.3 KB
/
main.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
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
import {App, MarkdownView, Plugin, PluginSettingTab, Setting, TFile, WorkspaceWindow, View, Notice} from 'obsidian';
import { Util, HandleZoomParams } from "./src/util";
interface MouseWheelZoomSettings {
initialSize: number;
modifierKey: ModifierKey;
stepSize: number;
resizeInCanvas: boolean;
}
enum ModifierKey {
ALT = "AltLeft",
CTRL = "ControlLeft",
SHIFT = "ShiftLeft",
ALT_RIGHT = "AltRight",
CTRL_RIGHT = "ControlRight",
SHIFT_RIGHT = "ShiftRight"
}
const DEFAULT_SETTINGS: MouseWheelZoomSettings = {
modifierKey: ModifierKey.ALT,
stepSize: 25,
initialSize: 500,
resizeInCanvas: true,
}
const CtrlCanvasConflictWarning = "Warning: Using Ctrl as the modifier key conflicts with default canvas zooming behavior when 'Resize in canvas' is enabled. Consider using another modifier key or disabling 'Resize in canvas'.";
export default class MouseWheelZoomPlugin extends Plugin {
settings: MouseWheelZoomSettings;
isKeyHeldDown = false;
async onload() {
await this.loadSettings();
this.registerEvent(
this.app.workspace.on("window-open", (newWindow: WorkspaceWindow) => this.registerEvents(newWindow.win))
);
this.registerEvents(window);
this.addSettingTab(new MouseWheelZoomSettingsTab(this.app, this));
console.log("Loaded: Mousewheel image zoom")
this.checkExistingUserConflict();
}
checkExistingUserConflict() {
const noticeShownKey = 'mousewheel-zoom-ctrl-warning-shown'; // Key for localStorage flag
const isCtrl = this.settings.modifierKey === ModifierKey.CTRL || this.settings.modifierKey === ModifierKey.CTRL_RIGHT;
// Only show the notice if the conflict exists AND the user hasn't dismissed it before (using localStorage flag)
if (isCtrl && this.settings.resizeInCanvas && !localStorage.getItem(noticeShownKey)) {
const fragment = document.createDocumentFragment();
const titleEl = document.createElement('strong');
titleEl.textContent = "Mousewheel Image Zoom";
fragment.appendChild(titleEl);
fragment.appendChild(document.createElement('br'));
const messageEl = document.createElement('span');
messageEl.textContent = CtrlCanvasConflictWarning;
fragment.appendChild(messageEl);
fragment.appendChild(document.createElement('br'));
const settingsButton = document.createElement('button');
settingsButton.textContent = "Open Settings";
settingsButton.style.marginTop = "5px";
settingsButton.onclick = () => {
// settings is a private property of the app object, so we need to cast it to any to access it
// See https://forum.obsidian.md/t/open-settings-for-my-plugin-community-plugin-settings-deeplink/61563/4
const setting = (this.app as any).setting;
setting.open();
setting.openTabById(this.manifest.id);
};
fragment.appendChild(settingsButton);
const notice = new Notice(fragment, 0);
// Set the flag in localStorage so the notice doesn't appear again
// unless the user clears their localStorage or the key changes.
localStorage.setItem(noticeShownKey, 'true');
}
}
/**
* When the config key is released, we enable the scroll again and reset the key held down flag.
*/
onConfigKeyUp(currentWindow: Window) {
this.isKeyHeldDown = false;
this.enableScroll(currentWindow);
}
onunload(currentWindow: Window = window) {
// Re-enable the normal scrolling behavior when the plugin unloads
this.enableScroll(currentWindow);
}
/**
* Registers image resizing events for the specified window
* @param currentWindow window in which to register events
* @private
*/
private registerEvents(currentWindow: Window) {
const doc: Document = currentWindow.document;
this.registerDomEvent(doc, "keydown", (evt) => {
if (evt.code === this.settings.modifierKey.toString()) {
// When canvas mode is enabled we just ignore the keydown event if the canvas is active
const isActiveViewCanvas = this.app.workspace.getActiveViewOfType(View)?.getViewType() === "canvas";
if (isActiveViewCanvas && !this.settings.resizeInCanvas) {
return;
}
this.isKeyHeldDown = true;
if (this.settings.modifierKey !== ModifierKey.SHIFT && this.settings.modifierKey !== ModifierKey.SHIFT_RIGHT) { // Ignore shift to allow horizontal scrolling
// Disable the normal scrolling behavior when the key is held down
this.disableScroll(currentWindow);
}
}
});
this.registerDomEvent(doc, "keyup", (evt) => {
if (evt.code === this.settings.modifierKey.toString()) {
this.onConfigKeyUp(currentWindow);
}
});
this.registerDomEvent(doc, "wheel", (evt) => {
if (this.isKeyHeldDown) {
// When for example using Alt + Tab to switch between windows, the key is still recognized as held down.
// We check if the key is really held down by checking if the key is still pressed in the event when the
// wheel event is triggered.
if (!this.isConfiguredKeyDown(evt)) {
this.onConfigKeyUp(currentWindow);
return;
}
const eventTarget = evt.target as Element;
const targetIsCanvas: boolean = eventTarget.hasClass("canvas-node-content-blocker")
const targetIsCanvasNode: boolean = eventTarget.closest(".canvas-node-content") !== null;
const targetIsImage: boolean = eventTarget.nodeName === "IMG";
if (targetIsCanvas || targetIsCanvasNode || targetIsImage) {
this.disableScroll(currentWindow);
}
if (targetIsCanvas && this.settings.resizeInCanvas){
// seems we're trying to zoom on some canvas node.
this.handleZoomForCanvas(evt, eventTarget);
}
else if (targetIsCanvasNode) {
// we trying to resize focused canvas node.
// i think here can be implementation of zoom images in embded markdown files on canvas.
}
else if (targetIsImage) {
// Handle the zooming of the image
this.handleZoom(evt, eventTarget);
}
}
});
this.registerDomEvent(currentWindow, "blur", () => {
// When the window loses focus, ensure scrolling is re-enabled for this window
// and reset the key held state defensively, although the keyup should ideally handle it.
this.isKeyHeldDown = false;
this.enableScroll(currentWindow);
});
}
/**
* Handles zooming with the mousewheel on canvas node
* @param evt wheel event
* @param eventTarget targeted canvas node element
* @private
*/
handleZoomForCanvas(evt: WheelEvent, eventTarget: Element) {
// get active canvas
const isCanvas: boolean = this.app.workspace.getActiveViewOfType(View).getViewType() === "canvas";
if (!isCanvas) {
throw new Error("Can't find canvas");
};
// Unfortunately the current type definitions don't include any canvas functionality...
const canvas = (this.app.workspace.getActiveViewOfType(View) as any).canvas;
// get triggered canvasNode
const canvasNode =
Array.from(canvas.nodes.values())
.find(node => (node as any).contentBlockerEl == eventTarget) as any;
// Adjust delta based on the direction of the resize
let delta = evt.deltaY > 0 ? this.settings.stepSize : this.settings.stepSize * -1;
// Calculate new dimensions directly using the delta and aspectRatio
const aspectRatio = canvasNode.width / canvasNode.height;
const newWidth = canvasNode.width + delta;
const newHeight = newWidth / aspectRatio;
// Resize the canvas node using the new dimensions
canvasNode.resize({width: newWidth, height: newHeight});
}
/**
* Handles zooming with the mousewheel on an image
* @param evt wheel event
* @param eventTarget targeted image element
* @private
*/
private async handleZoom(evt: WheelEvent, eventTarget: Element) {
const imageUri = eventTarget.attributes.getNamedItem("src").textContent;
const activeFile: TFile = await this.getActivePaneWithImage(eventTarget);
await this.app.vault.process(activeFile, (fileText) => {
let frontmatter = "";
let body = fileText;
const frontmatterRegex = /^---\s*([\s\S]*?)\s*---\n*/;
const match = fileText.match(frontmatterRegex);
if (match) {
frontmatter = match[0]; // Keep the full matched frontmatter block including delimiters and trailing newline
body = fileText.slice(frontmatter.length); // The rest is the body
}
const zoomParams: HandleZoomParams = this.getZoomParams(imageUri, body, eventTarget);
// Perform replacements ONLY on the body
let modifiedBody = body;
const sizeMatches = body.match(zoomParams.sizeMatchRegExp);
// Element already has a size entry in the body
if (sizeMatches !== null) {
const oldSize: number = parseInt(sizeMatches[1]);
let newSize: number = oldSize;
if (evt.deltaY < 0) {
newSize += this.settings.stepSize;
} else if (evt.deltaY > 0 && newSize > this.settings.stepSize) {
newSize -= this.settings.stepSize;
}
// Replace within the body
modifiedBody = body.replace(zoomParams.replaceSizeExist.getReplaceFromString(oldSize), zoomParams.replaceSizeExist.getReplaceWithString(newSize));
} else { // Element has no size entry in the body -> give it an initial size
const initialSize = this.settings.initialSize;
const image = new Image();
image.src = imageUri;
const width = image.naturalWidth || initialSize;
const minWidth = Math.min(width, initialSize);
// Replace within the body
modifiedBody = body.replace(zoomParams.replaceSizeNotExist.getReplaceFromString(0), zoomParams.replaceSizeNotExist.getReplaceWithString(minWidth));
}
// Combine original frontmatter with the modified body
return frontmatter + modifiedBody;
});
}
/**
* Loop through all panes and get the pane that hosts a markdown file with the image to zoom
* @param imageElement The HTML Element of the image
* @private
*/
private async getActivePaneWithImage(imageElement: Element): Promise<TFile> {
return new Promise(((resolve, reject) => {
this.app.workspace.iterateAllLeaves(leaf => {
if (leaf.view.containerEl.contains(imageElement) && leaf.view instanceof MarkdownView) {
resolve(leaf.view.file);
}
})
reject(new Error("No file belonging to the image found"))
}))
}
private getZoomParams(imageUri: string, fileText: string, target: Element) {
if (imageUri.contains("http")) {
return Util.getRemoteImageZoomParams(imageUri, fileText)
} else if (target.classList.value.match("excalidraw-svg.*")) {
const src = target.attributes.getNamedItem("filesource").textContent;
// remove ".md" from the end of the src
const imageName = src.substring(0, src.length - 3);
// Only get text after "/"
const imageNameAfterSlash = imageName.substring(imageName.lastIndexOf("/") + 1);
return Util.getLocalImageZoomParams(imageNameAfterSlash, fileText)
} else if (imageUri.contains("app://")) {
const imageName = Util.getLocalImageNameFromUri(imageUri);
return Util.getLocalImageZoomParams(imageName, fileText)
}
throw new Error("Image is not zoomable")
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
// Utilities to disable and enable scrolling //
preventDefault(ev: WheelEvent) {
ev.preventDefault();
}
wheelOpt: AddEventListenerOptions = {passive: false, capture: true }
wheelEvent = 'wheel' as keyof WindowEventMap;
/**
* Disables the normal scroll event
*/
disableScroll(currentWindow: Window) {
currentWindow.addEventListener(this.wheelEvent, this.preventDefault, this.wheelOpt);
}
/**
* Enables the normal scroll event
*/
enableScroll(currentWindow: Window) {
currentWindow.removeEventListener(this.wheelEvent, this.preventDefault, this.wheelOpt);
}
private isConfiguredKeyDown(evt: WheelEvent): boolean {
switch (this.settings.modifierKey) {
case ModifierKey.ALT:
case ModifierKey.ALT_RIGHT:
return evt.altKey;
case ModifierKey.CTRL:
case ModifierKey.CTRL_RIGHT:
return evt.ctrlKey;
case ModifierKey.SHIFT:
case ModifierKey.SHIFT_RIGHT:
return evt.shiftKey;
}
}
}
class MouseWheelZoomSettingsTab extends PluginSettingTab {
plugin: MouseWheelZoomPlugin;
warningEl: HTMLDivElement;
constructor(app: App, plugin: MouseWheelZoomPlugin) {
super(app, plugin);
this.plugin = plugin;
}
// Helper function to update the warning message
updateWarningMessage(modifierKey: ModifierKey, resizeInCanvas: boolean): void {
if (!this.warningEl) return;
const isCtrl = modifierKey === ModifierKey.CTRL || modifierKey === ModifierKey.CTRL_RIGHT;
const conflict = isCtrl && resizeInCanvas;
if (conflict) {
this.warningEl.setText(CtrlCanvasConflictWarning);
this.warningEl.style.display = 'block';
this.warningEl.style.color = 'var(--text-warning)';
this.warningEl.style.marginTop = '10px';
} else {
this.warningEl.setText("");
this.warningEl.style.display = 'none';
}
}
display(): void {
let {containerEl} = this;
containerEl.empty();
containerEl.createEl('h2', {text: 'Settings for mousewheel zoom'});
new Setting(containerEl)
.setName('Trigger Key')
.setDesc('Key that needs to be pressed down for mousewheel zoom to work.')
.addDropdown(dropdown => dropdown
.addOption(ModifierKey.CTRL, "Ctrl")
.addOption(ModifierKey.ALT, "Alt")
.addOption(ModifierKey.SHIFT, "Shift")
.addOption(ModifierKey.CTRL_RIGHT, "Right Ctrl")
.addOption(ModifierKey.ALT_RIGHT, "Right Alt")
.addOption(ModifierKey.SHIFT_RIGHT, "Right Shift")
.setValue(this.plugin.settings.modifierKey)
.onChange(async (value) => {
this.plugin.settings.modifierKey = value as ModifierKey;
this.updateWarningMessage(this.plugin.settings.modifierKey , this.plugin.settings.resizeInCanvas);
await this.plugin.saveSettings()
})
);
new Setting(containerEl)
.setName('Step size')
.setDesc('Step value by which the size of the image should be increased/decreased')
.addSlider(slider => {
slider
.setValue(25)
.setLimits(0, 100, 1)
.setDynamicTooltip()
.setValue(this.plugin.settings.stepSize)
.onChange(async (value) => {
this.plugin.settings.stepSize = value
await this.plugin.saveSettings()
})
})
new Setting(containerEl)
.setName('Initial Size')
.setDesc('Initial image size if no size was defined beforehand')
.addSlider(slider => {
slider
.setValue(500)
.setLimits(0, 1000, 25)
.setDynamicTooltip()
.setValue(this.plugin.settings.initialSize)
.onChange(async (value) => {
this.plugin.settings.initialSize = value
await this.plugin.saveSettings()
})
})
new Setting(containerEl)
.setName('Resize in canvas')
.setDesc('When enabled, all nodes on the Obsidian canvas can also be resized using the Modifier key')
.addToggle((toggle) => {
toggle.setValue(this.plugin.settings.resizeInCanvas)
.onChange(async (value) => {
this.plugin.settings.resizeInCanvas = value;
this.updateWarningMessage(this.plugin.settings.modifierKey, value);
await this.plugin.saveSettings();
});
});
this.warningEl = containerEl.createDiv({ cls: 'mousewheel-zoom-warning' });
this.warningEl.style.display = 'none';
this.updateWarningMessage(this.plugin.settings.modifierKey, this.plugin.settings.resizeInCanvas);
}
}