-
Notifications
You must be signed in to change notification settings - Fork 59
/
SelectionPlaceholderPlugin.js
128 lines (108 loc) · 2.66 KB
/
SelectionPlaceholderPlugin.js
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
// @flow
import {EditorState, Plugin} from 'prosemirror-state';
import {Transform} from 'prosemirror-transform';
import {Decoration, DecorationSet} from 'prosemirror-view';
import './ui/czi-selection-placeholder.css';
const PLACE_HOLDER_ID = {name: 'SelectionPlaceholderPlugin'};
let singletonInstance = null;
// https://prosemirror.net/examples/upload/
const SPEC = {
state: {
init() {
return DecorationSet.empty;
},
apply(tr, set) {
set = set.map(tr.mapping, tr.doc);
const action = tr.getMeta(this);
if (!action) {
return set;
}
if (action.add) {
const deco = Decoration.inline(
action.add.from,
action.add.to,
{
class: 'czi-selection-placeholder',
},
{
id: PLACE_HOLDER_ID,
}
);
set = set.add(tr.doc, [deco]);
} else if (action.remove) {
const found = set.find(null, null, specFinder);
set = set.remove(found);
}
return set;
},
},
props: {
decorations: state => {
const plugin = singletonInstance;
return plugin ? plugin.getState(state) : null;
},
},
};
class SelectionPlaceholderPlugin extends Plugin {
constructor() {
super(SPEC);
if (singletonInstance) {
return singletonInstance;
}
singletonInstance = this;
}
}
function specFinder(spec: Object): boolean {
return spec.id == PLACE_HOLDER_ID;
}
function findSelectionPlaceholder(state: EditorState): ?Decoration {
if (!singletonInstance) {
return null;
}
if (!state.plugins.includes(singletonInstance)) {
console.warn('SelectionPlaceholderPlugin is not installed');
return null;
}
const decos = singletonInstance.getState(state);
const found = decos.find(null, null, specFinder);
const pos = found.length ? found[0] : null;
return pos || null;
}
export function showSelectionPlaceholder(
state: EditorState,
tr: ?Transform
): Transform {
tr = tr || state.tr;
const plugin = singletonInstance;
if (!plugin || !tr.selection || tr.selection.empty) {
return tr;
}
const deco = findSelectionPlaceholder(state);
if (deco === null) {
tr = tr.setMeta(plugin, {
add: {
from: tr.selection.from,
to: tr.selection.to,
},
});
}
return tr;
}
export function hideSelectionPlaceholder(
state: EditorState,
tr: ?Transform
): Transform {
tr = tr || state.tr;
const plugin = singletonInstance;
if (!plugin) {
return tr;
}
const deco = findSelectionPlaceholder(state);
if (deco) {
tr = tr.setMeta(plugin, {
remove: {},
});
}
return tr;
}
export default SelectionPlaceholderPlugin;