1
0
silverbullet/web/cm_plugins/inline_image.ts

91 lines
2.3 KiB
TypeScript
Raw Normal View History

2022-08-29 13:47:16 +00:00
import {
Decoration,
EditorState,
Range,
syntaxTree,
2022-08-29 13:47:16 +00:00
WidgetType,
} from "../deps.ts";
import { decoratorStateField } from "./util.ts";
2022-08-23 06:12:24 +00:00
import type { Space } from "../space.ts";
import type { Editor } from "../editor.tsx";
2022-08-23 06:12:24 +00:00
class InlineImageWidget extends WidgetType {
constructor(
readonly url: string,
readonly title: string,
readonly space: Space,
) {
2022-08-23 06:12:24 +00:00
super();
2023-05-29 08:26:56 +00:00
// console.log("Creating widget", url);
2022-08-23 06:12:24 +00:00
}
eq(other: InlineImageWidget) {
return other.url === this.url && other.title === this.title;
2022-08-23 06:12:24 +00:00
}
2023-05-29 08:26:56 +00:00
get estimatedHeight(): number {
const cachedHeight = this.space.getCachedImageHeight(this.url);
// console.log("Estimated height requested", this.url, cachedHeight);
return cachedHeight;
}
2022-08-23 06:12:24 +00:00
toDOM() {
2022-08-29 13:47:16 +00:00
const img = document.createElement("img");
2023-05-29 08:26:56 +00:00
// console.log("Creating DOM", this.url);
const cachedImageHeight = this.space.getCachedImageHeight(this.url);
img.onload = () => {
// console.log("Loaded", this.url, "with height", img.height);
if (img.height !== cachedImageHeight) {
this.space.setCachedImageHeight(this.url, img.height);
}
};
img.src = this.url;
img.alt = this.title;
img.title = this.title;
2022-08-29 13:47:16 +00:00
img.style.display = "block";
img.className = "sb-inline-img";
2023-05-29 08:26:56 +00:00
if (cachedImageHeight > 0) {
img.height = cachedImageHeight;
}
2022-08-23 06:12:24 +00:00
return img;
}
}
export function inlineImagesPlugin(editor: Editor) {
return decoratorStateField((state: EditorState) => {
const widgets: Range<Decoration>[] = [];
const imageRegex = /!\[(?<title>[^\]]*)\]\((?<url>.+)\)/;
2022-08-23 06:12:24 +00:00
syntaxTree(state).iterate({
2022-08-23 06:12:24 +00:00
enter: (node) => {
2022-08-29 13:47:16 +00:00
if (node.name !== "Image") {
return;
2022-08-23 06:12:24 +00:00
}
2022-08-29 13:47:16 +00:00
const imageRexexResult = imageRegex.exec(
state.sliceDoc(node.from, node.to),
2022-08-29 13:47:16 +00:00
);
2022-08-23 06:12:24 +00:00
if (imageRexexResult === null || !imageRexexResult.groups) {
return;
}
2022-08-29 13:47:16 +00:00
let url = imageRexexResult.groups.url;
const title = imageRexexResult.groups.title;
if (url.indexOf("://") === -1) {
url = decodeURI(url);
}
widgets.push(
Decoration.widget({
widget: new InlineImageWidget(url, title, editor.space),
block: true,
}).range(node.to),
);
2022-08-29 13:47:16 +00:00
},
2022-08-23 06:12:24 +00:00
});
return Decoration.set(widgets, true);
});
}