An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
/// #if !BROWSER
import {ipcRenderer} from "electron";
import * as path from "path";
/// #endif
import {fetchPost, fetchSyncPost} from "../util/fetch";
import {ContractFormData} from "../util/contractFormData";
import {genUUID} from "../util/genID";
import {getAssetExtension, getAssetName, useShell} from "../util/pathName";
import {openFileById} from "../editor/util";
import {Constants} from "../constants";
import {openNewWindowById} from "../window/openNewWindow";
import {MenuItem} from "./Menu";
import type {App} from "../index";
import {isInAndroid, isPhablet, saveExportFile, updateHotkeyTip} from "../protyle/util/compatibility";
import {checkFold} from "../util/noRelyPCFunction";
import {showMessage} from "../dialog/message";
import type {Editor} from "../editor";
import {setEditMode} from "../protyle/util/setEditMode";
import {getDownloadURL} from "../util/imageURL";
import {getHostCapabilities} from "../util/hostCapabilities";
export const exportAsset = (src: string) => {
if (!getHostCapabilities().importExport) {
return {ignore: true};
}
return {
id: "export",
label: window.siyuan.languages.export,
icon: "iconDownload",
async click() {
/// #if BROWSER
saveExportFile(getDownloadURL(src));
/// #else
const result = await ipcRenderer.invoke(Constants.SIYUAN_GET, {
cmd: "showSaveDialog",
defaultPath: getAssetName(src) + getAssetExtension(src),
properties: ["showOverwriteConfirmation"],
});
if (!result.canceled) {
fetchPost("/api/file/copyFile", {src, dest: result.filePath}, (response) => {
if (response.code === 0) {
showMessage(window.siyuan.languages.exported);
}
});
}
/// #endif
}
};
};
// 复制资源文件到系统剪贴板,在文件资源管理器中可粘贴为文件(仅 Windows、macOS 桌面端支持)
export const writeAssetToClipboard = (src: string) => {
if (!getHostCapabilities().localFileSystem) {
return {ignore: true};
}
/// #if !BROWSER
if (["windows", "darwin"].includes(window.siyuan.config.system.os)) {
return {
id: "copyFile",
label: window.siyuan.languages.copyFile,
icon: "iconFile",
click: () => {
fetchPost("/api/clipboard/writeFilePath", {path: src}, () => {
showMessage(window.siyuan.languages.copied);
});
}
};
} else {
return {ignore: true};
}
/// #else
return {ignore: true};
/// #endif
};
export const openEditorTab = (app: App, ids: string[], notebookId?: string, pathString?: string, onlyGetMenus = false) => {
/// #if !MOBILE
const openSubmenus: IMenu[] = [{
id: "insertRight",
icon: "iconLayoutRight",
label: window.siyuan.languages.insertRight,
accelerator: ids.length === 1 ? updateHotkeyTip(window.siyuan.config.keymap.editor.general.insertRight.custom) +
(window.siyuan.config.keymap.editor.general.insertRight.custom ? "/" : "") +
updateHotkeyTip("⌥" + window.siyuan.languages.click) : undefined,
click: () => {
if (notebookId) {
openFileById({
app,
id: ids[0],
position: "right",
action: isPhablet() ? [Constants.CB_GET_SCROLL] : [Constants.CB_GET_FOCUS, Constants.CB_GET_SCROLL]
});
} else {
ids.forEach((id) => {
checkFold(id, (zoomIn, action) => {
openFileById({
app,
id,
position: "right",
action,
zoomIn
});
});
});
}
}
}, {
id: "insertBottom",
icon: "iconLayoutBottom",
label: window.siyuan.languages.insertBottom,
accelerator: ids.length === 1 ? "⇧⌘" + window.siyuan.languages.click : "",
click: () => {
if (notebookId) {
openFileById({
app,
id: ids[0],
position: "bottom",
action: isPhablet() ? [Constants.CB_GET_SCROLL] : [Constants.CB_GET_FOCUS, Constants.CB_GET_SCROLL]
});
} else {
ids.forEach((id) => {
checkFold(id, (zoomIn, action) => {
openFileById({
app,
id,
position: "bottom",
action,
zoomIn
});
});
});
}
}
}];
if (window.siyuan.config.fileTree.openFilesUseCurrentTab) {
openSubmenus.push({
id: "openInNewTab",
label: window.siyuan.languages.openInNewTab,
accelerator: ids.length === 1 ? "⌥⌘" + window.siyuan.languages.click : undefined,
click: () => {
if (notebookId) {
openFileById({
app,
id: ids[0],
action: isPhablet() ? [Constants.CB_GET_SCROLL] : [Constants.CB_GET_FOCUS, Constants.CB_GET_SCROLL],
removeCurrentTab: false
});
} else {
ids.forEach((id) => {
checkFold(id, (zoomIn, action) => {
openFileById({
app,
id,
action,
zoomIn,
removeCurrentTab: false
});
});
});
}
}
});
}
/// #if !BROWSER
openSubmenus.push({
id: "openByNewWindow",
label: window.siyuan.languages.openByNewWindow,
icon: "iconOpenWindow",
click() {
openNewWindowById(ids);
}
});
/// #endif
openSubmenus.push({id: "separator_1", type: "separator"});
openSubmenus.push({
id: "preview",
icon: "iconPreview",
label: window.siyuan.languages.preview,
click: () => {
ids.forEach((id) => {
openFileById({
app, id, mode: "preview", afterOpen(editor: Editor) {
setEditMode(editor.editor.protyle, "preview");
}
});
});
}
});
/// #if !BROWSER
if (getHostCapabilities().localFileSystem) {
openSubmenus.push({id: "separator_2", type: "separator"});
openSubmenus.push({
id: "showInFolder",
icon: "iconFolder",
label: window.siyuan.languages.showInFolder,
click: () => {
if (notebookId) {
useShell("showItemInFolder", path.join(window.siyuan.config.system.dataDir, notebookId, pathString));
} else {
ids.forEach((id) => {
fetchPost("/api/block/getBlockInfo", {id}, (response) => {
if (response.code !== 0 || response.data.publishAccessRequired) {
return;
}
useShell("showItemInFolder", path.join(window.siyuan.config.system.dataDir, response.data.box, response.data.path));
});
});
}
}
});
}
/// #endif
if (onlyGetMenus) {
return openSubmenus;
}
window.siyuan.menus.menu.append(new MenuItem({
id: "openBy",
label: window.siyuan.languages.openBy,
icon: "iconOpen",
submenu: openSubmenus,
}).element);
/// #endif
};
export const writePNGBlob = async (blob: Blob): Promise<boolean> => {
if (isInAndroid()) {
try {
// 通过已有临时导出通道向原生剪贴板传递 PNG,支持 WebView 渲染的矢量图片。
const response = await fetchSyncPost("/api/export/exportAsFile", new ContractFormData({
file: new File([blob], `clipboard-${genUUID()}.png`, {type: "image/png"}),
type: "image/png",
}));
if (response.code !== 0 || !response.data?.file) {
throw new Error("could not prepare clipboard image");
}
window.JSAndroid.writeImageClipboard(response.data.file);
return true;
} catch (e) {
showMessage(window.siyuan.languages.imageCopyFailed, 6000, "error");
return false;
}
}
try {
if (!navigator.clipboard?.write || typeof ClipboardItem === "undefined") {
throw new Error("image clipboard is unavailable");
}
await navigator.clipboard.write([
new ClipboardItem({
// @ts-ignore
["image/png"]: blob
})
]);
return true;
} catch (e) {
showMessage(window.siyuan.languages.clipboardPermissionDenied);
return false;
}
};
export const copyPNGByLink = (link: string) => {
const showCopyError = () => showMessage(window.siyuan.languages.imageCopyFailed, 6000, "error");
const copyBlob = async (blob: Blob) => {
if (await writePNGBlob(blob)) {
showMessage(window.siyuan.languages.copied);
}
};
const imageToPNGClipboard = (image: HTMLImageElement, vector = false) => {
try {
const canvas = document.createElement("canvas");
// 矢量图片以至少两倍分辨率采样,限制额外放大的画布尺寸和像素总量。
const scale = vector ? Math.max(1, Math.min(Math.max(2, window.devicePixelRatio || 1),
16384 / image.naturalWidth, 16384 / image.naturalHeight,
Math.sqrt(16777216 / (image.naturalWidth * image.naturalHeight)))) : 1;
canvas.width = Math.round(image.naturalWidth * scale);
canvas.height = Math.round(image.naturalHeight * scale);
canvas.getContext("2d").drawImage(image, 0, 0, canvas.width, canvas.height);
canvas.toBlob((blob) => {
if (blob) {
copyBlob(blob);
} else {
showCopyError();
}
}, "image/png", 1);
} catch (e) {
showCopyError();
}
};
// 通过 fetch 拿到 blob 后再写入剪贴板,避免跨域图片直接 drawImage 污染 canvas 导致 toBlob 失败
// (浏览器访问 Docker 部署时常见,报错:Tainted canvases may not be exported)
// 把任意图片 blob 画进 canvas 再导出为 PNG;blob URL 为同源,不会污染 canvas
const blobToPNGClipboard = (blob: Blob) => {
if (blob.type === "image/png") {
copyBlob(blob);
return;
}
const objectURL = URL.createObjectURL(blob);
const tempElement = document.createElement("img");
tempElement.onload = () => {
imageToPNGClipboard(tempElement, blob.type.split(";")[0].trim().toLowerCase() === "image/svg+xml");
URL.revokeObjectURL(objectURL);
};
tempElement.onerror = () => {
URL.revokeObjectURL(objectURL);
showCopyError();
};
tempElement.src = objectURL;
};
fetch(link).then(async (response) => {
if (!response.ok) {
throw new Error(response.statusText);
}
blobToPNGClipboard(await response.blob());
}).catch(() => {
// fetch 失败时回退:以 CORS 模式加载后再导出(需目标服务器返回 ACAO)
const tempElement = document.createElement("img");
tempElement.crossOrigin = "anonymous";
tempElement.onload = () => imageToPNGClipboard(tempElement);
tempElement.onerror = showCopyError;
tempElement.src = link;
});
};