Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

保存的时候能不弹框 直接保存到思源内部吗? #17

Open
crendy opened this issue Sep 8, 2022 · 15 comments
Open

保存的时候能不弹框 直接保存到思源内部吗? #17

crendy opened this issue Sep 8, 2022 · 15 comments
Labels
question Further information is requested

Comments

@crendy
Copy link

crendy commented Sep 8, 2022

目前打开需要指定一个本地磁盘保存的路径,很多都集成到笔记或wiki内部了

@Zuoqiu-Yingyi Zuoqiu-Yingyi added the question Further information is requested label Sep 8, 2022
@Zuoqiu-Yingyi
Copy link
Owner

不弹窗的话就没法设置保存选项了呀👀

@crendy
Copy link
Author

crendy commented Sep 14, 2022

不弹窗的话就没法设置保存选项了呀👀

做成和思维导图的集成程度就好了,可以体验一下 思源挂件里面的:cc-KityMinder, 思维导图的数据直接无缝和编辑器集成到了一起,数据自动按文档内容保存了

@Zuoqiu-Yingyi
Copy link
Owner

不弹窗的话就没法设置保存选项了呀👀

做成和思维导图的集成程度就好了,可以体验一下 思源挂件里面的:cc-KityMinder, 思维导图的数据直接无缝和编辑器集成到了一起,数据自动按文档内容保存了

不能自动保存, 因为有许多配置项需要有需求的用户手动选择

@crendy
Copy link
Author

crendy commented Sep 15, 2022

不弹窗的话就没法设置保存选项了呀👀

做成和思维导图的集成程度就好了,可以体验一下 思源挂件里面的:cc-KityMinder, 思维导图的数据直接无缝和编辑器集成到了一起,数据自动按文档内容保存了

不能自动保存, 因为有许多配置项需要有需求的用户手动选择

飞书集成了draw.io 就是自动保存的,辛苦大佬再研究下~~

@Zuoqiu-Yingyi
Copy link
Owner

飞书集成了draw.io 就是自动保存的,辛苦大佬再研究下~~

飞书没开源呀👀

@crendy
Copy link
Author

crendy commented Sep 15, 2022

飞书集成了draw.io 就是自动保存的,辛苦大佬再研究下~~

飞书没开源呀👀

哈哈,另外保存完 可以变成预览模式的,也就是打开文档默认是预览模式,双击进入编辑模式,我找了一个文档不知道有没有用:https://blog.51cto.com/waxyz/5335947

@crendy
Copy link
Author

crendy commented Sep 15, 2022

26135148_628f15745878416722

@Zuoqiu-Yingyi
Copy link
Owner

26135148_628f15745878416722 26135148_628f15745878416722

试试 cover-drawio 这个挂件, 就是做这个的

@crendy
Copy link
Author

crendy commented Sep 28, 2022

在现在的基础上,点击保存,可以直接不弹下面这个弹窗,直接选择思源进行保存吗?使用思源笔记的应该绝大部分直接保存到思源的
image

@Zuoqiu-Yingyi
Copy link
Owner

在现在的基础上,点击保存,可以直接不弹下面这个弹窗,直接选择思源进行保存吗?使用思源笔记的应该绝大部分直接保存到思源的 image

不太好搞, 因为当前方案是直接 hack 了原来的另存为文件方法(如下所示), 如果有更好的方案欢迎贡献一下~

