Skip to content

A fully open source & end-to-end encrypted note taking alternative to Evernote.

editor: use prosemirror plugin for managing task list state (#3252)

Muhammad Ali846efc5351a8
diff --git a/packages/editor/src/extensions/task-item/component.tsx b/packages/editor/src/extensions/task-item/component.tsx
index be4dd6586..138b47d01 100644
--- a/packages/editor/src/extensions/task-item/component.tsx
+++ b/packages/editor/src/extensions/task-item/component.tsx
@@ -21,9 +21,7 @@ import { Box, Flex } from "@theme-ui/components";
import { ReactNodeViewProps } from "../react";
import { Icon } from "@notesnook/ui";
import { Icons } from "../../toolbar/icons";
-import { Node as ProsemirrorNode } from "prosemirror-model";
-import { Transaction } from "prosemirror-state";
-import { findChildren, findChildrenInRange } from "@tiptap/core";
+import { findChildrenInRange } from "@tiptap/core";
import { useCallback } from "react";
import { TaskItemNode, TaskItemAttributes } from "./task-item";
import { useIsMobile } from "../../toolbar/stores/toolbar-store";
@@ -48,27 +46,17 @@ export function TaskItemComponent(
);
if (!empty && selectedTaskItems.findIndex((a) => a.node === node) > -1) {
editor.current.commands.command(({ tr }) => {
- for (const { node, pos } of selectedTaskItems) {
+ for (const { pos } of selectedTaskItems) {
tr.setNodeMarkup(pos, null, { checked: !checked });
- toggleChildren(node, tr, !checked, pos);
}
return true;
});
} else {
updateAttributes({ checked: !checked });
-
- const pos = getPos();
- const node = editor.current?.state.doc.nodeAt(pos);
- if (!node) return false;
-
- editor.commands.command(({ tr }) => {
- toggleChildren(node, tr, !checked, pos);
- return true;
- });
}
return true;
- }, [editor, checked, updateAttributes, getPos, node]);
+ }, [editor, checked, updateAttributes, node]);
return (
<>
@@ -184,24 +172,3 @@ export function TaskItemComponent(
</>
);
}
-
-function toggleChildren(
- node: ProsemirrorNode,
- tr: Transaction,
- toggleState: boolean,
- parentPos: number
-): Transaction {
- const children = findChildren(
- node,
- (node) => node.type.name === TaskItemNode.name
- );
-
- for (const { pos } of children) {
- // need to add 1 to get inside the node
- const actualPos = pos + parentPos + 1;
- tr.setNodeMarkup(actualPos, undefined, {
- checked: toggleState
- });
- }
- return tr;
-}
diff --git a/packages/editor/src/extensions/task-list/component.tsx b/packages/editor/src/extensions/task-list/component.tsx
index d6604587f..390078a2e 100644
--- a/packages/editor/src/extensions/task-list/component.tsx
+++ b/packages/editor/src/extensions/task-list/component.tsx
@@ -18,80 +18,29 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { Box, Flex, Input, Text } from "@theme-ui/components";
-import {
- findChildren,
- findParentNodeClosestToPos,
- getNodeType
-} from "@tiptap/core";
-import { Node } from "prosemirror-model";
-import { useCallback, useEffect, useMemo, useState } from "react";
+import { useMemo } from "react";
import { ToolButton } from "../../toolbar/components/tool-button";
-import { findParentNodeOfTypeClosestToPos } from "../../utils/prosemirror";
import { ReactNodeViewProps } from "../react";
-import { TaskItemNode } from "../task-item";
-import { TaskListAttributes, TaskListNode } from "./task-list";
-import { countCheckedItems, deleteCheckedItems, sortList } from "./utils";
+import { type TaskListAttributes } from "./task-list";
import { replaceDateTime } from "../date-time";
+import { deleteCheckedItems, sortList } from "./utils";
+import TaskList from "@tiptap/extension-task-list";
+import TaskItem from "@tiptap/extension-task-item";
export function TaskListComponent(
props: ReactNodeViewProps<TaskListAttributes>
) {
- // const isMobile = useIsMobile();
const { editor, getPos, node, updateAttributes, forwardRef, pos } = props;
- const taskItemType = getNodeType(TaskItemNode.name, editor.schema);
- const { title, textDirection, readonly } = node.attrs;
- const [stats, setStats] = useState({ checked: 0, total: 0, percentage: 0 });
-
- const getParent = useCallback(() => {
- if (pos === undefined) return;
- return findParentNodeOfTypeClosestToPos(
- editor.state.doc.resolve(pos),
- taskItemType
- );
- }, [editor.state.doc, pos, taskItemType]);
+ const { title, textDirection, readonly, stats } = node.attrs;
const isNested = useMemo(() => {
- return !!getParent();
- }, [getParent]);
-
- const isReadonly = useMemo(() => {
- console.log("HEERE!");
- const isParentReadonly =
- !!isNested &&
- !!pos &&
- !!findParentNodeClosestToPos(
- editor.state.doc.resolve(pos),
- (node) => node.type.name === TaskListNode.name && node.attrs.readonly
- );
- return readonly || isParentReadonly;
- }, [isNested, readonly, editor.state.doc, pos]);
-
- useEffect(() => {
- const parent = getParent();
- if (!parent) return;
- const { node, pos } = parent;
- const allChecked = areAllChecked(node, pos, editor.state.doc);
-
- // no need to create a transaction if the check state is
- // not changed.
- if (node.attrs.checked === allChecked) return;
-
- // check parent item if all child items are checked.
- editor.commands.command(({ tr }) => {
- tr.setNodeMarkup(pos, undefined, { checked: allChecked });
- return true;
- });
- }, [editor.commands, editor.state.doc, getParent, node, node.childCount]);
-
- useEffect(() => {
- const { checked, total } = countCheckedItems(node);
- const percentage = Math.round((checked / total) * 100);
- setStats({ checked, total, percentage });
- }, [isNested, node]);
+ if (!pos) return false;
+ return editor.state.doc.resolve(pos).parent.type.name === TaskItem.name;
+ }, [editor.state.doc, pos]);
return (
<>
- {!isNested && (
+ {isNested ? null : (
<Flex
sx={{
position: "relative",
@@ -110,7 +59,7 @@ export function TaskListComponent(
<Box
sx={{
height: "100%",
- width: `${stats.percentage}%`,
+ width: `${Math.round((stats.checked / stats.total) * 100)}%`,
position: "absolute",
bg: "shade",
@@ -156,13 +105,24 @@ export function TaskListComponent(
zIndex: 1
}}
onClick={() => {
- const pos = getPos();
- const node = editor.current?.state.doc.nodeAt(pos);
- if (!node) return;
- updateAttributes(
- { readonly: !node.attrs.readonly },
- { addToHistory: true, preventUpdate: false }
- );
+ const parentPos = getPos();
+ editor.current?.commands.command(({ tr }) => {
+ const node = tr.doc.nodeAt(parentPos);
+ if (!node) return false;
+ const toggleState = !node.attrs.readonly;
+ tr.setNodeMarkup(tr.mapping.map(parentPos), null, {
+ readonly: toggleState
+ });
+ node.descendants((node, pos) => {
+ if (node.type.name === TaskList.name) {
+ const actualPos = pos + parentPos + 1;
+ tr.setNodeMarkup(tr.mapping.map(actualPos), null, {
+ readonly: toggleState
+ });
+ }
+ });
+ return true;
+ });
}}
/>
<ToolButton
@@ -224,7 +184,7 @@ export function TaskListComponent(
<Box
ref={forwardRef}
dir={textDirection}
- contentEditable={editor.isEditable && !isReadonly}
+ contentEditable={editor.isEditable && !readonly}
sx={{
ul: {
display: "block",
@@ -255,18 +215,3 @@ export function TaskListComponent(
</>
);
}
-
-function areAllChecked(node: Node, pos: number, doc: Node) {
- const children = findChildren(
- node,
- (node) => node.type.name === TaskItemNode.name
- );
-
- for (const child of children) {
- const childPos = pos + child.pos + 1;
- const node = doc.nodeAt(childPos);
- if (!node?.attrs.checked) return false;
- }
-
- return true;
-}
diff --git a/packages/editor/src/extensions/task-list/task-list.ts b/packages/editor/src/extensions/task-list/task-list.ts
index 74d66a5fa..2441277ed 100644
--- a/packages/editor/src/extensions/task-list/task-list.ts
+++ b/packages/editor/src/extensions/task-list/task-list.ts
@@ -21,25 +21,41 @@ import { mergeAttributes, wrappingInputRule } from "@tiptap/core";
import { TaskList } from "@tiptap/extension-task-list";
import { createNodeView } from "../react";
import { TaskListComponent } from "./component";
-import { Plugin, PluginKey, NodeSelection } from "prosemirror-state";
-import TaskItem, { inputRegex } from "@tiptap/extension-task-item";
+import {
+ Plugin,
+ PluginKey,
+ NodeSelection,
+ Transaction
+} from "prosemirror-state";
+import { inputRegex } from "@tiptap/extension-task-item";
import { dropPoint } from "prosemirror-transform";
import {
findChildrenByType,
+ getChangedNodes,
+ getDeletedNodes,
getParentAttributes,
- hasSameAttributes
+ hasSameAttributes,
+ findParentNodeClosestToPos
} from "../../utils/prosemirror";
-import { countCheckedItems } from "./utils";
+import { countCheckedItems, findRootTaskList } from "./utils";
+import { Node as ProsemirrorNode } from "@tiptap/pm/model";
+import { TaskItemNode } from "../task-item";
+type TaskListStats = { checked: number; total: number };
export type TaskListAttributes = {
title: string;
readonly: boolean;
+ stats: TaskListStats;
};
const stateKey = new PluginKey("task-item-drop-override");
export const TaskListNode = TaskList.extend({
addAttributes() {
return {
+ stats: {
+ default: { checked: 0, total: 0 },
+ rendered: false
+ },
title: {
default: null,
keepOnSplit: false,
@@ -138,6 +154,7 @@ export const TaskListNode = TaskList.extend({
shouldUpdate: (prev, next) => {
return (
!hasSameAttributes(prev.attrs, next.attrs) ||
+ !hasSameAttributes(prev.attrs.stats, next.attrs.stats) ||
prev.childCount !== next.childCount ||
countCheckedItems(prev).checked !== countCheckedItems(next).checked
);
@@ -157,7 +174,7 @@ export const TaskListNode = TaskList.extend({
// behavior and instead moves the item to the very end.
handleDrop(view, event, slice, moved) {
const isTaskItem =
- slice.content.firstChild?.type.name === TaskItem.name;
+ slice.content.firstChild?.type.name === TaskItemNode.name;
if (isTaskItem) {
const eventPos = view.posAtCoords(eventCoords(event));
if (!eventPos) return;
@@ -207,6 +224,106 @@ export const TaskListNode = TaskList.extend({
return false;
}
}
+ }),
+ // this plugin is responsible for handling all the interactive/reactive
+ // logic of a task list:
+ // 1. Auto checking parent task item based on its children
+ // 2. Auto checking child task items based on its parent
+ // 3. Keeping the stats (checked/total items etc.) synced with
+ // the task list.
+ new Plugin({
+ key: new PluginKey("task-list-state-management"),
+ view(view) {
+ const { tr } = view.state;
+ tr.doc.descendants((node, pos) => {
+ if (node.type.name === TaskList.name) {
+ tr.setNodeMarkup(pos, undefined, {
+ stats: countCheckedItems(node)
+ });
+ return false;
+ }
+ });
+ view.dispatch(tr);
+ return {};
+ },
+ appendTransaction(transactions, _oldState, newState) {
+ if (!transactions[0].docChanged) return;
+
+ const changedNodes = getChangedNodes(transactions[0], {
+ predicate: (node) => node.type.name === TaskItemNode.name
+ });
+ const deletedNodes = getDeletedNodes(
+ transactions[0],
+ (node) => node.type.name === TaskList.name
+ );
+ if (changedNodes.length <= 0 && deletedNodes.length <= 0) return;
+
+ let changeCount = 0;
+ const { tr } = newState;
+ const roots = new WeakSet();
+
+ for (const edit of [...changedNodes, ...deletedNodes]) {
+ // sync the stats with the new changes.
+ // we add a small optimization here to avoid checking the same
+ // root task list over and over again in case of multiple
+ // node changes
+ const root = findRootTaskList(tr.doc, edit.pos) || edit;
+ if (root && !roots.has(root)) {
+ roots.add(root);
+
+ const stats = countCheckedItems(root.node);
+ console.log(stats);
+ tr.setNodeMarkup(root.pos, undefined, { stats });
+ changeCount++;
+ }
+
+ // Case # 1
+ // if the user clicks on a task item that has children, we
+ // should automatically check/uncheck all its children
+ if (
+ // when a task item has children, the task list is always the
+ // last child
+ edit.node.lastChild?.type.name === TaskList.name
+ ) {
+ changeCount += toggleChildren(
+ tr,
+ edit.node,
+ edit.node.attrs.checked,
+ tr.mapping.map(edit.pos)
+ );
+ }
+
+ // Case # 2
+ // if the user clicks on a task item without any children,
+ // we should recursively move upwards in the tree to see
+ // if it's parent needs to be checked or not. We check
+ // a parent if all it's children have been checked as well.
+ // ---
+ // We use a while loop and start from the bottom up. Each iteration
+ // checks the previous task item's parent recursively.
+ let childPos = edit.pos;
+ while (childPos !== undefined) {
+ const resolvedPos = tr.doc.resolve(tr.mapping.map(childPos));
+ const parentTaskItem = findParentNodeClosestToPos(
+ resolvedPos,
+ (n) => n.type.name === TaskItemNode.name
+ );
+ //
+ if (!parentTaskItem) break;
+
+ const allChecked = areAllChecked(parentTaskItem.node);
+ // if no change needs to be made, we break the loop.
+ if (allChecked === parentTaskItem.node.attrs.checked) break;
+
+ changeCount++;
+ tr.setNodeMarkup(tr.mapping.map(parentTaskItem.pos), undefined, {
+ checked: allChecked
+ });
+ childPos = parentTaskItem.pos;
+ }
+ }
+ return changeCount > 0 ? tr : null;
+ }
})
];
},
@@ -240,3 +357,41 @@ export const TaskListNode = TaskList.extend({
function eventCoords(event: MouseEvent) {
return { left: event.clientX, top: event.clientY };
}
+
+function areAllChecked(node: ProsemirrorNode) {
+ const taskList = node.lastChild;
+ if (!taskList || taskList.type.name !== TaskList.name)
+ return !!node.attrs.checked;
+
+ let allChecked = true;
+ for (let i = 0; i < taskList.childCount; ++i) {
+ const child = taskList.child(i);
+ if (!child.attrs.checked) {
+ allChecked = false;
+ break;
+ }
+ }
+ return allChecked;
+}
+
+function toggleChildren(
+ tr: Transaction,
+ node: ProsemirrorNode,
+ toggleState: boolean,
+ parentPos: number
+) {
+ let changes = 0;
+ node.descendants((node, pos) => {
+ if (
+ node.type.name === TaskItemNode.name &&
+ toggleState !== node.attrs.checked
+ ) {
+ const actualPos = pos + parentPos + 1;
+ tr.setNodeMarkup(tr.mapping.map(actualPos), undefined, {
+ checked: toggleState
+ });
+ changes++;
+ }
+ });
+ return changes;
+}
diff --git a/packages/editor/src/extensions/task-list/utils.ts b/packages/editor/src/extensions/task-list/utils.ts
index ddce7c968..d3c6485a1 100644
--- a/packages/editor/src/extensions/task-list/utils.ts
+++ b/packages/editor/src/extensions/task-list/utils.ts
@@ -20,14 +20,15 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
import TaskList from "@tiptap/extension-task-list";
import { Transaction } from "@tiptap/pm/state";
import { Fragment, Node as ProsemirrorNode } from "prosemirror-model";
-import { TaskItemNode } from "../task-item";
import { NodeWithPos } from "@tiptap/core";
+import { findParentNodeClosestToPos } from "../../utils/prosemirror";
+import TaskItem from "@tiptap/extension-task-item";
export function countCheckedItems(node: ProsemirrorNode) {
let checked = 0;
let total = 0;
node.descendants((node) => {
- if (node.type.name === TaskItemNode.name) {
+ if (node.type.name === TaskItem.name) {
if (node.attrs.checked) checked++;
total++;
}
@@ -121,3 +122,14 @@ export function sortList(tr: Transaction, pos: number) {
if (!tr.steps.length) return null;
return tr;
}
+
+const invalidTaskListParents = [TaskList.name, TaskItem.name];
+export function findRootTaskList(doc: ProsemirrorNode, pos?: number) {
+ if (!pos) return;
+ return findParentNodeClosestToPos(
+ doc.resolve(pos),
+ (node, parent) =>
+ node.type.name === TaskList.name &&
+ (!parent || !invalidTaskListParents.includes(parent.type.name))
+ );
+}
diff --git a/packages/editor/src/utils/prosemirror.ts b/packages/editor/src/utils/prosemirror.ts
index b3e7c0ad0..7b3590afb 100644
--- a/packages/editor/src/utils/prosemirror.ts
+++ b/packages/editor/src/utils/prosemirror.ts
@@ -22,7 +22,6 @@ import {
findParentNode,
NodeWithPos,
Predicate,
- findParentNodeClosestToPos,
getChangedRanges
} from "@tiptap/core";
import {
@@ -31,7 +30,8 @@ import {
Mark,
NodeType,
ResolvedPos,
- Attrs
+ Attrs,
+ Slice
} from "prosemirror-model";
import { EditorState, Selection, Transaction } from "prosemirror-state";
import { BulletList } from "../extensions/bullet-list";
@@ -165,6 +165,34 @@ export const findParentNodeOfTypeClosestToPos = (
);
};
+export type NodeWithPosAndDepth = {
+ pos: number;
+ start: number;
+ depth: number;
+ node: ProsemirrorNode;
+};
+type PredicateWithParent = (
+ node: ProsemirrorNode,
+ parent?: ProsemirrorNode
+) => boolean;
+export function findParentNodeClosestToPos(
+ $pos: ResolvedPos,
+ predicate: PredicateWithParent
+): NodeWithPosAndDepth | undefined {
+ for (let i = $pos.depth; i > 0; i -= 1) {
+ const node = $pos.node(i);
+
+ if (predicate(node, i === 1 ? undefined : $pos.node(i - 1))) {
+ return {
+ pos: i > 0 ? $pos.before(i) : 0,
+ start: $pos.start(i),
+ depth: i,
+ node
+ };
+ }
+ }
+}
+
export function hasParentNode(predicate: Predicate) {
return function (selection: Selection) {
return !!findParentNode(predicate)(selection);
@@ -283,22 +311,38 @@ export function getChangedNodes(
// The container for the nodes which have been added..
const nodes: NodeWithPos[] = [];
-
for (const range of nodeRange) {
- const { start, end } = range;
+ const { start } = range;
- // Find all the nodes between the provided node range.
- tr.doc.nodesBetween(start, end, (node, pos) => {
- // Check wether this is a node that should be added.
- const shouldAdd = predicate?.(node, pos, range) ?? true;
+ if (nodeRange && nodes.every((n) => n.pos !== start)) {
+ const node = tr.doc.nodeAt(start);
+ if (node && (!predicate || predicate(node, start, range)))
+ nodes.push({ node, pos: start });
+ }
+ }
- if (shouldAdd) {
- nodes.push({ node, pos });
- }
+ return nodes;
+}
- return descend;
- });
+export function getDeletedNodes(
+ tr: Transaction,
+ predicate: (node: ProsemirrorNode, parent?: ProsemirrorNode) => boolean
+) {
+ const nodes: NodeWithPos[] = [];
+ for (const step of tr.steps) {
+ if (
+ "slice" in step &&
+ step.slice instanceof Slice &&
+ "to" in step &&
+ typeof step.to === "number" &&
+ "from" in step &&
+ typeof step.from === "number" &&
+ step.slice === Slice.empty
+ ) {
+ const $from = tr.doc.resolve(step.from);
+ const node = findParentNodeClosestToPos($from, predicate);
+ if (node) nodes.push(node);
+ }
}
-
return nodes;
}