-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
53 lines (39 loc) · 1.24 KB
/
index.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
var editable = require("make-editable");
var pubsub = require("pubsub");
var debounce = require("debounce-fn");
var classes = require("dom-classes");
var counter = 1;
module.exports = create;
function create (textarea) {
var iframe = replace(textarea);
var api = editable(iframe.contentWindow.document);
api.iframe = iframe;
api.onUpdate = pubsub();
api.read = read;
watch(api, function () {
textarea.value = read();
api.onUpdate.publish();
});
return api;
function read () {
return iframe.contentWindow.document.body.innerHTML;
};
}
function replace (textarea) {
var id = counter++;
var iframe = document.createElement('iframe');
iframe.setAttribute('class', 'wysiwyg wysiwyg-' + id);
textarea.style.display = 'none';
textarea.parentNode.insertBefore(iframe, textarea);
iframe.contentWindow.document.body.innerHTML = textarea.value;
iframe.contentWindow.addEventListener('focus', function () {
classes.add(iframe, 'focus');
}, false);
iframe.contentWindow.addEventListener('blur', function () {
classes.remove(iframe, 'focus');
}, false);
return iframe;
}
function watch (api, callback) {
api.iframe.contentWindow.document.body.addEventListener('input', debounce(callback, 500), false);
}