generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.ts
275 lines (244 loc) · 7.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
import { MarkdownView, Plugin, Platform } from "obsidian";
import { CommandMenu } from "src/components/command-menu";
import {
CMD_CONFIG,
CODE_LAN,
CONTENT_MAP,
HEADING_MENU,
ICON_MAP,
TEXT_MAP,
} from "src/constants";
import { InsertLinkModal } from "src/components/link-input-modal";
import { SelectionBtns } from "src/components/selection-menu";
import { type ExamplePluginSettings, ExampleSettingTab, CMD_TYPE } from "src/components/plugin-setting";
import { linkParse, loadIcons, loadCommands, generateBookMark, isLineEdit, isLineSelect } from "src/util/util";
const { isMobile } = Platform;
export default class TypingAsstPlugin extends Plugin {
commands: CommandMenu;
btns: SelectionBtns;
linkModal: InsertLinkModal;
scrollArea?: Element;
settings: ExamplePluginSettings;
async loadSettings() {
const initialMenu = HEADING_MENU.filter(item => item === 'insert-note-callout' || !item.includes("callout"));
this.settings = Object.assign({}, { showPlaceholder: true, cmdsSorting: initialMenu, disableSelectionMenu: isMobile }, await this.loadData());
// console.log('commands======>', this.app.commands.commands)
}
async saveSettings() {
await this.saveData(this.settings);
}
async onload() {
await this.loadSettings();
loadCommands.call(this)
this.addSettingTab(new ExampleSettingTab(this.app, this));
// import svg to Obsidian-Icon
loadIcons(ICON_MAP);
const onSelectionAction = async (
content: string,
isHeading: boolean
) => {
const view =
this.app.workspace.getActiveViewOfType(MarkdownView);
if (!view?.editor) return;
if (isHeading) {
const editor = view.editor;
const cursor = editor.getCursor();
const lineContent = editor.getLine(cursor.line);
editor.setLine(cursor.line, lineContent.replace(/^.*?\s/, ""));
}
(this.app as any).commands.executeCommandById((CMD_CONFIG as any)[content].cmd);
if (content === "set-link") {
view.editor.focus();
}
this.btns.hide();
};
const onMenuClick = async (content: CMD_TYPE) => {
const view = this.app.workspace.getActiveViewOfType(MarkdownView);
if (view) {
(this.app as any).commands.executeCommandById(
CMD_CONFIG[content].cmd
);
view.editor.focus();
if (content === CONTENT_MAP['bookmark']) {
view.editor.blur();
this.linkModal.open();
}
}
};
const onLinkSubmit = async (url: string) => {
const parsedResult = await linkParse(url);
let codeStr = "```" + CODE_LAN + "\n";
for (const key in parsedResult) {
codeStr += key + ":" + (parsedResult as any)[key] + "\n";
}
codeStr += "```\n";
const view = this.app.workspace.getActiveViewOfType(MarkdownView);
if (view) {
const cursor = view.editor.getCursor();
const editLine = view.editor.getLine(cursor.line);
if (editLine.length > 0) {
view.editor.replaceRange(
`\n${codeStr}`,
{ line: cursor.line, ch: cursor.ch - 1 },
cursor
);
view.editor.setCursor({
line: cursor.line + 1,
ch: codeStr.length,
});
} else {
view.editor.setLine(cursor.line, codeStr);
view.editor.setCursor({
line: cursor.line,
ch: codeStr.length,
});
}
}
};
const handleSelection = () => {
const selection = document.getSelection()?.toString();
if (selection) {
const view =
this.app.workspace.getActiveViewOfType(MarkdownView);
if (!view?.editor) return;
const editor = view.editor;
const cursor = editor.getCursor();
const lineContent = editor.getLine(cursor.line);
let lineStyle = "Text";
for (const cmd in CONTENT_MAP) {
if (cmd === "text") {
continue;
// } else if (/^\> \[!/.test(lineContent)) {
// lineStyle = TEXT_MAP["callout"];
// break;
} else if (/^\`\`\`/.test(lineContent)) {
lineStyle = TEXT_MAP["code"];
break;
} else if (
lineContent.startsWith((CONTENT_MAP as any)[cmd])
) {
lineStyle = (TEXT_MAP as any)[cmd];
break;
} else if (/^[\d]+\.\s/.test(lineContent)) {
lineStyle = TEXT_MAP["numberList"];
break;
}
}
this.btns?.display(lineStyle);
}
};
this.linkModal = new InsertLinkModal(this.app, onLinkSubmit);
this.registerDomEvent(document, "click", (evt: MouseEvent) => {
this.commands?.hide();
const selection = document.getSelection()?.toString();
if (!selection && this.btns?.isVisible()) {
this.btns.hide();
}
});
this.registerDomEvent(document, "mouseup", (evt: MouseEvent) => {
// prevent title or code selection
if (!isLineSelect(evt?.target)) return;
// desable seletion menu in mobile env
// if (isMobile) return;
if(this.settings.disableSelectionMenu)return;
handleSelection();
});
this.registerDomEvent(document, "keydown", (evt: KeyboardEvent) => {
if ((evt?.target as any)?.getAttribute?.('class')?.includes('command-option')) {
const view =
this.app.workspace.getActiveViewOfType(MarkdownView);
if (view) {
view.editor.focus();
}
}
})
this.registerDomEvent(document, "keyup", (evt: KeyboardEvent) => {
if (this.commands?.isVisible()) {
const { key } = evt;
if (
key !== "ArrowUp" &&
key !== "ArrowDown" &&
key !== "ArrowLeft" &&
key !== "ArrowRight"
) {
const view =
this.app.workspace.getActiveViewOfType(MarkdownView);
if (view) {
const cursor = view.editor.getCursor();
const editLine = view.editor.getLine(cursor.line);
const _cmd = (editLine?.match(/[^\/]*$/)?.[0] || '')
if (!editLine) {
this.commands?.hide();
} else {
this.commands?.search(_cmd);
}
view.editor.focus();
}
}
}
this.btns?.hide();
});
// const scrollEvent = () => {
// if (this.btns?.isVisible()) {
// // handleSelection();
// }
// };
const renderPlugin = () => {
const showEmptyPrompt = this.settings.showPlaceholder;
document.documentElement.style.setProperty('--show-empty-prompt', showEmptyPrompt ? 'block' : 'none')
const view = this.app.workspace.getActiveViewOfType(MarkdownView);
if (!view) return;
this.scrollArea =
view.containerEl.querySelector(".cm-scroller") ?? undefined;
const appHeader = document.querySelector(".titlebar");
const viewHeader = view.containerEl.querySelector(".view-header");
const headerHeight =
(appHeader?.clientHeight ?? 0) +
(viewHeader?.clientHeight ?? 0);
if (!this.scrollArea) return;
const scrollArea = this.scrollArea;
this.commands?.remove();
this.commands = new CommandMenu({
scrollArea,
onMenu: onMenuClick,
defaultCmds: this.settings.cmdsSorting
});
this.btns?.remove();
this.btns = new SelectionBtns({
scrollArea,
headerHeight,
onAction: onSelectionAction,
});
// scrollArea?.addEventListener("scroll", scrollEvent);
};
/**Ensure that the plugin can be loaded and used immediately after it is turned on */
renderPlugin();
this.registerEvent(
this.app.workspace.on("active-leaf-change", renderPlugin)
);
this.registerDomEvent(document, "input", (evt: InputEvent) => {
if (!isLineEdit(evt?.target)) return;
if (this.linkModal.isOpen) return;
if (evt && evt.data === "/") {
const view =
this.app.workspace.getActiveViewOfType(MarkdownView);
if (!view) return;
const cursor = view.editor.getCursor();
const editLine = view.editor.getLine(cursor.line);
if (editLine.replace(/[\s]*$/, "").length <= cursor.ch) {
this.commands?.display();
} else {
// this.commands?.hide();
}
}
});
this.registerMarkdownCodeBlockProcessor(CODE_LAN, (source, el, ctx) => {
const bookmark = generateBookMark(source);
el?.appendChild(bookmark);
});
}
onunload() {
this.commands?.remove();
this.btns?.remove();
}
}