-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
255 lines (206 loc) · 5.19 KB
/
Copy pathmain.ts
File metadata and controls
255 lines (206 loc) · 5.19 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
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
import {
MarkdownRenderChild,
Notice,
Plugin,
normalizePath,
} from "obsidian";
const NOTELET_LANGUAGE = "notelet";
const NOTELETS_FOLDER = "Notelets";
export default class NoteletsPlugin extends Plugin {
async onload() {
console.log("Loading Notelets");
/*
* Render ```notelet blocks as sandboxed iframes.
*/
this.registerMarkdownCodeBlockProcessor(
NOTELET_LANGUAGE,
(source, el, ctx) => {
const child = new NoteletRenderChild(el, source);
ctx.addChild(child);
}
);
/*
* Command: Import an HTML file as a Notelet.
*/
this.addCommand({
id: "import-html-as-notelet",
name: "Import HTML as Notelet",
callback: () => {
void this.importHtmlFile();
},
});
/*
* Ribbon button.
*/
this.addRibbonIcon(
"file-code-2",
"Import HTML as Notelet",
() => {
void this.importHtmlFile();
}
);
}
private async importHtmlFile(): Promise<void> {
const input = document.createElement("input");
input.type = "file";
input.accept = ".html,.htm,text/html";
input.multiple = false;
input.addEventListener(
"change",
() => {
const file = input.files?.[0];
if (!file) {
return;
}
void this.createNoteletFromFile(file);
},
{ once: true }
);
input.click();
}
private async createNoteletFromFile(file: File): Promise<void> {
try {
const html = await file.text();
if (!html.trim()) {
new Notice("The selected HTML file is empty.");
return;
}
await this.ensureFolder(NOTELETS_FOLDER);
const originalName = removeHtmlExtension(file.name);
const safeName = sanitizeFileName(originalName);
const notePath = await this.getAvailableNotePath(
NOTELETS_FOLDER,
safeName
);
const fence = createSafeFence(html);
const markdown = [
"---",
"notelet: true",
"notelet-version: 1",
`source-file: "${escapeYamlString(file.name)}"`,
`imported: "${new Date().toISOString()}"`,
"---",
"",
`${fence}${NOTELET_LANGUAGE}`,
html,
fence,
"",
].join("\n");
const createdFile = await this.app.vault.create(
notePath,
markdown
);
new Notice(`Created Notelet: ${createdFile.basename}`);
/*
* Open immediately in Reading mode so the Notelet renders.
*/
const leaf = this.app.workspace.getLeaf(false);
await leaf.setViewState({
type: "markdown",
state: {
file: createdFile.path,
mode: "preview",
source: false,
},
});
} catch (error) {
console.error("Notelet import failed:", error);
new Notice(
"Could not create the Notelet. Check the developer console for details."
);
}
}
private async ensureFolder(folderPath: string): Promise<void> {
const normalized = normalizePath(folderPath);
if (this.app.vault.getAbstractFileByPath(normalized)) {
return;
}
await this.app.vault.createFolder(normalized);
}
private async getAvailableNotePath(
folder: string,
baseName: string
): Promise<string> {
let counter = 0;
while (true) {
const suffix = counter === 0 ? "" : ` ${counter}`;
const path = normalizePath(
`${folder}/${baseName}${suffix}.md`
);
if (!this.app.vault.getAbstractFileByPath(path)) {
return path;
}
counter++;
}
}
}
class NoteletRenderChild extends MarkdownRenderChild {
private iframe: HTMLIFrameElement | null = null;
constructor(
containerEl: HTMLElement,
private readonly html: string
) {
super(containerEl);
}
onload(): void {
this.containerEl.empty();
this.containerEl.addClass("notelet-container");
this.iframe = document.createElement("iframe");
this.iframe.addClass("notelet-frame");
/*
* The HTML stored directly inside the Markdown note becomes
* the iframe document.
*/
this.iframe.srcdoc = this.html;
/*
* Keep Notelet JavaScript isolated from Obsidian itself.
*
* Deliberately omit allow-same-origin.
*/
this.iframe.setAttribute(
"sandbox",
"allow-scripts allow-forms allow-modals allow-downloads"
);
this.iframe.setAttribute(
"title",
"Notelet"
);
this.containerEl.appendChild(this.iframe);
}
onunload(): void {
if (this.iframe) {
this.iframe.srcdoc = "";
this.iframe.remove();
this.iframe = null;
}
}
}
function removeHtmlExtension(filename: string): string {
return filename.replace(/\.html?$/i, "");
}
function sanitizeFileName(filename: string): string {
const sanitized = filename
.replace(/[\\/:*?"<>|]/g, "-")
.replace(/\s+/g, " ")
.trim();
return sanitized || "Untitled Notelet";
}
function escapeYamlString(value: string): string {
return value
.replace(/\\/g, "\\\\")
.replace(/"/g, '\\"');
}
/*
* Choose a Markdown fence longer than any sequence of backticks
* that already exists inside the imported HTML.
*/
function createSafeFence(content: string): string {
const matches = content.match(/`+/g);
let longest = 2;
if (matches) {
for (const match of matches) {
longest = Math.max(longest, match.length);
}
}
return "`".repeat(Math.max(3, longest + 1));
}