// 思源笔记保存
function siyuanSave(img, title) {
var button = document.createElement('a');
button.style.overflow = 'hidden';
var logo = document.createElement('img');
logo.src = img;
logo.setAttribute('border', '0');
logo.setAttribute('align', 'absmiddle');
logo.style.width = '60px';
logo.style.height = '60px';
logo.style.paddingBottom = '6px';
button.style.display = 'inline-block';
button.className = 'geBaseButton';
button.style.position = 'relative';
button.style.margin = '4px';
button.style.padding = '8px 8px 10px 8px';
button.style.whiteSpace = 'nowrap';
button.appendChild(logo);
button.style.color = 'gray';
button.style.fontSize = '11px';
var label = document.createElement('div');
button.appendChild(label);
mxUtils.write(label, title);
mxEvent.addListener(button, 'click', async () => {
let id = (window.frameElement != null
? window.frameElement.parentElement.parentElement.dataset.nodeId
: null)
|| (new URL(window.location.href)).searchParams.get('id')
|| null;
// console.log(id);
function filenameParse(filename) {
// 提取主文件名与文件扩展名
let idx2 = filename.lastIndexOf('.drawio.');
let idx = (idx2 > 0) ? idx2 : filename.lastIndexOf('.');
let file_name_main = idx > 0 ? filename.substring(0, idx) : filename;
let file_name_ext = idx > 0 ? filename.substring(filename.lastIndexOf('.') + 1) : 'drawio';
filename = `${file_name_main}.${file_name_ext}`;
return { name: filename, main: file_name_main, ext: file_name_ext };
}
async function saveDataToSiyuan(filename, format, filedata, mime, base64Encoded) {
// 上传至资源文件夹
let { name, ext } = filenameParse(filename);
let blob = new Blob([filedata], { type: mime });
let file = new File([blob], name, { lastModified: Date.now() });
let formdata = new FormData();
formdata.append("assetsDirPath", "/assets/");
formdata.append("file[]", file);
fetch("/api/asset/upload", {
body: formdata,
method: "POST",
// headers: { Authorization: "Token " + this.apitoken },
}).then((response) => {
return response.json();
}).then((data) => {
// console.log(data);
let asset = data.data.succMap[name];
console.log(asset);
if (!asset.endsWith(name)) {
// 文件名更改
let markdown;
switch (ext) {
case 'svg':
case 'png':
markdown = `![](${asset})`;
break;
default:
markdown = '';
break;
}
// console.log(filename, asset);
fetch('/api/attr/setBlockAttrs', {
body: JSON.stringify({
id: id,
attrs: {
'custom-data-assets': asset,
'data-assets': asset,
'data-export-md': markdown,
},
}),
method: 'POST',
}).then((response) => {
return response.json();
}).then((data) => {
if (data.code == 0) {
let name = asset.substring(asset.lastIndexOf('/') + 1);
// console.log(editorUi);
editorUi.getCurrentFile().rename(name);
let url = new URL(window.location.href);
url.hash = `#U${url.origin}/${asset}`
console.log(url.href);
// REF [js修改url参数,无刷新更换页面url - 放飞的回忆 - 博客园](https://www.cnblogs.com/ziyoublog/p/9776764.html)
history.pushState(null, null, url.href)
editorUi.hideDialog();
editorUi.editor.setStatus(mxResources.get('allChangesSaved'));
}
})
} else {
editorUi.hideDialog();
editorUi.editor.setStatus(mxResources.get('allChangesSaved'));
}
});
};
if (id != null) {
// change(App.MODE_DEVICE);
let filename = filenameParse(nameInput.value);
file_name = filename.name;
file_name_main = filename.main;
file_name_ext = filename.ext;
let file_content = null;
let file_type = null;
// 根据文件扩展名调用不同的保存方法
switch (file_name_ext) {
case 'jpg':
case 'pdf':
case 'vsdx':
default:
return;
case 'drawio':
file_content = editorUi.getFileData(
true,
null,
null,
null,
true, // ignoreSelection, // 是否仅保存选中内容
false, // currentPage, // 是否仅保存当前页面
null,
null,
null,
true, // uncompressed, // 是否格式化 XML 文本
);
// console.log(file_content);
file_type = "application/xml";
saveDataToSiyuan(file_name, null, file_content, file_type, null);
break;
case 'png':
return;
// editorUi.showExportDialog(
// mxResources.get('formatPng'),
// true,
// mxResources.get('save'),
// 'https://www.diagrams.net/doc/faq/export-diagram',
// mxUtils.bind(this, function (scale, transparentBackground, ignoreSelection, addShadow, editable,
// embedImages, border, cropImage, currentPage, dummy, grid, keepTheme, exportType) {
// var val = parseInt(scale);
// if (!isNaN(val) && val > 0) {
// let temp_isLocalFileSave = editorUi.isLocalFileSave;
// let temp_saveData = editorUi.saveData;
// let temp_getBaseFilename = editorUi.getBaseFilename;
// editorUi.isLocalFileSave = () => { return true; };
// editorUi.saveData = saveDataToSiyuan;
// editorUi.getBaseFilename = (_) => { return file_name_main; };
// editorUi.exportImage(val / 100, transparentBackground, ignoreSelection,
// addShadow, editable, border, !cropImage, false, null, grid, null,
// keepTheme, exportType);
// editorUi.isLocalFileSave = temp_isLocalFileSave;
// editorUi.saveData = temp_saveData;
// editorUi.getBaseFilename = temp_getBaseFilename;
// }
// }),
// true,
// Editor.defaultIncludeDiagram,
// 'png',
// true,
// );
break;
case 'svg':
/**
* ~/js/diagramly/EditorUi.js -> EditorUi.prototype.showExportDialog
* REF ~/js/diagramly/Menus.js -> editorUi.showExportDialog(mxResources.get('formatSvg')
*/
editorUi.showExportDialog(
mxResources.get('formatSvg'),
true,
mxResources.get('save'),
'https://www.diagrams.net/doc/faq/export-diagram',
mxUtils.bind(this, function (scale, transparentBackground, ignoreSelection,
addShadow, editable, embedImages, border, cropImage, currentPage,
linkTarget, grid, keepTheme, exportType, embedFonts, lblToSvg) {
var val = parseInt(scale);
if (!isNaN(val) && val > 0) {
let temp_isLocalFileSave = editorUi.isLocalFileSave;
let temp_saveData = editorUi.saveData;
let temp_getBaseFilename = editorUi.getBaseFilename;
editorUi.isLocalFileSave = () => { return true; };
editorUi.saveData = saveDataToSiyuan;
editorUi.getBaseFilename = (_) => { return file_name_main; };
editorUi.exportSvg(val / 100, transparentBackground, ignoreSelection,
addShadow, editable, embedImages, border, !cropImage, false,
linkTarget, keepTheme, exportType, embedFonts);
editorUi.isLocalFileSave = temp_isLocalFileSave;
editorUi.saveData = temp_saveData;
editorUi.getBaseFilename = temp_getBaseFilename;
}
}),
true,
null,
'svg',
true,
);
break;
case 'html':
/**
* ~/js/diagramly/EditorUi.js -> EditorUi.prototype.showHtmlDialog
* REF ~/js/diagramly/Menus.js -> editorUi.showHtmlDialog(mxResources.get('export')
*/
editorUi.showHtmlDialog(
mxResources.get('create'),
'https://www.diagrams.net/doc/faq/embed-html-options',
null,
function (publicUrl, zoomEnabled, initialZoom, linkTarget, linkColor, fit, allPages, layers, tags, lightbox, editLink) {
/**
* ~/js/diagramly/EditorUi.js -> EditorUi.prototype.createHtml
* REF ~/js/diagramly/Menus.js -> editorUi.showHtmlDialog(mxResources.get('export')
*/
editorUi.createHtml(publicUrl, zoomEnabled, initialZoom, linkTarget, linkColor, fit, allPages, layers, tags, lightbox, editLink, mxUtils.bind(this, function (html, scriptTag) {
scriptTag = `<script type="text/javascript" src="${window.DRAWIO_VIEWER_URL}"></script>`;
/**
* ~/js/diagramly/dialogs.js -> EmbedDialog
*/
let EmbedDialog = function (editorUi, result, timeout, ignoreSize, previewFn, title, tweet, previewTitle, filename) {
tweet = (tweet != null) ? tweet : 'Check out the diagram I made using @drawio';
var div = document.createElement('div');
var maxSize = 500000;
var maxFbSize = 51200;
var maxTwitterSize = 7168;
// Checks if result is a link
var validUrl = /^https?:\/\//.test(result) || /^mailto:\/\//.test(result);
if (title != null) {
mxUtils.write(div, title);
}
else {
mxUtils.write(div, mxResources.get((result.length < maxSize) ?
((validUrl) ? 'link' : 'mainEmbedNotice') : 'preview') + ':');
}
mxUtils.br(div);
var size = document.createElement('div');
size.style.position = 'absolute';
size.style.top = '30px';
size.style.right = '30px';
size.style.color = 'gray';
mxUtils.write(size, editorUi.formatFileSize(result.length));
div.appendChild(size);
// Using DIV for faster rendering
var text = document.createElement('textarea');
text.setAttribute('autocomplete', 'off');
text.setAttribute('autocorrect', 'off');
text.setAttribute('autocapitalize', 'off');
text.setAttribute('spellcheck', 'false');
text.style.fontFamily = 'monospace';
text.style.wordBreak = 'break-all';
text.style.marginTop = '10px';
text.style.resize = 'none';
text.style.height = '150px';
text.style.width = '440px';
text.style.border = '1px solid gray';
text.value = mxResources.get('updatingDocument');
div.appendChild(text);
mxUtils.br(div);
this.init = function () {
window.setTimeout(function () {
if (result.length < maxSize) {
text.value = result;
text.focus();
if (mxClient.IS_GC || mxClient.IS_FF || document.documentMode >= 5) {
text.select();
}
else {
document.execCommand('selectAll', false, null);
}
}
else {
text.setAttribute('readonly', 'true');
text.value = mxResources.get('tooLargeUseDownload');
}
}, 0);
};
var buttons = document.createElement('div');
buttons.style.position = 'absolute';
buttons.style.bottom = '36px';
buttons.style.right = '32px';
var previewBtn = null;
// Loads forever in IE9
if (EmbedDialog.showPreviewOption && (!mxClient.IS_CHROMEAPP || validUrl) && !navigator.standalone && (validUrl ||
(mxClient.IS_SVG && (document.documentMode == null || document.documentMode > 9)))) {
previewBtn = mxUtils.button((previewTitle != null) ? previewTitle :
mxResources.get((result.length < maxSize) ? 'preview' : 'openInNewWindow'), function () {
var value = (result.length < maxSize) ? text.value : result;
if (previewFn != null) {
previewFn(value);
}
else {
if (validUrl) {
try {
var win = editorUi.openLink(value);
if (win != null && (timeout == null || timeout > 0)) {
window.setTimeout(mxUtils.bind(this, function () {
try {
if (win != null && win.location.href != null &&
win.location.href.substring(0, 8) != value.substring(0, 8)) {
win.close();
editorUi.handleError({ message: mxResources.get('drawingTooLarge') });
}
}
catch (e) {
// ignore
}
}), timeout || 500);
}
}
catch (e) {
editorUi.handleError({ message: e.message || mxResources.get('drawingTooLarge') });
}
}
else {
var wnd = window.open();
var doc = (wnd != null) ? wnd.document : null;
if (doc != null) {
doc.writeln('<html><head><title>' + encodeURIComponent(mxResources.get('preview')) +
'</title><meta charset="utf-8"></head>' +
'<body>' + result + '</body></html>');
doc.close();
}
else {
editorUi.handleError({ message: mxResources.get('errorUpdatingPreview') });
}
}
}
});
previewBtn.className = 'geBtn';
buttons.appendChild(previewBtn);
}
if (!validUrl || result.length > 7500) {
var downloadBtn = mxUtils.button(mxResources.get('download'), function () {
editorUi.hideDialog();
editorUi.saveData((filename != null) ? filename : 'embed.txt', 'txt', result, 'text/plain');
});
downloadBtn.className = 'geBtn';
buttons.appendChild(downloadBtn);
}
// Twitter-intent does not allow more characters, must be pasted manually
if (validUrl && (!editorUi.isOffline() || mxClient.IS_CHROMEAPP)) {
if (result.length < maxFbSize) {
var fbBtn = mxUtils.button('', function () {
try {
var url = 'https://www.facebook.com/sharer.php?p[url]=' +
encodeURIComponent(text.value);
editorUi.openLink(url);
}
catch (e) {
editorUi.handleError({ message: e.message || mxResources.get('drawingTooLarge') });
}
});
var img = document.createElement('img');
img.setAttribute('src', Editor.facebookImage);
img.setAttribute('width', '18');
img.setAttribute('height', '18');
img.setAttribute('border', '0');
fbBtn.appendChild(img);
fbBtn.setAttribute('title', mxResources.get('facebook') + ' (' +
editorUi.formatFileSize(maxFbSize) + ' max)');
fbBtn.style.verticalAlign = 'bottom';
fbBtn.style.paddingTop = '4px';
fbBtn.style.minWidth = '46px'
fbBtn.className = 'geBtn';
buttons.appendChild(fbBtn);
}
if (result.length < maxTwitterSize) {
var tweetBtn = mxUtils.button('', function () {
try {
var url = 'https://twitter.com/intent/tweet?text=' +
encodeURIComponent(tweet) + '&url=' +
encodeURIComponent(text.value);
editorUi.openLink(url);
}
catch (e) {
editorUi.handleError({ message: e.message || mxResources.get('drawingTooLarge') });
}
});
var img = document.createElement('img');
img.setAttribute('src', Editor.tweetImage);
img.setAttribute('width', '18');
img.setAttribute('height', '18');
img.setAttribute('border', '0');
img.style.marginBottom = '5px'
tweetBtn.appendChild(img);
tweetBtn.setAttribute('title', mxResources.get('twitter') + ' (' +
editorUi.formatFileSize(maxTwitterSize) + ' max)');
tweetBtn.style.verticalAlign = 'bottom';
tweetBtn.style.paddingTop = '4px';
tweetBtn.style.minWidth = '46px'
tweetBtn.className = 'geBtn';
buttons.appendChild(tweetBtn);
}
}
if (!editorUi.isOffline() && result.length < maxSize) {
var emailBtn = mxUtils.button('', function () {
try {
var url = 'mailto:?subject=' +
encodeURIComponent(filename || editorUi.defaultFilename) + '&body=' +
encodeURIComponent(text.value);
editorUi.openLink(url);
}
catch (e) {
editorUi.handleError({ message: e.message || mxResources.get('drawingTooLarge') });
}
});
var img = document.createElement('img');
img.setAttribute('src', Editor.mailImage);
img.setAttribute('width', '18');
img.setAttribute('height', '18');
img.setAttribute('border', '0');
img.style.marginBottom = '5px'
if (Editor.isDarkMode()) {
img.style.filter = 'invert(100%)';
}
emailBtn.appendChild(img);
emailBtn.style.verticalAlign = 'bottom';
emailBtn.style.paddingTop = '4px';
emailBtn.style.minWidth = '46px'
emailBtn.className = 'geBtn';
buttons.appendChild(emailBtn);
}
var closeBtn = mxUtils.button(mxResources.get('close'), function () {
editorUi.hideDialog();
});
buttons.appendChild(closeBtn);
var copyBtn = mxUtils.button(mxResources.get('copy'), function () {
text.focus();
if (mxClient.IS_GC || mxClient.IS_FF || document.documentMode >= 5) {
text.select();
}
else {
document.execCommand('selectAll', false, null);
}
document.execCommand('copy');
editorUi.alert(mxResources.get('copiedToClipboard'));
});
/* 👇 保存按钮单击事件处理器 👇 */
var saveBtn = mxUtils.button(mxResources.get('save'), function () {
editorUi.hideDialog();
saveDataToSiyuan(file_name, null, html.replace(/<\/div>\s*$/, `${scriptTag}<\/div>\n`), 'text/html', null);
});
/* 👆 保存按钮单击事件处理器 👆 */
if (result.length < maxSize) {
// Does not work in Safari and shows annoying dialog for IE11-
if (!mxClient.IS_SF && document.documentMode == null) {
buttons.appendChild(copyBtn);
copyBtn.className = 'geBtn gePrimaryBtn';
closeBtn.className = 'geBtn';
/* 👇 添加保存按钮 👇 */
buttons.appendChild(saveBtn);
saveBtn.className = 'geBtn gePrimaryBtn';
/* 👆 添加保存按钮 👆 */
}
else {
closeBtn.className = 'geBtn gePrimaryBtn';
}
}
else {
buttons.appendChild(previewBtn);
closeBtn.className = 'geBtn';
previewBtn.className = 'geBtn gePrimaryBtn';
}
div.appendChild(buttons);
this.container = div;
};
var dlg = new EmbedDialog(editorUi, html + '\n' + scriptTag, null, null, function () {
var wnd = window.open();
var doc = wnd.document;
if (doc != null) {
if (document.compatMode === 'CSS1Compat') {
doc.writeln('<!DOCTYPE html>');
}
doc.writeln('<html>');
doc.writeln('<head><title>' + encodeURIComponent(mxResources.get('preview')) +
'</title><meta charset="utf-8"></head>');
doc.writeln('<body>');
doc.writeln(html);
var direct = mxClient.IS_IE || mxClient.IS_EDGE || document.documentMode != null;
if (direct) {
doc.writeln(scriptTag);
}
doc.writeln('</body>');
doc.writeln('</html>');
doc.close();
// Adds script tag after closing page and delay to fix timing issues
if (!direct) {
var info = wnd.document.createElement('div');
info.marginLeft = '26px';
info.marginTop = '26px';
mxUtils.write(info, mxResources.get('updatingDocument'));
var img = wnd.document.createElement('img');
img.setAttribute('src', window.location.protocol + '//' + window.location.hostname +
'/' + IMAGE_PATH + '/spin.gif');
img.style.marginLeft = '6px';
info.appendChild(img);
wnd.document.body.insertBefore(info, wnd.document.body.firstChild);
window.setTimeout(function () {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = /<script.*?src="(.*?)"/.exec(scriptTag)[1];
doc.body.appendChild(script);
info.parentNode.removeChild(info);
}, 20);
}
}
else {
editorUi.handleError({ message: mxResources.get('errorUpdatingPreview') });
}
});
editorUi.showDialog(dlg.container, 450, 240, true, true);
dlg.init();
}));
}
);
break;
case 'xml':
/**
* REF ~/js/diagramly/Menus.js -> editorUi.actions.put('exportXml'
*/
let div = document.createElement('div');
div.style.whiteSpace = 'nowrap';
let noPages = editorUi.pages == null || editorUi.pages.length <= 1;
let hd = document.createElement('h3');
mxUtils.write(hd, mxResources.get('formatXml'));
hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:4px';
div.appendChild(hd);
let selection = editorUi.addCheckbox(div, mxResources.get('selectionOnly'),
false, editorUi.editor.graph.isSelectionEmpty());
let compressed = editorUi.addCheckbox(div, mxResources.get('compressed'), true);
let pages = editorUi.addCheckbox(div, mxResources.get('allPages'), !noPages, noPages);
pages.style.marginBottom = '16px';
mxEvent.addListener(selection, 'change', function () {
if (selection.checked) {
pages.setAttribute('disabled', 'disabled');
}
else {
pages.removeAttribute('disabled');
}
});
let dlg = new CustomDialog(editorUi, div, mxUtils.bind(this, function () {
let temp_isLocalFileSave = editorUi.isLocalFileSave;
let temp_saveData = editorUi.saveData;
let temp_getBaseFilename = editorUi.getBaseFilename;
editorUi.isLocalFileSave = () => { return true; };
editorUi.saveData = saveDataToSiyuan;
editorUi.getBaseFilename = (_) => { return file_name_main; };
editorUi.downloadFile('xml', !compressed.checked, null, !selection.checked, noPages || !pages.checked);
editorUi.isLocalFileSave = temp_isLocalFileSave;
editorUi.saveData = temp_saveData;
editorUi.getBaseFilename = temp_getBaseFilename;
}), null, mxResources.get('save'));
editorUi.showDialog(dlg.container, 300, 200, true, true);
break;
}
}
});
buttons.appendChild(button);
if (++count == rowLimit) {
mxUtils.br(buttons);
count = 0;
}
};

