-
Notifications
You must be signed in to change notification settings - Fork 5
/
widget.js
59 lines (49 loc) · 1.25 KB
/
widget.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
function trim (string) {
return string.substring(1, string.length - 1)
}
function style (rx, tag) {
return function (text) {
var m = rx.exec(text)
while (m) {
text = text.replace(m[0], '<'+tag+'>'+trim(m[0])+'</'+tag+'>')
m = rx.exec(text)
}
return text
}
}
var italics = style(/_[^_]+_/, 'em')
var bold = style(/\*[^\*]+\*/, 'strong')
var code = style(/`[^`]+`/, 'code')
function prefix (rx, tag) {
return function (val) {
var m = rx.exec(val)
if(m) {
var l = m[0].length
//oh yeah, escape chars...
var t = 'function' === typeof tag ? tag(m) : tag
return '<'+t+'>'+val.substring(l)+'</'+t+'>'
}
return val
}
}
var header = prefix(/^#+/, function (m) { return 'H'+m[0].length })
var li = prefix(/^\s*-+/, 'li')
function styles (text) {
return header(li(bold(italics(code(text)))))
}
function toHTML (val) {
if('\n' === val)
return '<br/>'
return styles(val)
}
function defaultTemplate (val, key, el) {
if(el)
return el.innerHTML = toHTML(val), el
var el = document.createElement('span')
el.innerHTML = toHTML(val)
return el
}
var widget = require('r-array/widget')
module.exports = function (rEdit, template) {
return widget(rEdit, template || defaultTemplate)
}