-
Notifications
You must be signed in to change notification settings - Fork 22
/
index.js
108 lines (98 loc) · 2.57 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
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
103
104
105
106
107
108
var _, checkboxReplace;
_ = require('underscore');
checkboxReplace = function(md, options, Token) {
"use strict";
var arrayReplaceAt, createTokens, defaults, lastId, pattern, splitTextToken;
arrayReplaceAt = md.utils.arrayReplaceAt;
lastId = 0;
defaults = {
divWrap: false,
divClass: 'checkbox',
idPrefix: 'checkbox'
};
options = _.extend(defaults, options);
pattern = /\[(X|\s|\_|\-)\]\s(.*)/i;
createTokens = function(checked, label, Token) {
var id, nodes, token;
nodes = [];
/**
* <div class="checkbox">
*/
if (options.divWrap) {
token = new Token("checkbox_open", "div", 1);
token.attrs = [["class", options.divClass]];
nodes.push(token);
}
/**
* <input type="checkbox" id="checkbox{n}" checked="true">
*/
id = options.idPrefix + lastId;
lastId += 1;
token = new Token("checkbox_input", "input", 0);
token.attrs = [["type", "checkbox"], ["id", id]];
if (checked === true) {
token.attrs.push(["checked", "true"]);
}
nodes.push(token);
/**
* <label for="checkbox{n}">
*/
token = new Token("label_open", "label", 1);
token.attrs = [["for", id]];
nodes.push(token);
/**
* content of label tag
*/
token = new Token("text", "", 0);
token.content = label;
nodes.push(token);
/**
* closing tags
*/
nodes.push(new Token("label_close", "label", -1));
if (options.divWrap) {
nodes.push(new Token("checkbox_close", "div", -1));
}
return nodes;
};
splitTextToken = function(original, Token) {
var checked, label, matches, text, value;
text = original.content;
matches = text.match(pattern);
if (matches === null) {
return original;
}
checked = false;
value = matches[1];
label = matches[2];
if (value === "X" || value === "x") {
checked = true;
}
return createTokens(checked, label, Token);
};
return function(state) {
var blockTokens, i, j, l, token, tokens;
blockTokens = state.tokens;
j = 0;
l = blockTokens.length;
while (j < l) {
if (blockTokens[j].type !== "inline") {
j++;
continue;
}
tokens = blockTokens[j].children;
i = tokens.length - 1;
while (i >= 0) {
token = tokens[i];
blockTokens[j].children = tokens = arrayReplaceAt(tokens, i, splitTextToken(token, state.Token));
i--;
}
j++;
}
};
};
/*global module */
module.exports = function(md, options) {
"use strict";
md.core.ruler.push("checkbox", checkboxReplace(md, options));
};