generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.ts
54 lines (45 loc) · 1.96 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
import { hasPseudoElements, parseRulesets, parseSelector, splitPseudoElements } from 'not-a-real-css-parser';
import { Plugin } from 'obsidian';
const CLASSNAME_TAG = 'classname:';
const makeScopedStyles = (rootSelector: string, source: string): string =>
parseRulesets(source).map(({ selector, declarations }) => {
if (hasPseudoElements(selector)) {
return parseSelector(selector).map((selector) => {
const [selectorHead, pseudoElement] = splitPseudoElements(selector);
return `${rootSelector} :is(${selectorHead})${pseudoElement ?? ''} {${declarations}}`;
})
.join(',');
}
return `${rootSelector} :is(${selector}) {${declarations}}`;
})
.join('\n');
export default class extends Plugin {
private lastClassName: string | undefined;
onload() {
this.registerMarkdownCodeBlockProcessor('style', (source, element) => {
element.createEl('style', {
text: makeScopedStyles('.markdown-preview-view', source)
});
});
this.registerMarkdownPostProcessor((element) => {
if (element.hasClass('next-class-skip')) {
return;
}
if (this.lastClassName !== undefined) {
element.classList.add(...this.lastClassName.split(/\s+/));
this.lastClassName = undefined;
}
const codeElements = element.querySelectorAll('code');
const classElement = [...codeElements].find(
(element) => element.innerText.trim().startsWith(CLASSNAME_TAG)
);
if (classElement) {
this.lastClassName = classElement.innerText.slice(CLASSNAME_TAG.length);
if (classElement.parentElement?.childElementCount === 1) {
classElement.parentElement.remove();
}
element.classList.add('next-class-skip');
}
});
}
}