generated from obsidianmd/obsidian-sample-plugin
-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
reading-view.ts
162 lines (128 loc) · 6.37 KB
/
reading-view.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
/**
* Display equation numbers in reading view, embeds, hover page preview, and PDF export.
*/
import { App, MarkdownRenderChild, finishRenderMath, MarkdownPostProcessorContext, TFile, Notice } from "obsidian";
import MathBooster from 'main';
import { resolveSettings } from 'utils/plugin';
import { EquationBlock, MarkdownPage } from "index/typings/markdown";
import { MathIndex } from "index/math-index";
import { isPdfExport, resolveLinktext } from "utils/obsidian";
import { replaceMathTag } from "./common";
export const createEquationNumberProcessor = (plugin: MathBooster) => async (el: HTMLElement, ctx: MarkdownPostProcessorContext) => {
if (isPdfExport(el)) preprocessForPdfExport(plugin, el, ctx);
const sourceFile = plugin.app.vault.getAbstractFileByPath(ctx.sourcePath);
if (!(sourceFile instanceof TFile)) return;
const mjxContainerElements = el.querySelectorAll<HTMLElement>('mjx-container.MathJax[display="true"]');
for (const mjxContainerEl of mjxContainerElements) {
ctx.addChild(
new EquationNumberRenderer(mjxContainerEl, plugin, sourceFile, ctx)
);
}
finishRenderMath();
}
/**
* As a preprocessing for displaying equation numbers in the exported PDF,
* add an attribute representing a block ID to each numbered equation element
* so that EquationNumberRenderer can find the corresponding block from the index
* without relying on the line number.
*/
function preprocessForPdfExport(plugin: MathBooster, el: HTMLElement, ctx: MarkdownPostProcessorContext) {
try {
const topLevelMathDivs = el.querySelectorAll<HTMLElement>(':scope > div.math.math-block > mjx-container.MathJax[display="true"]');
const page = plugin.indexManager.index.getMarkdownPage(ctx.sourcePath);
if (!page) {
new Notice(`${plugin.manifest.name}: Failed to fetch the metadata for PDF export; equation numbers will not be displayed in the exported PDF.`);
return;
}
let equationIndex = 0;
for (const section of page.$sections) {
for (const block of section.$blocks) {
if (!EquationBlock.isEquationBlock(block)) continue;
const div = topLevelMathDivs[equationIndex++];
if (block.$printName) div.setAttribute('data-equation-id', block.$id);
}
}
if (topLevelMathDivs.length != equationIndex) {
new Notice(`${plugin.manifest.name}: Something unexpected occured while preprocessing for PDF export. Equation numbers might not be displayed properly in the exported PDF.`);
}
} catch (err) {
new Notice(`${plugin.manifest.name}: Something unexpected occured while preprocessing for PDF export. See the developer console for the details. Equation numbers might not be displayed properly in the exported PDF.`);
console.error(err);
}
}
export class EquationNumberRenderer extends MarkdownRenderChild {
app: App
index: MathIndex;
constructor(containerEl: HTMLElement, public plugin: MathBooster, public file: TFile, public context: MarkdownPostProcessorContext) {
// containerEl, currentEL are mjx-container.MathJax elements
super(containerEl);
this.app = plugin.app;
this.index = this.plugin.indexManager.index;
this.registerEvent(this.plugin.indexManager.on("index-initialized", () => {
setTimeout(() => this.update());
}));
this.registerEvent(this.plugin.indexManager.on("index-updated", (file) => {
setTimeout(() => {
if (file.path === this.file.path) this.update();
});
}));
}
getEquationCache(lineOffset: number = 0): EquationBlock | null {
const info = this.context.getSectionInfo(this.containerEl);
const page = this.index.getMarkdownPage(this.file.path);
if (!info || !page) return null;
// get block ID
const block = page.getBlockByLineNumber(info.lineStart + lineOffset) ?? page.getBlockByLineNumber(info.lineEnd + lineOffset);
if (EquationBlock.isEquationBlock(block)) return block;
return null;
}
async onload() {
setTimeout(() => this.update());
}
onunload() {
// I don't know if this is really necessary, but just in case...
finishRenderMath();
}
update() {
// for PDF export
const id = this.containerEl.getAttribute('data-equation-id');
const equation = id ? this.index.getEquationBlock(id) : this.getEquationCacheCaringHoverAndEmbed();
if (!equation) return;
const settings = resolveSettings(undefined, this.plugin, this.file);
replaceMathTag(this.containerEl, equation, settings);
}
getEquationCacheCaringHoverAndEmbed(): EquationBlock | null {
/**
* https://github.com/RyotaUshio/obsidian-math-booster/issues/179
*
* In the case of embeds or hover popovers, the line numbers contained
* in the result of MarkdownPostProcessorContext.getSectionInfo() is
* relative to the content included in the embed.
* In other words, they does not always represent the offset from the beginning of the file.
* So they require special handling.
*/
const equation = this.getEquationCache();
let linktext = this.containerEl.closest('[src]')?.getAttribute('src'); // in the case of embeds
if (!linktext) {
const hoverEl = this.containerEl.closest<HTMLElement>('.hover-popover:not(.hover-editor)');
if (hoverEl) {
// The current context is hover page preview; read the linktext saved in the plugin instance.
linktext = this.plugin.lastHoverLinktext;
}
}
if (linktext) { // linktext was found
const { file, subpathResult } = resolveLinktext(this.app, linktext, this.context.sourcePath) ?? {};
if (!file || !subpathResult) return null;
const page = this.index.load(file.path);
if (!MarkdownPage.isMarkdownPage(page)) return null;
if (subpathResult.type === "block") {
const block = page.$blocks.get(subpathResult.block.id);
if (!EquationBlock.isEquationBlock(block)) return null;
return block;
} else {
return this.getEquationCache(subpathResult.start.line);
}
}
return equation;
}
}