Skip to content

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

:art: Improve blockquote shortcut behavior https://github.com/siyuan-note/siyuan/issues/14124

Daniel87a8d1a7edad
diff --git a/app/src/protyle/wysiwyg/blockquote.test.ts b/app/src/protyle/wysiwyg/blockquote.test.ts
new file mode 100644
index 0000000000..dcf7a86fd7
--- /dev/null
+++ b/app/src/protyle/wysiwyg/blockquote.test.ts
@@ -0,0 +1,122 @@
+import {describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import {getBlockquoteContext, isBlockquoteMarker, shouldCancelBlockquote} from "./blockquote";
+
+class TestElement {
+ parentElement: TestElement | null = null;
+ children: TestElement[] = [];
+ private attributes = new Map<string, string>();
+
+ constructor(type?: string, id?: string) {
+ if (type) {
+ this.attributes.set("data-type", type);
+ }
+ if (id) {
+ this.attributes.set("data-node-id", id);
+ }
+ }
+
+ 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;
+
+describe("getBlockquoteContext", () => {
+ it("returns the direct blockquote child containing a nested cursor block", () => {
+ const paragraph = new TestElement("NodeParagraph", "paragraph");
+ const listItem = new TestElement("NodeListItem", "list-item").append(paragraph);
+ const list = new TestElement("NodeList", "list").append(listItem);
+ const sibling = new TestElement("NodeParagraph", "sibling");
+ const attr = new TestElement();
+ const blockquote = new TestElement("NodeBlockquote", "blockquote").append(list, sibling, attr);
+ const editor = new TestElement().append(blockquote);
+
+ const context = getBlockquoteContext(asHTMLElement(paragraph), asHTMLElement(editor));
+
+ assert.equal(context?.blockquoteElement, asHTMLElement(blockquote));
+ assert.equal(context?.childElement, asHTMLElement(list));
+ assert.deepEqual(context?.childElements, [asHTMLElement(list), asHTMLElement(sibling)]);
+ });
+
+ it("uses the nearest blockquote", () => {
+ const paragraph = new TestElement("NodeParagraph", "paragraph");
+ const inner = new TestElement("NodeBlockquote", "inner").append(paragraph, new TestElement());
+ const outer = new TestElement("NodeBlockquote", "outer").append(inner, new TestElement());
+ const editor = new TestElement().append(outer);
+
+ const context = getBlockquoteContext(asHTMLElement(paragraph), asHTMLElement(editor));
+
+ assert.equal(context?.blockquoteElement, asHTMLElement(inner));
+ assert.equal(context?.childElement, asHTMLElement(paragraph));
+ assert.deepEqual(context?.childElements, [asHTMLElement(paragraph)]);
+ assert.notEqual(context?.blockquoteElement, asHTMLElement(outer));
+ });
+
+ it("returns undefined outside a blockquote", () => {
+ const paragraph = new TestElement("NodeParagraph", "paragraph");
+ const editor = new TestElement().append(paragraph);
+
+ assert.equal(getBlockquoteContext(asHTMLElement(paragraph), asHTMLElement(editor)), undefined);
+ });
+
+ it("does not cross the current editor boundary", () => {
+ const paragraph = new TestElement("NodeParagraph", "paragraph");
+ const editor = new TestElement().append(paragraph);
+ new TestElement("NodeBlockquote", "outer").append(editor, new TestElement());
+
+ assert.equal(getBlockquoteContext(asHTMLElement(paragraph), asHTMLElement(editor)), undefined);
+ });
+
+ it("does not cancel a blockquote whose only visible child is a folded heading", () => {
+ const heading = new TestElement("NodeHeading", "heading");
+ heading.setAttribute("fold", "1");
+ const blockquote = new TestElement("NodeBlockquote", "blockquote").append(heading, new TestElement());
+ const editor = new TestElement().append(blockquote);
+ const context = getBlockquoteContext(asHTMLElement(heading), asHTMLElement(editor));
+
+ assert.equal(shouldCancelBlockquote(context!), false);
+ });
+
+ it("cancels a blockquote with one unfolded child", () => {
+ const paragraph = new TestElement("NodeParagraph", "paragraph");
+ const blockquote = new TestElement("NodeBlockquote", "blockquote").append(paragraph, new TestElement());
+ const editor = new TestElement().append(blockquote);
+ const context = getBlockquoteContext(asHTMLElement(paragraph), asHTMLElement(editor));
+
+ assert.equal(shouldCancelBlockquote(context!), true);
+ });
+});
+
+describe("isBlockquoteMarker", () => {
+ it("accepts ASCII and Chinese blockquote markers", () => {
+ assert.equal(isBlockquoteMarker(">"), true);
+ assert.equal(isBlockquoteMarker("》"), true);
+ assert.equal(isBlockquoteMarker("> "), true);
+ assert.equal(isBlockquoteMarker("》 "), true);
+ assert.equal(isBlockquoteMarker(" >"), true);
+ });
+
+ it("rejects over-indented markers and ordinary text", () => {
+ assert.equal(isBlockquoteMarker(" > "), false);
+ assert.equal(isBlockquoteMarker("text > "), false);
+ assert.equal(isBlockquoteMarker("> "), false);
+ });
+});
diff --git a/app/src/protyle/wysiwyg/blockquote.ts b/app/src/protyle/wysiwyg/blockquote.ts
new file mode 100644
index 0000000000..adf38c52b8
--- /dev/null
+++ b/app/src/protyle/wysiwyg/blockquote.ts
@@ -0,0 +1,39 @@
+type TBlockquoteContext = {
+ blockquoteElement: HTMLElement,
+ childElement: HTMLElement,
+ childElements: HTMLElement[],
+};
+
+export const getBlockquoteContext = (nodeElement: HTMLElement, editorElement: HTMLElement): TBlockquoteContext | undefined => {
+ let blockquoteElement = nodeElement.parentElement;
+ while (blockquoteElement && blockquoteElement !== editorElement &&
+ blockquoteElement.getAttribute("data-type") !== "NodeBlockquote") {
+ blockquoteElement = blockquoteElement.parentElement;
+ }
+ if (!blockquoteElement || blockquoteElement === editorElement) {
+ return;
+ }
+
+ let childElement = nodeElement;
+ while (childElement.parentElement && childElement.parentElement !== blockquoteElement) {
+ childElement = childElement.parentElement;
+ }
+ if (childElement.parentElement !== blockquoteElement) {
+ return;
+ }
+
+ return {
+ blockquoteElement,
+ childElement,
+ childElements: Array.from(blockquoteElement.children).filter((item) =>
+ item.hasAttribute("data-node-id")) as HTMLElement[],
+ };
+};
+
+export const shouldCancelBlockquote = (context: TBlockquoteContext) => {
+ return context.childElements.length === 1 && context.childElement.getAttribute("fold") !== "1";
+};
+
+export const isBlockquoteMarker = (marker: string) => {
+ return /^ {0,3}[>》] ?$/.test(marker);
+};
diff --git a/app/src/protyle/wysiwyg/input.ts b/app/src/protyle/wysiwyg/input.ts
index 93c2358bfc..61de99e451 100644
--- a/app/src/protyle/wysiwyg/input.ts
+++ b/app/src/protyle/wysiwyg/input.ts
@@ -1,7 +1,7 @@
-import {focusBlock, focusByWbr} from "../util/selection";
+import {focusBlock, focusByOffset, focusByWbr, getSelectionOffset} from "../util/selection";
import {Constants} from "../../constants";
import * as dayjs from "dayjs";
-import {transaction, updateTransaction} from "./transaction";
+import {insertEmptyBlockquote, transaction, turnsOneInto, updateTransaction} from "./transaction";
import {mathRender} from "../render/mathRender";
import {highlightRender} from "../render/highlightRender";
import {
@@ -23,6 +23,7 @@ import {headingTurnIntoList, turnIntoTaskList} from "./turnIntoList";
import {updateAVName} from "../render/av/action";
import {setFold} from "../util/blockFold";
import {nbsp2space} from "../util/normalizeText";
+import {getBlockquoteContext, isBlockquoteMarker, shouldCancelBlockquote} from "./blockquote";
interface IInputOperations {
doOperations: IOperation[];
@@ -146,6 +147,47 @@ export const input = async (protyle: IProtyle, blockElement: HTMLElement, range:
)) {
editElement.innerHTML = editElement.innerHTML.replace("》<wbr>", "><wbr>");
}
+ const blockquoteContext = type === "NodeParagraph" ?
+ getBlockquoteContext(blockElement, protyle.wysiwyg.element) : undefined;
+ const currentWbrElement = editElement.querySelector("wbr") as HTMLElement;
+ if (blockquoteContext && currentWbrElement) {
+ const markerPrefixRange = document.createRange();
+ markerPrefixRange.setStart(editElement, 0);
+ markerPrefixRange.setEndBefore(currentWbrElement);
+ const markerPrefix = nbsp2space(markerPrefixRange.toString()).split(Constants.ZWSP).join("");
+ const marker = markerPrefix.substring(markerPrefix.lastIndexOf("\n") + 1);
+ if (isBlockquoteMarker(marker)) {
+ const markerEnd = getSelectionOffset(editElement, undefined, markerPrefixRange, true).end;
+ const markerRange = focusByOffset(editElement, markerEnd - marker.length, markerEnd, false, true);
+ if (!markerRange) {
+ return;
+ }
+ const oldChildHTML = protyle.wysiwyg.lastHTMLs[id] || blockElement.outerHTML;
+ markerRange.deleteContents();
+ if (shouldCancelBlockquote(blockquoteContext)) {
+ await turnsOneInto({
+ protyle,
+ nodeElement: blockquoteContext.blockquoteElement,
+ id: blockquoteContext.blockquoteElement.dataset.nodeId,
+ type: "CancelBlockquote",
+ undoElement: {
+ id,
+ html: oldChildHTML,
+ },
+ additionalOperations: inputOperations,
+ });
+ } else {
+ currentWbrElement.remove();
+ insertEmptyBlockquote(protyle, blockquoteContext.childElement, {
+ updateElement: blockElement,
+ oldHTML: oldChildHTML,
+ undoContext: inputOperations?.undoContext,
+ additionalOperations: inputOperations,
+ });
+ }
+ return;
+ }
+ }
const trimStartHTML = editElement.innerHTML.trimStart();
const trimStartText = editElement.textContent.trimStart();
const enableCodeBlockMiddleDot = window.siyuan.config.editor.markdown.codeBlockMiddleDot !== false;
diff --git a/app/src/protyle/wysiwyg/keydown.ts b/app/src/protyle/wysiwyg/keydown.ts
index 4917b2bb60..b7397d2555 100644
--- a/app/src/protyle/wysiwyg/keydown.ts
+++ b/app/src/protyle/wysiwyg/keydown.ts
@@ -46,12 +46,14 @@ import {enter, softEnter} from "./enter";
import {clearTableCell, fixTable} from "../util/table";
import {
transaction,
+ insertEmptyBlockquote,
turnsIntoOneTransaction,
turnsIntoTransaction,
turnsOneInto,
updateBatchTransaction,
updateTransaction
} from "./transaction";
+import {getBlockquoteContext, shouldCancelBlockquote} from "./blockquote";
import {fontEvent} from "../toolbar/Font";
import {addSubList, listIndent, listOutdent, toggleTaskListItem} from "./list";
import {newFileContentBySelect, rename, replaceFileName} from "../../editor/rename";
@@ -1763,14 +1765,36 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
const isMatchQuote = matchHotKey(window.siyuan.config.keymap.editor.insert.quote.custom, event);
if ((isMatchList || isMatchOList || isMatchCheck || isMatchQuote) && !isInEmbedBlock(nodeElement)) {
const selectsElement: HTMLElement[] = Array.from(protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select"));
- if (selectsElement.length === 0) {
+ const hasBlockSelection = selectsElement.length > 0;
+ if (!hasBlockSelection) {
selectsElement.push(nodeElement);
}
if (selectsElement.length === 1) {
const subType = selectsElement[0].dataset.subtype;
const type = selectsElement[0].dataset.type;
if (isMatchQuote) {
- if (["NodeHeading", "NodeParagraph", "NodeList"].includes(type)) {
+ const blockquoteContext = hasBlockSelection ? undefined :
+ getBlockquoteContext(selectsElement[0], protyle.wysiwyg.element);
+ if (hasBlockSelection && type === "NodeBlockquote") {
+ turnsOneInto({
+ protyle,
+ nodeElement: selectsElement[0],
+ id: selectsElement[0].dataset.nodeId,
+ type: "CancelBlockquote",
+ });
+ } else if (blockquoteContext && shouldCancelBlockquote(blockquoteContext)) {
+ const focusRange = range.cloneRange();
+ focusRange.collapse(true);
+ focusRange.insertNode(document.createElement("wbr"));
+ turnsOneInto({
+ protyle,
+ nodeElement: blockquoteContext.blockquoteElement,
+ id: blockquoteContext.blockquoteElement.dataset.nodeId,
+ type: "CancelBlockquote",
+ });
+ } else if (blockquoteContext) {
+ insertEmptyBlockquote(protyle, blockquoteContext.childElement);
+ } else if (["NodeHeading", "NodeParagraph", "NodeList"].includes(type)) {
turnsIntoOneTransaction({
protyle,
selectsElement,
diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.ts
index a075239635..89240f7727 100644
--- a/app/src/protyle/wysiwyg/transaction.ts
+++ b/app/src/protyle/wysiwyg/transaction.ts
@@ -1,5 +1,5 @@
import {fetchPost, fetchSyncPost} from "../../util/fetch";
-import {focusBlock, focusByWbr, focusSideBlock, getEditorRange} from "../util/selection";
+import {focusBlock, focusByWbr, focusSideBlock, getEditorRange, getUndoFocusContext} from "../util/selection";
import {
getContenteditableElement,
getEmbedChildOperationContext,
@@ -1389,6 +1389,70 @@ export const turnsIntoOneTransaction = async (options: {
hideElements(["gutter"], options.protyle);
};
+export const insertEmptyBlockquote = (protyle: IProtyle, previousElement: HTMLElement, options?: {
+ updateElement: HTMLElement,
+ oldHTML: string,
+ undoContext?: Record<string, string>,
+ additionalOperations?: {
+ doOperations: IOperation[],
+ undoOperations: IOperation[],
+ },
+}) => {
+ const range = getEditorRange(protyle.wysiwyg.element);
+ const undoFocusContext = getUndoFocusContext(protyle.wysiwyg.element, range, true);
+ const template = document.createElement("template");
+ template.innerHTML = protyle.lute.SpinBlockDOM(">" + Lute.Caret);
+ const blockquoteElement = template.content.firstElementChild as HTMLElement;
+ if (!blockquoteElement || blockquoteElement.getAttribute("data-type") !== "NodeBlockquote") {
+ return;
+ }
+
+ let foldData;
+ if (previousElement.getAttribute("data-type") === "NodeHeading" && previousElement.getAttribute("fold") === "1") {
+ foldData = setFold(protyle, previousElement, true, false, false, true);
+ }
+
+ const id = blockquoteElement.getAttribute("data-node-id");
+ const doOperations: IOperation[] = [{
+ action: "insert",
+ id,
+ data: blockquoteElement.outerHTML,
+ previousID: previousElement.getAttribute("data-node-id"),
+ parentID: previousElement.parentElement.getAttribute("data-node-id"),
+ }];
+ const undoOperations: IOperation[] = [{
+ action: "delete",
+ id,
+ context: options ? options.undoContext : undoFocusContext,
+ }];
+ if (options) {
+ doOperations.unshift({
+ action: "update",
+ id: options.updateElement.getAttribute("data-node-id"),
+ data: options.updateElement.outerHTML,
+ });
+ undoOperations.push({
+ action: "update",
+ id: options.updateElement.getAttribute("data-node-id"),
+ data: options.oldHTML,
+ context: options.undoContext,
+ });
+ if (options.additionalOperations) {
+ doOperations.unshift(...options.additionalOperations.doOperations);
+ undoOperations.push(...options.additionalOperations.undoOperations);
+ }
+ }
+ if (foldData?.doOperations?.length > 0) {
+ doOperations.push(...foldData.doOperations);
+ undoOperations.push(...foldData.undoOperations);
+ }
+
+ previousElement.insertAdjacentElement("afterend", blockquoteElement);
+ transaction(protyle, doOperations, undoOperations);
+ focusByWbr(blockquoteElement, range);
+ hideElements(["gutter"], protyle);
+};
+
export const turnsIntoGroupsTransaction = async (options: {
protyle: IProtyle,
selectsElementGroups: Element[][],
@@ -1792,7 +1856,15 @@ export const turnsOneInto = async (options: {
nodeElement: Element,
id: string,
type: string,
- level?: number
+ level?: number,
+ undoElement?: {
+ id: string,
+ html: string,
+ },
+ additionalOperations?: {
+ doOperations: IOperation[],
+ undoOperations: IOperation[],
+ },
}) => {
if (!options.nodeElement.querySelector("wbr")) {
getContenteditableElement(options.nodeElement)?.insertAdjacentHTML("afterbegin", "<wbr>");
@@ -1801,7 +1873,15 @@ export const turnsOneInto = async (options: {
if (["CancelBlockquote", "CancelList", "CancelCallout"].includes(options.type)) {
foldOperations = await unfoldListHeadings(options.protyle, [options.nodeElement]);
}
- const oldHTML = options.nodeElement.outerHTML;
+ let oldHTML = options.nodeElement.outerHTML;
+ if (options.undoElement) {
+ const oldElement = options.nodeElement.cloneNode(true) as HTMLElement;
+ const undoElement = oldElement.querySelector(`[data-node-id="${options.undoElement.id}"]`);
+ if (undoElement) {
+ undoElement.outerHTML = options.undoElement.html;
+ oldHTML = oldElement.outerHTML;
+ }
+ }
const previousBlockElement = getPreviousBlockSibling(options.nodeElement);
let previousId = previousBlockElement?.getAttribute("data-node-id");
if (!previousBlockElement && options.protyle.block.showAll) {
@@ -1849,6 +1929,10 @@ export const turnsOneInto = async (options: {
previousID: previousId,
parentID: parentId
});
+ if (options.additionalOperations) {
+ doOperations.unshift(...options.additionalOperations.doOperations);
+ undoOperations.push(...options.additionalOperations.undoOperations);
+ }
const doFoldOperations = foldOperations.map((operation) => ({...operation}));
const undoFoldOperations = foldOperations.map((operation) => ({...operation}));
transaction(options.protyle, doOperations.concat(doFoldOperations), undoOperations.concat(undoFoldOperations));