/
image-extension.ts
73 lines (65 loc) 路 1.75 KB
/
image-extension.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
import {
Attrs,
bool,
Cast,
CommandFunction,
CommandNodeTypeParams,
isElementDOMNode,
NodeExtension,
NodeExtensionSpec,
} from '@remirror/core';
import { ResolvedPos } from 'prosemirror-model';
import { createImageExtensionPlugin } from './image-plugin';
import { getAttrs } from './image-utils';
const hasCursor = <T extends object>(arg: T): arg is T & { $cursor: ResolvedPos } => {
return bool(Cast(arg).$cursor);
};
export class ImageExtension extends NodeExtension {
get name() {
return 'image' as const;
}
get schema(): NodeExtensionSpec {
return {
inline: true,
attrs: {
...this.extraAttrs(null),
align: { default: null },
alt: { default: '' },
crop: { default: null },
height: { default: null },
width: { default: null },
rotate: { default: null },
src: { default: null },
title: { default: '' },
},
group: 'inline',
draggable: true,
parseDOM: [
{
tag: 'img[src]',
getAttrs: domNode => (isElementDOMNode(domNode) ? getAttrs(this.getExtraAttrs(domNode)) : {}),
},
],
toDOM(node) {
return ['img', node.attrs];
},
};
}
public commands({ type }: CommandNodeTypeParams) {
return {
insertImage: (attrs?: Attrs): CommandFunction => (state, dispatch) => {
const { selection } = state;
const position = hasCursor(selection) ? selection.$cursor.pos : selection.$to.pos;
const node = type.create(attrs);
const transaction = state.tr.insert(position, node);
if (dispatch) {
dispatch(transaction);
}
return true;
},
};
}
public plugin() {
return createImageExtensionPlugin();
}
}