2024-07-30 23:33:33 +08:00
|
|
|
import type { IndexTreeEvent } from "../../plug-api/types.ts";
|
2024-03-09 19:26:58 +08:00
|
|
|
import { collectNodesOfType, findNodeOfType } from "../../plug-api/lib/tree.ts";
|
2024-07-30 23:33:33 +08:00
|
|
|
import type { ObjectValue } from "../../plug-api/types.ts";
|
2024-03-09 19:26:58 +08:00
|
|
|
import { indexObjects } from "./api.ts";
|
2024-08-07 02:11:38 +08:00
|
|
|
import { cleanPageRef } from "@silverbulletmd/silverbullet/lib/resolve";
|
|
|
|
import { system } from "@silverbulletmd/silverbullet/syscalls";
|
2024-03-09 19:26:58 +08:00
|
|
|
|
|
|
|
export type StyleObject = ObjectValue<{
|
|
|
|
style: string;
|
|
|
|
origin: string;
|
|
|
|
}>;
|
|
|
|
|
2024-03-12 03:14:49 +08:00
|
|
|
let customStylePages: string[] = [];
|
|
|
|
let lastCustomStyleRead: number | null = null;
|
|
|
|
|
2024-03-09 19:26:58 +08:00
|
|
|
export async function indexSpaceStyle({ name, tree }: IndexTreeEvent) {
|
|
|
|
const allStyles: StyleObject[] = [];
|
|
|
|
|
2024-03-12 03:14:49 +08:00
|
|
|
// Cache the setting for 10s
|
|
|
|
if (
|
|
|
|
lastCustomStyleRead === null || Date.now() > lastCustomStyleRead + 10000
|
|
|
|
) {
|
2024-08-02 22:47:36 +08:00
|
|
|
customStylePages = await system.getSpaceConfig("customStyles", []);
|
2024-03-12 03:14:49 +08:00
|
|
|
lastCustomStyleRead = Date.now();
|
|
|
|
if (!Array.isArray(customStylePages)) {
|
|
|
|
customStylePages = [customStylePages];
|
|
|
|
}
|
|
|
|
customStylePages = customStylePages.map((page: string) =>
|
|
|
|
cleanPageRef(page)
|
|
|
|
);
|
2024-03-09 19:26:58 +08:00
|
|
|
}
|
|
|
|
|
2024-08-02 22:47:36 +08:00
|
|
|
// Also collect CSS from custom styles in config
|
2024-03-09 19:26:58 +08:00
|
|
|
collectNodesOfType(tree, "FencedCode").map((t) => {
|
|
|
|
const codeInfoNode = findNodeOfType(t, "CodeInfo");
|
|
|
|
if (!codeInfoNode) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const fenceType = codeInfoNode.children![0].text!;
|
|
|
|
if (fenceType !== "space-style") {
|
|
|
|
if (
|
|
|
|
!customStylePages.includes(name) || fenceType !== "css"
|
|
|
|
) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const codeTextNode = findNodeOfType(t, "CodeText");
|
|
|
|
if (!codeTextNode) {
|
|
|
|
// Honestly, this shouldn't happen
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
const codeText = codeTextNode.children![0].text!;
|
|
|
|
let codeOrigin = "";
|
|
|
|
if (customStylePages.includes(name)) {
|
2024-08-02 22:47:36 +08:00
|
|
|
codeOrigin = "config";
|
2024-03-09 19:26:58 +08:00
|
|
|
} else if (name.startsWith("Library/")) {
|
|
|
|
codeOrigin = "library";
|
|
|
|
} else {
|
|
|
|
codeOrigin = "user";
|
|
|
|
}
|
|
|
|
|
|
|
|
allStyles.push({
|
|
|
|
ref: `${name}@${t.from!}`,
|
|
|
|
tag: "space-style",
|
|
|
|
style: codeText,
|
|
|
|
origin: codeOrigin,
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
await indexObjects<StyleObject>(name, allStyles);
|
|
|
|
}
|