Add maximum width to inline images

This commit is contained in:
Zef Hemel
2022-08-29 15:47:16 +02:00
parent ff24358269
commit 56af04daa2
3 changed files with 32 additions and 14 deletions
+23 -12
View File
@@ -1,6 +1,13 @@
import { syntaxTree } from "@codemirror/language";
import { Range } from "@codemirror/state";
import { Decoration, DecorationSet, EditorView, ViewPlugin, ViewUpdate, WidgetType } from "@codemirror/view";
import {
Decoration,
DecorationSet,
EditorView,
ViewPlugin,
ViewUpdate,
WidgetType,
} from "@codemirror/view";
class InlineImageWidget extends WidgetType {
constructor(readonly url: string, readonly title: string) {
@@ -12,11 +19,12 @@ class InlineImageWidget extends WidgetType {
}
toDOM() {
const img = document.createElement('img')
const img = document.createElement("img");
img.src = this.url;
img.alt = this.title;
img.title = this.title;
img.style.display = 'block';
img.style.display = "block";
img.className = "sb-inline-img";
return img;
}
@@ -26,31 +34,34 @@ const inlineImages = (view: EditorView) => {
let widgets: Range<Decoration>[] = [];
const imageRegex = /!\[(?<title>[^\]]*)\]\((?<url>.+)\)/;
for (let {from, to} of view.visibleRanges) {
for (let { from, to } of view.visibleRanges) {
syntaxTree(view.state).iterate({
from, to,
from,
to,
enter: (node) => {
if (node.name !== 'Image') {
return
if (node.name !== "Image") {
return;
}
const imageRexexResult = imageRegex.exec(view.state.sliceDoc(node.from, node.to));
const imageRexexResult = imageRegex.exec(
view.state.sliceDoc(node.from, node.to)
);
if (imageRexexResult === null || !imageRexexResult.groups) {
return;
}
const url = imageRexexResult.groups.url;
const title = imageRexexResult.groups.title;
let deco = Decoration.widget({
widget: new InlineImageWidget(url, title),
});
widgets.push(deco.range(node.to));
}
},
});
}
return Decoration.set(widgets, true);
}
};
export const inlineImagesPlugin = () =>
ViewPlugin.fromClass(
+6 -1
View File
@@ -1,10 +1,15 @@
.cm-editor {
font-size: 18px;
padding: 0 20px;
--max-width: 800px;
.cm-content {
margin: auto;
max-width: 800px;
max-width: var(--max-width);
}
.sb-inline-img {
max-width: calc(var(--max-width) * 0.9);
}
&.cm-focused {