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: Correct image pasting and block dragging in table cells https://github.com/siyuan-note/siyuan/issues/19247
Daniel660f212de1b7
diff --git a/app/src/protyle/render/tableCellRichEditor.ts b/app/src/protyle/render/tableCellRichEditor.tsindex d32569eef9..9e7fce7f5a 100644--- a/app/src/protyle/render/tableCellRichEditor.ts+++ b/app/src/protyle/render/tableCellRichEditor.ts@@ -137,7 +137,7 @@ export const openTableCellRichEditor = (owner: IProtyle, cell: HTMLTableCellEleminitialBlockHTML,protyleOptions: {notebookId: owner.notebookId, toolbar, hint},runtimeCapabilities: {- upload: false,+ upload: true,websocket: false,pluginExtensions: false,customBlockRender: false,@@ -161,6 +161,7 @@ export const openTableCellRichEditor = (owner: IProtyle, cell: HTMLTableCellElem}},});+ fragment.protyle.block.rootID = owner.block.rootID;const commit = () => {window.clearTimeout(timer);if (!cell.isConnected || !table.isConnected || !host.isConnected || owner.disabled || composing) {diff --git a/app/src/protyle/upload/index.test.ts b/app/src/protyle/upload/index.test.tsindex 140e77e490..b0252d1c79 100644--- a/app/src/protyle/upload/index.test.ts+++ b/app/src/protyle/upload/index.test.ts@@ -16,6 +16,7 @@ const createHarness = () => {let confirm: (() => void) | undefined;let delayConfirmation = false;const protyle = {+ lite: false,element: {isConnected: true},block: {rootID: "doc-a"}, notebookId: "box-a", app: {plugins: [] as unknown[]},wysiwyg: {element: {}},@@ -104,6 +105,27 @@ const createHarness = () => {const settle = () => new Promise(resolve => setImmediate(resolve));describe("upload document binding", () => {+ it("uploads lightweight document fragments to their owning document", async () => {+ const harness = createHarness();+ harness.protyle.lite = true;+ harness.start("files");+ harness.resume();+ await settle();+ assert.equal(harness.requests.length, 1);+ assert.equal(harness.requests[0].id, "doc-a");+ });++ it("keeps standalone lightweight uploads independent of documents", async () => {+ const harness = createHarness();+ harness.protyle.lite = true;+ harness.protyle.block.rootID = "";+ harness.start("files");+ harness.resume();+ await settle();+ assert.equal(harness.requests.length, 1);+ assert.equal(harness.requests[0].id, undefined);+ });+for (const kind of ["files", "local-files"] as const) {it(`${kind}: preserves the document captured by a parent paste operation`, () => {const harness = createHarness();diff --git a/app/src/protyle/upload/index.ts b/app/src/protyle/upload/index.tsindex 9d984869be..e8665f3f62 100644--- a/app/src/protyle/upload/index.ts+++ b/app/src/protyle/upload/index.ts@@ -464,7 +464,7 @@ const uploadPreparedFiles = (input: Extract<IAssetUploadInput, { kind: "files" }msg += window.siyuan.languages.uploadFileTooLarge.replace("${x}", escapeHtml(validateResult.files[i].name)).replace("${y}", filesize(validateResult.files[i].size, {standard: "iec"})) + "<br>";}}- if (protyle.lite) {+ if (protyle.lite && !options.document.rootID) {formData.append("assetsDirPath", "/assets/");} else {formData.append("id", options.document.rootID);diff --git a/app/src/protyle/util/dragDocument.test.ts b/app/src/protyle/util/dragDocument.test.tsindex 75a5a99441..7130a67ca2 100644--- a/app/src/protyle/util/dragDocument.test.ts+++ b/app/src/protyle/util/dragDocument.test.ts@@ -10,6 +10,7 @@ import {getSuperBlockResizeDropTarget,getTopListDragTarget,isAttributeViewTitleTarget,+ isCopyBlockDrag,isDragTargetInSource,isSameDragEditor,isSameSiblingMove,@@ -20,6 +21,38 @@ import {uniqueDragIds} from "./dragDocument";+describe("lightweight editor block dragging", () => {+ const editor = {closest: (): Element => null} as unknown as Element;+ const otherEditor = {closest: (): Element => null} as unknown as Element;+ const fragment = {closest: (selector: string) =>+ selector === ".protyle-lite-fragment" ? {} : null} as unknown as Element;++ it("copies temporary cell blocks into the outer document", () => {+ assert.equal(isCopyBlockDrag(false, false, editor, fragment), true);+ assert.equal(isCopyBlockDrag(false, true, editor, fragment), true);+ });++ it("moves within a cell and copies between fragments", () => {+ assert.equal(isCopyBlockDrag(true, false, fragment, fragment), false);+ assert.equal(isCopyBlockDrag(true, false, editor, fragment), true);+ });++ it("moves local blocks and preserves explicit copies", () => {+ assert.equal(isCopyBlockDrag(true, false, editor, editor), false);+ assert.equal(isCopyBlockDrag(true, true, editor, editor), true);+ });++ it("copies external and unavailable sources into lightweight editors", () => {+ assert.equal(isCopyBlockDrag(true, false, editor, otherEditor), true);+ assert.equal(isCopyBlockDrag(true, false, editor), true);+ });++ it("preserves normal editor move semantics", () => {+ assert.equal(isCopyBlockDrag(false, false, editor, otherEditor), false);+ assert.equal(isCopyBlockDrag(false, true, editor, otherEditor), true);+ });+});+const createClassElement = (classNames: string[], parentElement: Element = null, dataID = "") => ({nodeType: 1,classList: {diff --git a/app/src/protyle/util/dragDocument.ts b/app/src/protyle/util/dragDocument.tsindex 84aefb7c17..cd1e89e2f6 100644--- a/app/src/protyle/util/dragDocument.ts+++ b/app/src/protyle/util/dragDocument.ts@@ -2,6 +2,14 @@ export const isSameDragEditor = (targetEditor: Pick<Element, "contains">, sourcereturn targetEditor.contains(sourceElement);};+export const isCopyBlockDrag = (lite: boolean, ctrlKey: boolean, targetEditor: Element, sourceEditor?: Element) => {+ // 片段块没有独立的持久化 ID,跨编辑器时创建新块,仅在片段内部移动。+ return ctrlKey || (sourceEditor !== targetEditor && (lite || isFragmentBlockDrag(sourceEditor)));+};++export const isFragmentBlockDrag = (sourceEditor?: Element) =>+ !!sourceEditor?.closest(".protyle-lite-fragment");+export type TBlockDragData = {html: string,notebookID: string,diff --git a/app/src/protyle/util/editorCommonEvent.ts b/app/src/protyle/util/editorCommonEvent.tsindex f5e0511fd4..5dafcfa7fc 100644--- a/app/src/protyle/util/editorCommonEvent.ts+++ b/app/src/protyle/util/editorCommonEvent.ts@@ -67,6 +67,8 @@ import {getSuperBlockResizeDropTarget,getTopListDragTarget,isAttributeViewTitleTarget,+ isCopyBlockDrag,+ isFragmentBlockDrag,isDragTargetInSource,isSameDragEditor,isSameSiblingMove,@@ -1056,6 +1058,8 @@ export const dropEvent = (protyle: IProtyle, editorElement: HTMLElement) => {let kanbanGroupDragHeight = "";const isLiteTabDrag = (event: DragEvent) => protyle.lite &&event.dataTransfer.types.includes(Constants.SIYUAN_DROP_TAB);+ const shouldCopyBlockDrag = (event: DragEvent) => isCopyBlockDrag(protyle.lite, event.ctrlKey,+ protyle.wysiwyg.element, window.siyuan.dragElement);const clearKanbanGroupDragover = () => {if (kanbanGroupDragoverElement) {kanbanGroupDragoverElement.classList.remove("dragover__left", "dragover__right");@@ -1383,8 +1387,7 @@ export const dropEvent = (protyle: IProtyle, editorElement: HTMLElement) => {event.preventDefault();};editorElement.addEventListener("drop", async (event: DragEvent & { target: HTMLElement }) => {- // lite 模式不落盘,拖拽块时强制复制语义(避免移动操作删除源块)。- const isCopyDrag = protyle.lite || event.ctrlKey;+ const isCopyDrag = shouldCopyBlockDrag(event);counter = 0;hideDragTip();window.siyuan.dragTitle = "";@@ -1506,6 +1509,13 @@ export const dropEvent = (protyle: IProtyle, editorElement: HTMLElement) => {targetElement.removeAttribute("select-end");}if (gutterType) {+ // 片段中的临时块不能作为正文的引用或嵌入查询目标。+ if ((event.altKey || event.shiftKey) && isFragmentBlockDrag(window.siyuan.dragElement)) {+ event.preventDefault();+ event.stopPropagation();+ clearBlockDragoverTarget();+ return;+ }// gutter 或反链面板拖拽const sourceElements: Element[] = [];const gutterTypes = gutterType.replace(Constants.SIYUAN_DROP_GUTTER, "").split(Constants.ZWSP);@@ -2319,8 +2329,7 @@ export const dropEvent = (protyle: IProtyle, editorElement: HTMLElement) => {action = window.siyuan.languages.dragTipRef;} else if (event.shiftKey) {action = window.siyuan.languages.dragTipEmbed;- } else if (event.ctrlKey || protyle.lite) {- // Ctrl=创建副本;lite 模式无修饰键也为复制+ } else if (shouldCopyBlockDrag(event)) {action = window.siyuan.languages.duplicateCopy;} else if (isChild) {action = window.siyuan.languages.dragTipListItemChild.replace("${x}", targetText);@@ -2335,11 +2344,13 @@ export const dropEvent = (protyle: IProtyle, editorElement: HTMLElement) => {let cachedIsCol = false;editorElement.addEventListener("dragover", (event: DragEvent & { target: HTMLElement }) => {if (protyle.disabled || isLiteTabDrag(event) ||+ ((event.altKey || event.shiftKey) && isFragmentBlockDrag(window.siyuan.dragElement)) ||event.dataTransfer.types.includes(Constants.SIYUAN_DROP_EDITOR)) {event.preventDefault();event.stopPropagation();event.dataTransfer.dropEffect = "none";hideDragTip();+ clearBlockDragoverTarget();return;}if (event.dataTransfer.types.includes(Constants.SIYUAN_DROP_BLOCK_REF)) {@@ -2472,8 +2483,7 @@ export const dropEvent = (protyle: IProtyle, editorElement: HTMLElement) => {action = window.siyuan.languages.dragTipRef;} else if (event.shiftKey) {action = window.siyuan.languages.dragTipEmbed;- } else if (event.ctrlKey || protyle.lite) {- // Ctrl=创建副本;lite 模式无修饰键也为复制(不移动源块)+ } else if (shouldCopyBlockDrag(event)) {action = window.siyuan.languages.duplicateCopy;} else {action = window.siyuan.languages.move;diff --git a/app/src/protyle/util/paste.test.ts b/app/src/protyle/util/paste.test.tsnew file mode 100644index 0000000000..419c6c832b--- /dev/null+++ b/app/src/protyle/util/paste.test.ts@@ -0,0 +1,94 @@+import {describe, it} from "node:test";+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {join} from "node:path";+import {runInNewContext} from "node:vm";+import * as ts from "typescript";++// 执行粘贴入口,替换剪贴板和上传接口,检查图片不会在受限片段中被丢弃。+const source = ts.transpileModule(readFileSync(join(process.cwd(), "src/protyle/util/paste.ts"), "utf8"), {+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022},+}).outputText;++const createHarness = (disabled = false) => {+ const uploads: Array<{files: unknown; options: {document: {rootID: string}; insertPosition: unknown}}> = [];+ const position = {range: {startContainer: {}}};+ let available = true;+ let localFiles: unknown[] = [];+ const restrictedFallback = new Error("restricted fallback");+ const mocks: Record<string, unknown> = {+ "../../constants": {Constants: {SIYUAN_ASSETS_IMAGE: [".png", ".jpg"]}},+ "../runtimeCapabilities": {+ getProtyleBlockDOMSanitizer: () => (html: string) => html,+ isProtyleUploadDisabled: () => disabled,+ areProtylePluginExtensionsEnabled: () => false,+ getProtyleUnsupportedPasteBlocks: () => { throw restrictedFallback; },+ },+ "../upload/insertPosition": {+ createUploadInsertPosition: () => position,+ captureUploadDocument: () => ({rootID: "document", notebookID: "notebook"}),+ isUploadInsertPositionAvailable: () => available,+ },+ "./selection": {getEditorRange: () => position.range},+ "./hasClosest": {hasClosestBlock: (): undefined => undefined},+ "./wpsPresentation": {extractWPSPresentationClipboard: (): undefined => undefined},+ "./compatibility": {getLocalFiles: async () => localFiles},+ "../upload": {+ uploadFiles: (_protyle: unknown, files: unknown, _element: unknown, _success: unknown,+ _complete: unknown, options: typeof uploads[number]["options"]) => uploads.push({files, options}),+ uploadLocalFiles: (files: unknown, _protyle: unknown, _upload: boolean,+ options: typeof uploads[number]["options"]) => uploads.push({files, options}),+ },+ };+ const module = {exports: {}};+ runInNewContext(source, {module, exports: module.exports, require: (id: string) => mocks[id] || {}});+ const api = module.exports as typeof import("./paste");+ const paste = (files: unknown[] = [], siyuanHTML = "") => api.paste({wysiwyg: {element: {}}} as IProtyle, {+ target: {}, stopPropagation() {}, preventDefault() {},+ clipboardData: {files, types: [], getData: (type: string) => type === "text/siyuan" ? siyuanHTML : ""},+ } as unknown as ClipboardEvent & {target: HTMLElement});+ return {paste, uploads, position, restrictedFallback,+ setLocalFiles: (files: unknown[]) => { localFiles = files; },+ invalidate: () => { available = false; }};+};++describe("restricted cell image paste", () => {+ it("uploads screenshot clipboard files with the captured document and cursor", async () => {+ const harness = createHarness();+ const files = [{name: "image.png", type: "image/png"}];+ await harness.paste(files);+ assert.equal(harness.uploads.length, 1);+ assert.equal(harness.uploads[0].files, files);+ assert.equal(harness.uploads[0].options.document.rootID, "document");+ assert.equal(harness.uploads[0].options.insertPosition, harness.position);+ });++ it("uploads image files copied from the desktop clipboard", async () => {+ const harness = createHarness();+ const files = [{path: "C:/images/photo.JPG", size: 10}];+ harness.setLocalFiles(files);+ await harness.paste();+ assert.equal(harness.uploads.length, 1);+ assert.equal(harness.uploads[0].files, files);+ });++ it("does not upload after the paste target disappears", async () => {+ const harness = createHarness();+ harness.setLocalFiles([{path: "C:/image.png"}]);+ harness.invalidate();+ await harness.paste();+ assert.equal(harness.uploads.length, 0);+ });++ for (const [name, disabled, files, siyuanHTML] of [+ ["disabled uploads", true, [{name: "image.png"}], ""],+ ["unsupported files", false, [{name: "movie.mp4"}], ""],+ ["internal block content", false, [{name: "image.png"}], "internal"],+ ] as const) {+ it(`preserves restricted handling for ${name}`, async () => {+ const harness = createHarness(disabled);+ await assert.rejects(harness.paste([...files], siyuanHTML), harness.restrictedFallback);+ assert.equal(harness.uploads.length, 0);+ });+ }+});diff --git a/app/src/protyle/util/paste.ts b/app/src/protyle/util/paste.tsindex 78db2e3ad4..c3a6285e85 100644--- a/app/src/protyle/util/paste.ts+++ b/app/src/protyle/util/paste.ts@@ -69,6 +69,7 @@ import {getProtyleBlockDOMSanitizer,getProtyleUnsupportedPasteBlocks,getProtyleRestrictedPlainTextHTML,+ isProtyleUploadDisabled,restoreProtyleLuteMarkdownSyntax,} from "../runtimeCapabilities";/// #if !BROWSER@@ -714,6 +715,28 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEvensiyuanHTML = event.siyuanHTML;files = event.files;}+ if (blockDOMSanitizer && !siyuanHTML && !isProtyleUploadDisabled(protyle)) {+ // 受限片段中的图片走附件上传,避免被后续纯文本降级丢弃。+ const isImage = (name: string) => Constants.SIYUAN_ASSETS_IMAGE.includes(+ name.substring(name.lastIndexOf(".")).toLowerCase());+ if (files?.length > 0 && Array.from(files as FileList).every(file => isImage(file.name))) {+ uploadFiles(protyle, files, undefined, avAssetUploadSuccess, undefined, directAssetUploadOptions);+ return;+ }+ let localImages = "localFiles" in event ? event.localFiles : undefined;+ /// #if !BROWSER+ if (!localImages?.length && !files?.length && !textHTML && !textPlain && "clipboardData" in event) {+ localImages = await getLocalFiles();+ if (!isPasteInsertPositionAvailable()) {+ return;+ }+ }+ /// #endif+ if (localImages?.length > 0 && localImages.every(file => !file.isDir && isImage(file.path))) {+ await readLocalFile(protyle, localImages, directAssetUploadOptions, avAssetUploadSuccess);+ return;+ }+ }if (blockDOMSanitizer) {// 在清洗和修改选区前检查完整载荷,避免不支持的块被静默删除后只粘贴部分内容。const getUnsupportedBlocks = getProtyleUnsupportedPasteBlocks(protyle);