From 26a72ea8df044a46424893a6b1010e38ae68e60d Mon Sep 17 00:00:00 2001 From: Zef Hemel Date: Sun, 30 Mar 2025 16:09:45 +0200 Subject: [PATCH] Remove share functionality and related components, replaced with import and export infrastructure - Deleted the `share` plug, including its associated files and YAML configuration. - Removed references to share options and commands from the codebase. - Cleaned up unused event listeners and functions related to sharing content. --- Library/Std/Export.md | 96 ++++++++++++++++ Library/Std/Gist.md | 187 +++++++++++++++++++++++++++++++ Library/Std/Import.md | 107 ++++++++++++++++++ Library/Std/Widgets.md | 1 - common/space_lua/stdlib.ts | 4 +- common/space_lua/stdlib/table.ts | 2 +- plugs/builtin_plugs.ts | 1 - plugs/share/publish.ts | 59 ---------- plugs/share/share.plug.yaml | 34 ------ plugs/share/share.ts | 108 ------------------ 10 files changed, 393 insertions(+), 206 deletions(-) create mode 100644 Library/Std/Export.md create mode 100644 Library/Std/Gist.md create mode 100644 Library/Std/Import.md delete mode 100644 plugs/share/publish.ts delete mode 100644 plugs/share/share.plug.yaml delete mode 100644 plugs/share/share.ts diff --git a/Library/Std/Export.md b/Library/Std/Export.md new file mode 100644 index 00000000..e601f594 --- /dev/null +++ b/Library/Std/Export.md @@ -0,0 +1,96 @@ +#meta + +Provides infrastructure for exporting pages outside of your space. It standardizes the ${widgets.commandButton("Export: Page Or Selection")} to export the current page or selection in various ways. + +# Architecture +Flow: + +1. Emit event `export:discover` with: + * `pageMeta` + * `selection` text +2. Respond with: + * `id`: Call identifier + * `name` +3. Ask user to select option, then invoke `export:run:${id}` with the same data as step 1 +4. Exporter listens to this event and handles it as it sees fit. + +# Implementation +```space-lua +command.define { + name = "Export: Page Or Selection", + key = "Ctrl-e", + mac = "Cmd-e", + run = function() + editor.save() + local text = editor.getText() + local meta = editor.getCurrentPageMeta() + local selection = editor.getSelection() + local exportObj = { + pageMeta = meta, + text = selection.text != "" and selection.text or text + } + local handlers = event.dispatch("export:discover", exportObj) + if #handlers == 0 then + editor.flashNotification("No exporters available", "error") + return + end + local selectionOptions = {} + for _, handler in ipairs(handlers) do + for _, option in ipairs(handler) do + table.insert(selectionOptions, option) + end + end + local selectedOption = editor.filterBox("Export to", + selectionOptions, "Select your export mechanism") + if not selectedOption then + return + end + event.dispatch("export:run:" .. selectedOption.id, exportObj) + end +} +``` + +# Clipboard exporters +Implements two exporters: +* Copy clean markdown +* Copy rich text (e.g. for pasting into a Google Docs) + +```space-lua +event.listen { + name = "export:discover", + run = function(event) + return { + { + id = "clipboard-clean-markdown", + name = "Clipboard as clean markdown" + }, + { + id = "clipboard-rich-text", + name = "Clipboard as rich text" + }, + } + end +} + +event.listen { + name = "export:run:clipboard-clean-markdown", + run = function(event) + local mdTree = markdown.parseMarkdown(event.data.text) + mdTree = markdown.expandMarkdown(mdTree) + local renderedMd = markdown.renderParseTree(mdTree) + editor.copyToClipboard(renderedMd) + editor.flashNotification "Copied markdown to clip board!" + end +} + +event.listen { + name = "export:run:clipboard-rich-text", + run = function(event) + local mdTree = markdown.parseMarkdown(event.data.text) + mdTree = markdown.expandMarkdown(mdTree) + local html = markdown.markdownToHtml(markdown.renderParseTree(mdTree)) + editor.copyToClipboard(js.Blob({html}, {type="text/html"})) + editor.flashNotification "Copied rich text to clip board!" + end +} +``` diff --git a/Library/Std/Gist.md b/Library/Std/Gist.md new file mode 100644 index 00000000..29473424 --- /dev/null +++ b/Library/Std/Gist.md @@ -0,0 +1,187 @@ +#meta + +[[^Library/Std/Import]] and [[^Library/Std/Export]] support for [Github Gists](https://gist.github.com/). + +# Configuration +If you only want to _import_ from Gist URLs, no configuration is required. + +To _export_ gists, you need to get a [personal Github token](https://github.com/settings/personal-access-tokens) (with at least Gist permissions). Configure your token somewhere in Space Lua (use a `space-lua` block): + +```lua +config.set("github.token", "your token") +``` + +# Implementation: constants +```space-lua +-- priority: 50 +githubGist = { + fmUrlKey = "gistUrl", + fmFileKey = "gistFile" +} +``` + +# Import implementation +```space-lua +-- Import discovery +event.listen { + name = "import:discover", + run = function(event) + local url = event.data.url + if githubGist.extractGistId(url) then + return { + { + id = "github-gist", + name = "Gist" + }, + } + end + end +} + +-- Gist export implementation +event.listen { + name = "import:run:github-gist", + run = function(event) + local url = event.data.url + local gistUrl = githubGist.extractGistId(url) + local resp = http.request("https://api.github.com/gists/" .. gistUrl, { + headers = { + Accept = "application/vnd.github.v3+json" + } + }) + if not resp.ok then + editor.flashNotification("Failed, see console for error") + js.log("Error", resp) + return + end + local files = resp.body.files + for filename, meta in pairs(files) do + if filename:endsWith(".md") then + -- Fetch the content + local content = http.request(meta.raw_url).body + local fm = index.extractFrontmatter(content) + local suggestedPath = filename:gsub("%.md$", "") + if table.includes(fm.frontmatter.tags, "meta") then + -- Maybe more of a library function + suggestedPath = "Library/" .. suggestedPath + end + local localPath = editor.prompt("Save to", suggestedPath) + if not localPath then + return + end + if space.fileExists(localPath .. ".md") then + editor.flashNotification("Page already exists, won't do that", "error") + return + end + space.writePage(localPath, content) + editor.flashNotification("Imported to " .. localPath) + editor.navigate({kind="page", page=localPath}) + local updated = index.patchFrontmatter(editor.getText(), + { + {op="set-key", path="source", value="github-gist"}, + {op="set-key", path=githubGist.fmUrlKey, value=resp.body.html_url}, + {op="set-key", path=githubGist.fmFileKey, value=filename}, + }) + editor.setText(updated) + end + end + end +} +``` + +# Export implementation +```space-lua +-- Utility functions +function githubGist.extractGistId(url) + if not url:startsWith("https://gist.github.com/") then + return nil + end + return url:match("([^/]+)$") +end + +function githubGist.request(url, method, body) + local token = config.get("github.token") + if not token then + error("github.token config not set") + end + return http.request(url, { + method = method, + headers = { + Authorization = "token " .. token, + Accept = "application/vnd.github+json" + }, + body = body + }) +end + +-- Export discovery +event.listen { + name = "export:discover", + run = function(event) + return { + { + id = "github-gist", + name = "Gist" + }, + } + end +} + +-- Gist export implementation +event.listen { + name = "export:run:github-gist", + run = function(event) + -- Extract any existing gist URLs + local text = event.data.text + local fm = index.extractFrontmatter(text, { + removeKeys = {githubGist.fmUrlKey, githubGist.fmFileKey} + }) + if not fm.frontmatter[githubGist.fmUrlKey] then + -- Not there? This will be a fresh gist + local filename = "content.md" + filename = editor.prompt("File name", filename) + if not filename then + return + end + local resp = githubGist.request("https://api.github.com/gists", "POST", { + public = true, + files = { + [filename] = { + content = fm.text + } + } + }) + if resp.ok then + editor.flashNotification "Published new gist successfully" + local updated = index.patchFrontmatter(editor.getText(), + { + {op="set-key", path=githubGist.fmUrlKey, value=resp.body.html_url}, + {op="set-key", path=githubGist.fmFileKey, value=filename}, + }) + editor.setText(updated) + editor.flashNotification "Done!" + else + editor.flashNotification("Error, check console") + js.log("Error", resp) + end + else + -- Already published, should update + local gistId = githubGist.extractGistId(fm.frontmatter[githubGist.fmUrlKey]) + local resp = githubGist.request("https://api.github.com/gists/" .. gistId, "PATCH", { + public = true, + files = { + [fm.frontmatter[githubGist.fmFileKey]] = { + content = fm.text + } + } + }) + if resp.ok then + editor.flashNotification "Updated gist successfully!" + else + editor.flashNotification("Error, check console") + js.log("Error", resp) + end + end + end +} +``` \ No newline at end of file diff --git a/Library/Std/Import.md b/Library/Std/Import.md new file mode 100644 index 00000000..246281f3 --- /dev/null +++ b/Library/Std/Import.md @@ -0,0 +1,107 @@ +#meta + +Provides infrastructure for importing pages outside of your space. It standardizes the ${widgets.commandButton("Import: URL")} to export the current page or selection in various ways. + +# Technical architecture +Steps: +1. The user is asked to supply a URL +2. An `import:discover` event is triggered with: + * `url` the URL the user supplied +3. Listeners can respond with: + * `id`: Call identifier + * `name`: Presented name for the importer +4. Ask user to select option, then invoke `import:run:${id}` with the same data as step 2 +5. Importer listens to this event and handles it as it sees fit. + +General best practices for importers: +* Set the `source` key in the imported frontmatter to the type importer used (to allow for later automated updating of content) +* Set another key in frontmatter that points to the origin URL somehow (also for later updating use) + +# Implementation +```space-lua +command.define { + name = "Import: URL", + key = "Ctrl-Shift-i", + mac = "Cmd-Shift-i", + run = function() + local url = editor.prompt("URL to import:") + if not url then + return + end + local importObj = { url = url } + local handlers = event.dispatch("import:discover", importObj) + if #handlers == 0 then + editor.flashNotification("No importers available for URL", "error") + return + end + local selectionOptions = {} + for _, handler in ipairs(handlers) do + for _, option in ipairs(handler) do + table.insert(selectionOptions, option) + end + end + local selectedOption = editor.filterBox("Select importer", + selectionOptions, "Pick your desired importer from the list") + if not selectedOption then + return + end + event.dispatch("import:run:" .. selectedOption.id, importObj) + end +} +``` + +# Implementation for .md URLs +```space-lua +event.listen { + name = "import:discover", + run = function(event) + local url = event.data.url + if url:endsWith(".md") then + return { + { + id = "markdown-import", + name = "Markdown" + }, + } + end + end +} + +event.listen { + name = "import:run:markdown-import", + run = function(e) + local url = e.data.url + local req = http.request(url) + if not req.ok then + editor.flashNotification("Failed to import, see console for error") + js.log("Error", req) + return + end + local content = req.body + local fm = index.extractFrontmatter(content) + -- Extract the last part of the path, without the .md + local suggestedPath = url:match("^.*/([^/?#]+)%.md$") + if table.includes(fm.frontmatter.tags, "meta") then + -- Maybe more of a library function + suggestedPath = "Library/" .. suggestedPath + end + local localPath = editor.prompt("Save to", suggestedPath) + if not localPath then + return + end + if space.fileExists(localPath .. ".md") then + editor.flashNotification("Page already exists, won't do that", "error") + return + end + space.writePage(localPath, content) + editor.flashNotification("Imported to " .. localPath) + editor.navigate({kind="page", page=localPath}) + local updated = index.patchFrontmatter(editor.getText(), + { + {op="set-key", path="source", value="markdown-import"}, + {op="set-key", path="sourceUrl", value=url}, + }) + editor.setText(updated) + end +} +``` \ No newline at end of file diff --git a/Library/Std/Widgets.md b/Library/Std/Widgets.md index 8903bb3d..84413cb9 100644 --- a/Library/Std/Widgets.md +++ b/Library/Std/Widgets.md @@ -170,7 +170,6 @@ end event.listen { name = "hooks:renderTopWidgets", run = function(e) - print("Linked tasks") return widgets.linkedTasks() end } diff --git a/common/space_lua/stdlib.ts b/common/space_lua/stdlib.ts index a4bdda5a..0b49bbf3 100644 --- a/common/space_lua/stdlib.ts +++ b/common/space_lua/stdlib.ts @@ -6,7 +6,7 @@ import { luaGet, LuaMultiRes, LuaRuntimeError, - LuaTable, + type LuaTable, luaToString, luaTypeOf, type LuaValue, @@ -52,7 +52,7 @@ const pairsFunction = new LuaBuiltinFunction( let keys: any[]; if (Array.isArray(t)) { keys = Array.from({ length: t.length }, (_, i) => i + 1); // For arrays, generate 1-based indices - } else if (t instanceof LuaTable) { + } else if (t.keys) { keys = t.keys(); } else { keys = Object.keys(t); // For plain JavaScript objects diff --git a/common/space_lua/stdlib/table.ts b/common/space_lua/stdlib/table.ts index 5e1a2a6e..663bde92 100644 --- a/common/space_lua/stdlib/table.ts +++ b/common/space_lua/stdlib/table.ts @@ -112,7 +112,7 @@ export const tableApi = new LuaTable({ * @returns True if the value is in the table, false otherwise. */ includes: new LuaBuiltinFunction( - (sf, tbl: LuaTable | Record, value: LuaValue) => { + (sf, tbl: LuaTable | any[], value: LuaValue) => { if (!tbl) { return false; } diff --git a/plugs/builtin_plugs.ts b/plugs/builtin_plugs.ts index 160ff13b..6d4c359e 100644 --- a/plugs/builtin_plugs.ts +++ b/plugs/builtin_plugs.ts @@ -7,7 +7,6 @@ export const builtinPlugNames = [ "plug-manager", "emoji", "markdown", - "share", "tasks", "search", "image-viewer", diff --git a/plugs/share/publish.ts b/plugs/share/publish.ts deleted file mode 100644 index bced8bcc..00000000 --- a/plugs/share/publish.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { - editor, - events, - markdown, -} from "@silverbulletmd/silverbullet/syscalls"; -import { extractFrontmatter } from "@silverbulletmd/silverbullet/lib/frontmatter"; -import type { PublishEvent } from "../../plug-api/types.ts"; - -export async function publishShareOptions() { - const text = await editor.getText(); - const tree = await markdown.parseMarkdown(text); - let { $share } = await extractFrontmatter(tree); - if (!$share) { - return []; - } - if (!Array.isArray($share)) { - $share = [$share]; - } - 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]; - } - await editor.flashNotification("Sharing..."); - try { - await publish(pageName, $share); - await editor.flashNotification("Done!"); - } catch (e: any) { - await editor.flashNotification(e.message, "error"); - } -} - -async function publish(pageName: string, uris: string[]) { - const broadcastResults = await events.dispatchEvent(`share:_`, { - name: pageName, - } as PublishEvent); - for (const uri of uris) { - const publisher = uri.split(":")[0]; - const results = await events.dispatchEvent( - `share:${publisher}`, - { - uri: uri, - name: pageName, - } as PublishEvent, - ); - if (broadcastResults.length === 0 && results.length === 0) { - throw new Error(`Unsupported publisher: ${publisher} for URI: ${uri}`); - } - } -} diff --git a/plugs/share/share.plug.yaml b/plugs/share/share.plug.yaml deleted file mode 100644 index 523f1d9f..00000000 --- a/plugs/share/share.plug.yaml +++ /dev/null @@ -1,34 +0,0 @@ -name: share -functions: - shareCommand: - path: share.ts:shareCommand - command: - name: "Share: Page Or Selection" - key: "Ctrl-s" - mac: "Cmd-s" - requireEditor: page - - clipboardShareOptions: - path: share.ts:clipboardShareOptions - events: - - share:options - - clipboardMarkdownShare: - path: share.ts:clipboardMarkdownShare - events: - - share:clean-markdown - - clipboardRichTextShare: - path: share.ts:clipboardRichTextShare - events: - - share:rich-text - - publishShareOptions: - path: publish.ts:publishShareOptions - events: - - share:options - - publishShare: - path: publish.ts:publishShare - events: - - share:publish diff --git a/plugs/share/share.ts b/plugs/share/share.ts deleted file mode 100644 index cb25d09b..00000000 --- a/plugs/share/share.ts +++ /dev/null @@ -1,108 +0,0 @@ -import { - editor, - events, - markdown, - system, -} from "@silverbulletmd/silverbullet/syscalls"; -import { findNodeOfType, renderToText } from "../../plug-api/lib/tree.ts"; -import { replaceNodesMatching } from "../../plug-api/lib/tree.ts"; -import type { ParseTree } from "../../plug-api/lib/tree.ts"; -import { - encodePageURI, - parseRef, -} from "@silverbulletmd/silverbullet/lib/page_ref"; - -type ShareOption = { - id: string; - name: string; -}; - -export async function shareCommand() { - await editor.save(); - const pageName = await editor.getCurrentPage(); - - const optionResponses: ShareOption[] = - (await events.dispatchEvent("share:options", pageName)).flat(); - console.log("All options", optionResponses); - const selectedShareOption: any = await editor.filterBox( - "Share", - optionResponses, - "Pick a share option", - ); - if (!selectedShareOption) { - return; - } - console.log("Picked", selectedShareOption); - - let text = await editor.getText(); - const selection = await editor.getSelection(); - if (selection.from !== selection.to) { - text = text.substring(selection.from, selection.to); - } - - await events.dispatchEvent( - `share:${selectedShareOption.id}`, - text, - ); -} - -export function clipboardShareOptions() { - return [ - { - id: "clean-markdown", - name: "Copy to clipboard as clean markdown", - }, - { - id: "rich-text", - name: "Copy to clipboard as rich text", - }, - ]; -} - -export async function clipboardMarkdownShare(text: string) { - const tree = await markdown.parseMarkdown(text); - let rendered = await markdown.expandMarkdown(tree); - rendered = cleanMarkdown(rendered); - await editor.copyToClipboard(renderToText(rendered).trim()); - await editor.flashNotification("Copied to clipboard!"); -} - -export function cleanMarkdown(tree: ParseTree): ParseTree { - replaceNodesMatching(tree, (node) => { - switch (node.type) { - case "FrontMatter": - return null; - case "WikiLink": { - const ref = findNodeOfType(node, "WikiLinkPage")!.children![0].text!; - let linkText = ref.split("/").pop()!; - const aliasNode = findNodeOfType(node, "WikiLinkAlias"); - if (aliasNode) { - linkText = aliasNode.children![0].text!; - } - const pageRef = parseRef(ref); - return { - text: `[${linkText}](${ - typeof location !== "undefined" ? location.origin : "" - }/${encodePageURI(pageRef.page)})`, - }; - } - case "Attribute": - // Just remove these - return null; - } - }); - return tree; -} - -export async function clipboardRichTextShare(text: string) { - const tree = await markdown.parseMarkdown(text); - let rendered = await markdown.expandMarkdown(tree); - rendered = cleanMarkdown(rendered); - const html = await system.invokeFunction( - "markdown.markdownToHtml", - renderToText(rendered), - ); - console.log("HTML", html); - await editor.copyToClipboard(new Blob([html], { type: "text/html" })); - await editor.flashNotification("Copied to rich text to clipboard!"); -}