A fully open source & end-to-end encrypted note taking alternative to Evernote.
TypeScript asp-net-coredotnet-coreelectronfosshacktoberfestnote-managmentnote-takingnote-taking-appnotebooknotesnotes-appopen-sourceopensourceprivacyproductivityreactreact-nativereactjsself-hosted
editor: use list-keymap extension instead of own workarounds
Abdullah Atta271aa11f747a
diff --git a/packages/editor/src/extensions/key-map/key-map.ts b/packages/editor/src/extensions/key-map/key-map.tsindex e6eb6e144..47d67343c 100644--- a/packages/editor/src/extensions/key-map/key-map.ts+++ b/packages/editor/src/extensions/key-map/key-map.ts@@ -17,9 +17,8 @@ You should have received a copy of the GNU General Public Licensealong with this program. If not, see <http://www.gnu.org/licenses/>.*/-import { Editor, Extension } from "@tiptap/core";+import { Extension } from "@tiptap/core";import { isInTable } from "@tiptap/pm/tables";-import { LIST_ITEM_NODE_TYPES, LIST_NODE_TYPES } from "../../utils/node-types";import { isListActive } from "../../utils/prosemirror";import { CodeBlock } from "../code-block";@@ -41,53 +40,7 @@ export const KeyMap = Extension.create({"Shift-Tab": ({ editor }) => {if (isListActive(editor)) return false;return true;- },- Backspace: ({ editor }) => {- return joinUpWithLastListItem(editor);}};}});--/**- * By default, in ProseMirror, if the cursor is right below a list,- * pressing Backspace creates a new empty list item at the end.- * This function corrects this behavior and moves the cursor to the- * end of the list.- */-export function joinUpWithLastListItem(editor: Editor) {- const { selection, doc } = editor.state;- const { $from, empty } = selection;-- const parentPos = $from.pos - $from.parentOffset - 1;- const before = doc.resolve(parentPos).nodeBefore;-- if (- empty &&- $from.parentOffset === 0 &&- before &&- LIST_NODE_TYPES.includes(before.type.name)- ) {- // The last list item can be at any depth and the number of joinBackwards- // depend on how deep it is.- let lastItemDepth = 0;- before.descendants((node, pos) => {- if (LIST_ITEM_NODE_TYPES.includes(node.type.name)) {- const { depth } = before.resolve(pos);- lastItemDepth = depth / 2;- }- });- // The depth of the last list item does not take into account- // the parent depth (i.e. 1) so we have to increment it.- lastItemDepth++;-- let commands = editor.chain().joinBackward();- for (let i = 0; i < lastItemDepth; ++i) {- commands = commands.joinBackward().joinBackward();- }-- return commands.run();- }-- return false;-}diff --git a/packages/editor/src/extensions/key-map/tests/__snapshots__/key-map.test.ts.snap b/packages/editor/src/extensions/key-map/tests/__snapshots__/key-map.test.ts.snapdeleted file mode 100644index c6f257300..000000000--- a/packages/editor/src/extensions/key-map/tests/__snapshots__/key-map.test.ts.snap+++ /dev/null@@ -1,268 +0,0 @@-// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html--exports[`join up with last list item in a flat list 1`] = `-[- {- "attrs": {- "listType": "",- },- "content": [- {- "content": [- {- "content": [- {- "text": "Hello",- "type": "text",- },- ],- "type": "paragraph",- },- ],- "type": "listItem",- },- {- "content": [- {- "content": [- {- "text": "World",- "type": "text",- },- ],- "type": "paragraph",- },- ],- "type": "listItem",- },- ],- "type": "bulletList",- },-]-`;--exports[`join up with last list item in a nested list 1`] = `-[- {- "attrs": {- "listType": "",- },- "content": [- {- "content": [- {- "content": [- {- "text": "Hello",- "type": "text",- },- ],- "type": "paragraph",- },- ],- "type": "listItem",- },- {- "content": [- {- "content": [- {- "text": "World",- "type": "text",- },- ],- "type": "paragraph",- },- {- "attrs": {- "listType": "",- },- "content": [- {- "content": [- {- "content": [- {- "text": "Hello",- "type": "text",- },- ],- "type": "paragraph",- },- ],- "type": "listItem",- },- {- "content": [- {- "content": [- {- "text": "World",- "type": "text",- },- ],- "type": "paragraph",- },- {- "attrs": {- "listType": "",- },- "content": [- {- "content": [- {- "content": [- {- "text": "Hello",- "type": "text",- },- ],- "type": "paragraph",- },- ],- "type": "listItem",- },- ],- "type": "bulletList",- },- ],- "type": "listItem",- },- {- "content": [- {- "content": [- {- "text": "A very nested world",- "type": "text",- },- ],- "type": "paragraph",- },- ],- "type": "listItem",- },- ],- "type": "bulletList",- },- ],- "type": "listItem",- },- ],- "type": "bulletList",- },-]-`;--exports[`join up with last list item in a nested list 2`] = `-[- {- "attrs": {- "listType": "",- },- "content": [- {- "content": [- {- "content": [- {- "text": "Hello",- "type": "text",- },- ],- "type": "paragraph",- },- ],- "type": "listItem",- },- {- "content": [- {- "content": [- {- "text": "World",- "type": "text",- },- ],- "type": "paragraph",- },- {- "attrs": {- "listType": "",- },- "content": [- {- "content": [- {- "content": [- {- "text": "Hello",- "type": "text",- },- ],- "type": "paragraph",- },- ],- "type": "listItem",- },- {- "content": [- {- "content": [- {- "text": "World",- "type": "text",- },- ],- "type": "paragraph",- },- {- "attrs": {- "listType": "",- },- "content": [- {- "content": [- {- "content": [- {- "text": "Hello",- "type": "text",- },- ],- "type": "paragraph",- },- ],- "type": "listItem",- },- ],- "type": "bulletList",- },- ],- "type": "listItem",- },- {- "content": [- {- "content": [- {- "text": "A very nested world",- "type": "text",- },- ],- "type": "paragraph",- },- ],- "type": "listItem",- },- ],- "type": "bulletList",- },- ],- "type": "listItem",- },- ],- "type": "bulletList",- },-]-`;diff --git a/packages/editor/src/extensions/key-map/tests/key-map.test.ts b/packages/editor/src/extensions/key-map/tests/key-map.test.tsdeleted file mode 100644index 1872db03d..000000000--- a/packages/editor/src/extensions/key-map/tests/key-map.test.ts+++ /dev/null@@ -1,105 +0,0 @@-/*-This file is part of the Notesnook project (https://notesnook.com/)--Copyright (C) 2023 Streetwriters (Private) Limited--This program is free software: you can redistribute it and/or modify-it under the terms of the GNU General Public License as published by-the Free Software Foundation, either version 3 of the License, or-(at your option) any later version.--This program is distributed in the hope that it will be useful,-but WITHOUT ANY WARRANTY; without even the implied warranty of-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-GNU General Public License for more details.--You should have received a copy of the GNU General Public License-along with this program. If not, see <http://www.gnu.org/licenses/>.-*/--import { createEditor, h } from "@/test-utils";-import { test, expect } from "vitest";-import BulletList from "../../bullet-list";-import { ListItem } from "../../list-item";-import { joinUpWithLastListItem } from "../key-map";--test(`join up with last list item in a flat list`, async () => {- const { editor } = createEditor({- initialContent: h("div", [- h("ul", [h("li", ["Hello"]), h("li", ["World"])]),- h("p")- ]).innerHTML,- extensions: {- bulletList: BulletList,- listItem: ListItem- }- });-- editor.commands.setTextSelection(editor.state.doc.nodeSize - 2);- joinUpWithLastListItem(editor);-- expect(editor.state.selection.$from.parent.textContent).toBe("World");- expect(editor.state.doc.content.toJSON()).toMatchSnapshot();-});--test(`join up with last list item in a nested list`, async () => {- const { editor } = createEditor({- initialContent: h("div", [- h("ul", [- h("li", ["Hello"]),- h("li", [- "World",- h("ul", [- h("li", ["Hello"]),- h("li", ["World", h("ul", [h("li", ["Hello"])])]),- h("li", ["A very nested world"])- ])- ])- ]),- h("p")- ]).innerHTML,- extensions: {- bulletList: BulletList,- listItem: ListItem- }- });-- editor.commands.setTextSelection(editor.state.doc.nodeSize - 2);- joinUpWithLastListItem(editor);-- expect(editor.state.selection.$from.parent.textContent).toBe(- "A very nested world"- );- expect(editor.state.doc.content.toJSON()).toMatchSnapshot();-});--test(`join up with last list item in a nested list`, async () => {- const { editor } = createEditor({- initialContent: h("div", [- h("ul", [- h("li", ["Hello"]),- h("li", [- "World",- h("ul", [- h("li", ["Hello"]),- h("li", ["World", h("ul", [h("li", ["Hello"])])]),- h("li", ["A very nested world"])- ])- ])- ]),- h("p")- ]).innerHTML,- extensions: {- bulletList: BulletList,- listItem: ListItem- }- });-- editor.commands.setTextSelection(editor.state.doc.nodeSize - 2);- joinUpWithLastListItem(editor);-- expect(editor.state.selection.$from.parent.textContent).toBe(- "A very nested world"- );- expect(editor.state.doc.content.toJSON()).toMatchSnapshot();-});diff --git a/packages/editor/src/extensions/list-item/commands.ts b/packages/editor/src/extensions/list-item/commands.tsindex 884b64a01..00ec37b72 100644--- a/packages/editor/src/extensions/list-item/commands.ts+++ b/packages/editor/src/extensions/list-item/commands.ts@@ -20,56 +20,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.import { EditorState } from "prosemirror-state";import { NodeType } from "prosemirror-model";import { Editor } from "@tiptap/core";-import {- findParentNodeOfType,- hasParentNodeOfType-} from "../../utils/prosemirror";--// WORKAROUND: if we're at the start of a list item, we need to either-// backspace directly to an empty list item above, or outdent this node-export function onBackspacePressed(- editor: Editor,- name: string,- type: NodeType-) {- const { selection } = editor.state;- const { empty, $from } = selection;-- if (- !empty ||- !isInside(name, type, editor.state) ||- $from.parentOffset !== 0 ||- !isFirstChildOfParent(editor.state) ||- !editor.can().liftListItem(type)- )- return false;-- const isEmpty = isListItemEmpty(type, editor.state);-- if (isEmpty) {- if (isFirstOfType(type, editor.state)) {- const parentList = getListFromListItem(type, editor.state);- if (!parentList) return false;- if (parentList.childCount > 1) {- return editor.commands.liftListItem(type);- }- }-- return editor.chain().joinBackward().joinBackward().run();- } else if (isFirstOfType(type, editor.state)) {- return editor.commands.liftListItem(type);- } else {- const block = findParentNodeOfType(type)(selection);- if (block && block.start === $from.pos - 1) {- // we have to run join backward twice because on the first join- // the two list items are joined i.e., the editor just puts their- // paragraphs next to each other. The next join merges the paragraphs- // like it should be.- return editor.chain().joinBackward().joinBackward().run();- }- }- return false;-}+import { findParentNodeOfType } from "../../utils/prosemirror";export function onArrowUpPressed(editor: Editor, name: string, type: NodeType) {const { selection } = editor.state;@@ -82,25 +33,6 @@ export function onArrowUpPressed(editor: Editor, name: string, type: NodeType) {return false;}-function isInside(name: string, type: NodeType, state: EditorState) {- const { $from } = state.selection;-- const node = type || state.schema.nodes[name];- const { paragraph } = state.schema.nodes;-- return (- hasParentNodeOfType(node)(state.selection) &&- $from.parent.type === paragraph- );-}--function isFirstChildOfParent(state: EditorState): boolean {- const { $from } = state.selection;- return $from.depth > 1- ? $from.parentOffset === 0 || $from.index($from.depth - 1) === 0- : true;-}-const isFirstOfType = (type: NodeType, state: EditorState) => {const block = findParentNodeOfType(type)(state.selection);if (!block) return false;@@ -122,10 +54,3 @@ const getListFromListItem = (type: NodeType, state: EditorState) => {return resolved.parent;};--function isListItemEmpty(type: NodeType, state: EditorState) {- const block = findParentNodeOfType(type)(state.selection);- if (!block) return false;- const { node } = block;- return !node.textContent.length;-}diff --git a/packages/editor/src/extensions/list-item/list-item.ts b/packages/editor/src/extensions/list-item/list-item.tsindex b8a63edd3..cc74e5d44 100644--- a/packages/editor/src/extensions/list-item/list-item.ts+++ b/packages/editor/src/extensions/list-item/list-item.ts@@ -18,7 +18,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.*/import { ListItem as TiptapListItem } from "@tiptap/extension-list-item";-import { onArrowUpPressed, onBackspacePressed } from "./commands";+import { onArrowUpPressed } from "./commands";export const ListItem = TiptapListItem.extend({addKeyboardShortcuts() {@@ -34,8 +34,6 @@ export const ListItem = TiptapListItem.extend({return this.parent?.()?.Tab(props) || false;},- Backspace: ({ editor }) =>- onBackspacePressed(editor, this.name, this.type),ArrowUp: ({ editor }) => onArrowUpPressed(editor, this.name, this.type)};}diff --git a/packages/editor/src/extensions/outline-list-item/outline-list-item.ts b/packages/editor/src/extensions/outline-list-item/outline-list-item.tsindex e2515d550..d9acead6e 100644--- a/packages/editor/src/extensions/outline-list-item/outline-list-item.ts+++ b/packages/editor/src/extensions/outline-list-item/outline-list-item.ts@@ -26,7 +26,7 @@ import {} from "@tiptap/core";import { NodeType } from "prosemirror-model";import { findParentNodeOfTypeClosestToPos } from "../../utils/prosemirror";-import { onArrowUpPressed, onBackspacePressed } from "../list-item/commands";+import { onArrowUpPressed } from "../list-item/commands";import { OutlineList } from "../outline-list/outline-list";export interface ListItemOptions {@@ -111,8 +111,6 @@ export const OutlineListItem = Node.create<ListItemOptions>({},Tab: () => this.editor.commands.sinkListItem(this.name),"Shift-Tab": () => this.editor.commands.liftListItem(this.name),- Backspace: ({ editor }) =>- onBackspacePressed(editor, this.name, this.type),ArrowUp: ({ editor }) => onArrowUpPressed(editor, this.name, this.type)};},diff --git a/packages/editor/src/extensions/task-item/task-item.ts b/packages/editor/src/extensions/task-item/task-item.tsindex 4d21cb788..f4f7ac872 100644--- a/packages/editor/src/extensions/task-item/task-item.ts+++ b/packages/editor/src/extensions/task-item/task-item.ts@@ -18,7 +18,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.*/import { mergeAttributes } from "@tiptap/core";-import { onArrowUpPressed, onBackspacePressed } from "../list-item/commands";+import { onArrowUpPressed } from "../list-item/commands";import { TaskItem } from "@tiptap/extension-task-item";import { TaskItemComponent } from "./component";import { createNodeView } from "../react";@@ -74,8 +74,6 @@ export const TaskItemNode = TaskItem.extend({addKeyboardShortcuts() {return {...this.parent?.(),- Backspace: ({ editor }) =>- onBackspacePressed(editor, this.name, this.type),ArrowUp: ({ editor }) => onArrowUpPressed(editor, this.name, this.type)};},diff --git a/packages/editor/src/index.ts b/packages/editor/src/index.tsindex 0e21a59d2..a19999756 100644--- a/packages/editor/src/index.ts+++ b/packages/editor/src/index.ts@@ -36,6 +36,7 @@ import TextAlign from "@tiptap/extension-text-align";import TextStyle from "@tiptap/extension-text-style";import Underline from "@tiptap/extension-underline";import StarterKit from "@tiptap/starter-kit";+import ListKeymap from "@tiptap/extension-list-keymap";import { useEffect, useMemo } from "react";import "./extensions";import { AttachmentNode, AttachmentOptions } from "./extensions/attachment";@@ -219,6 +220,22 @@ const useTiptap = (OrderedList.configure({ keepMarks: true, keepAttributes: true }),TaskItemNode.configure({ nested: true }),TaskListNode,+ ListKeymap.configure({+ listTypes: [+ {+ itemName: ListItem.name,+ wrapperNames: [BulletList.name, OrderedList.name]+ },+ {+ itemName: TaskItemNode.name,+ wrapperNames: [TaskListNode.name]+ },+ {+ itemName: OutlineListItem.name,+ wrapperNames: [OutlineList.name]+ }+ ]+ }),Link.extend({inclusive: true}).configure({