@crendy
Copy link
Author

crendy commented Oct 9, 2022

在现在的基础上,点击保存,可以直接不弹下面这个弹窗,直接选择思源进行保存吗?使用思源笔记的应该绝大部分直接保存到思源的 image

不太好搞, 因为当前方案是直接 hack 了原来的另存为文件方法(如下所示), 如果有更好的方案欢迎贡献一下~

// 思源笔记保存
function siyuanSave(img, title) {
var button = document.createElement('a');
button.style.overflow = 'hidden';
var logo = document.createElement('img');
logo.src = img;
logo.setAttribute('border', '0');
logo.setAttribute('align', 'absmiddle');
logo.style.width = '60px';
logo.style.height = '60px';
logo.style.paddingBottom = '6px';
button.style.display = 'inline-block';
button.className = 'geBaseButton';
button.style.position = 'relative';
button.style.margin = '4px';
button.style.padding = '8px 8px 10px 8px';
button.style.whiteSpace = 'nowrap';
button.appendChild(logo);
button.style.color = 'gray';
button.style.fontSize = '11px';
var label = document.createElement('div');
button.appendChild(label);
mxUtils.write(label, title);
mxEvent.addListener(button, 'click', async () => {
let id = (window.frameElement != null
? window.frameElement.parentElement.parentElement.dataset.nodeId
: null)
|| (new URL(window.location.href)).searchParams.get('id')
|| null;
// console.log(id);
function filenameParse(filename) {
// 提取主文件名与文件扩展名
let idx2 = filename.lastIndexOf('.drawio.');
let idx = (idx2 > 0) ? idx2 : filename.lastIndexOf('.');
let file_name_main = idx > 0 ? filename.substring(0, idx) : filename;
let file_name_ext = idx > 0 ? filename.substring(filename.lastIndexOf('.') + 1) : 'drawio';
filename = `${file_name_main}.${file_name_ext}`;
return { name: filename, main: file_name_main, ext: file_name_ext };
}
async function saveDataToSiyuan(filename, format, filedata, mime, base64Encoded) {
// 上传至资源文件夹
let { name, ext } = filenameParse(filename);
let blob = new Blob([filedata], { type: mime });
let file = new File([blob], name, { lastModified: Date.now() });
let formdata = new FormData();
formdata.append("assetsDirPath", "/assets/");
formdata.append("file[]", file);
fetch("/api/asset/upload", {
body: formdata,
method: "POST",
// headers: { Authorization: "Token " + this.apitoken },
}).then((response) => {
return response.json();
}).then((data) => {
// console.log(data);
let asset = data.data.succMap[name];
console.log(asset);
if (!asset.endsWith(name)) {
// 文件名更改
let markdown;
switch (ext) {
case 'svg':
case 'png':
markdown = `![](${asset})`;
break;
default:
markdown = '';
break;
}
// console.log(filename, asset);
fetch('/api/attr/setBlockAttrs', {
body: JSON.stringify({
id: id,
attrs: {
'custom-data-assets': asset,
'data-assets': asset,
'data-export-md': markdown,
},
}),
method: 'POST',
}).then((response) => {
return response.json();
}).then((data) => {
if (data.code == 0) {
let name = asset.substring(asset.lastIndexOf('/') + 1);
// console.log(editorUi);
editorUi.getCurrentFile().rename(name);
let url = new URL(window.location.href);
url.hash = `#U${url.origin}/${asset}`
console.log(url.href);
// REF [js修改url参数,无刷新更换页面url - 放飞的回忆 - 博客园](https://www.cnblogs.com/ziyoublog/p/9776764.html)
history.pushState(null, null, url.href)
editorUi.hideDialog();
editorUi.editor.setStatus(mxResources.get('allChangesSaved'));
}
})
} else {
editorUi.hideDialog();
editorUi.editor.setStatus(mxResources.get('allChangesSaved'));
}
});
};
if (id != null) {
// change(App.MODE_DEVICE);
let filename = filenameParse(nameInput.value);
file_name = filename.name;
file_name_main = filename.main;
file_name_ext = filename.ext;
let file_content = null;
let file_type = null;
// 根据文件扩展名调用不同的保存方法
switch (file_name_ext) {
case 'jpg':
case 'pdf':
case 'vsdx':
default:
return;
case 'drawio':
file_content = editorUi.getFileData(
true,
null,
null,
null,
true, // ignoreSelection, // 是否仅保存选中内容
false, // currentPage, // 是否仅保存当前页面
null,
null,
null,
true, // uncompressed, // 是否格式化 XML 文本
);
// console.log(file_content);
file_type = "application/xml";
saveDataToSiyuan(file_name, null, file_content, file_type, null);
break;
case 'png':
return;
// editorUi.showExportDialog(
// mxResources.get('formatPng'),
// true,
// mxResources.get('save'),
// 'https://www.diagrams.net/doc/faq/export-diagram',
// mxUtils.bind(this, function (scale, transparentBackground, ignoreSelection, addShadow, editable,
// embedImages, border, cropImage, currentPage, dummy, grid, keepTheme, exportType) {
// var val = parseInt(scale);
// if (!isNaN(val) && val > 0) {
// let temp_isLocalFileSave = editorUi.isLocalFileSave;
// let temp_saveData = editorUi.saveData;
// let temp_getBaseFilename = editorUi.getBaseFilename;
// editorUi.isLocalFileSave = () => { return true; };
// editorUi.saveData = saveDataToSiyuan;
// editorUi.getBaseFilename = (_) => { return file_name_main; };
// editorUi.exportImage(val / 100, transparentBackground, ignoreSelection,
// addShadow, editable, border, !cropImage, false, null, grid, null,
// keepTheme, exportType);
// editorUi.isLocalFileSave = temp_isLocalFileSave;
// editorUi.saveData = temp_saveData;
// editorUi.getBaseFilename = temp_getBaseFilename;
// }
// }),
// true,
// Editor.defaultIncludeDiagram,
// 'png',
// true,
// );
break;
case 'svg':
/**
* ~/js/diagramly/EditorUi.js -> EditorUi.prototype.showExportDialog
* REF ~/js/diagramly/Menus.js -> editorUi.showExportDialog(mxResources.get('formatSvg')
*/
editorUi.showExportDialog(
mxResources.get('formatSvg'),
true,
mxResources.get('save'),
'https://www.diagrams.net/doc/faq/export-diagram',
mxUtils.bind(this, function (scale, transparentBackground, ignoreSelection,
addShadow, editable, embedImages, border, cropImage, currentPage,
linkTarget, grid, keepTheme, exportType, embedFonts, lblToSvg) {
var val = parseInt(scale);
if (!isNaN(val) && val > 0) {
let temp_isLocalFileSave = editorUi.isLocalFileSave;
let temp_saveData = editorUi.saveData;
let temp_getBaseFilename = editorUi.getBaseFilename;
editorUi.isLocalFileSave = () => { return true; };
editorUi.saveData = saveDataToSiyuan;
editorUi.getBaseFilename = (_) => { return file_name_main; };
editorUi.exportSvg(val / 100, transparentBackground, ignoreSelection,
addShadow, editable, embedImages, border, !cropImage, false,
linkTarget, keepTheme, exportType, embedFonts);
editorUi.isLocalFileSave = temp_isLocalFileSave;
editorUi.saveData = temp_saveData;
editorUi.getBaseFilename = temp_getBaseFilename;
}
}),
true,
null,
'svg',
true,
);
break;
case 'html':
/**
* ~/js/diagramly/EditorUi.js -> EditorUi.prototype.showHtmlDialog
* REF ~/js/diagramly/Menus.js -> editorUi.showHtmlDialog(mxResources.get('export')
*/
editorUi.showHtmlDialog(
mxResources.get('create'),
'https://www.diagrams.net/doc/faq/embed-html-options',
null,
function (publicUrl, zoomEnabled, initialZoom, linkTarget, linkColor, fit, allPages, layers, tags, lightbox, editLink) {
/**
* ~/js/diagramly/EditorUi.js -> EditorUi.prototype.createHtml
* REF ~/js/diagramly/Menus.js -> editorUi.showHtmlDialog(mxResources.get('export')
*/
editorUi.createHtml(publicUrl, zoomEnabled, initialZoom, linkTarget, linkColor, fit, allPages, layers, tags, lightbox, editLink, mxUtils.bind(this, function (html, scriptTag) {
scriptTag = `<script type="text/javascript" src="${window.DRAWIO_VIEWER_URL}"></script>`;
/**
* ~/js/diagramly/dialogs.js -> EmbedDialog
*/
let EmbedDialog = function (editorUi, result, timeout, ignoreSize, previewFn, title, tweet, previewTitle, filename) {
tweet = (tweet != null) ? tweet : 'Check out the diagram I made using @drawio';
var div = document.createElement('div');
var maxSize = 500000;
var maxFbSize = 51200;
var maxTwitterSize = 7168;
// Checks if result is a link
var validUrl = /^https?:\/\//.test(result) || /^mailto:\/\//.test(result);
if (title != null) {
mxUtils.write(div, title);
}
else {
mxUtils.write(div, mxResources.get((result.length < maxSize) ?
((validUrl) ? 'link' : 'mainEmbedNotice') : 'preview') + ':');
}
mxUtils.br(div);
var size = document.createElement('div');
size.style.position = 'absolute';
size.style.top = '30px';
size.style.right = '30px';
size.style.color = 'gray';
mxUtils.write(size, editorUi.formatFileSize(result.length));
div.appendChild(size);
// Using DIV for faster rendering
var text = document.createElement('textarea');
text.setAttribute('autocomplete', 'off');
text.setAttribute('autocorrect', 'off');
text.setAttribute('autocapitalize', 'off');
text.setAttribute('spellcheck', 'false');
text.style.fontFamily = 'monospace';
text.style.wordBreak = 'break-all';
text.style.marginTop = '10px';
text.style.resize = 'none';
text.style.height = '150px';
text.style.width = '440px';
text.style.border = '1px solid gray';
text.value = mxResources.get('updatingDocument');
div.appendChild(text);
mxUtils.br(div);
this.init = function () {
window.setTimeout(function () {
if (result.length < maxSize) {
text.value = result;
text.focus();
if (mxClient.IS_GC || mxClient.IS_FF || document.documentMode >= 5) {
text.select();
}
else {
document.execCommand('selectAll', false, null);
}
}
else {
text.setAttribute('readonly', 'true');
text.value = mxResources.get('tooLargeUseDownload');
}
}, 0);
};
var buttons = document.createElement('div');
buttons.style.position = 'absolute';
buttons.style.bottom = '36px';
buttons.style.right = '32px';
var previewBtn = null;
// Loads forever in IE9
if (EmbedDialog.showPreviewOption && (!mxClient.IS_CHROMEAPP || validUrl) && !navigator.standalone && (validUrl ||
(mxClient.IS_SVG && (document.documentMode == null || document.documentMode > 9)))) {
previewBtn = mxUtils.button((previewTitle != null) ? previewTitle :
mxResources.get((result.length < maxSize) ? 'preview' : 'openInNewWindow'), function () {
var value = (result.length < maxSize) ? text.value : result;
if (previewFn != null) {
previewFn(value);
}
else {
if (validUrl) {
try {
var win = editorUi.openLink(value);
if (win != null && (timeout == null || timeout > 0)) {
window.setTimeout(mxUtils.bind(this, function () {
try {
if (win != null && win.location.href != null &&
win.location.href.substring(0, 8) != value.substring(0, 8)) {
win.close();
editorUi.handleError({ message: mxResources.get('drawingTooLarge') });
}
}
catch (e) {
// ignore
}
}), timeout || 500);
}
}
catch (e) {
editorUi.handleError({ message: e.message || mxResources.get('drawingTooLarge') });
}
}
else {
var wnd = window.open();
var doc = (wnd != null) ? wnd.document : null;
if (doc != null) {
doc.writeln('<html><head><title>' + encodeURIComponent(mxResources.get('preview')) +
'</title><meta charset="utf-8"></head>' +
'<body>' + result + '</body></html>');
doc.close();
}
else {
editorUi.handleError({ message: mxResources.get('errorUpdatingPreview') });
}
}
}
});
previewBtn.className = 'geBtn';
buttons.appendChild(previewBtn);
}
if (!validUrl || result.length > 7500) {
var downloadBtn = mxUtils.button(mxResources.get('download'), function () {
editorUi.hideDialog();
editorUi.saveData((filename != null) ? filename : 'embed.txt', 'txt', result, 'text/plain');
});
downloadBtn.className = 'geBtn';
buttons.appendChild(downloadBtn);
}
// Twitter-intent does not allow more characters, must be pasted manually
if (validUrl && (!editorUi.isOffline() || mxClient.IS_CHROMEAPP)) {
if (result.length < maxFbSize) {
var fbBtn = mxUtils.button('', function () {
try {
var url = 'https://www.facebook.com/sharer.php?p[url]=' +
encodeURIComponent(text.value);
editorUi.openLink(url);
}
catch (e) {
editorUi.handleError({ message: e.message || mxResources.get('drawingTooLarge') });
}
});
var img = document.createElement('img');
img.setAttribute('src', Editor.facebookImage);
img.setAttribute('width', '18');
img.setAttribute('height', '18');
img.setAttribute('border', '0');
fbBtn.appendChild(img);
fbBtn.setAttribute('title', mxResources.get('facebook') + ' (' +
editorUi.formatFileSize(maxFbSize) + ' max)');
fbBtn.style.verticalAlign = 'bottom';
fbBtn.style.paddingTop = '4px';
fbBtn.style.minWidth = '46px'
fbBtn.className = 'geBtn';
buttons.appendChild(fbBtn);
}
if (result.length < maxTwitterSize) {
var tweetBtn = mxUtils.button('', function () {
try {
var url = 'https://twitter.com/intent/tweet?text=' +
encodeURIComponent(tweet) + '&url=' +
encodeURIComponent(text.value);
editorUi.openLink(url);
}
catch (e) {
editorUi.handleError({ message: e.message || mxResources.get('drawingTooLarge') });
}
});
var img = document.createElement('img');
img.setAttribute('src', Editor.tweetImage);
img.setAttribute('width', '18');
img.setAttribute('height', '18');
img.setAttribute('border', '0');
img.style.marginBottom = '5px'
tweetBtn.appendChild(img);
tweetBtn.setAttribute('title', mxResources.get('twitter') + ' (' +
editorUi.formatFileSize(maxTwitterSize) + ' max)');
tweetBtn.style.verticalAlign = 'bottom';
tweetBtn.style.paddingTop = '4px';
tweetBtn.style.minWidth = '46px'
tweetBtn.className = 'geBtn';
buttons.appendChild(tweetBtn);
}
}
if (!editorUi.isOffline() && result.length < maxSize) {
var emailBtn = mxUtils.button('', function () {
try {
var url = 'mailto:?subject=' +
encodeURIComponent(filename || editorUi.defaultFilename) + '&body=' +
encodeURIComponent(text.value);
editorUi.openLink(url);
}
catch (e) {
editorUi.handleError({ message: e.message || mxResources.get('drawingTooLarge') });
}
});
var img = document.createElement('img');
img.setAttribute('src', Editor.mailImage);
img.setAttribute('width', '18');
img.setAttribute('height', '18');
img.setAttribute('border', '0');
img.style.marginBottom = '5px'
if (Editor.isDarkMode()) {
img.style.filter = 'invert(100%)';
}
emailBtn.appendChild(img);
emailBtn.style.verticalAlign = 'bottom';
emailBtn.style.paddingTop = '4px';
emailBtn.style.minWidth = '46px'
emailBtn.className = 'geBtn';
buttons.appendChild(emailBtn);
}
var closeBtn = mxUtils.button(mxResources.get('close'), function () {
editorUi.hideDialog();
});
buttons.appendChild(closeBtn);
var copyBtn = mxUtils.button(mxResources.get('copy'), function () {
text.focus();
if (mxClient.IS_GC || mxClient.IS_FF || document.documentMode >= 5) {
text.select();
}
else {
document.execCommand('selectAll', false, null);
}
document.execCommand('copy');
editorUi.alert(mxResources.get('copiedToClipboard'));
});
/* 👇 保存按钮单击事件处理器 👇 */
var saveBtn = mxUtils.button(mxResources.get('save'), function () {
editorUi.hideDialog();
saveDataToSiyuan(file_name, null, html.replace(/<\/div>\s*$/, `${scriptTag}<\/div>\n`), 'text/html', null);
});
/* 👆 保存按钮单击事件处理器 👆 */
if (result.length < maxSize) {
// Does not work in Safari and shows annoying dialog for IE11-
if (!mxClient.IS_SF && document.documentMode == null) {
buttons.appendChild(copyBtn);
copyBtn.className = 'geBtn gePrimaryBtn';
closeBtn.className = 'geBtn';
/* 👇 添加保存按钮 👇 */
buttons.appendChild(saveBtn);
saveBtn.className = 'geBtn gePrimaryBtn';
/* 👆 添加保存按钮 👆 */
}
else {
closeBtn.className = 'geBtn gePrimaryBtn';
}
}
else {
buttons.appendChild(previewBtn);
closeBtn.className = 'geBtn';
previewBtn.className = 'geBtn gePrimaryBtn';
}
div.appendChild(buttons);
this.container = div;
};
var dlg = new EmbedDialog(editorUi, html + '\n' + scriptTag, null, null, function () {
var wnd = window.open();
var doc = wnd.document;
if (doc != null) {
if (document.compatMode === 'CSS1Compat') {
doc.writeln('<!DOCTYPE html>');
}
doc.writeln('<html>');
doc.writeln('<head><title>' + encodeURIComponent(mxResources.get('preview')) +
'</title><meta charset="utf-8"></head>');
doc.writeln('<body>');
doc.writeln(html);
var direct = mxClient.IS_IE || mxClient.IS_EDGE || document.documentMode != null;
if (direct) {
doc.writeln(scriptTag);
}
doc.writeln('</body>');
doc.writeln('</html>');
doc.close();
// Adds script tag after closing page and delay to fix timing issues
if (!direct) {
var info = wnd.document.createElement('div');
info.marginLeft = '26px';
info.marginTop = '26px';
mxUtils.write(info, mxResources.get('updatingDocument'));
var img = wnd.document.createElement('img');
img.setAttribute('src', window.location.protocol + '//' + window.location.hostname +
'/' + IMAGE_PATH + '/spin.gif');
img.style.marginLeft = '6px';
info.appendChild(img);
wnd.document.body.insertBefore(info, wnd.document.body.firstChild);
window.setTimeout(function () {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = /<script.*?src="(.*?)"/.exec(scriptTag)[1];
doc.body.appendChild(script);
info.parentNode.removeChild(info);
}, 20);
}
}
else {
editorUi.handleError({ message: mxResources.get('errorUpdatingPreview') });
}
});
editorUi.showDialog(dlg.container, 450, 240, true, true);
dlg.init();
}));
}
);
break;
case 'xml':
/**
* REF ~/js/diagramly/Menus.js -> editorUi.actions.put('exportXml'
*/
let div = document.createElement('div');
div.style.whiteSpace = 'nowrap';
let noPages = editorUi.pages == null || editorUi.pages.length <= 1;
let hd = document.createElement('h3');
mxUtils.write(hd, mxResources.get('formatXml'));
hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:4px';
div.appendChild(hd);
let selection = editorUi.addCheckbox(div, mxResources.get('selectionOnly'),
false, editorUi.editor.graph.isSelectionEmpty());
let compressed = editorUi.addCheckbox(div, mxResources.get('compressed'), true);
let pages = editorUi.addCheckbox(div, mxResources.get('allPages'), !noPages, noPages);
pages.style.marginBottom = '16px';
mxEvent.addListener(selection, 'change', function () {
if (selection.checked) {
pages.setAttribute('disabled', 'disabled');
}
else {
pages.removeAttribute('disabled');
}
});
let dlg = new CustomDialog(editorUi, div, mxUtils.bind(this, function () {
let temp_isLocalFileSave = editorUi.isLocalFileSave;
let temp_saveData = editorUi.saveData;
let temp_getBaseFilename = editorUi.getBaseFilename;
editorUi.isLocalFileSave = () => { return true; };
editorUi.saveData = saveDataToSiyuan;
editorUi.getBaseFilename = (_) => { return file_name_main; };
editorUi.downloadFile('xml', !compressed.checked, null, !selection.checked, noPages || !pages.checked);
editorUi.isLocalFileSave = temp_isLocalFileSave;
editorUi.saveData = temp_saveData;
editorUi.getBaseFilename = temp_getBaseFilename;
}), null, mxResources.get('save'));
editorUi.showDialog(dlg.container, 300, 200, true, true);
break;
}
}
});
buttons.appendChild(button);
if (++count == rowLimit) {
mxUtils.br(buttons);
count = 0;
}
};

