Files
deck/js/legacy/markdown-it-checkbox.js
Julius Härtl 71e6ff1b79 Make checkbox id order ascending (fixes #678)
Signed-off-by: Julius Härtl <jus@bitgrid.net>
2018-11-09 12:39:12 +01:00

121 lines
3.0 KiB
JavaScript

/**
* Original source code from https://github.com/mcecot/markdown-it-checkbox
* © 2015 Markus Cecot
* licenced under MIT
* https://github.com/mcecot/markdown-it-checkbox/blob/master/LICENSE
*/
var checkboxReplace;
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 = Object.assign(defaults, options);
pattern = /(.*?)(\[(X|\s|\_|\-)\])(.*)/igm;
createTokens = function(checked, label, Token, before) {
var id, idNumeric, nodes, token;
nodes = [];
token = new Token("text", "", 0);
token.content = before;
nodes.push(token);
/**
* <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;
idNumeric = lastId;
lastId += 1;
token = new Token("checkbox_input", "input", 0);
token.attrs = [["type", "checkbox"], ["id", id], ["data-id", idNumeric]];
if (checked === true) {
token.attrs.push(["checked", "true"]);
}
token.attrs.push(["class", "checkbox"]);
nodes.push(token);
/**
* <label for="checkbox{n}">
*/
token = new Token("label_open", "label", 1);
token.attrs = [["for", id], ["data-id", idNumeric]];
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, before;
text = original.content;
matches = pattern.exec(text);
if (matches === null) {
return original;
}
checked = false;
before = matches[1];
value = matches[3];
label = matches[4];
if (value === "X" || value === "x") {
checked = true;
}
return createTokens(checked, label, Token, before);
};
return function(state) {
lastId = 0;
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 = 0;
while (i < tokens.length) {
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));
};