2022-08-23 06:12:24 +00:00
|
|
|
import { syntaxTree } from "@codemirror/language";
|
|
|
|
import { Range } from "@codemirror/state";
|
|
|
|
import { Decoration, DecorationSet, EditorView, ViewPlugin, ViewUpdate, WidgetType } from "@codemirror/view";
|
|
|
|
|
|
|
|
class InlineImageWidget extends WidgetType {
|
2022-08-23 16:53:05 +00:00
|
|
|
constructor(readonly url: string, readonly title: string) {
|
2022-08-23 06:12:24 +00:00
|
|
|
super();
|
|
|
|
}
|
|
|
|
|
|
|
|
eq(other: InlineImageWidget) {
|
2022-08-23 16:53:05 +00:00
|
|
|
return other.url === this.url && other.title === this.title;
|
2022-08-23 06:12:24 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
toDOM() {
|
|
|
|
const img = document.createElement('img')
|
|
|
|
img.src = this.url;
|
2022-08-23 16:53:05 +00:00
|
|
|
img.alt = this.title;
|
|
|
|
img.title = this.title;
|
2022-08-23 06:12:24 +00:00
|
|
|
img.style.display = 'block';
|
|
|
|
|
|
|
|
return img;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const inlineImages = (view: EditorView) => {
|
|
|
|
let widgets: Range<Decoration>[] = [];
|
2022-08-23 16:53:05 +00:00
|
|
|
const imageRegex = /!\[(?<title>[^\]]*)\]\((?<url>.+)\)/;
|
2022-08-23 06:12:24 +00:00
|
|
|
|
|
|
|
for (let {from, to} of view.visibleRanges) {
|
|
|
|
syntaxTree(view.state).iterate({
|
|
|
|
from, to,
|
|
|
|
enter: (node) => {
|
|
|
|
if (node.name !== 'Image') {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
const imageRexexResult = imageRegex.exec(view.state.sliceDoc(node.from, node.to));
|
|
|
|
if (imageRexexResult === null || !imageRexexResult.groups) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const url = imageRexexResult.groups.url;
|
2022-08-23 16:53:05 +00:00
|
|
|
const title = imageRexexResult.groups.title;
|
2022-08-23 06:12:24 +00:00
|
|
|
let deco = Decoration.widget({
|
2022-08-23 16:53:05 +00:00
|
|
|
widget: new InlineImageWidget(url, title),
|
2022-08-23 06:12:24 +00:00
|
|
|
});
|
|
|
|
widgets.push(deco.range(node.to));
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
return Decoration.set(widgets, true);
|
|
|
|
}
|
|
|
|
|
|
|
|
export const inlineImagesPlugin = () =>
|
|
|
|
ViewPlugin.fromClass(
|
|
|
|
class {
|
|
|
|
decorations: DecorationSet;
|
|
|
|
|
|
|
|
constructor(view: EditorView) {
|
|
|
|
this.decorations = inlineImages(view);
|
|
|
|
}
|
|
|
|
|
|
|
|
update(update: ViewUpdate) {
|
|
|
|
if (update.docChanged) {
|
|
|
|
this.decorations = inlineImages(update.view);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
{
|
|
|
|
decorations: (v) => v.decorations,
|
|
|
|
}
|
|
|
|
);
|