Skip to content

Commit

Permalink
feat: write to specific frontmatter fields
Browse files Browse the repository at this point in the history
  • Loading branch information
Vinzent03 committed Feb 2, 2024
1 parent e6d0a60 commit 73e6388
Showing 1 changed file with 62 additions and 18 deletions.
80 changes: 62 additions & 18 deletions src/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,31 +37,75 @@ export default class Handlers {
}
handleFrontmatterKey(parameters: Parameters) {
const key = parameters.frontmatterkey;
const frontmatter = app.metadataCache.getCache(
const file = app.vault.getAbstractFileByPath(
parameters.filepath ?? app.workspace.getActiveFile().path
).frontmatter;
);
if (!(file instanceof TFile)) {
return;
}
const frontmatter = app.metadataCache.getFileCache(file).frontmatter;

let res: string;
if (key.startsWith("[") && key.endsWith("]")) {
const list = key.substring(1, key.length - 1).split(",");
let cache: any = frontmatter;
for (const item of list) {
if (cache instanceof Array) {
const index = parseInt(item);
if (Number.isNaN(index)) {
cache = cache.find((e) => e == item);
if (parameters.data) {
let data = parameters.data;
try {
// This try catch is needed to allow passing strings as a data value without extra ".
data = JSON.parse(data);
} catch {
data = `"${data}"`;
data = JSON.parse(data);
}
app.fileManager.processFrontMatter(file, (frontmatter) => {
if (key.startsWith("[") && key.endsWith("]")) {
const list = key.substring(1, key.length - 1).split(",");
let cache: any = frontmatter;
for (let i = 0; i < list.length; i++) {
const item = list[i];
if (cache instanceof Array) {
const index = parseInt(item);
if (Number.isNaN(index)) {
cache = cache.find((e) => e == item);
}
if (i == list.length - 1) {
cache[parseInt(item)] = data;
} else {
cache = cache[parseInt(item)];
}
} else {
if (i == list.length - 1) {
cache[item] = data;
} else {
cache = cache[item];
}
}
}
cache = cache[parseInt(item)];
} else {
cache = cache[item];
frontmatter[key] = data;
}
}
res = cache;
});
} else {
res = frontmatter[key];
}
let res: string;
if (key.startsWith("[") && key.endsWith("]")) {
const list = key.substring(1, key.length - 1).split(",");
let cache: any = frontmatter;
for (const item of list) {
if (cache instanceof Array) {
const index = parseInt(item);
if (Number.isNaN(index)) {
cache = cache.find((e) => e == item);
}
cache = cache[parseInt(item)];
} else {
cache = cache[item];
}
}
res = cache;
const a = 4;
} else {
res = frontmatter[key];
}

copyText(res);
copyText(res);
}
}

handleWorkspace(parameters: Parameters) {
Expand Down

0 comments on commit 73e6388

Please sign in to comment.