Fixes #8: SETTINGS page to keep all settings

This commit is contained in:
Zef Hemel
2022-07-15 11:17:02 +02:00
parent a8274d225c
commit a69289f1ab
6 changed files with 103 additions and 27 deletions
+23
View File
@@ -0,0 +1,23 @@
import { readYamlPage } from "./yaml_page";
export async function readSettings<T extends object>(settings: T): Promise<T> {
try {
let allSettings = (await readYamlPage("SETTINGS", ["yaml"])) || {};
// TODO: I'm sure there's a better way to type this than "any"
let collectedSettings: any = {};
for (let [key, defaultVal] of Object.entries(settings)) {
if (allSettings[key]) {
collectedSettings[key] = allSettings[key];
} else {
collectedSettings[key] = defaultVal;
}
}
return collectedSettings as T;
} catch (e: any) {
if (e.message === "Page not found") {
// No settings yet, return default values for all
return settings;
}
throw e;
}
}
+42
View File
@@ -0,0 +1,42 @@
import { findNodeOfType, traverseTree } from "@silverbulletmd/common/tree";
import { parseMarkdown } from "@silverbulletmd/plugos-silverbullet-syscall/markdown";
import { readPage } from "@silverbulletmd/plugos-silverbullet-syscall/space";
import YAML from "yaml";
export async function readYamlPage(
pageName: string,
allowedLanguages = ["yaml"]
): Promise<any> {
const { text } = await readPage(pageName);
let tree = await parseMarkdown(text);
let data: any = {};
traverseTree(tree, (t): boolean => {
// Find a fenced code block
if (t.type !== "FencedCode") {
return false;
}
let codeInfoNode = findNodeOfType(t, "CodeInfo");
if (!codeInfoNode) {
return false;
}
if (!allowedLanguages.includes(codeInfoNode.children![0].text!)) {
return false;
}
let codeTextNode = findNodeOfType(t, "CodeText");
if (!codeTextNode) {
// Honestly, this shouldn't happen
return false;
}
let codeText = codeTextNode.children![0].text!;
try {
data = YAML.parse(codeText);
} catch (e: any) {
console.error("YAML Page parser error", e);
throw new Error(`YAML Error: ${e.message}`);
}
return true;
});
return data;
}