Skip to content

Commit

Permalink
fix: add checklist toggling (#56)
Browse files Browse the repository at this point in the history
  • Loading branch information
thecodrr committed Sep 13, 2021
1 parent 5eadb6b commit 14fc8e8
Showing 1 changed file with 55 additions and 5 deletions.
60 changes: 55 additions & 5 deletions packages/tinymce-plugins/checklist/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,14 @@ function register(editor) {
insertChecklist(editor);
});

editor.ui.registry.addButton("checklist", {
editor.ui.registry.addToggleButton("checklist", {
icon: "checklist",
tooltip: "Insert checklist",
active: false,
tooltip: "Checklist",
onAction: () => insertChecklist(editor),
onSetup: function (api) {
return listState(editor, api.setActive);
},
});

editor.on(
Expand Down Expand Up @@ -63,9 +67,55 @@ function register(editor) {
* @param {import("tinymce").Editor} editor
*/
function insertChecklist(editor) {
editor.undoManager.transact(function () {
editor.insertContent(EMPTY_CHECKLIST_HTML);
});
const node = editor.selection.getNode();
if (node.classList.contains(CLASS_NAMES.list)) {
editor.undoManager.transact(function () {
editor.execCommand("RemoveList");
});
} else {
editor.execCommand("InsertUnorderedList", false, {
"list-style-type": "none",
"list-attributes": { class: CLASS_NAMES.list },
});
}
}

function listState(editor, activate) {
var nodeChangeHandler = function (e) {
var inList = findUntil(e.parents, isListNode, isTableCellNode);
if (inList)
inList =
inList.filter(function (list) {
return list.className === CLASS_NAMES.list;
}).length > 0;
activate(inList);
};
var parents = editor.dom.getParents(editor.selection.getNode());
nodeChangeHandler({ parents: parents });
editor.on("NodeChange", nodeChangeHandler);
return function () {
return editor.off("NodeChange", nodeChangeHandler);
};
}

function findUntil(xs, pred, until) {
for (var i = 0, len = xs.length; i < len; i++) {
var x = xs[i];
if (pred(x, i)) {
return [x];
} else if (until(x, i)) {
break;
}
}
return;
}

var isListNode = matchNodeNames(/^(OL|UL|DL)$/);
var isTableCellNode = matchNodeNames(/^(TH|TD)$/);
function matchNodeNames(regex) {
return function (node) {
return node && regex.test(node.nodeName);
};
}

/**
Expand Down

0 comments on commit 14fc8e8

Please sign in to comment.