generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.ts
361 lines (290 loc) · 9.67 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
import {
Editor,
MarkdownView,
Notice,
Plugin,
Menu,
Scope,
ButtonComponent,
Modal,
} from 'obsidian';
import { DEFAULT_SETTINGS, FastTextColorPluginSettingTab, FastTextColorPluginSettings, getColors, SETTINGS_VERSION, updateSettings, CSS_COLOR_PREFIX, getCurrentTheme } from 'src/FastTextColorSettings';
import { TextColor } from 'src/color/TextColor';
import { PREFIX, SUFFIX } from 'src/utils/regularExpressions';
import { textColorViewPlugin } from 'src/rendering/TextColorViewPlugin'
import { textColorParserField } from 'src/rendering/TextColorStateField';
import { textColorPostProcessor } from 'src/rendering/TextColorPostProcessor'
import { EditorState, Prec, Extension, Compartment } from "@codemirror/state";
import { keymap, EditorView } from '@codemirror/view'
import { settingsFacet } from "./src/SettingsFacet";
import { applyColor, removeColor } from "src/color/TextColorFunctions";
import { ColorSuggestModal } from 'src/utils/ColorSuggestModal';
const MAX_MENU_ITEMS: number = 10;
export default class FastTextColorPlugin extends Plugin {
settings: FastTextColorPluginSettings;
colorMenu: HTMLDivElement | null | undefined;
scope: Scope;
styleElement: HTMLElement;
settingsExtension: Extension;
settingsCompartment: Compartment;
async onload() {
await this.loadSettings();
// setup Editor Extensions
this.registerEditorExtension(textColorParserField);
this.registerEditorExtension(textColorViewPlugin);
this.registerMarkdownPostProcessor((el, ctx) => { textColorPostProcessor(el, ctx, this.settings); }, -1000);
this.registerMarkdownPostProcessor((el, ctx) => { textColorPostProcessor(el, ctx, this.settings); }, 1000);
// to make settings available in the ViewPlugin.
this.settingsCompartment = new Compartment();
this.settingsExtension = this.settingsCompartment.of(settingsFacet.of(this.settings));
this.registerEditorExtension(this.settingsExtension);
this.registerEditorExtension(
Prec.high(
keymap.of([
{
key: "Tab",
run: (editorView) => this.jumpOut(editorView),
},
])
)
);
this.addCommand({
id: 'change-text-color',
name: 'Change text color',
editorCallback: (editor: Editor) => { // for this to work, needs to be in editor mode
this.openColorMenu(editor);
}
});
this.addCommand({
id: 'remove-text-color',
name: 'Remove text color',
editorCallback: (editor, view) => {
// @ts-expect-error, not typed
const editorView = view.editor.cm as EditorView;
removeColor(editor, editorView);
}
})
// add coloring to editor context menu.
this.registerEvent(
this.app.workspace.on("editor-menu", (menu, editor, view) => {
if (editor.getSelection() == '') {
return;
}
menu.addItem((item) => {
item
.setSection("selection")
.setTitle("Color")
.setIcon("palette");
// @ts-ignore
const submenu: Menu = item.setSubmenu();
getColors(this.settings).forEach(tColor => {
submenu.addItem((subitem) => {
subitem
.setTitle(tColor.id)
.setIcon("circle")
.onClick(evt => {
applyColor(tColor, editor);
});
// @ts-ignore
(subitem.dom as HTMLElement).addClass(tColor.className);
// @ts-ignore
(subitem.iconEl as HTMLElement).addClass(tColor.className);
})
});
})
})
);
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new FastTextColorPluginSettingTab(this.app, this));
this.setCssVariables();
}
onunload() {
this.styleElement.remove();
this.closeColorMenu();
// remove editorextensions
}
async loadSettings() {
// this.settings = DEFAULT_SETTINGS; return; // DEBUG
const rawSettings = await this.loadData();
// if settings already exists but are an older version
if (rawSettings && +rawSettings.version < +SETTINGS_VERSION) {
console.log("outdated Settings! Trying to update.")
this.settings = updateSettings(rawSettings)
await this.saveData(this.settings);
return;
}
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
// reinitialize theme
for (let j = 0; j < this.settings.themes.length; j++) {
const colors = getColors(this.settings, j);
for (let i = 0; i < colors.length; i++) {
let obj: TextColor = colors[i]
colors[i] = new TextColor(obj.color, obj.id, this.settings.themes[j].name, obj.italic, obj.bold, obj.cap_mode.index, obj.line_mode.index, obj.keybind, obj.useCssColorVariable, obj.colorVariable);
}
}
}
async saveSettings() {
await this.saveData(this.settings);
const view = this.app.workspace.getActiveViewOfType(MarkdownView);
const editorView = (view?.editor as any)?.cm as EditorView;
if (editorView == null) {
return;
}
editorView.dispatch({
effects: this.settingsCompartment.reconfigure(settingsFacet.of(this.settings))
})
}
// create and open the color menu
/**
* opens the color menu and pushed the scope onto the keybindings.
*
* @param {Editor} editor - [TODO:description]
*/
openColorMenu(editor: Editor) {
if (!this.settings.useKeybindings) {
// if keybindings are not used create a normal choice
let modal = new ColorSuggestModal(this.app, getColors(this.settings), editor);
modal.open();
return;
}
// TODO: do i really need to rebuild this every time?
if (this.colorMenu != null) {
// console.log('colorMenu already exists');
return;
}
this.colorMenu = createDiv();
if (!this.colorMenu) {
// console.log("could not create colorMenu.");
new Notice("could not create Colormenu!")
return;
}
let attributes = `bottom: 8.25em; grid-template-columns: ${"1fr ".repeat(getColors(this.settings).length)}`;
this.colorMenu.setAttribute("style", attributes);
this.colorMenu.setAttribute("id", "fast-color-menu");
this.colorMenu.addClass("fast-color-menu");
// add menu to the workspace, adapted from
// cMenu https://github.com/chetachiezikeuzor/cMenu-Plugin/blob/master/src/modals/cMenuModal.ts#L5
document.body.querySelector(".mod-vertical.mod-root")?.insertAdjacentElement("afterbegin", this.colorMenu);
for (let i = 0; i < Math.min(getColors(this.settings).length, MAX_MENU_ITEMS); i++) {
this.createColorItem(this.colorMenu, getColors(this.settings)[i], i + 1, editor);
}
// have to apply it again, otherwise menu will not be centered.
this.colorMenu.setAttribute("style", `left: calc(50% - ${this.colorMenu.offsetWidth}px / 2); ${attributes}`);
if (!this.settings.useKeybindings) {
return;
}
// for now construct scope on every opening TODO
this.constructScope(editor);
this.app.keymap.pushScope(this.scope);
}
closeColorMenu() {
if (this.colorMenu) {
this.colorMenu.remove();
this.colorMenu = null;
}
this.app.keymap.popScope(this.scope);
}
constructScope(editor: Editor) {
this.scope = new Scope();
let { scope } = this;
// colors - number keys
for (let i = 0; i < getColors(this.settings).length; i++) {
const tColor = getColors(this.settings)[i];
scope.register([], tColor.keybind, (event) => {
if (event.isComposing) {
return true;
}
// let n = new Notice("activated color");
// n.noticeEl.setAttr("style", `background-color: ${tColor.color}`);
applyColor(tColor, editor);
this.closeColorMenu();
return false;
});
}
scope.register([], "Escape", (event) => {
if (event.isComposing) {
return true;
}
this.closeColorMenu();
return false;
})
scope.register([], "Delete", (event) => {
if (event.isComposing) {
return true;
}
this.closeColorMenu();
return false;
})
scope.register([], "Backspace", (event) => {
if (event.isComposing) {
return true;
}
this.closeColorMenu();
return false;
})
// TODO arrow keys movement.
// TODO mouse click ends
}
/**
* Move the cursor behind the next end marker.
*
* @param {EditorView} editorView
* @returns {boolean} true if jump possible.
*/
jumpOut(editorView: EditorView): boolean {
//@ts-ignore
const state: EditorState = editorView.state;
const tree = state.field(textColorParserField).tree;
const editor = this.app.workspace.getActiveViewOfType(MarkdownView)?.editor;
if (!editor) {
return false;
}
let inner = tree.resolve(state.selection.main.head);
if (inner.type.name == "Text" && inner.parent != null) {
inner = inner.parent;
}
if (inner.type.name != "TcRight") {
return false;
}
editor.setCursor(editor.offsetToPos(inner.to));
return true;
}
createColorItem(menu: HTMLDivElement, tColor: TextColor, counter: number, editor: Editor) {
new ButtonComponent(menu)
.setButtonText(`${tColor.keybind}`)
.setClass("fast-color-menu-item")
.onClick(() => {
let n = new Notice("activated color");
n.noticeEl.setAttr("style", `background-color: ${tColor.color}`);
applyColor(tColor, editor);
this.closeColorMenu();
})
.buttonEl.setAttr("style", `background-color: ${tColor.color}`);
}
/**
* creates the stylesheet needed for the colors in the root of the document.
* A different set of classes is created for each theme.
*
*/
setCssVariables() {
if (!this.styleElement) {
const root = document.querySelector(':root');
if (!root) {
return;
}
this.styleElement = root.createEl('style');
this.styleElement.id = "fast-text-color-stylesheet";
}
this.styleElement.innerText = "";
// dynamically create stylesheet.
for (let i = 0; i < this.settings.themes.length; i++) {
getColors(this.settings, i).forEach((tColor: TextColor) => {
const theme = this.settings.themes[i]
const className = `.${CSS_COLOR_PREFIX}${theme.name}-${tColor.id}`;
let cssClass =
`${className} {\n${tColor.getInnerCss()}}`
this.styleElement.innerText += cssClass + "\n";
});
}
}
}