-
Notifications
You must be signed in to change notification settings - Fork 5
/
banksy.js
102 lines (88 loc) · 2.57 KB
/
banksy.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
'use strict';
var crossvent = require('crossvent');
function banksy (el, options) {
var o = options || {};
var editor = o.editor;
var horse = o.horse;
var woofmarkLastMode;
var cachedChunks;
var cachedNeedle;
var ranchorleft;
var ranchorright;
if (horse.anchor) {
ranchorleft = new RegExp('^' + horse.anchor);
ranchorright = new RegExp(horse.anchor + '$');
}
horse.appendText = appendText;
horse.appendHTML = appendHTML;
horse.filterAnchoredHTML = filterAnchoredHTML;
inputEvents();
return {
destroy: destroy
};
function destroy () {
inputEvents(true);
horse.destroy();
}
function inputEvents (remove) {
var op = remove ? 'remove' : 'add';
crossvent[op](editor.editable, 'horsey-filter', getChunksForFilters);
crossvent[op](editor.textarea, 'woofmark-mode-change', woofmarkModeChanged);
}
function woofmarkModeChanged () {
if (editor.mode !== woofmarkLastMode) {
horse.retarget(editor.mode === 'wysiwyg' ? editor.editable : editor.textarea);
}
woofmarkLastMode = editor.mode;
}
function entitize (value) {
var rparagraph = /^<p>|<\/p>\n?$/g;
if (editor.mode !== 'markdown') {
return editor.parseMarkdown(value).replace(rparagraph, '');
}
return value;
}
function getChunksForFilters () {
editor.runCommand(function gotContext (chunks) {
var text = chunks.before + chunks.selection;
var anchored = false;
var start = text.length;
if (ranchorleft) {
while (anchored === false && start >= 0) {
cachedNeedle = text.substr(start - 1, text.length - start + 1);
anchored = ranchorleft.test(cachedNeedle);
start--;
}
}
if (anchored === false) {
cachedNeedle = null;
}
cachedChunks = chunks;
});
}
function appendText (value) {
var entity = entitize(value);
horse.defaultAppendText(entity);
}
function appendHTML (value) {
editor.runCommand(setEntity);
function setEntity (chunks) {
var entity = entitize(value);
var left = cachedChunks.before;
var len = left.length - 1;
while (len > 0 && (!ranchorright || !ranchorright.test(left))) {
left = left.substr(0, --len);
}
chunks.before = left.substr(0, len) + entity + ' ';
chunks.after = cachedChunks.selection + cachedChunks.after;
chunks.selection = '';
}
}
function filterAnchoredHTML (q, suggestion) {
if (cachedNeedle) {
return { input: cachedNeedle, suggestion: suggestion };
}
}
}
banksy.find = find;
module.exports = banksy;