不知道这个是否可以参考:https://github.com/timsengit/my-drawio

@Zuoqiu-Yingyi
Copy link
Owner

@crendy 不行😂

@crendy
Copy link
Author

crendy commented Oct 13, 2022

在现在的基础上,点击保存,可以直接不弹下面这个弹窗,直接选择思源进行保存吗?使用思源笔记的应该绝大部分直接保存到思源的 image

不太好搞, 因为当前方案是直接 hack 了原来的另存为文件方法(如下所示), 如果有更好的方案欢迎贡献一下~

// 思源笔记保存
function siyuanSave(img, title) {
var button = document.createElement('a');
button.style.overflow = 'hidden';
var logo = document.createElement('img');
logo.src = img;
logo.setAttribute('border', '0');
logo.setAttribute('align', 'absmiddle');
logo.style.width = '60px';
logo.style.height = '60px';
logo.style.paddingBottom = '6px';
button.style.display = 'inline-block';
button.className = 'geBaseButton';
button.style.position = 'relative';
button.style.margin = '4px';
button.style.padding = '8px 8px 10px 8px';
button.style.whiteSpace = 'nowrap';
button.appendChild(logo);
button.style.color = 'gray';
button.style.fontSize = '11px';
var label = document.createElement('div');
button.appendChild(label);
mxUtils.write(label, title);
mxEvent.addListener(button, 'click', async () => {
let id = (window.frameElement != null
? window.frameElement.parentElement.parentElement.dataset.nodeId
: null)
|| (new URL(window.location.href)).searchParams.get('id')
|| null;
// console.log(id);
function filenameParse(filename) {
// 提取主文件名与文件扩展名
let idx2 = filename.lastIndexOf('.drawio.');
let idx = (idx2 > 0) ? idx2 : filename.lastIndexOf('.');
let file_name_main = idx > 0 ? filename.substring(0, idx) : filename;
let file_name_ext = idx > 0 ? filename.substring(filename.lastIndexOf('.') + 1) : 'drawio';
filename = `${file_name_main}.${file_name_ext}`;
return { name: filename, main: file_name_main, ext: file_name_ext };
}
async function saveDataToSiyuan(filename, format, filedata, mime, base64Encoded) {
// 上传至资源文件夹
let { name, ext } = filenameParse(filename);
let blob = new Blob([filedata], { type: mime });
let file = new File([blob], name, { lastModified: Date.now() });
let formdata = new FormData();
formdata.append("assetsDirPath", "/assets/");
formdata.append("file[]", file);
fetch("/api/asset/upload", {
body: formdata,
method: "POST",
// headers: { Authorization: "Token " + this.apitoken },
}).then((response) => {
return response.json();
}).then((data) => {
// console.log(data);
let asset = data.data.succMap[name];
console.log(asset);
if (!asset.endsWith(name)) {
// 文件名更改
let markdown;
switch (ext) {
case 'svg':
case 'png':
markdown = `![](${asset})`;
break;
default:
markdown = '';
break;
}
// console.log(filename, asset);
fetch('/api/attr/setBlockAttrs', {
body: JSON.stringify({
id: id,
attrs: {
'custom-data-assets': asset,
'data-assets': asset,
'data-export-md': markdown,
},
}),
method: 'POST',
}).then((response) => {
return response.json();
}).then((data) => {
if (data.code == 0) {
let name = asset.substring(asset.lastIndexOf('/') + 1);
// console.log(editorUi);
editorUi.getCurrentFile().rename(name);
let url = new URL(window.location.href);
url.hash = `#U${url.origin}/${asset}`
console.log(url.href);
// REF [js修改url参数,无刷新更换页面url - 放飞的回忆 - 博客园](https://www.cnblogs.com/ziyoublog/p/9776764.html)
history.pushState(null, null, url.href)
editorUi.hideDialog();
editorUi.editor.setStatus(mxResources.get('allChangesSaved'));
}
})
} else {
editorUi.hideDialog();
editorUi.editor.setStatus(mxResources.get('allChangesSaved'));
}
});
};
if (id != null) {
// change(App.MODE_DEVICE);
let filename = filenameParse(nameInput.value);
file_name = filename.name;
file_name_main = filename.main;
file_name_ext = filename.ext;
let file_content = null;
let file_type = null;
// 根据文件扩展名调用不同的保存方法
switch (file_name_ext) {
case 'jpg':
case 'pdf':
case 'vsdx':
default:
return;
case 'drawio':
file_content = editorUi.getFileData(
true,
null,
null,
null,
true, // ignoreSelection, // 是否仅保存选中内容
false, // currentPage, // 是否仅保存当前页面
null,
null,
null,
true, // uncompressed, // 是否格式化 XML 文本
);
// console.log(file_content);
file_type = "application/xml";
saveDataToSiyuan(file_name, null, file_content, file_type, null);
break;
case 'png':
return;
// editorUi.showExportDialog(
// mxResources.get('formatPng'),
// true,
// mxResources.get('save'),
// 'https://www.diagrams.net/doc/faq/export-diagram',
// mxUtils.bind(this, function (scale, transparentBackground, ignoreSelection, addShadow, editable,
// embedImages, border, cropImage, currentPage, dummy, grid, keepTheme, exportType) {
// var val = parseInt(scale);
// if (!isNaN(val) && val > 0) {
// let temp_isLocalFileSave = editorUi.isLocalFileSave;
// let temp_saveData = editorUi.saveData;
// let temp_getBaseFilename = editorUi.getBaseFilename;
// editorUi.isLocalFileSave = () => { return true; };
// editorUi.saveData = saveDataToSiyuan;
// editorUi.getBaseFilename = (_) => { return file_name_main; };
// editorUi.exportImage(val / 100, transparentBackground, ignoreSelection,
// addShadow, editable, border, !cropImage, false, null, grid, null,
// keepTheme, exportType);
// editorUi.isLocalFileSave = temp_isLocalFileSave;
// editorUi.saveData = temp_saveData;
// editorUi.getBaseFilename = temp_getBaseFilename;
// }
// }),
// true,
// Editor.defaultIncludeDiagram,
// 'png',
// true,
// );
break;
case 'svg':
/**
* ~/js/diagramly/EditorUi.js -> EditorUi.prototype.showExportDialog
* REF ~/js/diagramly/Menus.js -> editorUi.showExportDialog(mxResources.get('formatSvg')
*/
editorUi.showExportDialog(
mxResources.get('formatSvg'),
true,
mxResources.get('save'),
'https://www.diagrams.net/doc/faq/export-diagram',
mxUtils.bind(this, function (scale, transparentBackground, ignoreSelection,
addShadow, editable, embedImages, border, cropImage, currentPage,
linkTarget, grid, keepTheme, exportType, embedFonts, lblToSvg) {
var val = parseInt(scale);
if (!isNaN(val) && val > 0) {
let temp_isLocalFileSave = editorUi.isLocalFileSave;
let temp_saveData = editorUi.saveData;
let temp_getBaseFilename = editorUi.getBaseFilename;
editorUi.isLocalFileSave = () => { return true; };
editorUi.saveData = saveDataToSiyuan;
editorUi.getBaseFilename = (_) => { return file_name_main; };
editorUi.exportSvg(val / 100, transparentBackground, ignoreSelection,
addShadow, editable, embedImages, border, !cropImage, false,
linkTarget, keepTheme, exportType, embedFonts);
editorUi.isLocalFileSave = temp_isLocalFileSave;
editorUi.saveData = temp_saveData;
editorUi.getBaseFilename = temp_getBaseFilename;
}
}),
true,
null,
'svg',
true,
);
break;
case 'html':
/**
* ~/js/diagramly/EditorUi.js -> EditorUi.prototype.showHtmlDialog
* REF ~/js/diagramly/Menus.js -> editorUi.showHtmlDialog(mxResources.get('export')
*/
editorUi.showHtmlDialog(
mxResources.get('create'),
'https://www.diagrams.net/doc/faq/embed-html-options',
null,
function (publicUrl, zoomEnabled, initialZoom, linkTarget, linkColor, fit, allPages, layers, tags, lightbox, editLink) {
/**
* ~/js/diagramly/EditorUi.js -> EditorUi.prototype.createHtml
* REF ~/js/diagramly/Menus.js -> editorUi.showHtmlDialog(mxResources.get('export')
*/
editorUi.createHtml(publicUrl, zoomEnabled, initialZoom, linkTarget, linkColor, fit, allPages, layers, tags, lightbox, editLink, mxUtils.bind(this, function (html, scriptTag) {
scriptTag = `<script type="text/javascript" src="${window.DRAWIO_VIEWER_URL}"></script>`;
/**
* ~/js/diagramly/dialogs.js -> EmbedDialog
*/
let EmbedDialog = function (editorUi, result, timeout, ignoreSize, previewFn, title, tweet, previewTitle, filename) {
tweet = (tweet != null) ? tweet : 'Check out the diagram I made using @drawio';
var div = document.createElement('div');
var maxSize = 500000;
var maxFbSize = 51200;
var maxTwitterSize = 7168;
// Checks if result is a link
var validUrl = /^https?:\/\//.test(result) || /^mailto:\/\//.test(result);
if (title != null) {
mxUtils.write(div, title);
}
else {
mxUtils.write(div, mxResources.get((result.length < maxSize) ?
((validUrl) ? 'link' : 'mainEmbedNotice') : 'preview') + ':');
}
mxUtils.br(div);
var size = document.createElement('div');
size.style.position = 'absolute';
size.style.top = '30px';
size.style.right = '30px';
size.style.color = 'gray';
mxUtils.write(size, editorUi.formatFileSize(result.length));
div.appendChild(size);
// Using DIV for faster rendering
var text = document.createElement('textarea');
text.setAttribute('autocomplete', 'off');
text.setAttribute('autocorrect', 'off');
text.setAttribute('autocapitalize', 'off');
text.setAttribute('spellcheck', 'false');
text.style.fontFamily = 'monospace';
text.style.wordBreak = 'break-all';
text.style.marginTop = '10px';
text.style.resize = 'none';
text.style.height = '150px';
text.style.width = '440px';
text.style.border = '1px solid gray';
text.value = mxResources.get('updatingDocument');
div.appendChild(text);
mxUtils.br(div);
this.init = function () {
window.setTimeout(function () {
if (result.length < maxSize) {
text.value = result;
text.focus();
if (mxClient.IS_GC || mxClient.IS_FF || document.documentMode >= 5) {
text.select();
}
else {
document.execCommand('selectAll', false, null);
}
}
else {
text.setAttribute('readonly', 'true');
text.value = mxResources.get('tooLargeUseDownload');
}
}, 0);
};
var buttons = document.createElement('div');
buttons.style.position = 'absolute';
buttons.style.bottom = '36px';
buttons.style.right = '32px';
var previewBtn = null;
// Loads forever in IE9
if (EmbedDialog.showPreviewOption && (!mxClient.IS_CHROMEAPP || validUrl) && !navigator.standalone && (validUrl ||
(mxClient.IS_SVG && (document.documentMode == null || document.documentMode > 9)))) {
previewBtn = mxUtils.button((previewTitle != null) ? previewTitle :
mxResources.get((result.length < maxSize) ? 'preview' : 'openInNewWindow'), function () {
var value = (result.length < maxSize) ? text.value : result;
if (previewFn != null) {
previewFn(value);
}
else {
if (validUrl) {
try {
var win = editorUi.openLink(value);
if (win != null && (timeout == null || timeout > 0)) {
window.setTimeout(mxUtils.bind(this, function () {
try {
if (win != null && win.location.href != null &&
win.location.href.substring(0, 8) != value.substring(0, 8)) {
win.close();
editorUi.handleError({ message: mxResources.get('drawingTooLarge') });
}
}
catch (e) {
// ignore
}
}), timeout || 500);
}
}
catch (e) {
editorUi.handleError({ message: e.message || mxResources.get('drawingTooLarge') });
}
}
else {
var wnd = window.open();
var doc = (wnd != null) ? wnd.document : null;
if (doc != null) {
doc.writeln('<html><head><title>' + encodeURIComponent(mxResources.get('preview')) +
'</title><meta charset="utf-8"></head>' +
'<body>' + result + '</body></html>');
doc.close();
}
else {
editorUi.handleError({ message: mxResources.get('errorUpdatingPreview') });
}
}
}
});
previewBtn.className = 'geBtn';
buttons.appendChild(previewBtn);
}
if (!validUrl || result.length > 7500) {
var downloadBtn = mxUtils.button(mxResources.get('download'), function () {
editorUi.hideDialog();
editorUi.saveData((filename != null) ? filename : 'embed.txt', 'txt', result, 'text/plain');
});
downloadBtn.className = 'geBtn';
buttons.appendChild(downloadBtn);
}
// Twitter-intent does not allow more characters, must be pasted manually
if (validUrl && (!editorUi.isOffline() || mxClient.IS_CHROMEAPP)) {
if (result.length < maxFbSize) {
var fbBtn = mxUtils.button('', function () {
try {
var url = 'https://www.facebook.com/sharer.php?p[url]=' +
encodeURIComponent(text.value);
editorUi.openLink(url);
}
catch (e) {
editorUi.handleError({ message: e.message || mxResources.get('drawingTooLarge') });
}
});
var img = document.createElement('img');
img.setAttribute('src', Editor.facebookImage);
img.setAttribute('width', '18');
img.setAttribute('height', '18');
img.setAttribute('border', '0');
fbBtn.appendChild(img);
fbBtn.setAttribute('title', mxResources.get('facebook') + ' (' +
editorUi.formatFileSize(maxFbSize) + ' max)');
fbBtn.style.verticalAlign = 'bottom';
fbBtn.style.paddingTop = '4px';
fbBtn.style.minWidth = '46px'
fbBtn.className = 'geBtn';
buttons.appendChild(fbBtn);
}
if (result.length < maxTwitterSize) {
var tweetBtn = mxUtils.button('', function () {
try {
var url = 'https://twitter.com/intent/tweet?text=' +
encodeURIComponent(tweet) + '&url=' +
encodeURIComponent(text.value);
editorUi.openLink(url);
}
catch (e) {
editorUi.handleError({ message: e.message || mxResources.get('drawingTooLarge') });
}
});
var img = document.createElement('img');
img.setAttribute('src', Editor.tweetImage);
img.setAttribute('width', '18');
img.setAttribute('height', '18');
img.setAttribute('border', '0');
img.style.marginBottom = '5px'
tweetBtn.appendChild(img);
tweetBtn.setAttribute('title', mxResources.get('twitter') + ' (' +
editorUi.formatFileSize(maxTwitterSize) + ' max)');
tweetBtn.style.verticalAlign = 'bottom';
tweetBtn.style.paddingTop = '4px';
tweetBtn.style.minWidth = '46px'
tweetBtn.className = 'geBtn';
buttons.appendChild(tweetBtn);
}
}
if (!editorUi.isOffline() && result.length < maxSize) {
var emailBtn = mxUtils.button('', function () {
try {
var url = 'mailto:?subject=' +
encodeURIComponent(filename || editorUi.defaultFilename) + '&body=' +
encodeURIComponent(text.value);
editorUi.openLink(url);
}
catch (e) {
editorUi.handleError({ message: e.message || mxResources.get('drawingTooLarge') });
}
});
var img = document.createElement('img');
img.setAttribute('src', Editor.mailImage);
img.setAttribute('width', '18');
img.setAttribute('height', '18');
img.setAttribute('border', '0');
img.style.marginBottom = '5px'
if (Editor.isDarkMode()) {
img.style.filter = 'invert(100%)';
}
emailBtn.appendChild(img);
emailBtn.style.verticalAlign = 'bottom';
emailBtn.style.paddingTop = '4px';
emailBtn.style.minWidth = '46px'
emailBtn.className = 'geBtn';
buttons.appendChild(emailBtn);
}
var closeBtn = mxUtils.button(mxResources.get('close'), function () {
editorUi.hideDialog();
});
buttons.appendChild(closeBtn);
var copyBtn = mxUtils.button(mxResources.get('copy'), function () {
text.focus();
if (mxClient.IS_GC || mxClient.IS_FF || document.documentMode >= 5) {
text.select();
}
else {
document.execCommand('selectAll', false, null);
}
document.execCommand('copy');
editorUi.alert(mxResources.get('copiedToClipboard'));
});
/* 👇 保存按钮单击事件处理器 👇 */
var saveBtn = mxUtils.button(mxResources.get('save'), function () {
editorUi.hideDialog();
saveDataToSiyuan(file_name, null, html.replace(/<\/div>\s*$/, `${scriptTag}<\/div>\n`), 'text/html', null);
});
/* 👆 保存按钮单击事件处理器 👆 */
if (result.length < maxSize) {
// Does not work in Safari and shows annoying dialog for IE11-
if (!mxClient.IS_SF && document.documentMode == null) {
buttons.appendChild(copyBtn);
copyBtn.className = 'geBtn gePrimaryBtn';
closeBtn.className = 'geBtn';
/* 👇 添加保存按钮 👇 */
buttons.appendChild(saveBtn);
saveBtn.className = 'geBtn gePrimaryBtn';
/* 👆 添加保存按钮 👆 */
}
else {
closeBtn.className = 'geBtn gePrimaryBtn';
}
}
else {
buttons.appendChild(previewBtn);
closeBtn.className = 'geBtn';
previewBtn.className = 'geBtn gePrimaryBtn';
}
div.appendChild(buttons);
this.container = div;
};
var dlg = new EmbedDialog(editorUi, html + '\n' + scriptTag, null, null, function () {
var wnd = window.open();
var doc = wnd.document;
if (doc != null) {
if (document.compatMode === 'CSS1Compat') {
doc.writeln('<!DOCTYPE html>');
}
doc.writeln('<html>');
doc.writeln('<head><title>' + encodeURIComponent(mxResources.get('preview')) +
'</title><meta charset="utf-8"></head>');
doc.writeln('<body>');
doc.writeln(html);
var direct = mxClient.IS_IE || mxClient.IS_EDGE || document.documentMode != null;
if (direct) {
doc.writeln(scriptTag);
}
doc.writeln('</body>');
doc.writeln('</html>');
doc.close();
// Adds script tag after closing page and delay to fix timing issues
if (!direct) {
var info = wnd.document.createElement('div');
info.marginLeft = '26px';
info.marginTop = '26px';
mxUtils.write(info, mxResources.get('updatingDocument'));
var img = wnd.document.createElement('img');
img.setAttribute('src', window.location.protocol + '//' + window.location.hostname +
'/' + IMAGE_PATH + '/spin.gif');
img.style.marginLeft = '6px';
info.appendChild(img);
wnd.document.body.insertBefore(info, wnd.document.body.firstChild);
window.setTimeout(function () {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = /<script.*?src="(.*?)"/.exec(scriptTag)[1];
doc.body.appendChild(script);
info.parentNode.removeChild(info);
}, 20);
}
}
else {
editorUi.handleError({ message: mxResources.get('errorUpdatingPreview') });
}
});
editorUi.showDialog(dlg.container, 450, 240, true, true);
dlg.init();
}));
}
);
break;
case 'xml':
/**
* REF ~/js/diagramly/Menus.js -> editorUi.actions.put('exportXml'
*/
let div = document.createElement('div');
div.style.whiteSpace = 'nowrap';
let noPages = editorUi.pages == null || editorUi.pages.length <= 1;
let hd = document.createElement('h3');
mxUtils.write(hd, mxResources.get('formatXml'));
hd.style.cssText = 'width:100%;text-align:center;margin-top:0px;margin-bottom:4px';
div.appendChild(hd);
let selection = editorUi.addCheckbox(div, mxResources.get('selectionOnly'),
false, editorUi.editor.graph.isSelectionEmpty());
let compressed = editorUi.addCheckbox(div, mxResources.get('compressed'), true);
let pages = editorUi.addCheckbox(div, mxResources.get('allPages'), !noPages, noPages);
pages.style.marginBottom = '16px';
mxEvent.addListener(selection, 'change', function () {
if (selection.checked) {
pages.setAttribute('disabled', 'disabled');
}
else {
pages.removeAttribute('disabled');
}
});
let dlg = new CustomDialog(editorUi, div, mxUtils.bind(this, function () {
let temp_isLocalFileSave = editorUi.isLocalFileSave;
let temp_saveData = editorUi.saveData;
let temp_getBaseFilename = editorUi.getBaseFilename;
editorUi.isLocalFileSave = () => { return true; };
editorUi.saveData = saveDataToSiyuan;
editorUi.getBaseFilename = (_) => { return file_name_main; };
editorUi.downloadFile('xml', !compressed.checked, null, !selection.checked, noPages || !pages.checked);
editorUi.isLocalFileSave = temp_isLocalFileSave;
editorUi.saveData = temp_saveData;
editorUi.getBaseFilename = temp_getBaseFilename;
}), null, mxResources.get('save'));
editorUi.showDialog(dlg.container, 300, 200, true, true);
break;
}
}
});
buttons.appendChild(button);
if (++count == rowLimit) {
mxUtils.br(buttons);
count = 0;
}
};

找了一个方法:
//保存入口不再调用弹窗:
//diagramly/App.js --> App.prototype.saveFile = function(forceDialog, success)
App.prototype.saveFile = function(forceDialog, success)
{
var file = this.getCurrentFile();
if(file !=null ){
/改为思源自动保存,不弹窗/
siyuanAutoSave();
}
// if (file != null)
// {
// var done = mxUtils.bind(this, function()
// {

@winter60
Copy link

winter60 commented Sep 8, 2024

。。。

@crendy
Copy link
Author

crendy commented Sep 27, 2024

大佬 可以做成这种直接预览模式吗,编辑完成后 在笔记中就是图片,双击进入编辑模式,找了一种集成方式,但是我不专业,辛苦看看是否可以:
https://jgraph.github.io/drawio-integration/webdav/self-editing.svg

上面链接是从这里的svg方式点进来的 https://github.com/jgraph/drawio-integration/tree/master/webdav

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

3 participants