Repository navigation
Expand file tree
/
Copy pathbuild.js
More file actions
157 lines (145 loc) · 11.5 KB
/
Copy pathbuild.js
File metadata and controls
157 lines (145 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
#!/usr/bin/env node
// Builds the plugin and the standalone graph page from src/.
// node build.js [--rules <file>] [--out <dir>] plugin: <out>/main.js, styles.css, manifest.json, rules.js (default out: dist)
// node build.js manifest the repo's manifest.json, from package.json's version
// node build.js page --data <graph.json> [--rules <file>] [--out <file>] the graph page (default out: .out/Vault Graph.html)
// --rules is a vault's rules file (folder names, thresholds); default config/rules.json, the sample vault's.
// The renderer is one closure (mountVaultGraph) written in parts, src/view/*.js in name order: the build joins them,
// so each part can be read and reviewed on its own while they share one scope. Each scene (src/scenes/*.js) gets its
// own scope inside the renderer, so it sees the renderer's helpers but its own names can't clash with them or each other.
const fs = require("fs"), path = require("path");
const ROOT = __dirname, SRC = path.join(ROOT, "src");
const read = f => fs.readFileSync(path.join(SRC, f), "utf8");
const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, "package.json"), "utf8"));
const loadRules = file => JSON.parse(fs.readFileSync(file || path.join(ROOT, "config", "rules.json"), "utf8"));
// The shared rulebook with its rule data filled in: the one place that's done (the build and every test use it).
// A function replacer, so a "$&" or "$'" in a rule pattern goes in as written.
const rulesSource = rules => { const src = read("shared.js") + "\n" + read("rules.js");
if (src.split("__RULES_JSON__").length !== 2) throw new Error("src/rules.js needs __RULES_JSON__ exactly once (where the rule data goes)");
return src.replace("__RULES_JSON__", () => JSON.stringify(rules)); };
// the engine or the science on their own, for tests: they need the shared helpers and nothing else from the bundle
const engineSource = () => read("shared.js") + "\n" + read("engine.js");
const scienceSource = () => read("shared.js") + "\n" + read("science.js");
// the release rules on their own: the plugin's updater bundles them, and scripts/install_release.js and the tests load them from here
const releaseSource = () => read("release.js");
const actionsSource = () => read("shared.js") + "\n" + read("actions.js");
// the rulebook, then the shared note actions (they use the rules)
// Vault HQ in parts (src/hq/*.js), one closure joined in name order, like the renderer
const hqJs = () => fs.readdirSync(path.join(SRC, "hq")).filter(f => f.endsWith(".js")).sort().map(f => fs.readFileSync(path.join(SRC, "hq", f), "utf8")).join("");
const rulesJs = rules => rulesSource(rules) + "\n" + read("parts.js") + "\n" + read("actions.js") + "\n" + read("tour.js") + "\n" + read("science.js");
// [[name, text]] for each part of the renderer, in the order they join (tests check them one by one)
const viewParts = () => fs.readdirSync(path.join(SRC, "view")).filter(f => f.endsWith(".js")).sort()
.map(f => [`view/${f}`, fs.readFileSync(path.join(SRC, "view", f), "utf8")]);
const pluginSource = () => fs.readdirSync(path.join(SRC, "plugin")).filter(f => f.endsWith(".js")).sort().map(f => fs.readFileSync(path.join(SRC, "plugin", f), "utf8")).join(""); // one file's worth of plugin, joined
const viewSource = () => viewParts().map(([, t]) => t).join(""); // the renderer as one file, scenes not spliced in
// The graphs library (vault-graph-views, pinned in package.json), built into the renderer: one bundle that defines VaultGraphViews.
const LIB_FILE = path.join(ROOT, "node_modules", "vault-graph-views", "dist", "vault-graph-views.js");
function libraryJs() {
if (!fs.existsSync(LIB_FILE)) throw new Error("the graphs library isn't installed (node_modules/vault-graph-views). Next: npm install (needs the internet once; see CONTRIBUTING.md)");
return fs.readFileSync(LIB_FILE, "utf8");
}
function viewJs() {
const scenes = fs.readdirSync(path.join(SRC, "scenes")).filter(f => f.endsWith(".js")).sort()
.map(f => `\n // ---- scene: ${f}\n (() => {\n` + fs.readFileSync(path.join(SRC, "scenes", f), "utf8") + "\n })();\n").join("");
const view = viewSource();
if (view.split("/*@scenes*/").length !== 2) throw new Error("src/view/ needs one /*@scenes*/ marker");
return libraryJs() + "\n" + view.replace("/*@scenes*/", () => scenes);
}
// The plugin's id is the folder its content log lives in (files.content_log in the rules): "jk-vault-graph", not
// "vault-graph", which a published plugin uses (Obsidian replaced this one with it on synced devices).
const pluginId = rules => rules.files.content_log.split("/").slice(-2, -1)[0];
function buildPlugin(rules) {
const header = "/* Vault Graph - GENERATED by build.js; do not edit.\n"
+ " Sources: src/shared.js, src/rules.js (+ the vault's rules file), src/parts.js, src/actions.js, src/tour.js, src/hq/*.js, src/engine.js, src/view/*.js (+ src/scenes/*.js), src/release.js, src/plugin/*.js. */\n";
return {
"main.js": header + rulesJs(rules) + "\n" + hqJs() + "\n" + read("engine.js") + "\n" + viewJs() + "\n" + releaseSource() + "\n" + pluginSource(),
"styles.css": read("tokens.css") + "\n" + read("parts.css") + "\n" + read("view.css") + "\n" + read("hq.css") + "\n.vg-host { padding: 0 !important; overflow: hidden; }\n.vg-host > div { height: 100%; }\n"
+ "/* Obsidian desktop's floating status bar covers the bottom of the pane: lift the bottom chrome */\n"
+ "body:not(.is-mobile) .vg-host .vg-root { --vg-bottom: calc(var(--status-bar-height, 22px) + 8px); }\n",
"manifest.json": JSON.stringify({
id: pluginId(rules), name: "Vault Graph", version: pkg.version, minAppVersion: "1.4.0",
description: "Your vault's home screen and map: capture, focus, what your notes know about any task, search that finds what you half remember, and views of your notes.",
author: "Jackson", isDesktopOnly: false,
}, null, 2) + "\n",
// the rulebook on its own, for the vault's own tests
"rules.js": "/* Vault Graph rules - GENERATED by build.js; do not edit. */\n" + rulesSource(rules)
+ "\nif (typeof module !== \"undefined\") module.exports = VGRules;\n",
};
}
const PAGE = `<!doctype html>
<html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Vault Graph</title>
<style>
/* Obsidian's theme variables, so the shared stylesheet works outside Obsidian too */
:root { color-scheme: light dark;
--background-primary:#ffffff; --background-secondary:#f7f7f8; --text-normal:#1d1d20; --text-muted:#6b6b76; --text-faint:#9a9aa3;
--background-modifier-border:#e4e4e8; --background-modifier-hover:rgba(30,30,40,.06); --text-accent:#6d4aff;
--interactive-accent:#6d4aff; --text-on-accent:#ffffff; }
@media (prefers-color-scheme: dark) { :root {
--background-primary:#16161a; --background-secondary:#1d1d22; --text-normal:#ececf1; --text-muted:#9d9daa; --text-faint:#6e6e7a;
--background-modifier-border:#2c2c33; --background-modifier-hover:rgba(255,255,255,.06); --text-accent:#9b87ff;
--interactive-accent:#7c66ff; --text-on-accent:#ffffff; } }
html, body { margin:0; height:100%; background:var(--background-primary); }
__CSS__
</style></head><body>
<div id="vg" style="height:100%"></div>
<script>
__VIEW__
const DATA = __DATA__;
window.vaultGraph = mountVaultGraph(document.getElementById("vg"), DATA, {
openNote: path => { location.href = \`obsidian://open?vault=\${encodeURIComponent(DATA.vault)}&file=\${encodeURIComponent(path.replace(/\\.md$/, ""))}\`; },
store: {
load: () => { try { return JSON.parse(localStorage.getItem("vault-graph:" + DATA.vault)); } catch (e) { return null; } },
save: v => { try { localStorage.setItem("vault-graph:" + DATA.vault, JSON.stringify(v)); } catch (e) { /* private window */ } },
},
});
</script></body></html>
`;
// The standalone page: the renderer with a vault's graph data built in, for the browser tests and for viewing outside Obsidian.
function buildPage(data, rules) {
const js = rulesJs(rules) + "\n" + viewJs();
// an inline <script> ends at the first "</script"; no source may contain one
if (js.toLowerCase().includes("</script")) throw new Error("inline script contains </script");
return PAGE.replace("__CSS__", () => read("tokens.css") + read("parts.css") + read("view.css")).replace("__VIEW__", () => js)
.replace("__DATA__", () => JSON.stringify(data).replace(/<\//g, "<\\/"));
}
// The HQ page: Vault HQ (src/hq.js) with a vault's graph data and its HQ notes built in, for the browser tests. A test
// puts its own mount options (stand-ins for the plugin's actions, a fixed clock) at HQ_OPTS; they win over the page's.
const HQ_OPTS = "/*@hq-opts*/";
function buildHQPage(data, rules) {
const js = rulesJs(rules) + "\n" + hqJs();
if (js.toLowerCase().includes("</script")) throw new Error("inline script contains </script");
// Obsidian's own rules for every button (mobile's included): HQ is tested against them, since they win over a
// single class (a project card showed one clipped line on the phone)
const obsidianButtons = "button { display: inline-flex; align-items: center; justify-content: center; white-space: nowrap; overflow: hidden; height: 30px; padding: 4px 12px; background-color: #3a3a3a; box-shadow: 0 1px 2px rgba(0,0,0,.4); text-align: center; }\n";
return PAGE.split("<script>")[0].replace("<title>Vault Graph</title>", "<title>Vault HQ</title>").replace("__CSS__", () => obsidianButtons + read("tokens.css") + read("parts.css") + read("hq.css"))
.replace('<div id="vg" style="height:100%"></div>', '<div id="hq" style="height:100%"></div>')
+ `<script>\n${js}\nconst DATA = ${JSON.stringify(data).replace(/<\//g, "<\\/")};\n`
+ `window.vaultHQ = mountVaultHQ(document.getElementById("hq"), DATA, {\n api: { openNote: p => { (window.__opened = window.__opened || []).push(p); } },\n ${HQ_OPTS}\n});\n</script></body></html>\n`;
}
// Write unless the file already holds it: an unchanged file in a synced vault isn't uploaded again.
function writeIfChanged(file, text) {
try { if (fs.readFileSync(file, "utf8") === text) return false; } catch (e) { /* new file */ }
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, text);
return true;
}
const arg = (name, dflt) => { const i = process.argv.indexOf(name); return i > 0 ? process.argv[i + 1] : dflt; };
if (require.main === module) {
const rules = loadRules(arg("--rules"));
if (process.argv[2] === "manifest") { // the repo's own manifest.json, which BRAT and Obsidian read for the version
writeIfChanged(path.join(ROOT, "manifest.json"), buildPlugin(rules)["manifest.json"]);
console.log(`Wrote manifest.json (${pluginId(rules)} ${pkg.version})`);
} else if (process.argv[2] === "page") {
const data = arg("--data"); if (!data) { console.error("page needs --data <graph.json>"); process.exit(2); }
const out = arg("--out", path.join(ROOT, ".out", "Vault Graph.html"));
writeIfChanged(out, buildPage(JSON.parse(fs.readFileSync(data, "utf8")), rules));
console.log(`Wrote ${path.relative(process.cwd(), out)}`);
} else {
const out = arg("--out", path.join(ROOT, "dist"));
for (const [f, text] of Object.entries(buildPlugin(rules))) writeIfChanged(path.join(out, f), text);
console.log(`Built ${path.relative(process.cwd(), out) || "."}/ (${pluginId(rules)} ${pkg.version})`);
}
}
module.exports = { ROOT, loadRules, pluginSource, rulesSource, engineSource, scienceSource, releaseSource, actionsSource, viewParts, viewSource, buildPlugin, buildPage, buildHQPage, HQ_OPTS, pluginId, writeIfChanged };