forked from yabwe/medium-editor
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathplaceholder.js
100 lines (80 loc) · 3.27 KB
/
placeholder.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
(function () {
'use strict';
var Placeholder = MediumEditor.Extension.extend({
name: 'placeholder',
/* Placeholder Options */
/* text: [string]
* Text to display in the placeholder
*/
text: 'Type your text',
/* hideOnClick: [boolean]
* Should we hide the placeholder on click (true) or when user starts typing (false)
*/
hideOnClick: true,
init: function () {
MediumEditor.Extension.prototype.init.apply(this, arguments);
this.initPlaceholders();
this.attachEventHandlers();
},
initPlaceholders: function () {
this.getEditorElements().forEach(function (el) {
if (!el.getAttribute('data-placeholder')) {
el.setAttribute('data-placeholder', this.text);
}
this.updatePlaceholder(el);
}, this);
},
destroy: function () {
this.getEditorElements().forEach(function (el) {
if (el.getAttribute('data-placeholder') === this.text) {
el.removeAttribute('data-placeholder');
}
}, this);
},
showPlaceholder: function (el) {
if (el) {
el.classList.add('medium-editor-placeholder');
}
},
hidePlaceholder: function (el) {
if (el) {
el.classList.remove('medium-editor-placeholder');
}
},
updatePlaceholder: function (el) {
// if one of these element ('img, blockquote, ul, ol') are found inside the given element, we won't display the placeholder
if (!(el.querySelector('img, blockquote, ul, ol')) && el.textContent.replace(/^\s+|\s+$/g, '') === '') {
return this.showPlaceholder(el);
}
this.hidePlaceholder(el);
},
attachEventHandlers: function () {
// Custom events
this.subscribe('blur', this.handleExternalInteraction.bind(this));
// Check placeholder on blur
this.subscribe('editableBlur', this.handleBlur.bind(this));
// if we don't want the placeholder to be removed on click but when user start typing
if (this.hideOnClick) {
this.subscribe('editableClick', this.handleHidePlaceholderEvent.bind(this));
} else {
this.subscribe('editableKeyup', this.handleBlur.bind(this));
}
// Events where we always hide the placeholder
this.subscribe('editableKeypress', this.handleHidePlaceholderEvent.bind(this));
this.subscribe('editablePaste', this.handleHidePlaceholderEvent.bind(this));
},
handleHidePlaceholderEvent: function (event, element) {
// Events where we hide the placeholder
this.hidePlaceholder(element);
},
handleBlur: function (event, element) {
// Update placeholder for element that lost focus
this.updatePlaceholder(element);
},
handleExternalInteraction: function () {
// Update all placeholders
this.initPlaceholders();
}
});
MediumEditor.extensions.placeholder = Placeholder;
}());