Skip to content

Commit

Permalink
functions extracted to class level and setting name updated
Browse files Browse the repository at this point in the history
  • Loading branch information
blacktau committed Feb 14, 2024
1 parent deadd0c commit 5699722
Show file tree
Hide file tree
Showing 2 changed files with 107 additions and 104 deletions.
205 changes: 104 additions & 101 deletions src/debouncedProcessors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,33 +51,7 @@ export class DebouncedProcessors implements Processor {
source = this.plugin.settings.header + "\r\n" + source;
await processor(source, el, ctx);
el.addEventListener('contextmenu', (event) => {
const renderToBlob = (img: HTMLImageElement, errorMessage: string, handleBlob: (blob: Blob) => Promise<void>) => {
const image = new Image();
image.crossOrigin = 'anonymous';
image.src = img.src;
image.addEventListener('load', () => {
const canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#fff';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(image, 0, 0);
try {
canvas.toBlob(async (blob) => {
try {
await handleBlob(blob);
} catch (error) {
new Notice(errorMessage);
console.error(error);
}
});
} catch (error) {
new Notice(errorMessage);
console.error(error);
}
});
}


const menu = new Menu(this.plugin.app)
.addItem(item => {
Expand All @@ -97,7 +71,7 @@ export class DebouncedProcessors implements Processor {
console.log(el);
const img = el.querySelector('img');
if (img) {
renderToBlob(
this.renderToBlob(
img,
'An error occurred while copying image to clipboard',
async (blob) => {
Expand Down Expand Up @@ -127,64 +101,13 @@ export class DebouncedProcessors implements Processor {
.setTitle('Export diagram')
.setIcon('image-file')
.onClick(async () => {

const getFilename = () => {
// try extract the title of the diagram
const startuml = source.match(/@startuml (.+)/i);
if (startuml?.length >= 2) {
return `${startuml[1].trim()}`;
}

const now = (new Date()).toISOString().replace(/[:T]+/g, '-');
return `${ctx.sourcePath.substring(0, ctx.sourcePath.lastIndexOf('.'))}-${now.substring(0, now.lastIndexOf('.'))}`;
}

const getFolder = async () => {
let exportPath = this.plugin.settings.exportPath;
if (!exportPath.startsWith('/')) {
// relative to the document
const documentPath = this.plugin.app.vault.getAbstractFileByPath(ctx.sourcePath).parent;
exportPath = `${documentPath.path}/${exportPath}`;
}

const exists = await this.plugin.app.vault.adapter.exists(exportPath);
if (!exists) {
this.plugin.app.vault.createFolder(exportPath);
}

return exportPath;
}

const getFilePath = async (type: string) => {

const filename = getFilename();
const path = await getFolder();

return `${path}${filename}.${type}`;
}

const getFile = (fileName: string) => {

let fName = fileName;
if (fName.startsWith('/')) {
fName = fName.substring(1);
}

const folderOrFile = this.plugin.app.vault.getAbstractFileByPath(fName);

if (folderOrFile instanceof TFile) {
return folderOrFile as TFile;
}

return undefined;
}

const img = el.querySelector('img');

if (img) {
renderToBlob(img, 'An error occurred while exporting the diagram', async (blob) => {
const filename = await getFilePath('png');
this.renderToBlob(img, 'An error occurred while exporting the diagram', async (blob) => {
const filename = await this.getFilePath(source, ctx, 'png');
const buffer = await blob.arrayBuffer();
const file = getFile(filename);
const file = this.getFile(filename);
if (file) {
await this.plugin.app.vault.modifyBinary(file, buffer);
} else {
Expand All @@ -195,30 +118,14 @@ export class DebouncedProcessors implements Processor {
});
}

const saveTextFile = async (type: string, data: string) => {
try {
const filename = await getFilePath(type);
const file = getFile(filename);
if (file) {
await this.plugin.app.vault.modify(file, data);
} else {
await this.plugin.app.vault.create(filename, data);
}
new Notice(`Diagram exported to '${filename}'`);
} catch (error) {
new Notice('An error occurred while while exporting the diagram');
console.error(error);
}
}

const svg = el.querySelector('svg');
if (svg) {
await saveTextFile('svg', svg.outerHTML);
await this.saveTextFile(source, ctx, 'svg', svg.outerHTML);
}

const code = el.querySelector('code');
if (code) {
await saveTextFile('txt', code.innerText);
await this.saveTextFile(source, ctx, 'txt', code.innerText);
}
})
});
Expand All @@ -227,5 +134,101 @@ export class DebouncedProcessors implements Processor {
}
}

renderToBlob = (img: HTMLImageElement, errorMessage: string, handleBlob: (blob: Blob) => Promise<void>) => {
const image = new Image();
image.crossOrigin = 'anonymous';
image.src = img.src;
image.addEventListener('load', () => {
const canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#fff';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(image, 0, 0);
try {
canvas.toBlob(async (blob) => {
try {
await handleBlob(blob);
} catch (error) {
new Notice(errorMessage);
console.error(error);
}
});
} catch (error) {
new Notice(errorMessage);
console.error(error);
}
});
}

getFilename = (source: string, ctx: MarkdownPostProcessorContext) => {
// try extract the title of the diagram
const startuml = source.match(/@startuml (.+)/i);
if (startuml?.length >= 2) {
return `${startuml[1].trim()}`;
}

const now = (new Date()).toISOString().replace(/[:T]+/g, '-');
const filename = this.plugin.app.vault.getAbstractFileByPath(ctx.sourcePath).name;
return `${filename.substring(0, filename.lastIndexOf('.'))}-${now.substring(0, now.lastIndexOf('.'))}`;
}

getFolder = async (ctx: MarkdownPostProcessorContext) => {
let exportPath = this.plugin.settings.exportPath;
if (!exportPath.startsWith('/')) {
// relative to the document
const documentPath = this.plugin.app.vault.getAbstractFileByPath(ctx.sourcePath).parent;
exportPath = `${documentPath.path}/${exportPath}`;
}

const exists = await this.plugin.app.vault.adapter.exists(exportPath);
if (!exists) {
this.plugin.app.vault.createFolder(exportPath);
}

return exportPath;
}

getFilePath = async (source: string, ctx: MarkdownPostProcessorContext, type: string) => {

const filename = this.getFilename(source, ctx);
const path = await this.getFolder(ctx);

return `${path}${filename}.${type}`;
}

getFile = (fileName: string) => {

let fName = fileName;
if (fName.startsWith('/')) {
fName = fName.substring(1);
}

const folderOrFile = this.plugin.app.vault.getAbstractFileByPath(fName);

if (folderOrFile instanceof TFile) {
return folderOrFile;
}

return undefined;
}

saveTextFile = async (source: string, ctx: MarkdownPostProcessorContext, type: string, data: string) => {
try {
const filename = await this.getFilePath(source, ctx, type);
const file = this.getFile(filename);

if (file) {
await this.plugin.app.vault.modify(file, data);
} else {
await this.plugin.app.vault.create(filename, data);
}

new Notice(`Diagram exported to '${filename}'`);
} catch (error) {
new Notice('An error occurred while while exporting the diagram');
console.error(error);
}
}
}
6 changes: 3 additions & 3 deletions src/settings.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Notice, Platform, PluginSettingTab, Setting } from "obsidian"
import PlantumlPlugin from "./main"
import { Notice, Platform, PluginSettingTab, Setting } from "obsidian";
import PlantumlPlugin from "./main";

export interface PlantUMLSettings {
server_url: string,
Expand Down Expand Up @@ -96,7 +96,7 @@ export class PlantUMLSettingsTab extends PluginSettingTab {
);

new Setting(containerEl)
.setName("Diagram Export Path")
.setName("Diagram export path")
.setDesc("Path where exported diagrams will be saved relative to the vault root. Leave blank to save along side the note.")
.addText(text => text.setPlaceholder(DEFAULT_SETTINGS.exportPath)
.setValue(this.plugin.settings.exportPath)
Expand Down

0 comments on commit 5699722

Please sign in to comment.