trigger le expensemanipulation depuis une commande et modifé expensmanipulation pour rééecrire un tableau sorted

This commit is contained in:
steeven 2024-04-21 18:15:16 +02:00
parent efee00c529
commit 36b1f17ae8
2 changed files with 49 additions and 30 deletions

View File

@ -1,31 +1,46 @@
import { App, TFile } from "obsidian";
import { App, MarkdownView } from "obsidian";
export async function playWithTable(app: App) {
const file = await this.app.workspace.getActiveFile();
// trigger if something changed in the file (ex. new expense added)
app.vault.on("modify", async (changedFile: TFile) => {
if (changedFile.path === file.path) {
if (file) {
const fileContent = await this.app.vault.read(file);
const lines = fileContent.split("\n");
let inTable = false;
lines.forEach((line) => {
if (line.startsWith("|")) {
if (line.includes("---")) {
// This is the header line, start reading from next line
inTable = true;
} else if (inTable) {
// This is a table line, read the cells
const cells = line
.split("|")
.map((cell) => cell.trim());
console.log(cells);
}
} else {
inTable = false;
}
});
const file = app.workspace.getActiveFile();
const fileContent = await this.app.vault.read(file);
const lines = fileContent.split("\n");
let inTable = false;
const tableLines = lines
.map((line: string) => {
if (/^\|.*\|$/.test(line)) {
if (line.includes("---")) {
// This is the header line, start reading from next line
inTable = true;
} else if (inTable) {
// This is a table line, read the cells
const cells = line
.split("|")
.map((cell: string) => cell.trim())
.filter((cell: string) => cell !== "");
return cells.reduce(
(
acc: Record<string, string>,
cell: string,
index: number
) => {
acc["cell" + (index + 1)] = cell;
return acc;
},
{ date: new Date(cells[0]), line }
);
}
}
}
});
})
.filter(Boolean); // Remove undefined values
// Sort table lines by date
tableLines.sort((a, b) => a.date - b.date);
const sortedLines = tableLines.map((obj) => obj.line);
console.log(sortedLines);
// set the cursor at the end of the document
const editor = this.app.workspace.getActiveViewOfType(MarkdownView);
// write hello in the start of the document
editor.editor.setCursor(2, 0);
editor.editor.replaceSelection(sortedLines.join("\n"));
editor.editor.replaceSelection("\n\n");
}

10
main.ts
View File

@ -32,6 +32,7 @@ export const DEFAULT_SETTINGS: BudgetSettings = {
export default class budgetPlugin extends Plugin {
settings: BudgetSettings;
file: TFile;
async onload() {
await this.loadSettings();
@ -61,9 +62,12 @@ export default class budgetPlugin extends Plugin {
// Adds a setting tag so the user can configure the aspects of the plugin
this.addSettingTab(new ExpenseSettingTab(this.app, this));
// Adds a listener to the layout-ready event to trigger the playWithTable function
this.app.workspace.on("layout-ready", async () => {
await playWithTable(this.app);
this.addCommand({
id: "play-with-table",
name: "Play with table",
callback: async () => {
await playWithTable(this.app);
},
});
}