-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathcodemirror-persist-document-extension.js
39 lines (36 loc) · 1.46 KB
/
codemirror-persist-document-extension.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
(function () {
const { ViewPlugin } = CM["@codemirror/view"];
CM["@overpy/codemirror-persist-document"] = {
persistDocument(storageKey, storage = window.sessionStorage) {
return ViewPlugin.define((view) => {
let saveDebounceTimeout = null;
const initialValue = storage.getItem(storageKey);
if (initialValue != null) {
setTimeout(() => {
// Wait for codemirror to initialize
view.dispatch({
changes: {
from: 0,
to: view.state.doc.toString().length,
insert: initialValue,
},
});
}, 0);
}
return {
update(viewUpdate) {
if (viewUpdate.docChanged) {
if (saveDebounceTimeout != null) {
clearTimeout(saveDebounceTimeout);
}
saveDebounceTimeout = setTimeout(() => {
storage.setItem(storageKey, viewUpdate.state.doc.toString());
saveDebounceTimeout = null;
}, 500);
}
},
};
});
},
};
})();