1
0
silverbullet/plugs/share/publish.ts

51 lines
1.4 KiB
TypeScript
Raw Normal View History

2022-11-24 11:04:00 +00:00
import { events } from "$sb/plugos-syscall/mod.ts";
import { editor, markdown } from "$sb/silverbullet-syscall/mod.ts";
2022-11-24 11:04:00 +00:00
import { extractFrontmatter } from "$sb/lib/frontmatter.ts";
2022-11-24 15:08:51 +00:00
import { PublishEvent } from "$sb/app_event.ts";
2022-11-24 11:04:00 +00:00
export async function publishCommand() {
await editor.save();
const text = await editor.getText();
const pageName = await editor.getCurrentPage();
const tree = await markdown.parseMarkdown(text);
const { $share } = await extractFrontmatter(tree);
2022-11-24 11:04:00 +00:00
if (!$share) {
2022-11-24 15:08:51 +00:00
await editor.flashNotification("Saved.");
2022-11-24 11:04:00 +00:00
return;
}
if (!Array.isArray($share)) {
2022-11-24 15:08:51 +00:00
await editor.flashNotification(
"$share front matter must be an array.",
"error",
);
return;
2022-11-24 11:04:00 +00:00
}
2022-11-24 15:08:51 +00:00
await editor.flashNotification("Sharing...");
2022-11-24 11:04:00 +00:00
// Delegate actual publishing to the server
try {
await publish(pageName, $share);
2022-11-24 11:04:00 +00:00
await editor.flashNotification("Done!");
} catch (e: any) {
await editor.flashNotification(e.message, "error");
}
}
async function publish(pageName: string, uris: string[]) {
2023-08-15 05:56:29 +00:00
if (!Array.isArray(uris)) {
uris = [uris];
}
2022-11-24 11:04:00 +00:00
for (const uri of uris) {
const publisher = uri.split(":")[0];
const results = await events.dispatchEvent(
`share:${publisher}`,
{
uri: uri,
name: pageName,
} as PublishEvent,
);
if (results.length === 0) {
throw new Error(`Unsupported publisher: ${publisher} for URI: ${uri}`);
}
}
}