An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Preserve selected table cell text when pasting links https://github.com/siyuan-note/siyuan/issues/19697
Daniel65a64f67a97e
diff --git a/app/src/protyle/util/paste.test.ts b/app/src/protyle/util/paste.test.tsindex b8cb728723..191a6e8e84 100644--- a/app/src/protyle/util/paste.test.ts+++ b/app/src/protyle/util/paste.test.ts@@ -4,6 +4,7 @@ import {readFileSync} from "node:fs";import {join} from "node:path";import {runInNewContext} from "node:vm";import * as ts from "typescript";+import {getAVRichTextSafeURL} from "../render/av/richTextValue";// 执行粘贴入口,替换剪贴板和上传接口,检查图片不会在受限片段中被丢弃。const source = ts.transpileModule(readFileSync(join(process.cwd(), "src/protyle/util/paste.ts"), "utf8"), {@@ -113,3 +114,108 @@ describe("strip pasted IAL data attributes", () => {assert.equal(harness.api.stripPastedIALDataAttributes(markdown), markdown);});});++describe("restricted cell selected text paste", () => {+ const runPaste = async (text: string, options: {selected?: string, code?: boolean, inlineCode?: boolean,+ unsupported?: boolean} = {}) => {+ const selected = options.selected ?? "Selected & text";+ const marks: Array<{type: string, value: ITextOption}> = [];+ const inserted: string[] = [];+ const messages: string[] = [];+ const range = {startContainer: {parentElement: {tagName: "DIV"}}, toString: () => selected,+ selectNodeContents: () => {}};+ const block = {classList: {contains: () => false},+ getAttribute: () => options.code ? "NodeCodeBlock" : "NodeParagraph"};+ const mocks: Record<string, unknown> = {+ "../../constants": {Constants: {ZWSP: "\u200b"}},+ "../runtimeCapabilities": {+ getProtyleBlockDOMSanitizer: () => (html: string) => html,+ getProtyleUnsupportedPasteBlocks: () => () => options.unsupported ? ["Table"] : [],+ getProtyleRestrictedPlainTextHTML: (text: string) => "plain:" + text,+ isProtyleUploadDisabled: () => true,+ areProtylePluginExtensionsEnabled: () => false,+ },+ "../upload/insertPosition": {+ createUploadInsertPosition: () => ({range}),+ captureUploadDocument: () => ({}),+ getAvailableUploadInsertRange: () => range,+ isUploadInsertPositionAvailable: () => true,+ },+ "./selection": {getEditorRange: () => range},+ "./hasClosest": {hasClosestBlock: () => block},+ "./compatibility": {isInHarmony: () => false},+ "./officeMath": {extractOfficeMathHTML: () => ""},+ "../upload/htmlLocalAssets": {resolveHTMLAssetURLs: () => {}, getHTMLAssetSourceURL: () => ""},+ "./pasteSource": {extractCrossBlockPasteContext: (html: string) => ({html})},+ "../ui/hideElements": {hideElements: () => {}},+ "./inlineElementMarker": {stripSemanticMarkersFromRangeText: () => selected},+ "../../editor/pdfAssetLink": {getPdfAnnotationReference: (): undefined => undefined},+ "../../util/functions": {isDynamicRef: (value: string) => /^\(\(\d{14}-\w{7} '.*'\)\)$/.test(value)},+ "../toolbar/util": {resolveLinkDest: (value: string) => /^(https?:|file:|assets\/)/.test(value) ? value : ""},+ "../render/av/richTextValue": {getAVRichTextSafeURL},+ "./normalizeText": {removeZWJ: (value: string) => value},+ "./insertHTML": {insertHTML: (value: string) => inserted.push(value)},+ "../../dialog/message": {showMessage: (value: string) => messages.push(value)},+ "../../util/escape": {escapeHtml: (value: string) => value},+ };+ const module = {exports: {}};+ runInNewContext(source, {module, exports: module.exports, require: (id: string) => mocks[id] || {},+ DOMParser: class {parseFromString() {return {querySelector: (): null => null, body: {innerHTML: ""}};}},+ Lute: {Sanitize: (value: string) => value},+ window: {siyuan: {languages: {cellPasteUnsupported: "Unsupported: ${x}"}}},+ });+ const protyle = {+ lite: true,+ lute: {Md2BlockDOM: (value: string) => value},+ hint: {enableExtend: false},+ wysiwyg: {element: {querySelectorAll: (): Element[] => []}},+ toolbar: {range, getCurrentType: () => options.inlineCode ? ["code"] : [],+ setInlineMark: (_protyle: unknown, type: string, _action: string, value: ITextOption) => {+ marks.push({type, value});+ return [{}];+ }},+ } as unknown as IProtyle;+ await (module.exports as typeof import("./paste")).paste(protyle, {+ textPlain: text, textHTML: "", siyuanHTML: "", target: block as unknown as HTMLElement,+ });+ return {marks, inserted, messages};+ };++ it("applies a static reference with the selected anchor text", async () => {+ const result = await runPaste("((20260921000000-abcdefg 'Document title'))");+ assert.equal(result.marks.length, 1);+ assert.equal(result.marks[0].type, "block-ref");+ assert.equal(result.marks[0].value.color, "20260921000000-abcdefg\u200bs\u200bSelected & text");+ assert.deepEqual(result.inserted, []);+ });++ for (const url of ["https://example.com", "assets/document.pdf"]) {+ it(`attaches ${url} without replacing the selected text`, async () => {+ const result = await runPaste(url);+ assert.equal(result.marks[0].type, "a");+ assert.equal(result.marks[0].value.color, url);+ assert.deepEqual(result.inserted, []);+ });+ }++ for (const [text, options] of [+ ["ordinary text", {}],+ ["https://example.com", {selected: ""}],+ ["https://example.com", {code: true}],+ ["https://example.com", {inlineCode: true}],+ ["file:///private/document", {}],+ ] as const) {+ it(`retains plain text fallback for ${text} ${JSON.stringify(options)}`, async () => {+ const result = await runPaste(text, options);+ assert.deepEqual(result.marks, []);+ assert.deepEqual(result.inserted, ["plain:" + text]);+ });+ }++ it("rejects unsupported content before changing the selection", async () => {+ const result = await runPaste("https://example.com", {unsupported: true});+ assert.deepEqual(result.marks, []);+ assert.deepEqual(result.inserted, []);+ assert.equal(result.messages.length, 1);+ });+});diff --git a/app/src/protyle/util/paste.ts b/app/src/protyle/util/paste.tsindex aa79cbff4b..4c9243fa8a 100644--- a/app/src/protyle/util/paste.ts+++ b/app/src/protyle/util/paste.ts@@ -25,6 +25,7 @@ import {showMessage} from "../../dialog/message";import {avRender} from "../render/av/render";import {cellScrollIntoView, getCellText} from "../render/av/cell";import {captureAVAssetUploadHandler} from "../render/av/asset";+import {getAVRichTextSafeURL} from "../render/av/richTextValue";import {fixAdjacentTags, getCalloutInfo, getContenteditableElement} from "../wysiwyg/getBlock";import {clearBlockElement} from "./clear";import {remapTabsDOMIDs, wrapPastedTabItems} from "./tabsCopy";@@ -81,6 +82,42 @@ import {ipcRenderer} from "electron";const PASTE_PLUGIN_TIMEOUT = 120_000;const PASTE_PLUGIN_TIMED_OUT = Symbol("paste-plugin-timed-out");+const pastePlainTextLink = (protyle: IProtyle, range: Range, text: string) => {+ const selectedText = stripSemanticMarkersFromRangeText(range).split(Constants.ZWSP).join("");+ if (!selectedText) {+ return false;+ }+ const annotationReference = getPdfAnnotationReference(text.split("\n")[0]);+ const restricted = !!getProtyleBlockDOMSanitizer(protyle);+ if (isDynamicRef(text)) {+ protyle.toolbar.range = range;+ const refElement = protyle.toolbar.setInlineMark(protyle, "block-ref", "range", {+ type: "id",+ // 选区文本由行内标记处理,保留原始锚文本。+ color: `${text.substring(2, 24)}${Constants.ZWSP}s${Constants.ZWSP}${selectedText}`+ });+ if (refElement[0]) {+ protyle.toolbar.range.selectNodeContents(refElement[0]);+ }+ return true;+ }+ if (annotationReference && (!restricted || getAVRichTextSafeURL(annotationReference))) {+ protyle.toolbar.range = range;+ protyle.toolbar.setInlineMark(protyle, "file-annotation-ref", "range", {+ type: "file-annotation-ref",+ color: annotationReference+ });+ return true;+ }+ const linkDest = resolveLinkDest(text, protyle.lute);+ if (linkDest && (!restricted || getAVRichTextSafeURL(linkDest))) {+ protyle.toolbar.range = range;+ protyle.toolbar.setInlineMark(protyle, "a", "range", {type: "a", color: linkDest});+ return true;+ }+ return false;+};+export const beforePaste = (protyle: IProtyle, blockElement: HTMLElement, validatedRange?: Range) => {// 受限单元格须先验证载荷,拒绝粘贴时保持行内元素边界处的光标不变。if (!validatedRange && getProtyleUnsupportedPasteBlocks(protyle)) {@@ -976,6 +1013,11 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEvenitem.classList.remove("protyle-wysiwyg--hl");});if (blockDOMSanitizer && !siyuanHTML) {+ // 受限片段保留选中文字附加引用或链接的行为,代码内容仍按纯文本粘贴。+ if (nodeElement.getAttribute("data-type") !== "NodeCodeBlock" &&+ !protyle.toolbar.getCurrentType(range).includes("code") && pastePlainTextLink(protyle, range, textPlain)) {+ return;+ }const plainHTML = getProtyleRestrictedPlainTextHTML(removeZWJ(textPlain));if (plainHTML) {insertAtPasteRange(plainHTML, range);@@ -1453,40 +1495,8 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEvenuploadFiles(protyle, files, undefined, avAssetUploadSuccess, undefined, directAssetUploadOptions);return;} else if (textPlain.trim() !== "" && (files && files.length === 0 || !files)) {- const selectedText = stripSemanticMarkersFromRangeText(range).split(Constants.ZWSP).join("");- if (selectedText !== "") {- const firstLine = textPlain.split("\n")[0];- const annotationReference = getPdfAnnotationReference(firstLine);- if (isDynamicRef(textPlain)) {- protyle.toolbar.range = range;- const refElement = protyle.toolbar.setInlineMark(protyle, "block-ref", "range", {- type: "id",- // range 不能 escape,否则 https://github.com/siyuan-note/siyuan/issues/8359- color: `${textPlain.substring(2, 22 + 2)}${Constants.ZWSP}s${Constants.ZWSP}${selectedText}`- });- if (refElement[0]) {- protyle.toolbar.range.selectNodeContents(refElement[0]);- }- return;- } else if (annotationReference) {- protyle.toolbar.range = range;- protyle.toolbar.setInlineMark(protyle, "file-annotation-ref", "range", {- type: "file-annotation-ref",- color: annotationReference- });- return;- } else {- // https://github.com/siyuan-note/siyuan/issues/8475- const linkDest = resolveLinkDest(textPlain, protyle.lute);- if (linkDest) {- protyle.toolbar.range = range;- protyle.toolbar.setInlineMark(protyle, "a", "range", {- type: "a",- color: linkDest- });- return;- }- }+ if (pastePlainTextLink(protyle, range, textPlain)) {+ return;}let textPlainDom: string;textPlain = stripPastedIALDataAttributes(textPlain);