silverbullet/plugs/share/publish.ts

60 lines
1.7 KiB
TypeScript
Raw Normal View History

import {
editor,
events,
markdown,
} from "@silverbulletmd/silverbullet/syscalls";
import { extractFrontmatter } from "@silverbulletmd/silverbullet/lib/frontmatter";
2024-07-30 23:33:33 +08:00
import type { PublishEvent } from "../../plug-api/types.ts";
2022-11-24 19:04:00 +08:00
2024-02-28 19:16:51 +08:00
export async function publishShareOptions() {
2022-11-24 19:04:00 +08:00
const text = await editor.getText();
const tree = await markdown.parseMarkdown(text);
let { $share } = await extractFrontmatter(tree);
2022-11-24 19:04:00 +08:00
if (!$share) {
2024-02-28 19:16:51 +08:00
return [];
2022-11-24 19:04:00 +08:00
}
if (!Array.isArray($share)) {
$share = [$share];
2022-11-24 19:04:00 +08:00
}
2024-02-28 19:16:51 +08:00
return [{
id: "publish",
name: `Publish to ${$share.map((s: string) => s.split(":")[0]).join(", ")}`,
}];
}
export async function publishShare() {
const pageName = await editor.getCurrentPage();
const text = await editor.getText();
const tree = await markdown.parseMarkdown(text);
let { $share } = await extractFrontmatter(tree);
if (!Array.isArray($share)) {
$share = [$share];
}
2022-11-24 23:08:51 +08:00
await editor.flashNotification("Sharing...");
2022-11-24 19:04:00 +08:00
try {
await publish(pageName, $share);
2022-11-24 19:04:00 +08:00
await editor.flashNotification("Done!");
} catch (e: any) {
await editor.flashNotification(e.message, "error");
}
}
async function publish(pageName: string, uris: string[]) {
2023-11-29 23:51:28 +08:00
const broadcastResults = await events.dispatchEvent(`share:_`, {
name: pageName,
} as PublishEvent);
2022-11-24 19:04:00 +08:00
for (const uri of uris) {
const publisher = uri.split(":")[0];
const results = await events.dispatchEvent(
`share:${publisher}`,
{
uri: uri,
name: pageName,
} as PublishEvent,
);
2023-11-29 23:51:28 +08:00
if (broadcastResults.length === 0 && results.length === 0) {
2022-11-24 19:04:00 +08:00
throw new Error(`Unsupported publisher: ${publisher} for URI: ${uri}`);
}
}
}