Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:art: Improve list shortcut behavior within lists https://github.com/siyuan-note/siyuan/issues/14123

Daniel0042d912d4af
diff --git a/app/src/protyle/wysiwyg/keydown.ts b/app/src/protyle/wysiwyg/keydown.ts
index b7397d2555..1e83082c30 100644
--- a/app/src/protyle/wysiwyg/keydown.ts
+++ b/app/src/protyle/wysiwyg/keydown.ts
@@ -47,6 +47,7 @@ import {clearTableCell, fixTable} from "../util/table";
import {
transaction,
insertEmptyBlockquote,
+ isEmptyParagraph,
turnsIntoOneTransaction,
turnsIntoTransaction,
turnsOneInto,
@@ -55,7 +56,15 @@ import {
} from "./transaction";
import {getBlockquoteContext, shouldCancelBlockquote} from "./blockquote";
import {fontEvent} from "../toolbar/Font";
-import {addSubList, listIndent, listOutdent, toggleTaskListItem} from "./list";
+import {
+ addSubList,
+ insertEmptyChildList,
+ insertEmptyListItem,
+ listIndent,
+ listOutdent,
+ toggleTaskListItem
+} from "./list";
+import {getListContext, getListConversionType, getListShortcutAction, type TListSubtype} from "./listContext";
import {newFileContentBySelect, rename, replaceFileName} from "../../editor/rename";
import {cancelSB, insertEmptyBlock, jumpToParent} from "../../block/util";
import {isEncryptedBox, isLocalPath} from "../../util/pathName";
@@ -1806,7 +1815,35 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
protyle.hint.fill(">" + Lute.Caret, protyle);
}
} else {
- if (type === "NodeParagraph") {
+ const targetSubtype: TListSubtype = isMatchCheck ? "t" : (isMatchList ? "u" : "o");
+ const listContext = hasBlockSelection ? undefined :
+ getListContext(selectsElement[0], protyle.wysiwyg.element);
+ if (listContext) {
+ const isListItemFocused = Boolean(protyle.block.showAll &&
+ protyle.block.id === listContext.listItemElement.dataset.nodeId);
+ const action = getListShortcutAction(listContext, targetSubtype,
+ listContext.childElements.length === 1 && isEmptyParagraph(listContext.childElements[0]),
+ isListItemFocused);
+ if (action === "cancelList" || action === "convertList") {
+ const conversionType = action === "convertList" ?
+ getListConversionType(listContext.subtype, targetSubtype) : "CancelList";
+ if (listContext.listElement && conversionType) {
+ const focusRange = range.cloneRange();
+ focusRange.collapse(true);
+ focusRange.insertNode(document.createElement("wbr"));
+ turnsOneInto({
+ protyle,
+ nodeElement: listContext.listElement,
+ id: listContext.listElement.dataset.nodeId,
+ type: conversionType,
+ });
+ }
+ } else if (action === "insertListItem") {
+ insertEmptyListItem(protyle, listContext.listItemElement, range);
+ } else {
+ insertEmptyChildList(protyle, listContext.childElement, targetSubtype, range);
+ }
+ } else if (type === "NodeParagraph") {
turnsIntoOneTransaction({
protyle,
selectsElement,
@@ -1814,26 +1851,23 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
});
} else if (type === "NodeList") {
const id = selectsElement[0].dataset.nodeId;
- if (subType === "o" && (isMatchList || isMatchCheck)) {
- turnsOneInto({
- protyle,
- nodeElement: selectsElement[0],
- id,
- type: isMatchCheck ? "UL2TL" : "OL2UL",
- });
- } else if (subType === "t" && (isMatchList || isMatchOList)) {
+ const currentSubtype = ["u", "o", "t"].includes(subType) ?
+ subType as TListSubtype : undefined;
+ const conversionType = currentSubtype ?
+ getListConversionType(currentSubtype, targetSubtype) : undefined;
+ if (currentSubtype === targetSubtype) {
turnsOneInto({
protyle,
nodeElement: selectsElement[0],
id,
- type: isMatchList ? "TL2UL" : "TL2OL",
+ type: "CancelList",
});
- } else if (subType === "u" && (isMatchCheck || isMatchOList)) {
+ } else if (conversionType) {
turnsOneInto({
protyle,
nodeElement: selectsElement[0],
id,
- type: isMatchCheck ? "OL2TL" : "UL2OL",
+ type: conversionType,
});
}
} else {
diff --git a/app/src/protyle/wysiwyg/list.ts b/app/src/protyle/wysiwyg/list.ts
index e0d9c090a9..4fa1247617 100644
--- a/app/src/protyle/wysiwyg/list.ts
+++ b/app/src/protyle/wysiwyg/list.ts
@@ -1,4 +1,4 @@
-import {focusByWbr} from "../util/selection";
+import {focusByWbr, getUndoFocusContext} from "../util/selection";
import {transaction, turnsIntoOneTransaction, updateTransaction} from "./transaction";
import {genEmptyBlock} from "../../block/util";
import * as dayjs from "dayjs";
@@ -8,6 +8,8 @@ import {hasClosestByClassName, isBlockElement} from "../util/hasClosest";
import {getEmbedChildOperationContext, getParentBlock, getPreviousBlockSibling} from "./getBlock";
import {setFold} from "../util/blockFold";
import {scrollCenter} from "../../util/highlightById";
+import {getFollowingOrderedListMarkerUpdates, type TListSubtype} from "./listContext";
+import {fetchSyncPost} from "../../util/fetch";
const getLastChildBlock = (element: Element) => {
if (!element || !element.lastElementChild) {
@@ -90,6 +92,160 @@ export const genListItemElement = (listItemElement: Element, offset = 0, wbr = f
return element.content.firstElementChild as HTMLElement;
};
+const getFocusedOrderedListUpdates = async (protyle: IProtyle, listItemElement: HTMLElement) => {
+ const doOperations: IOperation[] = [];
+ const undoOperations: IOperation[] = [];
+ if (listItemElement.getAttribute("data-subtype") !== "o" || !protyle.block.parentID) {
+ return {doOperations, undoOperations};
+ }
+
+ try {
+ const response = await fetchSyncPost("/api/block/getBlockDOM", {
+ id: protyle.block.parentID,
+ notebook: protyle.notebookId,
+ });
+ const template = document.createElement("template");
+ template.innerHTML = response.data?.dom || "";
+ const listElement = template.content.firstElementChild as HTMLElement;
+ if (listElement?.getAttribute("data-type") !== "NodeList" ||
+ listElement.getAttribute("data-subtype") !== "o") {
+ return {doOperations, undoOperations};
+ }
+
+ const listItemElements = Array.from(listElement.children).filter((item) =>
+ item.getAttribute("data-type") === "NodeListItem") as HTMLElement[];
+ const currentIndex = listItemElements.findIndex((item) =>
+ item.getAttribute("data-node-id") === listItemElement.getAttribute("data-node-id"));
+ if (currentIndex < 0) {
+ return {doOperations, undoOperations};
+ }
+
+ const followingElements = listItemElements.slice(currentIndex + 1);
+ const markerUpdates = getFollowingOrderedListMarkerUpdates(
+ listItemElements[currentIndex].getAttribute("data-marker"),
+ followingElements.map((item) => item.getAttribute("data-marker")));
+ followingElements.forEach((item, index) => {
+ const marker = markerUpdates[index];
+ if (!marker) {
+ return;
+ }
+ const id = item.getAttribute("data-node-id");
+ undoOperations.push({
+ action: "update",
+ id,
+ data: item.outerHTML,
+ });
+ item.setAttribute("data-marker", marker);
+ const actionElement = item.querySelector(".protyle-action--order");
+ if (actionElement) {
+ actionElement.textContent = marker;
+ }
+ doOperations.push({
+ action: "update",
+ id,
+ data: item.outerHTML,
+ });
+ });
+ } catch (error) {
+ console.warn("get focused ordered list failed", error);
+ }
+ return {doOperations, undoOperations};
+};
+
+const insertingFocusedListItems = new WeakSet<IProtyle>();
+
+export const insertEmptyListItem = async (protyle: IProtyle, listItemElement: HTMLElement, range: Range) => {
+ const listElement = listItemElement.parentElement;
+ if (!listElement) {
+ return;
+ }
+
+ const newListItemElement = genListItemElement(listItemElement, 0, true);
+ const id = newListItemElement.getAttribute("data-node-id");
+ if (listElement.classList.contains("protyle-wysiwyg")) {
+ if (insertingFocusedListItems.has(protyle)) {
+ return;
+ }
+ insertingFocusedListItems.add(protyle);
+ try {
+ const undoFocusContext = getUndoFocusContext(protyle.wysiwyg.element, range, true);
+ const orderOperations = await getFocusedOrderedListUpdates(protyle, listItemElement);
+ if (!listItemElement.isConnected) {
+ return;
+ }
+ listItemElement.insertAdjacentElement("afterend", newListItemElement);
+ transaction(protyle, [{
+ action: "insert",
+ id,
+ data: newListItemElement.outerHTML,
+ previousID: listItemElement.getAttribute("data-node-id"),
+ }, ...orderOperations.doOperations], [{
+ action: "delete",
+ id,
+ context: undoFocusContext,
+ }, ...orderOperations.undoOperations]);
+ focusByWbr(newListItemElement, range);
+ scrollCenter(protyle, newListItemElement);
+ } finally {
+ insertingFocusedListItems.delete(protyle);
+ }
+ return;
+ }
+
+ const oldHTML = listElement.outerHTML;
+ listItemElement.insertAdjacentElement("afterend", newListItemElement);
+ updateListOrder(listElement);
+ updateTransaction(protyle, listElement, oldHTML);
+ focusByWbr(newListItemElement, range);
+ scrollCenter(protyle, newListItemElement);
+};
+
+export const insertEmptyChildList = (protyle: IProtyle, previousElement: HTMLElement,
+ subtype: TListSubtype, range: Range) => {
+ const parentElement = previousElement.parentElement;
+ if (!parentElement) {
+ return;
+ }
+ const marker = subtype === "t" ? "- [ ] " : (subtype === "u" ? "- " : "1. ");
+ const template = document.createElement("template");
+ template.innerHTML = protyle.lute.SpinBlockDOM(marker + Lute.Caret);
+ const listElement = template.content.firstElementChild as HTMLElement;
+ if (!listElement || listElement.getAttribute("data-type") !== "NodeList" ||
+ listElement.getAttribute("data-subtype") !== subtype) {
+ return;
+ }
+
+ const undoFocusContext = getUndoFocusContext(protyle.wysiwyg.element, range, true);
+ const id = listElement.getAttribute("data-node-id");
+ const doOperations: IOperation[] = [{
+ action: "insert",
+ id,
+ data: listElement.outerHTML,
+ previousID: previousElement.getAttribute("data-node-id"),
+ parentID: parentElement.getAttribute("data-node-id"),
+ }];
+ const undoOperations: IOperation[] = [{
+ action: "delete",
+ id,
+ context: undoFocusContext,
+ }];
+ [previousElement, parentElement].forEach((item) => {
+ if (item.getAttribute("fold") !== "1") {
+ return;
+ }
+ const foldData = setFold(protyle, item, true, false, false, true);
+ if (foldData?.doOperations?.length > 0) {
+ doOperations.push(...foldData.doOperations);
+ undoOperations.push(...foldData.undoOperations);
+ }
+ });
+
+ previousElement.insertAdjacentElement("afterend", listElement);
+ transaction(protyle, doOperations, undoOperations);
+ focusByWbr(listElement, range);
+ scrollCenter(protyle, listElement);
+};
+
export const addSubList = (protyle: IProtyle, nodeElement: Element, range: Range) => {
const parentItemElement = hasClosestByClassName(nodeElement, "li");
if (!parentItemElement) {
diff --git a/app/src/protyle/wysiwyg/listContext.test.ts b/app/src/protyle/wysiwyg/listContext.test.ts
new file mode 100644
index 0000000000..6fd42d6834
--- /dev/null
+++ b/app/src/protyle/wysiwyg/listContext.test.ts
@@ -0,0 +1,188 @@
+import {describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import {
+ getFollowingOrderedListMarkerUpdates,
+ getListContext,
+ getListConversionType,
+ getListShortcutAction,
+ type TListSubtype
+} from "./listContext";
+
+class TestElement {
+ parentElement: TestElement | null = null;
+ children: TestElement[] = [];
+ private attributes = new Map<string, string>();
+
+ constructor(type?: string, id?: string, subtype?: TListSubtype) {
+ if (type) {
+ this.attributes.set("data-type", type);
+ }
+ if (id) {
+ this.attributes.set("data-node-id", id);
+ }
+ if (subtype) {
+ this.attributes.set("data-subtype", subtype);
+ }
+ }
+
+ append(...elements: TestElement[]) {
+ elements.forEach((element) => {
+ element.parentElement = this;
+ this.children.push(element);
+ });
+ return this;
+ }
+
+ getAttribute(name: string) {
+ return this.attributes.get(name) || null;
+ }
+
+ hasAttribute(name: string) {
+ return this.attributes.has(name);
+ }
+
+ setAttribute(name: string, value: string) {
+ this.attributes.set(name, value);
+ }
+}
+
+const asHTMLElement = (element: TestElement) => element as unknown as HTMLElement;
+
+const createList = (subtype: TListSubtype, ...children: TestElement[]) => {
+ const paragraph = new TestElement("NodeParagraph", "paragraph");
+ const listItem = new TestElement("NodeListItem", "list-item", subtype).append(paragraph, ...children,
+ new TestElement());
+ const list = new TestElement("NodeList", "list", subtype).append(listItem, new TestElement());
+ const editor = new TestElement().append(list);
+ return {paragraph, listItem, list, editor};
+};
+
+describe("getListContext", () => {
+ it("returns the nearest list and its direct cursor child", () => {
+ const paragraph = new TestElement("NodeParagraph", "paragraph");
+ const blockquote = new TestElement("NodeBlockquote", "blockquote").append(paragraph, new TestElement());
+ const listItem = new TestElement("NodeListItem", "list-item", "u").append(new TestElement(), blockquote,
+ new TestElement());
+ const list = new TestElement("NodeList", "list", "u").append(listItem, new TestElement());
+ const editor = new TestElement().append(list);
+
+ const context = getListContext(asHTMLElement(paragraph), asHTMLElement(editor));
+
+ assert.equal(context?.listElement, asHTMLElement(list));
+ assert.equal(context?.listItemElement, asHTMLElement(listItem));
+ assert.equal(context?.childElement, asHTMLElement(blockquote));
+ assert.deepEqual(context?.childElements, [asHTMLElement(blockquote)]);
+ assert.equal(context?.subtype, "u");
+ });
+
+ it("uses the nearest list in a nested list", () => {
+ const paragraph = new TestElement("NodeParagraph", "paragraph");
+ const innerListItem = new TestElement("NodeListItem", "inner-item", "t").append(new TestElement(), paragraph,
+ new TestElement());
+ const innerList = new TestElement("NodeList", "inner-list", "t").append(innerListItem, new TestElement());
+ const outerListItem = new TestElement("NodeListItem", "outer-item", "u").append(new TestElement(), innerList,
+ new TestElement());
+ const outerList = new TestElement("NodeList", "outer-list", "u").append(outerListItem, new TestElement());
+ const editor = new TestElement().append(outerList);
+
+ const context = getListContext(asHTMLElement(paragraph), asHTMLElement(editor));
+
+ assert.equal(context?.listElement, asHTMLElement(innerList));
+ assert.equal(context?.listItemElement, asHTMLElement(innerListItem));
+ assert.equal(context?.childElement, asHTMLElement(paragraph));
+ assert.equal(context?.subtype, "t");
+ });
+
+ it("supports a focused list item without its list wrapper", () => {
+ const paragraph = new TestElement("NodeParagraph", "paragraph");
+ const listItem = new TestElement("NodeListItem", "list-item", "o").append(new TestElement(), paragraph,
+ new TestElement());
+ const editor = new TestElement().append(listItem);
+
+ const context = getListContext(asHTMLElement(paragraph), asHTMLElement(editor));
+
+ assert.equal(context?.listElement, undefined);
+ assert.equal(context?.listItemElement, asHTMLElement(listItem));
+ assert.deepEqual(context?.listItemElements, [asHTMLElement(listItem)]);
+ assert.equal(context?.subtype, "o");
+ });
+
+ it("does not cross the current editor boundary", () => {
+ const paragraph = new TestElement("NodeParagraph", "paragraph");
+ const editor = new TestElement().append(paragraph);
+ new TestElement("NodeListItem", "list-item", "t").append(editor, new TestElement());
+
+ assert.equal(getListContext(asHTMLElement(paragraph), asHTMLElement(editor)), undefined);
+ });
+});
+
+describe("getListShortcutAction", () => {
+ it("cancels or converts a single empty list", () => {
+ const {paragraph, editor} = createList("u");
+ const context = getListContext(asHTMLElement(paragraph), asHTMLElement(editor))!;
+
+ assert.equal(getListShortcutAction(context, "u", true, false), "cancelList");
+ assert.equal(getListShortcutAction(context, "o", true, false), "convertList");
+ });
+
+ it("does not cancel a focused single empty list item", () => {
+ const {paragraph, editor} = createList("u");
+ const context = getListContext(asHTMLElement(paragraph), asHTMLElement(editor))!;
+
+ assert.equal(getListShortcutAction(context, "u", true, true), "insertListItem");
+ assert.equal(getListShortcutAction(context, "o", true, true), "insertChildList");
+ });
+
+ it("inserts a list item only for a matching single-child list item", () => {
+ const sibling = new TestElement("NodeListItem", "sibling", "t");
+ const {paragraph, list, editor} = createList("t");
+ sibling.parentElement = list;
+ list.children.splice(1, 0, sibling);
+ const context = getListContext(asHTMLElement(paragraph), asHTMLElement(editor))!;
+
+ assert.equal(getListShortcutAction(context, "t", false, false), "insertListItem");
+ assert.equal(getListShortcutAction(context, "u", false, false), "insertChildList");
+ });
+
+ it("inserts a child list when the list item has multiple children", () => {
+ const secondChild = new TestElement("NodeParagraph", "second");
+ const {paragraph, editor} = createList("o", secondChild);
+ const context = getListContext(asHTMLElement(paragraph), asHTMLElement(editor))!;
+
+ assert.equal(getListShortcutAction(context, "o", false, false), "insertChildList");
+ });
+
+ it("treats a folded heading as having hidden children", () => {
+ const heading = new TestElement("NodeHeading", "heading");
+ heading.setAttribute("fold", "1");
+ const listItem = new TestElement("NodeListItem", "list-item", "u").append(heading, new TestElement());
+ const list = new TestElement("NodeList", "list", "u").append(listItem, new TestElement());
+ const editor = new TestElement().append(list);
+ const context = getListContext(asHTMLElement(heading), asHTMLElement(editor))!;
+
+ assert.equal(getListShortcutAction(context, "u", false, false), "insertChildList");
+ });
+});
+
+describe("getFollowingOrderedListMarkerUpdates", () => {
+ it("increments following markers after inserting a list item", () => {
+ assert.deepEqual(getFollowingOrderedListMarkerUpdates("1.", ["2.", "3."]), ["3.", "4."]);
+ assert.deepEqual(getFollowingOrderedListMarkerUpdates("2.", ["4.", "5."]), [undefined, undefined]);
+ });
+
+ it("ignores an invalid current marker", () => {
+ assert.deepEqual(getFollowingOrderedListMarkerUpdates("*", ["2."]), [undefined]);
+ });
+});
+
+describe("getListConversionType", () => {
+ it("maps every list subtype conversion", () => {
+ assert.equal(getListConversionType("u", "o"), "UL2OL");
+ assert.equal(getListConversionType("u", "t"), "UL2TL");
+ assert.equal(getListConversionType("o", "u"), "OL2UL");
+ assert.equal(getListConversionType("o", "t"), "OL2TL");
+ assert.equal(getListConversionType("t", "u"), "TL2UL");
+ assert.equal(getListConversionType("t", "o"), "TL2OL");
+ assert.equal(getListConversionType("t", "t"), undefined);
+ });
+});
diff --git a/app/src/protyle/wysiwyg/listContext.ts b/app/src/protyle/wysiwyg/listContext.ts
new file mode 100644
index 0000000000..5050c685c4
--- /dev/null
+++ b/app/src/protyle/wysiwyg/listContext.ts
@@ -0,0 +1,89 @@
+export type TListSubtype = "u" | "o" | "t";
+
+export type TListShortcutAction = "cancelList" | "convertList" | "insertListItem" | "insertChildList";
+
+export type TListContext = {
+ listElement?: HTMLElement,
+ listItemElement: HTMLElement,
+ childElement: HTMLElement,
+ childElements: HTMLElement[],
+ listItemElements: HTMLElement[],
+ subtype: TListSubtype,
+};
+
+const LIST_CONVERSION_TYPES: Record<TListSubtype, Partial<Record<TListSubtype, string>>> = {
+ u: {o: "UL2OL", t: "UL2TL"},
+ o: {u: "OL2UL", t: "OL2TL"},
+ t: {u: "TL2UL", o: "TL2OL"},
+};
+
+export const getListContext = (nodeElement: HTMLElement, editorElement: HTMLElement): TListContext | undefined => {
+ let listItemElement: HTMLElement | null = nodeElement;
+ while (listItemElement && listItemElement !== editorElement &&
+ listItemElement.getAttribute("data-type") !== "NodeListItem") {
+ listItemElement = listItemElement.parentElement;
+ }
+ if (!listItemElement || listItemElement === editorElement) {
+ return;
+ }
+
+ let childElement = nodeElement;
+ while (childElement.parentElement && childElement.parentElement !== listItemElement) {
+ childElement = childElement.parentElement;
+ }
+ if (childElement.parentElement !== listItemElement) {
+ return;
+ }
+
+ const parentElement = listItemElement.parentElement;
+ const listElement = parentElement?.getAttribute("data-type") === "NodeList" ? parentElement : undefined;
+ const subtype = (listElement?.getAttribute("data-subtype") ||
+ listItemElement.getAttribute("data-subtype")) as TListSubtype;
+ if (!["u", "o", "t"].includes(subtype)) {
+ return;
+ }
+
+ return {
+ listElement,
+ listItemElement,
+ childElement,
+ childElements: Array.from(listItemElement.children).filter((item) =>
+ item.hasAttribute("data-node-id")) as HTMLElement[],
+ listItemElements: listElement ? Array.from(listElement.children).filter((item) =>
+ item.getAttribute("data-type") === "NodeListItem") as HTMLElement[] : [listItemElement],
+ subtype,
+ };
+};
+
+export const getListShortcutAction = (context: TListContext, targetSubtype: TListSubtype,
+ isEmptyChild: boolean, isListItemFocused: boolean): TListShortcutAction => {
+ const isSameSubtype = context.subtype === targetSubtype;
+ const hasFoldedHeading = context.childElements.some((item) =>
+ item.getAttribute("data-type") === "NodeHeading" && item.getAttribute("fold") === "1");
+ if (context.listElement && context.listItemElements.length === 1 && context.childElements.length === 1 &&
+ isEmptyChild && !isListItemFocused) {
+ return isSameSubtype ? "cancelList" : "convertList";
+ }
+ if (context.childElements.length === 1 && isSameSubtype && !hasFoldedHeading) {
+ return "insertListItem";
+ }
+ return "insertChildList";
+};
+
+export const getFollowingOrderedListMarkerUpdates = (currentMarker: string, followingMarkers: string[]) => {
+ const currentIndex = Number.parseInt(currentMarker, 10);
+ if (Number.isNaN(currentIndex)) {
+ return followingMarkers.map(() => undefined);
+ }
+ return followingMarkers.map((marker, index) => {
+ const expectedMarker = `${currentIndex + index + 2}.`;
+ return marker === expectedMarker ? undefined : expectedMarker;
+ });
+};
+
+export const getListConversionType = (sourceSubtype: TListSubtype, targetSubtype: TListSubtype) => {
+ if (sourceSubtype === targetSubtype) {
+ return;
+ }
+ return LIST_CONVERSION_TYPES[sourceSubtype][targetSubtype];
+};