-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathmain.ts
249 lines (216 loc) · 8.09 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
import { MarkdownView, MetadataCache, Notice, Plugin, TFile, Vault, Workspace } from 'obsidian';
import isURL from 'validator/lib/isURL';
import './styles/styles.scss';
import IconModal from './modals/IconModal';
import LocalImageModal from './modals/LocalImageModal';
import MetaManager from './MetaManager';
import SettingsTab, { INITIAL_SETTINGS, DEFAULT_VALUES, ISettingsOptions } from './Settings';
import getPostProcessor from './cm5';
import getExtension from './cm6';
export default class BannersPlugin extends Plugin {
settings: ISettingsOptions;
workspace: Workspace;
vault: Vault;
metadataCache: MetadataCache
metaManager: MetaManager;
holdingDragModKey: boolean
async onload() {
console.log('Loading Banners...');
this.settings = Object.assign({}, INITIAL_SETTINGS, await this.loadData());
this.workspace = this.app.workspace;
this.vault = this.app.vault;
this.metadataCache = this.app.metadataCache;
this.metaManager = new MetaManager(this);
this.holdingDragModKey = false;
this.loadProcessor();
this.loadExtension();
this.loadCommands();
this.loadStyles();
this.loadListeners();
this.loadPrecheck();
this.addSettingTab(new SettingsTab(this));
this.refreshViews();
}
async onunload() {
console.log('Unloading Banners...');
this.unloadListeners();
this.unloadBanners();
this.unloadStyles();
}
loadListeners() {
// Banner cursor toggling
window.addEventListener('keydown', this.isDragModHeld);
window.addEventListener('keyup', this.isDragModHeld);
}
loadProcessor() {
const processor = getPostProcessor(this);
this.registerMarkdownPostProcessor(processor);
}
loadExtension() {
const extension = getExtension(this);
this.registerEditorExtension(extension);
}
loadCommands() {
this.addCommand({
id: 'banners:addBanner',
name: 'Add/Change banner with local image',
checkCallback: (checking) => {
const file = this.workspace.getActiveFile();
if (checking) { return !!file }
new LocalImageModal(this, file).open();
}
});
this.addCommand({
id: 'banners:addIcon',
name: 'Add/Change emoji icon',
checkCallback: (checking) => {
const file = this.workspace.getActiveFile();
if (checking) { return !!file }
new IconModal(this, file).open();
}
});
this.addCommand({
id: 'banners:pasteBanner',
name: 'Paste banner from clipboard',
checkCallback: (checking) => {
const file = this.workspace.getActiveFile();
if (checking) { return !!file }
this.pasteBanner(file);
}
});
this.addCommand({
id: 'banners:lockBanner',
name: 'Lock/Unlock banner position',
checkCallback: (checking) => {
const file = this.workspace.getActiveFile();
if (checking) { return !!file }
this.toggleBannerLock(file);
}
})
this.addCommand({
id: 'banners:removeBanner',
name: 'Remove banner',
checkCallback: (checking) => {
const file = this.workspace.getActiveFile();
if (checking) {
if (!file) { return false }
return !!this.metaManager.getBannerDataFromFile(file)?.src;
}
this.removeBanner(file);
}
});
this.addCommand({
id: 'banners:removeIcon',
name: 'Remove icon',
checkCallback: (checking) => {
const file = this.workspace.getActiveFile();
if (checking) {
if (!file) { return false }
return !!this.metaManager.getBannerDataFromFile(file)?.icon;
}
this.removeIcon(file);
}
});
}
loadStyles() {
document.documentElement.style.setProperty('--banner-height', `${this.getSettingValue('height')}px`);
document.documentElement.style.setProperty('--banner-internal-embed-height', `${this.getSettingValue('internalEmbedHeight')}px`);
document.documentElement.style.setProperty('--banner-preview-embed-height', `${this.getSettingValue('previewEmbedHeight')}px`);
}
loadPrecheck() {
// Wrap banner source in quotes to prevent errors later in CM6 extension
const files = this.workspace.getLeavesOfType('markdown').map((leaf) => (leaf.view as MarkdownView).file);
const uniqueFiles = [...new Set(files)];
uniqueFiles.forEach((file) => this.lintBannerSource(file));
this.workspace.on('file-open', (file) => this.lintBannerSource(file));
}
unloadListeners() {
window.removeEventListener('keydown', this.isDragModHeld);
window.removeEventListener('keyup', this.isDragModHeld);
}
unloadBanners() {
this.workspace.containerEl
.querySelectorAll('.obsidian-banner-wrapper')
.forEach((wrapper) => {
wrapper.querySelector('.obsidian-banner')?.remove();
wrapper.querySelector('.obsidian-banner-icon')?.remove();
wrapper.removeClasses(['obsidian-banner-wrapper', 'has-banner-icon']);
});
}
unloadStyles() {
document.documentElement.style.removeProperty('--banner-height');
document.documentElement.style.removeProperty('--banner-internal-embed-height');
document.documentElement.style.removeProperty('--banner-preview-embed-height');
}
// Helper to check if the drag modifier key is being held down or not, if specified
isDragModHeld = (e: KeyboardEvent) => {
let ret: boolean;
switch (this.settings.bannerDragModifier) {
case 'alt': ret = e.altKey; break;
case 'ctrl': ret = e.ctrlKey; break;
case 'meta': ret = e.metaKey; break;
case 'shift': ret = e.shiftKey; break;
default: ret = true;
}
this.holdingDragModKey = ret;
this.toggleBannerCursor(ret);
}
// Helper to refresh markdown views
refreshViews() {
this.workspace.updateOptions();
this.workspace.getLeavesOfType('markdown').forEach((leaf) => {
if (leaf.getViewState().state.mode.includes('preview')) {
(leaf.view as MarkdownView).previewMode.rerender(true);
}
});
}
// Helper to use clipboard for banner
async pasteBanner(file: TFile) {
const clipboard = await navigator.clipboard.readText();
if (!isURL(clipboard)) {
new Notice('Your clipboard didn\'t had a valid URL! Please try again (and check the console if you wanna debug).');
console.error({ clipboard });
} else {
await this.metaManager.upsertBannerData(file, { src: `"${clipboard}"` });
new Notice('Pasted a new banner!');
}
}
// Helper to apply grab cursor for banner images
// TODO: This feels fragile, perhaps look for a better way
toggleBannerCursor = (val: boolean) => {
document.querySelectorAll('.banner-image').forEach((el) => el.toggleClass('draggable', val));
}
// Helper to toggle banner position locking
async toggleBannerLock(file: TFile) {
const { lock = false } = this.metaManager.getBannerDataFromFile(file);
if (lock) {
await this.metaManager.removeBannerData(file, 'lock');
new Notice(`Unlocked banner position for ${file.name}!`);
} else {
await this.metaManager.upsertBannerData(file, { lock: true });
new Notice(`Locked banner position for ${file.name}!`);
}
}
// Helper to remove banner
async removeBanner(file: TFile) {
await this.metaManager.removeBannerData(file, ['src', 'x', 'y', 'lock']);
new Notice(`Removed banner for ${file.name}!`);
}
// Helper to remove banner icon
async removeIcon(file: TFile) {
await this.metaManager.removeBannerData(file, 'icon');
new Notice(`Removed banner icon for ${file.name}!`);
}
// Helper to wrap banner source in quotes if not already (Patch for previous versions)
async lintBannerSource(file: TFile) {
if (!file) { return }
const { frontmatter } = this.metadataCache.getFileCache(file);
const src = this.metaManager.getBannerData(frontmatter)?.src;
if (!src || (src.startsWith('"') && src.endsWith('"'))) { return }
await this.metaManager.upsertBannerData(file, { src: `"${src}"` });
}
// Helper to get setting value (or the default setting value if not set)
getSettingValue<K extends keyof ISettingsOptions>(key: K): Partial<ISettingsOptions>[K] {
return this.settings[key] ?? DEFAULT_VALUES[key];
}
}