An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: Improve block reference insertion after cursor movement https://github.com/siyuan-note/siyuan/issues/16972
Danielb8ab0bcebc72
diff --git a/app/src/protyle/wysiwyg/keydown.ts b/app/src/protyle/wysiwyg/keydown.tsindex f1c09559ee..4917b2bb60 100644--- a/app/src/protyle/wysiwyg/keydown.ts+++ b/app/src/protyle/wysiwyg/keydown.ts@@ -1367,21 +1367,39 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {) {selectAll(protyle, nodeElement, range);}- // 同步 toolbar.range,避免 DOM 已被其他操作(undo/enter 等)替换后变为 detached,- // 导致后续异步回调中 setInlineMark 读到无效 range https://github.com/siyuan-note/siyuan/issues/17896- protyle.toolbar.range = range;- if (isNewNameFile) {- fetchPost("/api/filetree/getHPathByPath", {- notebook: protyle.notebookId,- path: protyle.path,- }, (response) => {- newFileBySelect(protyle, selectText, nodeElement, response.data, protyle.notebookId);- });- } else {- getRefCreateSavePath(protyle.notebookId, protyle.path, (targetNotebookId, hPath) => {- newFileBySelect(protyle, selectText, nodeElement, hPath, targetNotebookId);- });+ // 固定触发时的文档和选区,异步创建完成后仅修改原位置 https://github.com/siyuan-note/siyuan/issues/16972+ const selectionRange = range.cloneRange();+ const startBlockElement = hasClosestBlock(selectionRange.startContainer);+ const endBlockElement = hasClosestBlock(selectionRange.endContainer);+ if (startBlockElement && endBlockElement) {+ const sourceNotebookId = protyle.notebookId;+ const sourceRootID = protyle.block.rootID;+ const sourcePath = protyle.path;+ const newFileName = replaceFileName(selectText.trim() ? selectText.trim() :+ protyle.lute.BlockDOM2Content(nodeElement.outerHTML).replace(/\n/g, "").trim());+ const selectionContext = {+ range: selectionRange,+ notebookId: sourceNotebookId,+ rootID: sourceRootID,+ path: sourcePath,+ startBlockID: startBlockElement.getAttribute("data-node-id"),+ endBlockID: endBlockElement.getAttribute("data-node-id"),+ text: selectionRange.toString(),+ };+ if (isNewNameFile) {+ fetchPost("/api/filetree/getHPathByPath", {+ notebook: sourceNotebookId,+ path: sourcePath,+ }, (response) => {+ newFileBySelect(protyle, newFileName, selectionContext, response.data, sourceNotebookId);+ });+ } else {+ getRefCreateSavePath(sourceNotebookId, sourcePath, (targetNotebookId, hPath) => {+ newFileBySelect(protyle, newFileName, selectionContext, hPath, targetNotebookId);+ });+ }}+ hideElements(["toolbar"], protyle);}event.preventDefault();event.stopPropagation();diff --git a/app/src/util/newFile.ts b/app/src/util/newFile.tsindex c8fc5f5056..38e67816d3 100644--- a/app/src/util/newFile.ts+++ b/app/src/util/newFile.ts@@ -14,6 +14,13 @@ import {hideElements} from "../protyle/ui/hideElements";import {openMobileFileById} from "../mobile/editor";import type {App} from "../index";import {NewDocTargetByHPath, NewDocTargetSubDoc, getNewDocTargetFromSavePath, getNewDocTargetFromTree} from "./parseNewDocTarget";+import {focusByRange} from "../protyle/util/selection";+import {+ isNewFileSelectionValid,+ isRangeInEditor,+ isSameRange,+ NewFileSelectionContext+} from "./newFileSelection";export const getBlockRefAnchorText = (title: string) => {const trimmed = (title || "").trim();@@ -82,8 +89,38 @@ export const newFileInTree = (app: App, notebookId: string, currentPath: string,});};-export const newFileBySelect = (protyle: IProtyle, selectText: string, nodeElement: HTMLElement, pathDir: string, targetNotebookId: string) => {- const newFileName = replaceFileName(selectText.trim() ? selectText.trim() : protyle.lute.BlockDOM2Content(nodeElement.outerHTML).replace(/\n/g, "").trim());+const insertNewFileRef = (protyle: IProtyle, context: NewFileSelectionContext, id: string, refText: string) => {+ if (!isNewFileSelectionValid(protyle, context)) {+ return;+ }+ const selection = document.getSelection();+ const currentRange = selection?.rangeCount ? selection.getRangeAt(0).cloneRange() : undefined;+ const selectionMoved = currentRange && !isSameRange(currentRange, context.range);+ protyle.toolbar.range = context.range;+ const refElements = protyle.toolbar.setInlineMark(protyle, "block-ref", "range", {+ type: "id",+ color: `${id}${Constants.ZWSP}d${Constants.ZWSP}${refText}`+ }, false);+ if (!refElements?.[0]) {+ return;+ }+ const refRange = protyle.toolbar.range;+ refRange.selectNodeContents(refElements[0]);+ if (selectionMoved) {+ if (isRangeInEditor(protyle.wysiwyg.element, currentRange)) {+ protyle.toolbar.range = currentRange;+ focusByRange(currentRange);+ }+ } else {+ focusByRange(refRange);+ }+};++export const newFileBySelect = (protyle: IProtyle, newFileName: string, context: NewFileSelectionContext,+ pathDir: string, targetNotebookId: string) => {+ if (!isNewFileSelectionValid(protyle, context)) {+ return;+ }const hPath = pathPosix().join(pathDir, newFileName || window.siyuan.languages._kernel[16]);fetchPost("/api/filetree/getIDsByHPath", {path: hPath,@@ -91,31 +128,21 @@ export const newFileBySelect = (protyle: IProtyle, selectText: string, nodeEleme}, (idResponse) => {const refText = getBlockRefAnchorText(newFileName);if (idResponse.data && idResponse.data.length > 0) {- const refElement = protyle.toolbar.setInlineMark(protyle, "block-ref", "range", {- type: "id",- color: `${idResponse.data[0]}${Constants.ZWSP}d${Constants.ZWSP}${refText}`- });- if (refElement[0]) {- protyle.toolbar.range.selectNodeContents(refElement[0]);- }+ insertNewFileRef(protyle, context, idResponse.data[0], refText);} else {+ if (!isNewFileSelectionValid(protyle, context)) {+ return;+ }fetchPost("/api/filetree/createDocWithMd", {notebook: targetNotebookId,path: hPath,- parentID: protyle.notebookId === targetNotebookId ? protyle.block.rootID : "",+ parentID: context.notebookId === targetNotebookId ? context.rootID : "",markdown: "",titleEmpty: newFileName === "",}, response => {- const refElement = protyle.toolbar.setInlineMark(protyle, "block-ref", "range", {- type: "id",- color: `${response.data}${Constants.ZWSP}d${Constants.ZWSP}${refText}`- });- if (refElement[0]) {- protyle.toolbar.range.selectNodeContents(refElement[0]);- }+ insertNewFileRef(protyle, context, response.data, refText);});}- hideElements(["toolbar"], protyle);});};diff --git a/app/src/util/newFileSelection.test.ts b/app/src/util/newFileSelection.test.tsnew file mode 100644index 0000000000..7816615df3--- /dev/null+++ b/app/src/util/newFileSelection.test.ts@@ -0,0 +1,137 @@+import {describe, it} from "node:test";+import * as assert from "node:assert/strict";+import {+ isNewFileSelectionValid,+ isRangeInEditor,+ isSameRange,+ NewFileSelectionContext+} from "./newFileSelection";++class TestElement {+ nodeType = 1;+ tagName = "DIV";+ parentElement: TestElement | null = null;+ isConnected = true;+ private attributes = new Map<string, string>();+ private children: Array<TestElement | TestText> = [];+ classList = {+ contains: (name: string) => name === "protyle-wysiwyg" && this.attributes.get("class") === name,+ };++ constructor(id?: string, type?: string) {+ if (id) {+ this.attributes.set("data-node-id", id);+ }+ if (type) {+ this.attributes.set("data-type", type);+ }+ }++ append(...children: Array<TestElement | TestText>) {+ children.forEach(child => {+ child.parentElement = this;+ this.children.push(child);+ });+ return this;+ }++ setEditor() {+ this.attributes.set("class", "protyle-wysiwyg");+ return this;+ }++ getAttribute(name: string) {+ return this.attributes.get(name) || null;+ }++ hasAttribute(name: string) {+ return this.attributes.has(name);+ }++ contains(node: TestElement | TestText) {+ let current: TestElement | TestText | null = node;+ while (current) {+ if (current === this) {+ return true;+ }+ current = current.parentElement;+ }+ return false;+ }+}++class TestText {+ nodeType = 3;+ parentElement: TestElement | null = null;+ isConnected = true;+}++const asNode = (node: TestElement | TestText) => node as unknown as Node;+const asElement = (element: TestElement) => element as unknown as Element;++const createRange = (start: TestText, end: TestText, text = "selected") => ({+ startContainer: asNode(start),+ startOffset: 0,+ endContainer: asNode(end),+ endOffset: text.length,+ toString: () => text,+}) as unknown as Range;++const createFixture = () => {+ const startText = new TestText();+ const endText = new TestText();+ const startBlock = new TestElement("start", "NodeParagraph").append(startText);+ const endBlock = new TestElement("end", "NodeParagraph").append(endText);+ const editor = new TestElement().setEditor().append(startBlock, endBlock);+ const range = createRange(startText, endText);+ const context: NewFileSelectionContext = {+ range,+ notebookId: "notebook",+ rootID: "root",+ path: "/root.sy",+ startBlockID: "start",+ endBlockID: "end",+ text: "selected",+ };+ const protyle = {+ notebookId: "notebook",+ block: {rootID: "root"},+ path: "/root.sy",+ wysiwyg: {element: asElement(editor)},+ } as IProtyle;+ return {context, editor, endText, protyle, range, startText};+};++describe("new document selection context", () => {+ it("keeps a connected selection in the original document valid", () => {+ const {context, protyle} = createFixture();++ assert.equal(isNewFileSelectionValid(protyle, context), true);+ });++ it("rejects detached or changed selections", () => {+ const {context, protyle, startText} = createFixture();+ startText.isConnected = false;+ assert.equal(isNewFileSelectionValid(protyle, context), false);++ const changed = createFixture();+ changed.context.range = createRange(changed.startText, changed.endText, "changed");+ assert.equal(isNewFileSelectionValid(changed.protyle, changed.context), false);+ });++ it("rejects a selection after navigating to another document", () => {+ const {context, protyle} = createFixture();+ protyle.block.rootID = "another-root";++ assert.equal(isNewFileSelectionValid(protyle, context), false);+ });++ it("distinguishes the saved selection from a moved caret", () => {+ const {editor, range, startText} = createFixture();+ const movedRange = createRange(startText, startText, "");++ assert.equal(isSameRange(range, range), true);+ assert.equal(isSameRange(range, movedRange), false);+ assert.equal(isRangeInEditor(asElement(editor), movedRange), true);+ });+});diff --git a/app/src/util/newFileSelection.ts b/app/src/util/newFileSelection.tsnew file mode 100644index 0000000000..f5784a951a--- /dev/null+++ b/app/src/util/newFileSelection.ts@@ -0,0 +1,30 @@+import {hasClosestBlock} from "../protyle/util/hasClosest";++export type NewFileSelectionContext = {+ range: Range;+ notebookId: string;+ rootID: string;+ path: string;+ startBlockID: string;+ endBlockID: string;+ text: string;+};++export const isSameRange = (range: Range, targetRange: Range) => range.startContainer === targetRange.startContainer &&+ range.startOffset === targetRange.startOffset && range.endContainer === targetRange.endContainer &&+ range.endOffset === targetRange.endOffset;++export const isRangeInEditor = (editorElement: Element, range: Range) => range.startContainer.isConnected &&+ range.endContainer.isConnected && editorElement.contains(range.startContainer) && editorElement.contains(range.endContainer);++export const isNewFileSelectionValid = (protyle: IProtyle, context: NewFileSelectionContext) => {+ if (protyle.notebookId !== context.notebookId || protyle.block.rootID !== context.rootID ||+ protyle.path !== context.path || !isRangeInEditor(protyle.wysiwyg.element, context.range)) {+ return false;+ }+ const startBlockElement = hasClosestBlock(context.range.startContainer);+ const endBlockElement = hasClosestBlock(context.range.endContainer);+ return startBlockElement && endBlockElement &&+ startBlockElement.getAttribute("data-node-id") === context.startBlockID &&+ endBlockElement.getAttribute("data-node-id") === context.endBlockID && context.range.toString() === context.text;+};