1
0
silverbullet/common/spaces/evented_space_primitives.ts

68 lines
1.8 KiB
TypeScript
Raw Normal View History

2023-08-20 15:51:00 +00:00
import { FileMeta } from "$sb/types.ts";
import { EventHook } from "../../plugos/hooks/event.ts";
2022-04-26 18:31:31 +00:00
import type { SpacePrimitives } from "./space_primitives.ts";
export class EventedSpacePrimitives implements SpacePrimitives {
constructor(private wrapped: SpacePrimitives, private eventHook: EventHook) {}
2022-09-12 12:50:37 +00:00
fetchFileList(): Promise<FileMeta[]> {
return this.wrapped.fetchFileList();
}
2022-09-12 12:50:37 +00:00
readFile(
name: string,
): Promise<{ data: Uint8Array; meta: FileMeta }> {
return this.wrapped.readFile(name);
}
2022-09-12 12:50:37 +00:00
async writeFile(
name: string,
data: Uint8Array,
2023-01-13 14:41:29 +00:00
selfUpdate?: boolean,
meta?: FileMeta,
2022-09-12 12:50:37 +00:00
): Promise<FileMeta> {
const newMeta = await this.wrapped.writeFile(
name,
data,
2022-10-12 09:47:13 +00:00
selfUpdate,
meta,
);
// This can happen async
2022-09-12 12:50:37 +00:00
if (name.endsWith(".md")) {
const pageName = name.substring(0, name.length - 3);
let text = "";
const decoder = new TextDecoder("utf-8");
text = decoder.decode(data);
2022-09-12 12:50:37 +00:00
this.eventHook
.dispatchEvent("page:saved", pageName, newMeta)
.then(() => {
return this.eventHook.dispatchEvent("page:index_text", {
name: pageName,
text,
});
})
.catch((e) => {
console.error("Error dispatching page:saved event", e);
});
}
if (name.startsWith("_plug/") && name.endsWith(".plug.js")) {
await this.eventHook.dispatchEvent("plug:changed", name);
}
2022-09-12 12:50:37 +00:00
return newMeta;
}
2022-09-12 12:50:37 +00:00
getFileMeta(name: string): Promise<FileMeta> {
return this.wrapped.getFileMeta(name);
}
2022-09-12 12:50:37 +00:00
async deleteFile(name: string): Promise<void> {
if (name.endsWith(".md")) {
const pageName = name.substring(0, name.length - 3);
await this.eventHook.dispatchEvent("page:deleted", pageName);
}
return this.wrapped.deleteFile(name);
}
}