Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/frontend/editors/slate/elements/image/index.tsx
1698 views
1
/*
2
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
3
* License: MS-RSL – see LICENSE.md for details
4
*/
5
6
import { load } from "cheerio";
7
8
import { useFileContext } from "@cocalc/frontend/lib/file-context";
9
import { dict } from "@cocalc/util/misc";
10
import { register, SlateElement } from "../register";
11
12
export interface Image extends SlateElement {
13
type: "image";
14
isInline: true;
15
isVoid: true;
16
src: string;
17
alt?: string;
18
title?: string;
19
width?: string | number;
20
height?: string | number;
21
}
22
23
export function toSlate({ type, children, token }) {
24
switch (type) {
25
// IMPORTANT: this only gets called with type != 'image'
26
// because of explicit code in ./html.tsx.
27
case "html_inline":
28
case "html_block":
29
// token.content will be a string like this:
30
// <img src='https://wstein.org/bella-and-william.jpg' width=200px title='my pup' />
31
// easiest way to parse this is with jquery style api but via cheerio (not by hand).
32
const $ = load("");
33
const elt = $(token.content);
34
const node = {
35
type: "image",
36
children,
37
isInline: true,
38
isVoid: true,
39
src: elt.attr("src") ?? "",
40
alt: elt.attr("alt") ?? "",
41
title: elt.attr("title") ?? "",
42
width: elt.attr("width"),
43
height: elt.attr("height"),
44
} as any;
45
if (type == "html_inline") {
46
return node;
47
}
48
return {
49
type: "paragraph",
50
children: [{ text: "" }, node, { text: "" }],
51
};
52
case "image":
53
const attrs = dict(token.attrs as any);
54
return {
55
type: "image",
56
children,
57
isInline: true,
58
isVoid: true,
59
src: attrs.src,
60
alt: attrs.alt,
61
title: attrs.title,
62
};
63
default:
64
throw Error("bug");
65
}
66
}
67
68
register({
69
slateType: "image",
70
toSlate,
71
StaticElement: ({ attributes, element }) => {
72
const { urlTransform, reloadImages } = useFileContext();
73
const node = element as Image;
74
const { src, alt, title } = node;
75
return (
76
<img
77
{...attributes}
78
src={
79
(urlTransform?.(src, "img") ?? src) +
80
(reloadImages ? `?${Math.random()}` : "")
81
}
82
alt={alt}
83
title={title}
84
style={{
85
height: node.height,
86
width: node.width,
87
maxWidth: "100%",
88
maxHeight: "100%",
89
objectFit: "cover",
90
}}
91
/>
92
);
93
},
94
});
95
96