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: Restore asset uploads in standalone database item panels https://github.com/siyuan-note/siyuan/issues/20538
Daniel0dfb593fb9d5
diff --git a/app/src/protyle/render/av/asset.test.ts b/app/src/protyle/render/av/asset.test.tsindex f2ea4ca58e..a4f4e4a21d 100644--- a/app/src/protyle/render/av/asset.test.ts+++ b/app/src/protyle/render/av/asset.test.ts@@ -9,6 +9,7 @@ import * as assetUploadTarget from "./assetUploadTarget";import {updateAVCachedCellValue} from "./cellValue";import * as uploadResult from "../../upload/uploadResult";import * as viewType from "./viewType";+import * as insertPosition from "../../upload/insertPosition";// 使用完整资源消费者,控制上传完成与虚拟行移除的顺序,记录实际生成的事务。const createHarness = (layout = "table") => {@@ -27,6 +28,7 @@ const createHarness = (layout = "table") => {closest: () => ({dataset: {}}),};const block = {+ closest: (): HTMLElement | null => null,getAttribute: (key: string) => ({"data-av-type": layout, "data-av-id": "av", "data-node-id": "block"})[key],contains: () => rendered,querySelector: () => rendered ? element : null,@@ -39,6 +41,7 @@ const createHarness = (layout = "table") => {"./selectionState": selectionState,"./assetUploadTarget": assetUploadTarget,"../../upload/uploadResult": uploadResult,+ "../../upload/insertPosition": insertPosition,"./virtualScroll": {getAVData: () => data},"./col": {getColId: () => "assets"},"./row": {getFieldIdByCellElement: () => "row"},diff --git a/app/src/protyle/render/av/asset.ts b/app/src/protyle/render/av/asset.tsindex 6499265ff3..580f2ad5d7 100644--- a/app/src/protyle/render/av/asset.ts+++ b/app/src/protyle/render/av/asset.ts@@ -34,6 +34,7 @@ import {getAssetUploadSuccesses} from "../../upload/uploadResult";import {getAVSelectedCells, resolveAVSelectedCell, type IAVSelectedCell, type IAVCellPoint} from "./selectionState";import {getAVData, getAVSelectedTableCells} from "./virtualScroll";import {getAVAssetUploadTargets} from "./assetUploadTarget";+import {captureUploadDocument} from "../../upload/insertPosition";export const bindAssetEvent = (options: {protyle: IProtyle,@@ -47,11 +48,11 @@ export const bindAssetEvent = (options: {if (event.target.files.length === 0) {return;}- const applyUpload = captureAssetCellUpload(options.protyle, options.blockElement,+ const upload = captureAssetCellUpload(options.protyle, options.blockElement,options.cellElements, options.menuElement);uploadFiles(options.protyle, event.target.files, event.target, (_res, result) => {- applyUpload(result);- }, undefined, {source: "file-picker", target: "av-cell"});+ upload.apply(result);+ }, undefined, {source: "file-picker", target: "av-cell", document: upload.document});});};@@ -133,7 +134,7 @@ export const updateAssetCell = (options: {return;}const viewType = options.blockElement.getAttribute("data-av-type") as TAVView;- const colId = getColId(options.cellElements[0], viewType);+ const colId = options.targets?.[0]?.colID || getColId(options.cellElements[0], viewType);const cellDoOperations: IOperation[] = [];const cellUndoOperations: IOperation[] = [];let mAssetValue: IAVCellAssetValue[];@@ -148,14 +149,9 @@ export const updateAssetCell = (options: {if (target && data && selectedCell?.column.type !== "mAsset") {return;}- if (!options.blockElement.contains(item)) {- if (isTableLikeView(viewType)) {- item = (options.blockElement.querySelector(`.av__row[data-id="${rowID}"] .av__cell[data-col-id="${item.dataset.colId}"]`) ||- options.blockElement.querySelector(`.fn__flex-1[data-col-id="${item.dataset.colId}"]`)) as HTMLElement;- } else {- item = (options.blockElement.querySelector(`.av__gallery-item[data-id="${rowID}"] .av__cell[data-field-id="${item.dataset.fieldId}"]`)) as HTMLElement;- }- }+ item = resolveAssetCellElement(options.blockElement, item, target || {+ rowID, colID: getColId(item, viewType), groupID: "",+ }, viewType);if (!item && !selectedCell) {return;}@@ -554,24 +550,59 @@ const getAssetCellMenu = (cellElement: HTMLElement) => {return ids.includes(cellElement.dataset.id) ? menuElement : null;};+const resolveAssetCellElement = (blockElement: Element, cellElement: HTMLElement,+ target: IAVCellPoint, viewType: TAVView) => {+ let item = cellElement;+ if (!blockElement.contains(item) || getColId(item, viewType) !== target.colID ||+ getFieldIdByCellElement(item, viewType) !== target.rowID) {+ item = (cellElement.classList.contains("custom-attr__avvalue") ?+ blockElement.querySelector(`.custom-attr__avvalue[data-row-id="${target.rowID}"][data-col-id="${target.colID}"]`) :+ isTableLikeView(viewType) ?+ blockElement.querySelector(`.av__row[data-id="${target.rowID}"] .av__cell[data-col-id="${target.colID}"]`) :+ blockElement.querySelector(`.av__gallery-item[data-id="${target.rowID}"] .av__cell[data-field-id="${target.colID}"]`)) as HTMLElement;+ }+ return item && (getTypeByCellElement(item) || item.dataset.type) === "mAsset" ? item : null;+};+const captureAssetCellUpload = (protyle: IProtyle, blockElement: Element, cells: HTMLElement[],menuElement: HTMLElement | null) => {const cellElements = Array.from(cells);const viewType = blockElement.getAttribute("data-av-type") as TAVView;+ const avID = blockElement.getAttribute("data-av-id");+ const blockID = blockElement.getAttribute("data-node-id");+ const attributeID = blockElement.getAttribute("data-attribute-id");+ const ownerElement = blockElement.closest(".protyle-db-row");const targets = cellElements.map(item => ({rowID: getFieldIdByCellElement(item, viewType),colID: getColId(item, viewType),groupID: item.closest<HTMLElement>(".av__body")?.dataset.groupId || "",}));- return (result: Omit<IAssetUploadResult, "requestId" | "input">) => {- if (!document.body.contains(blockElement)) {- return;+ // 独立条目的上下文编辑器不挂载 DOM,使用可见面板并按原条目重新解析刷新后的字段。+ const resolveBlock = () => ownerElement ? ownerElement.querySelector<HTMLElement>(+ `[data-av-id="${avID}"][data-node-id="${blockID}"][data-attribute-id="${attributeID}"]`) : blockElement;+ const isAvailable = () => {+ const currentBlock = resolveBlock();+ if (protyle.disabled || !currentBlock || !document.body.contains(currentBlock) ||+ currentBlock.getAttribute("data-av-id") !== avID ||+ currentBlock.getAttribute("data-node-id") !== blockID) {+ return false;}- const addValue = getUploadedAssetValues(result);- if (addValue.length === 0) {- return;- }- updateAssetCell({protyle, blockElement, cellElements, targets, addValue, menuElement});+ const data = getAVData(currentBlock as HTMLElement);+ return targets.some((target, index) => data ? resolveAVSelectedCell(data, target)?.column.type === "mAsset" :+ Boolean(resolveAssetCellElement(currentBlock, cellElements[index], target, viewType)));+ };+ return {+ document: captureUploadDocument(protyle, {element: ownerElement || protyle.element, isAvailable}),+ apply: (result: Omit<IAssetUploadResult, "requestId" | "input">) => {+ if (!isAvailable()) {+ return;+ }+ const addValue = getUploadedAssetValues(result);+ if (addValue.length === 0) {+ return;+ }+ updateAssetCell({protyle, blockElement: resolveBlock(), cellElements, targets, addValue, menuElement});+ },};};@@ -643,7 +674,7 @@ export const captureAVAssetUploadHandler = (protyle: IProtyle, blockElement: HTM}if (usePanelTarget) {if (applyPanelUpload) {- applyPanelUpload(result);+ applyPanelUpload.apply(result);if (panelElement.isConnected) {panelElement.remove();}@@ -709,9 +740,9 @@ export const dragUpload = (files: ILocalFiles[], protyle: IProtyle, cellElement:return;}const menuElement = getAssetCellMenu(cellElement);- const applyUpload = captureAssetCellUpload(protyle, blockElement, [cellElement], menuElement);- uploadLocalFiles(files, protyle, true, {source: "drop", target: "av-cell", position}, (_response, result) => {- applyUpload(result);+ const upload = captureAssetCellUpload(protyle, blockElement, [cellElement], menuElement);+ uploadLocalFiles(files, protyle, true, {source: "drop", target: "av-cell", position, document: upload.document}, (_response, result) => {+ upload.apply(result);});};@@ -722,10 +753,10 @@ export const uploadFilesToAssetCell = (files: FileList | File[], protyle: IProtyreturn;}const menuElement = getAssetCellMenu(cellElement);- const applyUpload = captureAssetCellUpload(protyle, blockElement, [cellElement], menuElement);+ const upload = captureAssetCellUpload(protyle, blockElement, [cellElement], menuElement);uploadFiles(protyle, files, undefined, (_response, result) => {- applyUpload(result);- }, undefined, {source: options.source, target: "av-cell", position: options.position});+ upload.apply(result);+ }, undefined, {source: options.source, target: "av-cell", position: options.position, document: upload.document});};export const dragUploadFiles = (files: FileList | File[], protyle: IProtyle, cellElement: HTMLElement,diff --git a/app/src/protyle/render/av/assetUploadLifecycle.test.ts b/app/src/protyle/render/av/assetUploadLifecycle.test.tsnew file mode 100644index 0000000000..de27d70877--- /dev/null+++ b/app/src/protyle/render/av/assetUploadLifecycle.test.ts@@ -0,0 +1,293 @@+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 {ModuleKind, ScriptTarget, transpileModule} from "typescript";+import {DOMFixture, DOMElement} from "./testDOM";+import * as insertPosition from "../../upload/insertPosition";+import * as uploadResult from "../../upload/uploadResult";+import * as fetchAppId from "../../../util/fetchAppId";+import * as viewType from "./viewType";++const compile = (file: string) => transpileModule(readFileSync(join(__dirname, file), "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2022},+}).outputText;+const assetSource = compile("asset.ts");+const uploadSource = compile("../../upload/index.ts");+type UploadKind = "picker" | "drop" | "paste";+const settle = () => new Promise(resolve => setImmediate(resolve));++// 组合执行资源字段消费者和完整上传模块,使用真实父子节点连接状态,控制插件与网络的异步边界。+const createHarness = (standalone = true) => {+ const document = new DOMFixture();+ const owner = document.createElement("div");+ owner.className = standalone ? "protyle-db-row" : "protyle";+ document.body.append(owner);+ let block: DOMElement;+ let cell: DOMElement;+ const value = {id: "value", type: "mAsset", mAsset: [+ {type: "image", name: "original.png", content: "assets/original.png"},+ ]};+ const render = () => {+ const next = document.createElement("div");+ next.innerHTML = `<div data-av-id="database" data-node-id="carrier" data-attribute-id="row" data-av-type="table">+<div class="custom-attr__avvalue" data-av-id="database" data-row-id="row" data-col-id="assets" data-id="value" data-type="mAsset"></div>+</div>`;+ if (block) {+ block.replaceWith(next.firstElementChild);+ } else {+ owner.append(next.firstElementChild);+ }+ block = owner.firstElementChild;+ cell = block.firstElementChild;+ cell.dataset.cellValue = encodeURIComponent(JSON.stringify(value));+ };+ render();+ const ghost = document.createElement("div");+ const protyle = {+ element: standalone ? ghost : owner,+ block: {rootID: "document"}, notebookId: "notebook", disabled: false,+ app: {plugins: [] as unknown[]}, wysiwyg: {element: ghost},+ upload: {element: {style: {}}, isUploading: false},+ options: {upload: {max: 1024, accept: "", filename: (name: string) => name,+ extraData: {}, fieldName: "file[]", url: "/api/asset/upload"}},+ };+ const operations: IOperation[] = [];+ const messages: string[] = [];+ const pluginWaits: Array<() => void> = [];+ const requests: Array<{id: string, respond: () => void}> = [];+ const confirmations: Array<() => void> = [];+ let delayConfirmation = false;+ let destroyed = 0;+ let onComplete = () => {};+ const response = (name: string) => ({code: 0, data: {succMap: {[name]: `assets/${name}`},+ succFiles: [{index: 0, name, path: `assets/${name}`}]}});+ class FormDataStub {+ public values = new Map<string, unknown>();+ public append(key: string, item: unknown) { this.values.set(key, item); }+ }+ class XHRStub {+ public static DONE = 4;+ public readyState = 0;+ public status = 200;+ public responseText = "";+ public upload = {};+ public onreadystatechange: () => void;+ public open() {}+ public setRequestHeader() {}+ public send(form: FormDataStub) {+ const name = (form.values.get("file[]") as File).name;+ requests.push({id: form.values.get("id") as string, respond: () => {+ this.readyState = 4;+ this.responseText = JSON.stringify(response(name));+ this.onreadystatechange();+ }});+ }+ }+ const mocks: Record<string, unknown> = {+ "./insertPosition": insertPosition,+ "../../upload/insertPosition": insertPosition,+ "./uploadResult": uploadResult,+ "../../upload/uploadResult": uploadResult,+ "../../util/fetchAppId": fetchAppId,+ "../runtimeCapabilities": {isProtyleUploadDisabled: () => false},+ "../util/destroy": {destroy() { destroyed++; }},+ "../../util/hostCapabilities": {getHostCapabilities: () => ({localFileSystem: true})},+ "./viewType": viewType,+ "./virtualScroll": {getAVData: (): IAV | undefined => undefined},+ "./col": {getColId: (item: HTMLElement) => item.dataset.colId},+ "./row": {getFieldIdByCellElement: (item: HTMLElement) => item.dataset.rowId},+ "./batchValue": {getAVBatchEditMode: () => "replace"},+ "../../../util/pathName": {getAssetExtension: (name: string) => name.slice(name.lastIndexOf("."))},+ "../../util/hasClosest": {hasClosestBlock: (item: HTMLElement) => item.parentElement},+ "../../wysiwyg/transaction": {transaction: (_p: unknown, ops: IOperation[]) => operations.push(...ops)},+ "./action": {updateAttrViewCellAnimation() {}},+ "./cell": {+ getTypeByCellElement: (item: HTMLElement) => item.dataset.type,+ genCellValueByElement: (_type: string, item: HTMLElement) => JSON.parse(decodeURIComponent(item.dataset.cellValue)),+ updateAttrViewCellInOtherElements: (_p: unknown, _av: string, _row: string, _col: string,+ next: typeof value, item: HTMLElement) => {+ Object.assign(value, next);+ item.dataset.cellValue = encodeURIComponent(JSON.stringify(next));+ },+ },+ "dayjs": () => ({format: () => "20261014070000"}),+ "../../util/escape": {escapeHtml: (text: string) => text},+ "../../dialog/confirmDialog": {confirmDialog: (_title: string, _message: string, yes: () => void) => {+ if (delayConfirmation) {+ confirmations.push(yes);+ } else {+ yes();+ }+ }},+ "../../util/fetch": {fetchSyncPost: (_url: string, data: {id: string, assetPaths: string[]}) =>+ new Promise(resolve => requests.push({id: data.id, respond: () => resolve(response(data.assetPaths[0].split("/").pop()))}))},+ "./pluginEvent": {prepareAssetUpload: ({input}: {input: IAssetUploadInput}) => new Promise(resolve => {+ pluginWaits.push(() => resolve({state: "ready", task: {input, startUpload() {}, complete() {+ onComplete();+ return true;+ }}}));+ })},+ };+ for (const prefix of ["../../", "../../../"]) {+ mocks[prefix + "constants"] = {Constants: {SIZE_UPLOAD_TIP_SIZE: 1024, SIYUAN_APPID: "upload-window",+ SIYUAN_ASSETS_IMAGE: [".png"]}};+ mocks[prefix + "dialog/message"] = {showMessage: (message: string) => messages.push(message), hideMessage() {}};+ }+ const load = <T>(source: string) => {+ const module = {exports: {} as T};+ runInNewContext(source, {+ module, exports: module.exports, require: (name: string) => mocks[name] || {}, Promise,+ document: {body: document.body, baseURI: "https://siyuan.test/stage/build/app/", querySelector: (): Element | null => null},+ location: {origin: "https://siyuan.test"},+ window: {siyuan: {languages: {uploadInsertTargetUnavailable: "unavailable", uploading: "uploading"}}},+ FormData: FormDataStub, XMLHttpRequest: XHRStub, DataTransferItem: class {}, console,+ });+ return module.exports;+ };+ mocks["../../upload"] = load(uploadSource);+ const api = load<typeof import("./asset")>(assetSource);+ const start = (kind: UploadKind, name = "image.png") => {+ const files = [new File(["image"], name, {type: "image/png"})];+ if (kind === "picker") {+ const menu = document.createElement("div");+ const input = document.createElement("input");+ Object.assign(input, {files});+ menu.append(input);+ api.bindAssetEvent({protyle: protyle as unknown as IProtyle, blockElement: block as unknown as Element,+ cellElements: [cell as unknown as HTMLElement], menuElement: menu as unknown as HTMLElement});+ input.dispatch("change");+ } else if (kind === "drop") {+ api.dragUpload([{path: "/" + name, size: 5}], protyle as unknown as IProtyle, cell as unknown as HTMLElement);+ } else {+ api.uploadFilesToAssetCell(files, protyle as unknown as IProtyle, cell as unknown as HTMLElement, {source: "paste"});+ }+ };+ return {start, render, protyle, owner, value, operations, requests, messages,+ get block() { return block; }, get cell() { return cell; },+ get destroyed() { return destroyed; },+ resume: async () => { assert.ok(pluginWaits.length); pluginWaits.shift()(); await settle(); },+ complete: async (index = 0) => { requests[index].respond(); await settle(); },+ onComplete: (callback: () => void) => { onComplete = callback; },+ delayConfirmation: () => { delayConfirmation = true; },+ confirm: async () => { assert.ok(confirmations.length); confirmations.shift()(); await settle(); },+ };+};++describe("database asset upload lifecycle", () => {+ for (const kind of ["picker", "drop", "paste"] as const) {+ for (const standalone of [true, false]) {+ it(`${kind}: writes the original cell with a ${standalone ? "detached context" : "connected editor"}`, async () => {+ const h = createHarness(standalone);+ assert.equal(h.protyle.element.isConnected, !standalone);+ h.start(kind);+ await h.resume();+ assert.equal(h.requests.length, 1);+ assert.equal(h.requests[0].id, "document");+ await h.complete();+ const updates = h.operations.filter(op => op.action === "updateAttrViewCell");+ assert.equal(updates.length, 1);+ assert.equal(updates[0].avID, "database");+ assert.equal(updates[0].rowID, "row");+ assert.equal(updates[0].keyID, "assets");+ assert.equal(h.destroyed, 0);+ assert.deepEqual(h.value.mAsset.map(item => item.content), ["assets/original.png", "assets/image.png"]);+ assert.ok(h.messages.every(message => message.includes("uploading")));+ });+ }+ const changes = {+ close: (h: ReturnType<typeof createHarness>) => h.owner.remove(),+ row: (h: ReturnType<typeof createHarness>) => { h.block.dataset.attributeId = "other-row"; h.cell.dataset.rowId = "other-row"; },+ database: (h: ReturnType<typeof createHarness>) => { h.block.dataset.avId = "other-database"; },+ carrier: (h: ReturnType<typeof createHarness>) => { h.block.dataset.nodeId = "other-carrier"; },+ delete: (h: ReturnType<typeof createHarness>) => h.cell.remove(),+ field: (h: ReturnType<typeof createHarness>) => { h.cell.dataset.colId = "other-field"; },+ type: (h: ReturnType<typeof createHarness>) => { h.cell.dataset.type = "text"; },+ document: (h: ReturnType<typeof createHarness>) => { h.protyle.block.rootID = "other-document"; },+ notebook: (h: ReturnType<typeof createHarness>) => { h.protyle.notebookId = "other-notebook"; },+ lock: (h: ReturnType<typeof createHarness>) => { h.protyle.disabled = true; },+ };+ for (const [name, change] of Object.entries(changes)) {+ for (const stage of ["plugin", "request", "completion"] as const) {+ it(`${kind}: rejects ${name} changes during ${stage}`, async () => {+ const h = createHarness();+ h.start(kind);+ if (stage === "plugin") {+ change(h);+ }+ await h.resume();+ if (stage === "plugin") {+ assert.equal(h.requests.length, 0);+ } else {+ assert.equal(h.requests.length, 1);+ if (stage === "request") {+ change(h);+ } else {+ h.onComplete(() => change(h));+ }+ await h.complete();+ }+ assert.equal(h.operations.length, 0);+ assert.equal(h.value.mAsset.length, 1);+ });+ }+ }+ it(`${kind}: uploads ordinary files as file assets`, async () => {+ const h = createHarness();+ h.start(kind, "notes.txt");+ await h.resume();+ await h.complete();+ assert.equal(h.value.mAsset[1].type, "file");+ assert.equal(h.value.mAsset[1].name, "notes.txt");+ assert.equal(h.value.mAsset[1].content, "assets/notes.txt");+ });+ it(`${kind}: rechecks a closed owner after upload confirmation`, async () => {+ const h = createHarness();+ h.delayConfirmation();+ h.start(kind);+ await h.resume();+ assert.equal(h.requests.length, 0);+ h.owner.remove();+ await h.confirm();+ assert.equal(h.requests.length, 0);+ assert.equal(h.operations.length, 0);+ });+ for (const stage of ["plugin", "request", "completion"] as const) {+ it(`${kind}: still rejects an ordinary editor closed during ${stage}`, async () => {+ const h = createHarness(false);+ h.start(kind);+ if (stage === "plugin") {+ h.owner.remove();+ }+ await h.resume();+ if (stage === "plugin") {+ assert.equal(h.requests.length, 0);+ } else {+ assert.equal(h.requests.length, 1);+ if (stage === "request") {+ h.owner.remove();+ } else {+ h.onComplete(() => h.owner.remove());+ }+ await h.complete();+ assert.equal(h.destroyed, stage === "request" ? 1 : 0);+ }+ assert.equal(h.operations.length, 0);+ });+ }+ it(`${kind}: preserves both uploads when the visible row is refreshed`, async () => {+ const h = createHarness();+ h.start(kind, "first.png");+ h.start(kind, "second.png");+ await h.resume();+ await h.resume();+ h.render();+ await h.complete(0);+ h.render();+ await h.complete(1);+ assert.deepEqual(h.value.mAsset.map(item => item.content), ["assets/original.png", "assets/first.png", "assets/second.png"]);+ assert.equal(h.operations.filter(op => op.action === "updateAttrViewCell").length, 2);+ });+ }+});diff --git a/app/src/protyle/upload/index.ts b/app/src/protyle/upload/index.tsindex 2a8135ad93..25c80b694e 100644--- a/app/src/protyle/upload/index.ts+++ b/app/src/protyle/upload/index.ts@@ -13,7 +13,10 @@ import {getContenteditableElement} from "../wysiwyg/getBlock";import {scrollCenter} from "../../util/highlightById";import {confirmDialog} from "../../dialog/confirmDialog";import {filesize} from "filesize";-import {captureUploadDocument, createUploadInsertPosition, getAvailableUploadInsertRange, isUploadDocumentAvailable} from "./insertPosition";+import {+ captureUploadDocument, createUploadInsertPosition, getAvailableUploadInsertRange,+ getUploadDocumentElement, isUploadDocumentAvailable+} from "./insertPosition";import type {IUploadDocument, IUploadInsertPosition} from "./insertPosition";import {type IAssetUploadEventContext,@@ -348,7 +351,7 @@ const uploadPreparedLocalFiles = (input: Extract<IAssetUploadInput, { kind: "locfromHTMLPaste: options?.fromHTMLPaste,});hideMessage(msgId);- const detached = !document.body.contains(protyle.element);+ const detached = !document.body.contains(getUploadDocumentElement(protyle, options.document));if (detached) {destroy(protyle);}@@ -498,7 +501,7 @@ const uploadPreparedFiles = (input: Extract<IAssetUploadInput, { kind: "files" }try {protyle.upload.isUploading = false;hideMessage(validateResult.msgId);- const detached = !document.body.contains(protyle.element);+ const detached = !document.body.contains(getUploadDocumentElement(protyle, options.document));if (detached) {// 网络较慢时,页签已经关闭destroy(protyle);diff --git a/app/src/protyle/upload/insertPosition.test.ts b/app/src/protyle/upload/insertPosition.test.tsindex 49eecd1d86..72e38d4467 100644--- a/app/src/protyle/upload/insertPosition.test.ts+++ b/app/src/protyle/upload/insertPosition.test.ts@@ -94,6 +94,29 @@ describe("upload insert position", () => {assert.deepEqual(position.context, {undoFocusId: "target"});});+ it("uses an explicit consumer owner without relaxing document identity or target validity", () => {+ const editor = new TestElement();+ editor.isConnected = false;+ const owner = new TestElement();+ let available = true;+ const protyle = {element: editor, block: {rootID: "doc"}, notebookId: "box"} as unknown as IProtyle;+ const target = captureUploadDocument(protyle, {element: owner as unknown as Element,+ isAvailable: () => available});+ assert.equal(isUploadDocumentAvailable(protyle, target), true);+ available = false;+ assert.equal(isUploadDocumentAvailable(protyle, target), false);+ available = true;+ protyle.block.rootID = "other";+ assert.equal(isUploadDocumentAvailable(protyle, target), false);+ protyle.block.rootID = "doc";+ protyle.notebookId = "other";+ assert.equal(isUploadDocumentAvailable(protyle, target), false);+ protyle.notebookId = "box";+ owner.isConnected = false;+ assert.equal(isUploadDocumentAvailable(protyle, target), false);+ assert.equal(isUploadDocumentAvailable(protyle, captureUploadDocument(protyle)), false);+ });+it("uses the live range while its original boundaries remain in the editor", () => {const start = new TestElement();const end = new TestElement();diff --git a/app/src/protyle/upload/insertPosition.ts b/app/src/protyle/upload/insertPosition.tsindex 3114803d9b..d040574527 100644--- a/app/src/protyle/upload/insertPosition.ts+++ b/app/src/protyle/upload/insertPosition.ts@@ -1,16 +1,25 @@export interface IUploadDocument {rootID: string;notebookID: string;+ target?: {+ element: Element;+ isAvailable: () => boolean;+ };}-export const captureUploadDocument = (protyle: IProtyle): IUploadDocument => ({+export const captureUploadDocument = (protyle: IProtyle, target?: IUploadDocument["target"]): IUploadDocument => ({rootID: protyle.block?.rootID,notebookID: protyle.notebookId,+ target,});+export const getUploadDocumentElement = (protyle: IProtyle, target?: IUploadDocument) =>+ target?.target?.element || protyle.element;+export const isUploadDocumentAvailable = (protyle: IProtyle, target: IUploadDocument) => {- return protyle.element.isConnected && target?.rootID === protyle.block?.rootID &&- target?.notebookID === protyle.notebookId;+ return getUploadDocumentElement(protyle, target).isConnected &&+ target?.rootID === protyle.block?.rootID && target?.notebookID === protyle.notebookId &&+ (!target?.target || target.target.isAvailable());};export interface IUploadInsertPosition {