diff --git a/Library/Std/Command.md b/Library/Std/Command.md new file mode 100644 index 00000000..c001671c --- /dev/null +++ b/Library/Std/Command.md @@ -0,0 +1,79 @@ +#meta + +APIs to define and patch commands and slash commands. + +# API + +## command.define(commandDef) +Registers a command. + +Available keys: + +* `name`: Name of the command +* `run`: Callback function +* `contexts`: AST node context in which this command should be available +* `priority`: Command priority (how high it appears in the list) +* `key`: Windows/Linux key binding (and mac, if not separately defined) +* `mac`: Mac-specific key binding +* `hide`: Hide this command from the [[Command Palette]] +* `requireMode`: `rw` or `ro` — only enable this command in a particular mode (read-write, or read-only) + +Example: + +```lua +command.define { + name = "My custom command", + run = function() + editor.flashNotification "Triggered my custom command" + end +} +``` + +## command.patch(commandDef) +Equivalent to `command.define`, but can be used to patch (change) the definition of previously defined commands (including built-in ones) + +Example: + +```lua +-- To assign a new key binding and command priority to a built-in command +command.patch { + name = "Stats: Show", + key = "Ctrl-Shift-t", + priority = 100 +} + +-- To disable key bindings of an existing command +command.patch { + name = "Navigate: Document Picker", + key = nil, + mac = nil, +} +``` + +# Implementation +Most of the heavy lifting happens in SB itself. + +```space-lua +-- priority: 99 +command = command or {} +slashCommand = slashCommand or {} + +-- DEPRECATED: old name of API +slashcommand = slashCommand + +function command.define(def) + config.set({"commands", def.name}, def) +end + +function command.patch(newDef) + local def = config.get({"commands", newDef.name}, {}) + for k, v in pairs(newDef) do + def[k] = v + end + config.set({"commands", newDef.name}, def) +end + +function slashCommand.define(def) + config.set({"slashCommands", def.name}, def) +end +``` \ No newline at end of file diff --git a/Library/Std/Config.md b/Library/Std/Config.md index 7bfa56a6..87ab042a 100644 --- a/Library/Std/Config.md +++ b/Library/Std/Config.md @@ -3,7 +3,7 @@ SilverBullet's configuration can be tweaked using the `config.set` Space Lua API. This page defines all built-in configurations available. Individual Plugs and Space Lua scripts may define their own. -# Built-in options +# Built-in options (schema) This defines the [JSON schema](https://json-schema.org/) for built-in configuration. @@ -12,10 +12,7 @@ This defines the [JSON schema](https://json-schema.org/) for built-in configurat config.define("plugs", { description = "List of plugs to enable", oneOf = { - { - type = "array", - items = { type = "string" } - }, + schema.array "string", { -- only as a fallback for an empty table in Lua type = "object", } @@ -33,44 +30,61 @@ config.define("emoji", { properties = { aliases = { type = "object", - additionalProperties = { type = "string" } + additionalProperties = schema.string(), } } }) -config.define("shortcuts", { - type = "array", - items = { +config.define("commands", { + type = "object", + additionalProperties = { type = "object", properties = { - command = { - type = "string", - description = "Command we're creating the shortcut for" + name = schema.string(), + contexts = schema.nullableArray "string", + priority = schema.nullable "number", + key = schema.nullable "string", + mac = schema.nullable "string", + hid = schema.nullable "boolean", + requireMode = schema.nullable { + type = "string", + enum = {"rw", "ro"}, }, - args = { - type = "array", - description = "Optional array of arguments for the command" - }, - key = { - type = "string", - description = "(Re)bind to keyboard shortcut" - }, - mac = { - type = "string", - description = "Mac-specific keyboard shortcut" - }, - slashCommand = { - type = "string", - description = "Bind to slash command" - }, - priority = { - type = "number", - description = "Tweak priority in command palette" - } + requireEditor = schema.nullable("string"), + run = schema.func(), }, - required = {"command"}, - additionalProperties = false - } + }, +}) + +config.define("slashCommands", { + type = "object", + additionalProperties = { + type = "object", + properties = { + name = schema.string(), + description = schema.nullable "string", + priority = schema.nullable "number", + onlyContexts = schema.nullableArray "string", + exceptContexts = schema.nullableArray "string", + run = schema.func(), + }, + }, +}) + +config.define("eventHandlers", { + type = "object", + additionalProperties = schema.array(schema.func()), +}) + +config.define("tagDefinitions", { + type = "object", + additionalProperties = { + type = "object", + properties = { + schema = { type = "object" }, + metatable = { type = "object" }, + }, + }, }) config.define("smartQuotes", { @@ -130,20 +144,13 @@ config.define("actionButtons", { type = "string", description = "Optional description of the action button" }, - command = { - type = "string", - description = "Command the action button executes" - }, - args = { - type = "array", - description = "Optional array of arguments for the command" - }, mobile = { type = "boolean", description = "Optional boolean indicating if the action button is applicable for mobile" - } + }, + run = schema.func(), }, - required = {"icon", "command"}, + required = {"icon", "run"}, additionalProperties = false } }) @@ -245,3 +252,34 @@ config.define("queryCollation", { additionalProperties = false }) ``` + +Some default values + +```space-lua +-- priority: 99 +config.set { + actionButtons = { + { + icon = "home", + description = "Go to the index page", + run = function() + system.invokeCommand("Navigate: Home") + end + }, + { + icon = "book", + description = "Open page", + run = function() + system.invokeCommand("Navigate: Page Picker") + end + }, + { + icon = "terminal", + description = "Run command", + run = function() + system.invokeCommand "Open Command Palette" + end, + } + }, +} +``` \ No newline at end of file diff --git a/Library/Std/Date.md b/Library/Std/Date.md index 28a2aac0..d72d7fb3 100644 --- a/Library/Std/Date.md +++ b/Library/Std/Date.md @@ -28,21 +28,21 @@ function date.time() return os.date(date.time_format) end -slashcommand.define { +slashCommand.define { name = "today", run = function() editor.insertAtCursor(date.today()) end } -slashcommand.define { +slashCommand.define { name = "yesterday", run = function() editor.insertAtCursor(date.yesterday()) end } -slashcommand.define { +slashCommand.define { name = "tomorrow", run = function() editor.insertAtCursor(date.tomorrow()) @@ -51,4 +51,5 @@ slashcommand.define { ``` # Examples + Today: ${date.today()} and ${date.time()} \ No newline at end of file diff --git a/Library/Std/Page Templates.md b/Library/Std/Page Templates.md index 5dbc00e0..46234107 100644 --- a/Library/Std/Page Templates.md +++ b/Library/Std/Page Templates.md @@ -8,22 +8,26 @@ To create a page template, create a page and tag it with `#meta/template/page`. The last component of the page name will be used as the template name. ## Cursor placement -In the template’s body text, you can optionally use `|^|` as a placeholder for where the cursor should be after creating the page. +In the template’s body text, you can optionally use `|^|` as a placeholder for where the cursor should be after creating +the page. ## Configuration Optional keys you can set in the page’s frontmatter: * `suggestedName`: the proposed name for the new page, can use embedded Lua expressions, like `Daily/${date.today()}`. * `confirmName`: Confirm the suggested page name before creating it (defaults to `true`). -* `openIfExists`: If a page with the `suggestedName` already exists, open it rather than attempting to create it anew. +* `openIfExists`: If a page with the `suggestedName` already exists, open it rather than attempting to create it anew. * `command`: expose the page template as a command with this name. * `key`: Bind the snippet to a keyboard shortcut (note: this requires to _also_ specify the `command` configuration). * `mac`: Bind the snippet to a Mac-specific keyboard shortcut. * `frontmatter`: Frontmatter (encoded as a string) to set in the resulting page. -* `priority`: Similar to how space lua scripts are loaded, this controls the order in which page template _commands_ are created (see "overriding page templates" below) +* `priority`: Similar to how space lua scripts are loaded, this controls the order in which page template _commands_ are + created (see "overriding page templates" below) ## Example: Daily note -The following creates a page template that can be run using the `Journal: Daily Note` command, it automatically creates `Daily/today’s date` if it does not already exist with a bulleted list, putting the cursor at the first bullet. If the page already exists, it navigates there. +The following creates a page template that can be run using the `Journal: Daily Note` command, it automatically creates +`Daily/today’s date` if it does not already exist with a bulleted list, putting the cursor at the first bullet. If the +page already exists, it navigates there. ~~~ --- @@ -37,18 +41,27 @@ tags: meta/template/page ~~~ # Currently active page templates + ${template.each(query[[ - from index.tag "meta/template/page" - where _.tag == "page" +from index.tag "meta/template/page" +where _.tag == "page" ]], templates.fullPageItem)} # Instantiating page templates -You can create a page based on a page template via the ${widgets.commandButton("Page: From Template")} command, or via the command name that you defined in your template’s frontmatter. + +You can create a page based on a page template via the ${widgets.commandButton("Page: From Template")} command, or via +the command name that you defined in your template’s frontmatter. # Overriding page templates -If you would like to override an existing page template (for instance the Quick Note) template with your own, you can take advantage of the load order determined by the `priority` frontmatter. Built in page templates will have a priority set that is higher than the default. Therefore, their commands and keybindings will be set early. Therefore, by simply defining your own version of the page template _with the same command name_ will let that version override the versions that are built in. + +If you would like to override an existing page template (for instance the Quick Note) template with your own, you can +take advantage of the load order determined by the `priority` frontmatter. Built in page templates will have a priority +set that is higher than the default. Therefore, their commands and keybindings will be set early. Therefore, by simply +defining your own version of the page template _with the same command name_ will let that version override the versions +that are built in. ## Example: overriding the Quick Note template + ~~~ --- command: Quick Note @@ -110,6 +123,7 @@ for pt in query[[ createPageFromTemplate(pt.name, pageName) end } + print("Registered", pt.command) end command.define { diff --git a/Library/Std/Schema.md b/Library/Std/Schema.md new file mode 100644 index 00000000..94229dd6 --- /dev/null +++ b/Library/Std/Schema.md @@ -0,0 +1,76 @@ +#meta + +Utilities to succinctly define JSON schema types. + +```space-lua +-- priority: 101 +schema = schema or {} + +function schema.string() + return { type = "string" } +end + +function schema.number() + return { type = "number" } +end + +function schema.boolean() + return { type = "boolean" } +end + +function schema.array(typ) + if type(typ) == "string" then + return { + type = "array", + items = { type = typ } + } + else + return { + type = "array", + items = typ, + } + end +end + +function schema.nullable(typ) + if type(typ) == "string" then + return { + anyOf = { + { type = typ }, + { type = "null" }, + } + } + else + return { + anyOf = { + typ, + { type = "null" }, + } + } + end +end + +function schema.nullableArray(typ) + if type(typ) == "string" then + return { + anyOf = { + { type = "array", + items = { type = typ } }, + { type = "null" }, + } + } + else + return { + anyOf = { + { type = "array", + items = typ, }, + { type = "null" }, + } + } + end +end + +function schema.func() + return {} +end +``` \ No newline at end of file diff --git a/Library/Std/Slash Templates.md b/Library/Std/Slash Templates.md index 2f666a38..9b1e5df3 100644 --- a/Library/Std/Slash Templates.md +++ b/Library/Std/Slash Templates.md @@ -3,24 +3,31 @@ Allows for quick definition of slash commands based on templates. # Creating slash templates -Create a page with the `#meta/template/slash` tag. The last component of the page name (after the `/` if any) will be used as the slash command’s name. The body of the page will be used as the text to be inserted, using Lua directives is supported. + +Create a page with the `#meta/template/slash` tag. The last component of the page name (after the `/` if any) will be +used as the slash command’s name. The body of the page will be used as the text to be inserted, using Lua directives is +supported. ## Configuration + You can configure some specifics about your slash template in its template page’s frontmatter. Optional keys: + * `description`: The description of the slash command * `boost`: To prioritize the slash command higher in the list * `onlyContexts` (advanced): To only make the slash command appear in certain (AST node based) contexts * `exceptContexts` (advanced): To make the slash command appear everywhere _except_ in these (AST node) contexts # Currently active slash templates + ${template.each(query[[ - from index.tag "meta/template/slash" - where _.tag == "page" +from index.tag "meta/template/slash" +where _.tag == "page" ]], templates.fullPageItem)} # Implementation + ```space-lua for st in query[[ from index.tag "meta/template/slash" @@ -28,10 +35,10 @@ for st in query[[ ]] do local components = st.name:split("/") local name = components[#components] - slashcommand.define { + slashCommand.define { name = name, description = st.description, - boost = st.boost, + priority = st.priority, onlyContexts = st.onlyContexts, exceptContexts = st.exceptContexts, run = function() diff --git a/Library/Std/Slash Templates/lua-slash-command.md b/Library/Std/Slash Templates/lua-slash-command.md index aff2e479..628751a5 100644 --- a/Library/Std/Slash Templates/lua-slash-command.md +++ b/Library/Std/Slash Templates/lua-slash-command.md @@ -4,7 +4,8 @@ tags: meta/template/slash onlyContexts: - "FencedCode:space-lua" --- -slashcommand.define { + +slashCommand.define { name = "|^|", run = function() editor.insertAtCursor("Hello |^| world!", false, true) diff --git a/Library/Std/Slash.md b/Library/Std/Slash.md index 618b8285..a37610d6 100644 --- a/Library/Std/Slash.md +++ b/Library/Std/Slash.md @@ -12,35 +12,35 @@ local function headerSlashCommand(level) string.rep("#", level) .. " " .. cleanText, true) end -slashcommand.define { +slashCommand.define { name = "h1", run = function() headerSlashCommand(1) end } -slashcommand.define { +slashCommand.define { name = "h2", run = function() headerSlashCommand(2) end } -slashcommand.define { +slashCommand.define { name = "h3", run = function() headerSlashCommand(3) end } -slashcommand.define { +slashCommand.define { name = "h4", run = function() headerSlashCommand(4) end } -slashcommand.define { +slashCommand.define { name = "frontmatter", run = function() editor.insertAtPos([==[--- @@ -50,7 +50,7 @@ slashcommand.define { end } -slashcommand.define { +slashCommand.define { name = "task", run = function() local line = editor.getCurrentLine() @@ -59,7 +59,7 @@ slashcommand.define { end } -slashcommand.define { +slashCommand.define { name = "space-lua", description = "Insert Space Lua script", run = function() diff --git a/lib/command.ts b/lib/command.ts index beffe100..ca57fb28 100644 --- a/lib/command.ts +++ b/lib/command.ts @@ -1,36 +1,20 @@ -import type { SlashCommandDef } from "$lib/manifest.ts"; +import type { CommandDef, SlashCommandDef } from "$lib/manifest.ts"; +import { SlashCompletions } from "@silverbulletmd/silverbullet/types"; -export type CommandDef = { - name: string; - - contexts?: string[]; - - // Default 0, higher is higher priority = higher in the list - priority?: number; - - // Bind to keyboard shortcut - key?: string; - mac?: string; - - hide?: boolean; - requireMode?: "rw" | "ro"; - requireEditor?: "any" | "page" | "notpage" | string; +export type RunnableCommand = { + run?: (args?: any[]) => Promise; }; -export type AppCommand = { - command: CommandDef; - run: (args?: any[]) => Promise; -}; - -export type SlashCommand = { - slashCommand: SlashCommandDef; - run: (args?: any[]) => Promise; +export type Command = CommandDef & RunnableCommand; +export type SlashCommand = SlashCommandDef & { + run: (...args: any[]) => Promise; }; export type CommandHookEvents = { - commandsUpdated(commandMap: Map): void; + commandsUpdated(commands: Map): void; }; +// TODO: Move this elsewhere export function isValidEditor( currentEditor: string | undefined, requiredEditor: string | undefined, diff --git a/lib/event.ts b/lib/event.ts new file mode 100644 index 00000000..dc7f544a --- /dev/null +++ b/lib/event.ts @@ -0,0 +1,5 @@ +import type { EventSubscriptionDef } from "./manifest.ts"; + +export type EventSubscription = EventSubscriptionDef & { + run: (...args: any[]) => Promise; +}; diff --git a/lib/manifest.ts b/lib/manifest.ts index 04d3127f..0398f0be 100644 --- a/lib/manifest.ts +++ b/lib/manifest.ts @@ -1,12 +1,28 @@ import type { Manifest as PlugosManifest } from "./plugos/types.ts"; -import type { CommandDef } from "./command.ts"; import type { NamespaceOperation } from "./plugos/namespace.ts"; +import type { ILuaFunction } from "./space_lua/runtime.ts"; export type CodeWidgetT = { codeWidget?: string; renderMode?: "iframe"; }; +export type CommandDef = { + name: string; + + contexts?: string[]; + + // Default 0, higher is higher priority = higher in the list + priority?: number; + + // Bind to keyboard shortcut + key?: string; + mac?: string; + + hide?: boolean; + requireMode?: "rw" | "ro"; + requireEditor?: "any" | "page" | "notpage" | string; +}; export type CommandHookT = { command?: CommandDef; }; @@ -15,6 +31,10 @@ export type EventHookT = { events?: string[]; }; +export type EventSubscriptionDef = { + name: string; +}; + type MQSubscription = { queue: string; batchSize?: number; @@ -29,6 +49,7 @@ export type PlugNamespaceDef = { pattern: string; operation: NamespaceOperation; }; + export type PlugNamespaceHookT = { pageNamespace?: PlugNamespaceDef; }; @@ -36,7 +57,7 @@ export type PlugNamespaceHookT = { export type SlashCommandDef = { name: string; description?: string; - boost?: number; + priority?: number; // Parent AST nodes in which this slash command is available, defaults to everywhere onlyContexts?: string[]; // Parent AST nodes in which this slash command is not available @@ -59,7 +80,7 @@ export type DocumentEditorT = { * Hooks are associated with typescript functions through a manifest file. * On various triggers (user enters a slash command, an HTTP endpoint is hit, user clicks, etc) the typescript function is called. * - * related: plugos/type.ts#FunctionDef + * related: plugos/ui_types.ts#FunctionDef */ export type SilverBulletHooks = & CommandHookT diff --git a/plug-api/syscalls/system.ts b/plug-api/syscalls/system.ts index 8c5f7d2c..c615ccd0 100644 --- a/plug-api/syscalls/system.ts +++ b/plug-api/syscalls/system.ts @@ -1,6 +1,6 @@ -import type { CommandDef } from "../../lib/command.ts"; import type { SyscallMeta } from "../types.ts"; import { syscall } from "../syscall.ts"; +import { CommandDef } from "../../lib/manifest.ts"; /** * System level syscalls diff --git a/plugs/editor/editor.plug.yaml b/plugs/editor/editor.plug.yaml index 578ec1c4..dcb482e6 100644 --- a/plugs/editor/editor.plug.yaml +++ b/plugs/editor/editor.plug.yaml @@ -1,78 +1,6 @@ name: editor requiredPermissions: - fetch -config: - schema.config.properties: - shortcuts: - type: array - items: - type: object - properties: - command: - type: string - key: - type: string - nullable: true - mac: - type: string - nullable: true - slashCommand: - type: string - nullable: true - priority: - type: number - nullable: true - required: - - command - nullable: true - useSmartQuotes: - type: boolean - nullable: true - pwaOpenLastPage: - type: boolean - nullable: true - hideEditButton: - type: boolean - nullable: true - hideSyncButton: - type: boolean - nullable: true - mobileMenuStyle: - type: string - nullable: true - actionButtons: - type: array - items: - type: object - properties: - icon: - type: string - description: - type: string - nullable: true - command: - type: string - args: - type: array - items: - type: object - nullable: true - mobile: - type: boolean - nullable: true - required: - - icon - - command - defaultLinkStyle: - type: string - nullable: true - plugs: - type: array - items: - type: string - indentMultiplier: - type: number - nullable: true functions: setEditorMode: path: "./editor.ts:setEditorMode" @@ -298,13 +226,6 @@ functions: command: name: "Editor: Toggle Vim Mode" requireEditor: page - loadVimRc: - path: "./vim.ts:loadVimRc" - command: - name: "Editor: Vim: Load VIMRC" - requireEditor: page - events: - - editor:modeswitch loadVimConfig: path: "./vim.ts:loadVimConfig" command: diff --git a/plugs/editor/vim.ts b/plugs/editor/vim.ts index 54c1f47f..9d45bc98 100644 --- a/plugs/editor/vim.ts +++ b/plugs/editor/vim.ts @@ -1,4 +1,3 @@ -import { readCodeBlockPage } from "@silverbulletmd/silverbullet/lib/yaml_page"; import { clientStore, editor } from "@silverbulletmd/silverbullet/syscalls"; export async function toggleVimMode() { @@ -8,31 +7,6 @@ export async function toggleVimMode() { await clientStore.set("vimMode", vimMode); } -export async function loadVimRc() { - const vimMode = await editor.getUiOption("vimMode"); - if (!vimMode) { - console.log("Not in vim mode"); - return; - } - try { - const vimRc = await readCodeBlockPage("VIMRC"); - if (vimRc) { - console.log("Now running vim ex commands from VIMRC"); - const lines = vimRc.split("\n"); - for (const line of lines) { - try { - console.log("Running vim ex command", line); - await editor.vimEx(line); - } catch (e: any) { - await editor.flashNotification(e.message, "error"); - } - } - } - } catch { - // No VIMRC page found - } -} - export async function loadVimConfig() { const vimMode = await editor.getUiOption("vimMode"); if (!vimMode) { diff --git a/web/client.ts b/web/client.ts index 4cac8177..e6f56e23 100644 --- a/web/client.ts +++ b/web/client.ts @@ -10,14 +10,14 @@ import type { SyntaxNode } from "@lezer/common"; import { Space } from "./space.ts"; import type { FilterOption } from "@silverbulletmd/silverbullet/type/client"; import { EventHook } from "./hooks/event.ts"; -import { type AppCommand, isValidEditor } from "$lib/command.ts"; +import { type Command, isValidEditor } from "$lib/command.ts"; import { type LocationState, parseRefFromURI, PathPageNavigator, } from "./navigator.ts"; -import type { AppViewState } from "./type.ts"; +import type { AppViewState } from "./ui_types.ts"; import type { AppEvent, @@ -95,8 +95,9 @@ type WidgetCacheItem = { }; export class Client { + readonly config = new Config(); // Event bus used to communicate between components - eventHook = new EventHook(); + eventHook = new EventHook(this.config); space!: Space; @@ -107,7 +108,6 @@ export class Client { ui!: MainUI; ds!: DataStore; mq!: DataStoreMQ; - config = new Config(); // CodeMirror editor editorView!: EditorView; @@ -1296,9 +1296,9 @@ export class Client { const cmd = this.ui.viewState.commands.get(name); if (cmd) { if (args) { - await cmd.run(args); + await cmd.run!(args); } else { - await cmd.run(); + await cmd.run!(); } } else { throw new Error(`Command ${name} not found`); @@ -1307,19 +1307,19 @@ export class Client { getCommandsByContext( state: AppViewState, - ): Map { + ): Map { const currentEditor = client.documentEditor?.name; const commands = new Map(state.commands); for (const [k, v] of state.commands.entries()) { if ( - v.command.contexts && + v.contexts && (!state.showCommandPaletteContext || - !v.command.contexts.includes(state.showCommandPaletteContext)) + !v.contexts.includes(state.showCommandPaletteContext)) ) { commands.delete(k); } - const requiredEditor = v.command.requireEditor; + const requiredEditor = v.requireEditor; if (!isValidEditor(currentEditor, requiredEditor)) { commands.delete(k); } diff --git a/web/client_system.ts b/web/client_system.ts index d029b9e9..dadd5a88 100644 --- a/web/client_system.ts +++ b/web/client_system.ts @@ -38,14 +38,21 @@ import { plugPrefix } from "../lib/spaces/constants.ts"; import { jsonschemaSyscalls } from "./syscalls/jsonschema.ts"; import { luaSyscalls } from "./syscalls/lua.ts"; import { indexSyscalls } from "./syscalls/index.ts"; -import { commandSyscalls } from "./syscalls/command.ts"; import { configSyscalls } from "./syscalls/config.ts"; import { eventListenerSyscalls } from "./syscalls/event.ts"; import { DocumentEditorHook } from "./hooks/document_editor.ts"; import type { LuaCollectionQuery } from "../lib/space_lua/query_collection.ts"; -import type { AppCommand } from "$lib/command.ts"; -import { ScriptEnvironment } from "./space_script.ts"; +import type { Command } from "$lib/command.ts"; import { SpaceLuaEnvironment } from "./space_lua.ts"; +import { + ILuaFunction, + jsToLuaValue, + luaCall, + LuaStackFrame, + LuaValue, + luaValueToJS, +} from "../lib/space_lua/runtime.ts"; +import { buildThreadLocalEnv, handleLuaError } from "./space_lua_api.ts"; const plugNameExtractRegex = /\/(.+)\.plug\.js$/; const indexVersionKey = ["$indexVersion"]; @@ -68,8 +75,7 @@ export class ClientSystem { documentEditorHook!: DocumentEditorHook; readonly allKnownFiles = new Set(); - readonly scriptCommands = new Map(); - scriptEnv: ScriptEnvironment = new ScriptEnvironment(); + readonly scriptCommands = new Map(); spaceLuaEnv = new SpaceLuaEnvironment(); scriptsLoaded: boolean = false; private indexOngoing = false; @@ -160,7 +166,7 @@ export class ClientSystem { this.system.registerSyscalls( [], eventSyscalls(this.eventHook), - eventListenerSyscalls(this), + eventListenerSyscalls(this.client), editorSyscalls(this.client), spaceReadSyscalls(this.client), systemSyscalls(client, false), @@ -172,7 +178,7 @@ export class ClientSystem { languageSyscalls(), jsonschemaSyscalls(), indexSyscalls(client), - commandSyscalls(this), + //commandSyscalls(client), luaSyscalls(this), mqSyscalls(this.mq), dataStoreReadSyscalls(this.ds, this), @@ -208,7 +214,7 @@ export class ClientSystem { ); return; } - this.scriptEnv = new ScriptEnvironment(); + this.client.config.clear(); try { await this.spaceLuaEnv.reload(this.system); } catch (e: any) { @@ -217,15 +223,16 @@ export class ClientSystem { // Reset the space script commands this.scriptCommands.clear(); - for (const [name, command] of Object.entries(this.scriptEnv.commands)) { + for ( + const [name, command] of Object.entries( + this.client.config.get>("commands", {}), + ) + ) { this.scriptCommands.set(name, command); } - // Inject the registered events in the event hook - this.eventHook.scriptEnvironment = this.scriptEnv; - // Make scripted (slash) commands available - this.commandHook.throttledBuildAllCommands(); + this.commandHook.throttledBuildAllCommandsAndEmit(); this.slashCommandHook.throttledBuildAllCommands(); this.scriptsLoaded = true; @@ -305,6 +312,25 @@ export class ClientSystem { } } + public async evalLuaFunction( + luaFunction: ILuaFunction, + args: LuaValue[], + ): Promise { + const tl = await buildThreadLocalEnv( + this.system, + this.spaceLuaEnv.env, + ); + const sf = new LuaStackFrame(tl, null); + try { + return luaValueToJS( + await luaCall(luaFunction, args.map(jsToLuaValue), {}, sf), + sf, + ); + } catch (e: any) { + await handleLuaError(e, this.system); + } + } + public async hasFullIndexCompleted() { return (await this.ds.get(indexVersionKey)) === desiredIndexVersion; } diff --git a/web/cm_plugins/top_bottom_panels.ts b/web/cm_plugins/top_bottom_panels.ts index af5c45ea..ba18339c 100644 --- a/web/cm_plugins/top_bottom_panels.ts +++ b/web/cm_plugins/top_bottom_panels.ts @@ -25,7 +25,6 @@ export function postScriptPrefacePlugin( const widgetResults = await client.dispatchAppEvent( "hooks:renderTopWidgets", ); - // console.log("Widget results", widgetResults); const accumulatedWidget: LuaWidgetContent = { _isWidget: true, html: "", diff --git a/web/components/command_palette.tsx b/web/components/command_palette.tsx index 98303b81..a3c81ea5 100644 --- a/web/components/command_palette.tsx +++ b/web/components/command_palette.tsx @@ -4,7 +4,7 @@ import type { CompletionResult, } from "@codemirror/autocomplete"; import { Terminal } from "preact-feather"; -import type { AppCommand } from "../../lib/command.ts"; +import type { Command } from "../../lib/command.ts"; import type { FilterOption, Shortcut, @@ -17,42 +17,27 @@ export function CommandPalette({ onTrigger, vimMode, darkMode, - config, completer, }: { - commands: Map; + commands: Map; recentCommands: Map; vimMode: boolean; darkMode?: boolean; completer: (context: CompletionContext) => Promise; - config: Config; - onTrigger: (command: AppCommand | undefined) => void; + onTrigger: (command: Command | undefined) => void; }) { const options: FilterOption[] = []; const isMac = isMacLike(); for (const [name, def] of commands.entries()) { - if (def.command.hide) { + if (def.hide) { continue; } - let shortcut: { key?: string; mac?: string; priority?: number } = - def.command; - // Let's see if there's a shortcut override - if (config.has("shortcuts")) { - const shortcuts = config.get("shortcuts", []); - const commandOverride = shortcuts.find((shortcut) => - shortcut.command === name - ); - if (commandOverride) { - shortcut = commandOverride; - // console.log(`Shortcut override for ${name}:`, shortcut); - } - } options.push({ name: name, - hint: isMac && shortcut.mac ? shortcut.mac : shortcut.key, + hint: isMac && def.mac ? def.mac : def.key, orderId: recentCommands.has(name) ? -recentCommands.get(name)!.getTime() - : shortcut.priority || Infinity, + : def.priority || Infinity, }); // console.log("Options", options); } diff --git a/web/components/panel.tsx b/web/components/panel.tsx index 1a9fe19a..f9af050f 100644 --- a/web/components/panel.tsx +++ b/web/components/panel.tsx @@ -1,6 +1,6 @@ import { useEffect, useRef } from "preact/hooks"; import type { Client } from "../client.ts"; -import type { PanelConfig } from "../type.ts"; +import type { PanelConfig } from "../ui_types.ts"; import { panelHtml } from "./panel_html.ts"; export function Panel({ diff --git a/web/config.test.ts b/web/config.test.ts index e7ae6271..41417998 100644 --- a/web/config.test.ts +++ b/web/config.test.ts @@ -6,7 +6,7 @@ Deno.test("Config - basic functionality", () => { // Test set and get config.set("testKey", "testValue"); - assertEquals(config.get("testKey", null), "testValue"); + assertEquals(config.get(["testKey"], null), "testValue"); // Test default value assertEquals(config.get("nonExistentKey", "default"), "default"); @@ -31,7 +31,7 @@ Deno.test("Config - object-based setting", () => { assertEquals(config.get("key3", 0), 123); }); -Deno.test("Config - dot notation", () => { +Deno.test("Config - paths", () => { const config = new Config(); // Test setting with dot notation @@ -42,17 +42,26 @@ Deno.test("Config - dot notation", () => { assertEquals(config.get("user.name", null), "John"); assertEquals(config.get("user.profile.age", 0), 30); + config.set(["user", "name"], "Pete"); + config.set(["user", "profile", "age"], 20); + assertEquals(config.get(["user", "name"], null), "Pete"); + assertEquals(config.get(["user", "profile", "age"], 0), 20); + // Test has with dot notation assert(config.has("user.name")); assert(config.has("user.profile")); assert(config.has("user.profile.age")); assert(!config.has("user.profile.nonExistent")); + // Test with path notation + assert(config.has(["user", "name"])); + assert(config.has(["user", "profile", "age"])); + // Test getting the entire object assertEquals(config.get("user", {}), { - name: "John", + name: "Pete", profile: { - age: 30, + age: 20, }, }); }); @@ -137,6 +146,8 @@ Deno.test("Config - schema validation", () => { email: "john@example.com", }); + config.set("user.name", "John"); + // Missing required field should throw assertThrows( () => { @@ -160,6 +171,15 @@ Deno.test("Config - schema validation", () => { "Validation error for user", ); + // Wrong type should throw with path + assertThrows( + () => { + config.set(["user", "name"], 22); + }, + Error, + "Validation error for user", + ); + // Invalid format should throw assertThrows( () => { diff --git a/web/config.ts b/web/config.ts index 969e19e7..9fd847e7 100644 --- a/web/config.ts +++ b/web/config.ts @@ -21,6 +21,11 @@ export class Config { }); } + public clear() { + this.schemas = {}; + this.values = {}; + } + /** * Defines a JSON schema for a configuration key * @param key The configuration key to define a schema for @@ -44,7 +49,10 @@ export class Config { * @param defaultValue The default value to return if the path doesn't exist * @returns The value at the path, or the default value */ - get(path: string, defaultValue: T): T { + get(path: string | string[], defaultValue: T): T { + if (typeof path === "string") { + path = path.split("."); + } const resolved = this.resolvePath(path); if (!resolved) { return defaultValue; @@ -59,6 +67,12 @@ export class Config { * @param value The value to set */ set(path: string, value: T): void; + /** + * Sets a value in the config + * @param path The path to set (one path element per array element) + * @param value The value to set + */ + set(path: string[], value: T): void; /** * Sets multiple values in the config @@ -66,24 +80,38 @@ export class Config { */ set(values: Record): void; - set(keyOrValues: string | Record, value?: T): void { + set( + keyOrValues: string | string[] | Record, + value?: T, + ): void { if (typeof keyOrValues === "string") { - const key = keyOrValues; + // Normalize + keyOrValues = keyOrValues.split("."); + } + if (Array.isArray(keyOrValues)) { + const key = keyOrValues as string[]; - // Check if there's a schema for this key - if (this.schemas[key]) { - const validate = this.ajv.compile(this.schemas[key]); - if (!validate(value)) { - let errorText = this.ajv.errorsText(validate.errors); - errorText = errorText.replaceAll("/", "."); - errorText = errorText.replace(/^data[\.\s]/, ""); - throw new Error(`Validation error for ${key}: ${errorText}`); - } - } + const rootKey = key[0]; const resolved = this.resolvePath(key, true); if (resolved) { resolved.obj[resolved.key] = value; + } else { + throw new Error(`Invalid key ${key}`); + } + + // Check if there's a schema for this key + if (this.schemas[rootKey]) { + const validate = this.ajv.compile(this.schemas[rootKey]); + // Validate against the new injected value + if (!validate(this.values[rootKey])) { + let errorText = this.ajv.errorsText(validate.errors); + errorText = errorText.replaceAll("/", "."); + errorText = errorText.replace(/^data[\.\s]/, ""); + throw new Error( + `Validation error for ${key.join(".")}:> ${errorText}`, + ); + } } } else { // Handle object form @@ -98,7 +126,10 @@ export class Config { * @param path The path to check, supports dot notation (e.g. "foo.bar.baz") * @returns True if the path exists, false otherwise */ - has(path: string): boolean { + has(path: string | string[]): boolean { + if (typeof path === "string") { + path = path.split("."); + } const resolved = this.resolvePath(path); if (!resolved) { return false; @@ -116,25 +147,22 @@ export class Config { } /** - * Resolves a dot-notation path to the containing object and final key - * @param path The path to resolve (e.g. "foo.bar.baz") + * Resolves a configuration path to the containing object and final key + * @param path The path to resolve (e.g. ["foo", "bar", "baz"]) * @param create Whether to create objects along the path if they don't exist * @returns The containing object and the final key, or null if the path cannot be resolved */ private resolvePath( - path: string, + path: string[], create = false, ): { obj: any; key: string } | null { - if (!path.includes(".")) { - return { obj: this.values, key: path }; - } - - const parts = path.split("."); - const lastKey = parts.pop()!; + // To avoid side effects, let's clone the path bits + path = [...path]; + const lastKey = path.pop()!; let current = this.values; - for (const part of parts) { + for (const part of path) { if (current[part] === undefined) { if (create) { current[part] = {}; diff --git a/web/editor_state.ts b/web/editor_state.ts index 6e660181..7302bd32 100644 --- a/web/editor_state.ts +++ b/web/editor_state.ts @@ -305,53 +305,21 @@ export function createEditorState( export function createCommandKeyBindings(client: Client): KeyBinding[] { const commandKeyBindings: KeyBinding[] = []; - // Track which keyboard shortcuts for which commands we've overridden, so we can skip them later - const overriddenCommands = new Set(); - // Keyboard shortcuts from SETTINGS take precedence - if (client.config.has("shortcuts")) { - for (const shortcut of client.config.get("shortcuts", [])) { - overriddenCommands.add(shortcut.command); - commandKeyBindings.push({ - key: shortcut.key, - mac: shortcut.mac, - run: (): boolean => { - client.runCommandByName(shortcut.command, shortcut.args).catch( - (e: any) => { - console.error(e); - client.flashNotification( - `Error running command: ${e.message}`, - "error", - ); - }, - ).then((returnValue: any) => { - // Always be focusing the editor after running a command - if (returnValue !== false) { - client.focus(); - } - }); - return true; - }, - }); - } - } - // Then add bindings for plug commands - for (const def of client.clientSystem.commandHook.editorCommands.values()) { + for ( + const def of client.clientSystem.commandHook.buildAllCommands().values() + ) { const currentEditor = client.documentEditor?.name; - const requiredEditor = def.command.requireEditor; + const requiredEditor = def.requireEditor; - if (def.command.key && isValidEditor(currentEditor, requiredEditor)) { - // If we've already overridden this command, skip it - if (overriddenCommands.has(def.command.name)) { - continue; - } + if (def.key && isValidEditor(currentEditor, requiredEditor)) { commandKeyBindings.push({ - key: def.command.key, - mac: def.command.mac, + key: def.key, + mac: def.mac, run: (): boolean => { - if (def.command.contexts) { + if (def.contexts) { const context = client.getContext(); - if (!context || !def.command.contexts.includes(context)) { + if (!context || !def.contexts.includes(context)) { return false; } } diff --git a/web/editor_ui.tsx b/web/editor_ui.tsx index 52995ff0..f987d0ea 100644 --- a/web/editor_ui.tsx +++ b/web/editor_ui.tsx @@ -4,7 +4,11 @@ import { FilterList } from "./components/filter.tsx"; import { PageNavigator } from "./components/page_navigator.tsx"; import { TopBar } from "./components/top_bar.tsx"; import reducer from "./reducer.ts"; -import { type Action, type AppViewState, initialViewState } from "./type.ts"; +import { + type Action, + type AppViewState, + initialViewState, +} from "./ui_types.ts"; import * as featherIcons from "preact-feather"; import * as mdi from "./filtered_material_icons.ts"; import { h, render as preactRender } from "preact"; @@ -214,9 +218,9 @@ export class MainUI { onTrigger={(cmd) => { dispatch({ type: "hide-palette" }); if (cmd) { - dispatch({ type: "command-run", command: cmd.command.name }); + dispatch({ type: "command-run", command: cmd.name }); cmd - .run() + .run!() .catch((e: any) => { console.error("Error running command", e.message); }) @@ -235,7 +239,6 @@ export class MainUI { darkMode={viewState.uiOptions.darkMode} completer={client.miniEditorComplete.bind(client)} recentCommands={viewState.recentCommands} - config={client.config} /> )} {viewState.showFilterBox && ( @@ -334,7 +337,7 @@ export class MainUI { // Custom action buttons ...client.config.get( "actionButtons", - defaultActionButtons, + [], ).filter(( button, ) => @@ -351,12 +354,7 @@ export class MainUI { return { icon: mdiIcon ? mdiIcon : featherIcon, description: button.description || "", - callback: () => { - client.runCommandByName( - button.command, - button.args || [], - ); - }, + callback: button.run, href: "", }; }), @@ -423,29 +421,10 @@ export class MainUI { type ActionButton = { icon: string; description?: string; - command: string; - args?: any[]; mobile?: boolean; + run: () => void; }; -export const defaultActionButtons: ActionButton[] = [ - { - icon: "Home", - description: "Go to the index page", - command: "Navigate: Home", - }, - { - icon: "Book", - description: `Open page`, - command: "Navigate: Page Picker", - }, - { - icon: "Terminal", - description: `Run command`, - command: "Open Command Palette", - }, -]; - function kebabToCamel(str: string) { return str.replace(/-([a-z])/g, (g) => g[1].toUpperCase()).replace( /^./, diff --git a/web/hooks/command.ts b/web/hooks/command.ts index 3787c8f4..c13e6534 100644 --- a/web/hooks/command.ts +++ b/web/hooks/command.ts @@ -2,26 +2,33 @@ import type { Hook, Manifest } from "../../lib/plugos/types.ts"; import type { System } from "../../lib/plugos/system.ts"; import { EventEmitter } from "../../lib/plugos/event.ts"; import { throttle } from "../../lib/async.ts"; -import type { AppCommand, CommandHookEvents } from "../../lib/command.ts"; +import type { Command, CommandHookEvents } from "../../lib/command.ts"; import type { CommandHookT } from "$lib/manifest.ts"; export class CommandHook extends EventEmitter implements Hook { - editorCommands = new Map(); - system!: System; - throttledBuildAllCommands = throttle(() => { - this.buildAllCommands(); + system?: System; + public throttledBuildAllCommandsAndEmit = throttle(() => { + this.buildAllCommandsAndEmit(); }, 200); constructor( private readOnly: boolean, - private additionalCommandsMap: Map, + private additionalCommands: Map, ) { super(); } - buildAllCommands() { - this.editorCommands.clear(); + /** + * Build the command map + */ + buildAllCommands(): Map { + const commands = new Map(); + // Add commands from plugs + if (!this.system) { + // Not initialized yet + return commands; + } for (const plug of this.system.loadedPlugs.values()) { for ( const [name, functionDef] of Object.entries( @@ -36,30 +43,48 @@ export class CommandHook extends EventEmitter // Bit hacky, but don't expose commands that require write mode in read-only mode continue; } - this.editorCommands.set(cmd.name, { - command: cmd, + commands.set(cmd.name, { + ...cmd, run: (args?: string[]) => { return plug.invoke(name, [cmd, ...args ?? []]); }, }); } } - for (const [name, cmd] of this.additionalCommandsMap) { - this.editorCommands.set(name, cmd); + for (const [name, cmd] of this.additionalCommands) { + if (commands.has(name)) { + // Existing command, let's do some inline patching + const existingCommand = commands.get(name)!; + const command: Command = { + ...existingCommand, + ...cmd, + }; + if (cmd.run) { + command.run = cmd.run; + } + commands.set(name, command); + } else { + // New command, let's just set + commands.set(name, cmd); + } } - this.emit("commandsUpdated", this.editorCommands); + return commands; + } + + public buildAllCommandsAndEmit() { + this.emit("commandsUpdated", this.buildAllCommands()); } apply(system: System): void { this.system = system; system.on({ plugLoaded: () => { - this.throttledBuildAllCommands(); + this.throttledBuildAllCommandsAndEmit(); }, }); // On next tick setTimeout(() => { - this.throttledBuildAllCommands(); + this.throttledBuildAllCommandsAndEmit(); }); } diff --git a/web/hooks/event.ts b/web/hooks/event.ts index f2438b44..9d102ed8 100644 --- a/web/hooks/event.ts +++ b/web/hooks/event.ts @@ -1,17 +1,19 @@ import type { Manifest } from "$lib/plugos/types.ts"; import type { System } from "$lib/plugos/system.ts"; -import type { ScriptEnvironment } from "../space_script.ts"; import type { EventHookI } from "$lib/plugos/eventhook.ts"; import type { EventHookT } from "$lib/manifest.ts"; +import type { Config } from "../config.ts"; // System events: // - plug:load (plugName: string) export class EventHook implements EventHookI { - public scriptEnvironment?: ScriptEnvironment; private system?: System; private localListeners: Map any)[]> = new Map(); + constructor(readonly config?: Config) { + } + addLocalListener(eventName: string, callback: (...args: any[]) => any) { if (!this.localListeners.has(eventName)) { this.localListeners.set(eventName, []); @@ -97,12 +99,12 @@ export class EventHook implements EventHookI { } // Space script listeners - if (this.scriptEnvironment) { - for ( - const [name, listeners] of Object.entries( - this.scriptEnvironment.eventHandlers, - ) - ) { + if (this.config) { + const configListeners: Record = this.config.get( + "eventListeners", + {}, + ); + for (const [name, listeners] of Object.entries(configListeners)) { if (eventNameToRegex(name).test(eventName)) { for (const listener of listeners) { promises.push((async () => { diff --git a/web/hooks/slash_command.ts b/web/hooks/slash_command.ts index 21e13451..430f8331 100644 --- a/web/hooks/slash_command.ts +++ b/web/hooks/slash_command.ts @@ -12,18 +12,13 @@ import type { SlashCompletions, } from "../../plug-api/types.ts"; import { safeRun, throttle } from "$lib/async.ts"; -import type { SlashCommandDef, SlashCommandHookT } from "$lib/manifest.ts"; -import type { Shortcut } from "@silverbulletmd/silverbullet/type/client"; - -export type AppSlashCommand = { - slashCommand: SlashCommandDef; - run: () => Promise; -}; +import type { SlashCommandHookT } from "$lib/manifest.ts"; +import type { SlashCommand } from "../../lib/command.ts"; const slashCommandRegexp = /([^\w:]|^)\/[\w#\-]*/; export class SlashCommandHook implements Hook { - slashCommands: AppSlashCommand[] = []; + slashCommands: SlashCommand[] = []; throttledBuildAllCommands = throttle(() => { this.buildAllCommands(); }, 200); @@ -47,7 +42,7 @@ export class SlashCommandHook implements Hook { } const cmd = functionDef.slashCommand; this.slashCommands.push({ - slashCommand: cmd, + ...cmd, run: () => { return plug.invoke(name, [cmd]); }, @@ -57,27 +52,14 @@ export class SlashCommandHook implements Hook { // Iterate over script defined slash commands for ( const command of Object.values( - clientSystem.scriptEnv.slashCommands, + this.client.config.get>( + "slashCommands", + {}, + ), ) ) { this.slashCommands.push(command); } - // Iterate over all shortcuts - // Add slash commands for shortcuts that configure them - for ( - const shortcut of this.client.config.get("shortcuts", []) - ) { - if (shortcut.slashCommand) { - this.slashCommands.push({ - slashCommand: { - name: shortcut.slashCommand, - description: shortcut.command, - }, - run: () => - this.client.runCommandByName(shortcut.command, shortcut.args), - }); - } - } } // Completer for CodeMirror @@ -104,23 +86,24 @@ export class SlashCommandHook implements Hook { const parentNodes = this.client.extractParentNodes(ctx.state, currentNode); for (const def of this.slashCommands) { if ( - def.slashCommand.onlyContexts && !def.slashCommand.onlyContexts.some( - (context) => parentNodes.some((node) => node.startsWith(context)), + def.onlyContexts && + !def.onlyContexts.some((context) => + parentNodes.some((node) => node.startsWith(context)) ) ) { continue; } if ( - def.slashCommand.exceptContexts && def.slashCommand.exceptContexts.some( + def.exceptContexts && def.exceptContexts.some( (context) => parentNodes.some((node) => node.startsWith(context)), ) ) { continue; } options.push({ - label: def.slashCommand.name, - detail: def.slashCommand.description, - boost: def.slashCommand.boost, + label: def.name, + detail: def.description, + boost: def.priority, apply: () => { // Delete slash command part this.client.editorView.dispatch({ @@ -132,7 +115,7 @@ export class SlashCommandHook implements Hook { }); // Replace with whatever the completion is safeRun(async () => { - await def.run(); + await def.run!(); this.client.focus(); }); }, diff --git a/web/reducer.ts b/web/reducer.ts index a9c37fc3..a9da973c 100644 --- a/web/reducer.ts +++ b/web/reducer.ts @@ -1,5 +1,5 @@ import type { PageMeta } from "../plug-api/types.ts"; -import type { Action, AppViewState } from "./type.ts"; +import type { Action, AppViewState } from "./ui_types.ts"; export default function reducer( state: AppViewState, diff --git a/web/space_script.ts b/web/space_script.ts deleted file mode 100644 index cc0a846e..00000000 --- a/web/space_script.ts +++ /dev/null @@ -1,112 +0,0 @@ -import type { ParseTree } from "../plug-api/lib/tree.ts"; -import type { AppCommand, CommandDef, SlashCommand } from "$lib/command.ts"; -import type { SlashCommandDef } from "$lib/manifest.ts"; -import type { JSONSchemaType } from "ajv"; -import { jsToLuaValue, type LuaTable } from "../lib/space_lua/runtime.ts"; - -type FunctionDef = { - name: string; -}; - -type AttributeExtractorDef = { - tags: string[]; -}; - -export type EventListenerDef = { - name: string; -}; - -export type TagDef = { - name: string; - schema?: JSONSchemaType; - metatable?: LuaTable; -}; - -type AttributeExtractorCallback = ( - text: string, - tree: ParseTree, -) => Record | null | Promise | null>; - -export class ScriptEnvironment { - functions: Record any> = {}; - commands: Record = {}; - slashCommands: Record = {}; - eventHandlers: Record any)[]> = {}; - tagDefs: Record = {}; - - // DEPRECATED: To remove? - attributeExtractors: Record = {}; - - // Register function - registerFunction(def: FunctionDef, fn: (...args: any[]) => any): void; - // Legacy invocation - registerFunction(name: string, fn: (...args: any[]) => any): void; - registerFunction( - arg: string | FunctionDef, - fn: (...args: any[]) => any, - ): void { - if (typeof arg === "string") { - console.warn( - "registerFunction with string is deprecated, use `{name: string}` instead", - ); - arg = { name: arg }; - } - if (this.functions[arg.name]) { - console.warn(`Function ${arg.name} already registered, overwriting`); - } - this.functions[arg.name] = fn; - } - - registerCommand(command: CommandDef, fn: (...args: any[]) => any) { - this.commands[command.name] = { - command, - run: (...args: any[]) => { - return new Promise((resolve) => { - // Next tick - setTimeout(() => { - resolve(fn(...args)); - }); - }); - }, - }; - } - - registerSlashCommand( - def: SlashCommandDef, - fn: (...args: any[]) => any, - ) { - this.slashCommands[def.name] = { - slashCommand: def, - run: fn, - }; - } - - registerTag(def: TagDef) { - this.tagDefs[def.name] = { - ...def, - metatable: def.metatable ? jsToLuaValue(def.metatable) : undefined, - }; - } - - registerAttributeExtractor( - def: AttributeExtractorDef, - callback: AttributeExtractorCallback, - ) { - for (const tag of def.tags) { - if (!this.attributeExtractors[tag]) { - this.attributeExtractors[tag] = []; - } - this.attributeExtractors[tag].push(callback); - } - } - - registerEventListener( - def: EventListenerDef, - callback: (...args: any[]) => any, - ) { - if (!this.eventHandlers[def.name]) { - this.eventHandlers[def.name] = []; - } - this.eventHandlers[def.name].push(callback); - } -} diff --git a/web/syscalls/command.ts b/web/syscalls/command.ts deleted file mode 100644 index 03f92902..00000000 --- a/web/syscalls/command.ts +++ /dev/null @@ -1,69 +0,0 @@ -import type { SysCallMapping } from "$lib/plugos/system.ts"; -import type { CommandDef } from "$lib/command.ts"; -import { buildThreadLocalEnv, handleLuaError } from "../space_lua_api.ts"; -import { - type ILuaFunction, - jsToLuaValue, - luaCall, - LuaStackFrame, - luaValueToJS, -} from "../../lib/space_lua/runtime.ts"; -import type { ClientSystem } from "../client_system.ts"; - -export type CallbackCommandDef = CommandDef & { - run: ILuaFunction; -}; - -export function commandSyscalls( - clientSystem: ClientSystem, -): SysCallMapping { - return { - "command.define": ( - _ctx, - def: CallbackCommandDef, - ) => { - console.log("Registering Lua command: ", def.name); - clientSystem.scriptEnv.registerCommand( - def, - async (...args: any[]) => { - const tl = await buildThreadLocalEnv( - clientSystem.system, - clientSystem.spaceLuaEnv.env, - ); - const sf = new LuaStackFrame(tl, null); - try { - return luaValueToJS( - await luaCall(def.run, args.map(jsToLuaValue), {}, sf), - sf, - ); - } catch (e: any) { - await handleLuaError(e, clientSystem.system); - } - }, - ); - }, - "slashcommand.define": ( - _ctx, - def: CallbackCommandDef, - ) => { - clientSystem.scriptEnv.registerSlashCommand( - def, - async (...args: any[]) => { - const tl = await buildThreadLocalEnv( - clientSystem.system, - clientSystem.spaceLuaEnv.env, - ); - const sf = new LuaStackFrame(tl, null); - try { - return luaValueToJS( - await luaCall(def.run, args.map(jsToLuaValue), {}, sf), - sf, - ); - } catch (e: any) { - await handleLuaError(e, clientSystem.system); - } - }, - ); - }, - }; -} diff --git a/web/syscalls/config.ts b/web/syscalls/config.ts index 5c1a7d96..f4116588 100644 --- a/web/syscalls/config.ts +++ b/web/syscalls/config.ts @@ -8,11 +8,13 @@ export function configSyscalls(client: Client): SysCallMapping { }, "config.set": ( _ctx, - keyOrValues: string | Record, + keyOrValues: string | string[] | Record, value?: any, ) => { if (typeof keyOrValues === "string") { client.config.set(keyOrValues, value); + } else if (Array.isArray(keyOrValues)) { + client.config.set(keyOrValues, value); } else { client.config.set(keyOrValues); } diff --git a/web/syscalls/event.ts b/web/syscalls/event.ts index 1e7b8be1..e9f47947 100644 --- a/web/syscalls/event.ts +++ b/web/syscalls/event.ts @@ -1,5 +1,4 @@ import type { SysCallMapping } from "$lib/plugos/system.ts"; -import type { EventListenerDef } from "../space_script.ts"; import { buildThreadLocalEnv, handleLuaError } from "../space_lua_api.ts"; import { type ILuaFunction, @@ -8,14 +7,11 @@ import { LuaStackFrame, luaValueToJS, } from "../../lib/space_lua/runtime.ts"; -import type { ClientSystem } from "../client_system.ts"; - -export type CallbackEventListener = EventListenerDef & { - run: ILuaFunction; -}; +import { Client } from "../client.ts"; +import { EventSubscription } from "../../lib/event.ts"; export function eventListenerSyscalls( - clientSystem: ClientSystem, + client: Client, ): SysCallMapping { return { /** @@ -23,27 +19,20 @@ export function eventListenerSyscalls( */ "event.listen": ( _ctx, - def: CallbackEventListener, + def: EventSubscription, ) => { console.log("Registering Lua event listener: ", def.name); - clientSystem.scriptEnv.registerEventListener( - def, - async (...args: any[]) => { - const tl = await buildThreadLocalEnv( - clientSystem.system, - clientSystem.spaceLuaEnv.env, - ); - const sf = new LuaStackFrame(tl, null); - try { - return luaValueToJS( - await luaCall(def.run, args.map(jsToLuaValue), {}, sf), - sf, - ); - } catch (e: any) { - await handleLuaError(e, clientSystem.system); - } - }, - ); + const listeners = client.config.get([ + "eventListeners", + def.name, + ], []); + listeners.push((...args: any[]) => { + // Convert return value to JS + return def.run(...args).then((val) => + luaValueToJS(val, LuaStackFrame.lostFrame) + ); + }); + client.config.set(["eventListeners", def.name], listeners); }, }; } diff --git a/web/syscalls/index.ts b/web/syscalls/index.ts index 4c57e09d..7c340e4f 100644 --- a/web/syscalls/index.ts +++ b/web/syscalls/index.ts @@ -10,7 +10,12 @@ import { } from "../../lib/space_lua/runtime.ts"; import type { Client } from "../client.ts"; -import type { TagDef } from "../space_script.ts"; + +type TagDef = { + name: string; + schema?: any; + metatable?: any; +}; export function indexSyscalls(client: Client): SysCallMapping { return { @@ -28,11 +33,15 @@ export function indexSyscalls(client: Client): SysCallMapping { sf, (key, value: any) => { const tag = key[1]; - const tagDef = client.clientSystem.scriptEnv.tagDefs[tag]; + const tagDef = client.config.get>( + "tagDefinitions", + {}, + )[tag]; if (!tagDef) { // Return as is return value; } + console.log("Found this tagDef", tagDef); // Convert to LuaTable value = jsToLuaValue(value); value.metatable = tagDef.metatable; @@ -43,7 +52,7 @@ export function indexSyscalls(client: Client): SysCallMapping { }; }, "index.defineTag": (_ctx, tagDef: TagDef) => { - client.clientSystem.scriptEnv.registerTag(tagDef); + client.config.set(tagDef.name, tagDef); }, }; } diff --git a/web/syscalls/system.ts b/web/syscalls/system.ts index b9ed900d..8d94e3c9 100644 --- a/web/syscalls/system.ts +++ b/web/syscalls/system.ts @@ -1,8 +1,8 @@ import type { SyscallMeta } from "../../plug-api/types.ts"; import type { SysCallMapping } from "../../lib/plugos/system.ts"; import type { Client } from "../client.ts"; -import type { CommandDef } from "$lib/command.ts"; import { version } from "../../version.ts"; +import { CommandDef } from "../../lib/manifest.ts"; export function systemSyscalls( client: Client, @@ -53,15 +53,15 @@ export function systemSyscalls( "system.listCommands": (): { [key: string]: CommandDef } => { const commandHook = client.clientSystem.commandHook; const allCommands: { [key: string]: CommandDef } = {}; - for (const [cmd, def] of commandHook.editorCommands) { + for (const [cmd, def] of commandHook.buildAllCommands()) { allCommands[cmd] = { - name: def.command.name, - contexts: def.command.contexts, - priority: def.command.priority, - key: def.command.key, - mac: def.command.mac, - hide: def.command.hide, - requireMode: def.command.requireMode, + name: def.name, + contexts: def.contexts, + priority: def.priority, + key: def.key, + mac: def.mac, + hide: def.hide, + requireMode: def.requireMode, }; } return allCommands; diff --git a/web/type.ts b/web/ui_types.ts similarity index 96% rename from web/type.ts rename to web/ui_types.ts index 5d5f1ef2..1fca2be8 100644 --- a/web/type.ts +++ b/web/ui_types.ts @@ -1,4 +1,4 @@ -import type { AppCommand } from "../lib/command.ts"; +import type { Command } from "../lib/command.ts"; import type { FilterOption, Notification, PanelMode } from "../type/client.ts"; import type { DocumentMeta, @@ -40,7 +40,7 @@ export type AppViewState = { progressType?: string; // Used for styling panels: { [key: string]: PanelConfig }; - commands: Map; + commands: Map; notifications: Notification[]; recentCommands: Map; @@ -127,7 +127,7 @@ export type Action = | { type: "stop-navigate" } | { type: "update-commands"; - commands: Map; + commands: Map; } | { type: "show-palette"; context?: string } | { type: "hide-palette" } diff --git a/website/API/command.md b/website/API/command.md index 7ce1f41f..4c421727 100644 --- a/website/API/command.md +++ b/website/API/command.md @@ -1,25 +1 @@ -APIs related to editor commands - -### command.define(commandDef) -Registers a command. - -Available keys: - -* `name`: Name of the command -* `run`: Callback function -* `contexts`: AST node context in which this command should be available -* `priority`: Command priority (how high it appears in the list) -* `key`: Windows/Linux key binding (and mac, if not separately defined) -* `mac`: Mac-specific key binding -* `hide`: Hide this command from the [[Command Palette]] -* `requireMode`: `rw` or `ro` — only enable this command in a particular mode (read-write, or read-only) - -Example: -```lua -command.define { - name = "My custom command", - run = function() - editor.flashNotification "Triggered my custom command" - end -} -``` \ No newline at end of file +See [[^Library/Std/Command]] \ No newline at end of file diff --git a/website/API/slashcommand.md b/website/API/slashcommand.md index cb4a28b7..f0b956d9 100644 --- a/website/API/slashcommand.md +++ b/website/API/slashcommand.md @@ -1,16 +1,19 @@ APIs to create [[Slash Commands]]. For simple cases it is recommended to use [[Library/Std/Slash Templates]] instead. -## slashcommand.define(spec) +## slashCommand.define(spec) + Define a custom slash command. Supported keys in the spec: + * `name`: name of the command * `description`: Description of the command * `run`: The callback function that will be invoked once the command is run. Example: + ```lua -slashcommand.define { +slashCommand.define { name = "hello-world", run = function() editor.insertAtCursor("Hello |^| world!", false, true) diff --git a/website/CONFIG.md b/website/CONFIG.md index a4b245d9..922d71ae 100644 --- a/website/CONFIG.md +++ b/website/CONFIG.md @@ -8,42 +8,45 @@ config.set { actionButtons = { { icon = "home", - command = "Navigate: Home", - description = "Go to the index page" + description = "Go to the index page", + run = function() + system.invokeCommand("Navigate: Home") + end }, { icon = "activity", description = "What's new", - command = "Navigate: To Page", - args = {"CHANGELOG"} + run = function() + editor.navigate { + page = "CHANGELOG" + } + end }, { icon = "message-circle", description = "Community", - command = "Navigate: To URL", - args = {"https://community.silverbullet.md"} + run = function() + editor.openUrl "https://community.silverbullet.md" + end }, { icon = "book", - command = "Navigate: Page Picker", - description = "Open page" + description = "Open page", + run = function() + system.invokeCommand("Navigate: Page Picker") + end }, { icon = "terminal", - command = "Open Command Palette", - description = "Run command" + description = "Run command", + run = function() + system.invokeCommand "Open Command Palette" + end, } }, smartQuotes = { enabled = true, }, - shortcuts = { - { - command = "Stats: Show", - key = "Ctrl-Shift-s", - slashCommand = "stats" - } - }, queryCollate = { enabled = true, locale = "en", diff --git a/website/Manual.md b/website/Manual.md index 6be4b74e..9f0c17df 100644 --- a/website/Manual.md +++ b/website/Manual.md @@ -1,12 +1,17 @@ -Welcome to the wonderful world of SilverBullet. The goal of this manual is to give you a broad sense of how to use this tool and what it’s capable of. However, its full capabilities are yet to be discovered. You too may find new and creative ways to use the various SilverBullet features in ways nobody previously thought of. +Welcome to the wonderful world of SilverBullet. The goal of this manual is to give you a broad sense of how to use this +tool and what it’s capable of. However, its full capabilities are yet to be discovered. You too may find new and +creative ways to use the various SilverBullet features in ways nobody previously thought of. -However, that is all unlikely to happen unless you understand what SilverBullet can actually do. So let’s give you a bit of a sense. +However, that is all unlikely to happen unless you understand what SilverBullet can actually do. So let’s give you a bit +of a sense. # Keeping up-to-date -* [[CHANGELOG]]: what’s new in SilverBullet? This page will give you the latest details. It’s worth monitoring this page. +* [[CHANGELOG]]: what’s new in SilverBullet? This page will give you the latest details. It’s worth monitoring this + page. # Installation and deployment -The biggest hurdle to get over with SilverBullet is that you need to get this thing running. And as of yet, the only way to do that is to install and deploy it yourself. 🤷 +The biggest hurdle to get over with SilverBullet is that you need to get this thing running. And as of yet, the only way +to do that is to install and deploy it yourself. 🤷 * [[Install]]: Installation instructions for various setups @@ -24,6 +29,7 @@ SilverBullet’s UI is minimalist by design. Let’s look at the few UI elements # Core Concepts These are the core concepts used in SilverBullet: + * [[Spaces]] * [[Pages]] (and [[Meta Pages]]) * [[Frontmatter]] @@ -45,6 +51,7 @@ These are the core concepts used in SilverBullet: # Navigation The main ways to roam your space, beside following page links, are: + * [[Page Picker]] * [[Meta Picker]] * [[Full Text Search]] @@ -59,15 +66,18 @@ The main ways to roam your space, beside following page links, are: # Customization * [[^Library/Std/Config]] -* [[Shortcuts]] * [[Page Decorations]] * [[Space Style]] # Extending SilverBullet SilverBullet’s implementation is built on three things: + * The core is implemented as a TypeScript-based web app * A lot of core functionality is implemented in [[Plugs]]. * An increasing amount of additional functionality is now being implemented in “native” [[Space Lua]]. # Contributing -SilverBullet is free and open-source software. You can contribute to it [via Github](https://github.com/silverbulletmd/silverbullet). For some details on how to do this, have a look at [[Development]]. + +SilverBullet is free and open-source software. You can contribute to +it [via Github](https://github.com/silverbulletmd/silverbullet). For some details on how to do this, have a look +at [[Development]]. diff --git a/website/Shortcuts.md b/website/Shortcuts.md deleted file mode 100644 index fb488f01..00000000 --- a/website/Shortcuts.md +++ /dev/null @@ -1,36 +0,0 @@ -SilverBullet enables you to configure some custom shortcuts in [[^Library/Std/Config]] via the `shortcuts` attribute that trigger [[Commands]] in various ways. - -Supported types of shortcuts: -* Keyboard Shortcuts that create keyboard bindings for a given command -* [[Slash Commands]] shortcuts that enable triggering a command via a slash command -* Priority shortcuts to tweak the ordering of commands in the [[Command Palette]] - -# Configuration -Using Space Lua: - -```lua -config.set { - shortcuts = { - -- Keyboard shortcuts: - { - command = "Navigate: Center Cursor", - key = "Alt-x", -- for Linux/Windows - mac = "Alt-x", -- for macOS (and other Apple devices with keyboards) - }, - -- Slash command shortcuts: - { - command = "Outline: Move Right", - slashCommand = "indent", - }, - { - command = "Outline: Move Left", - slashCommand = "outdent", - }, - -- Priority shortcut - { - command = "Upload: File", - priority = 1, - } - } -} -``` diff --git a/website/Space Lua.md b/website/Space Lua.md index 0e00ebce..cb58d580 100644 --- a/website/Space Lua.md +++ b/website/Space Lua.md @@ -34,7 +34,7 @@ It is possible to control load order of space lua scripts using the special `-- Scripts are loaded in _reverse priority_ order. When you set no priority (the default) your scripts will be run last. -The order used is determined by this [[Space Lua/Lua Integrated Query|query]] (also part of your [[^Library/Std/Space Overview]]) page: +The order used is determined by this [[Space Lua/Lua Integrated Query|query]] (also part of your [[^Library/Std/Space Overview]]) page: query[[ from index.tag "space-lua" @@ -45,9 +45,9 @@ This means that the higher the priority, the earlier the script is loaded. That Here are the conventions used by the [[Library/Std]] library: - * `priority: 100` for config definitions (schemas) - * `priority: 50` for setting really core and root variables (like `template.*` APIs) that will be used by other scripts - * `priority: 10`: for standard library definitions that may be overriden (by scripts with lower priority) +* `priority: 100` for config definitions (schemas) +* `priority: 50` for setting really core and root variables (like `template.*` APIs) that will be used by other scripts +* `priority: 10`: for standard library definitions that may be overriden (by scripts with lower priority) > **note** Tip > All your space-lua scripts are loaded on boot, to reload them without reloading the page, simply run the ${widgets.commandButton("System: Reload")} (Ctrl-Alt-r) command. @@ -72,6 +72,7 @@ ${query[[ [[Space Lua/Widgets]] ## Commands + Custom commands can be defined using [[API/command#command.define(commandDef)]]: ```space-lua @@ -87,10 +88,11 @@ command.define { Try it: ${widgets.commandButton("Hello World")} ## Slash commands -Custom slash commands can be defined using [[API/slashcommand#slashcommand.define(spec)]]: + +Custom slash commands can be defined using [[API/slashcommand#slashCommand.define(spec)]]: ```space-lua -slashcommand.define { +slashCommand.define { name = "hello", run = function() editor.insertAtCursor("Hello |^| world!", false, true) @@ -99,6 +101,7 @@ editor.insertAtCursor("Hello |^| world!", false, true) ``` ## Event listeners + You can listen to events using [[API/event#event.listen(listenerDef)]]: ```space-lua @@ -112,21 +115,25 @@ event.listen { ``` # Space Lua Extensions + Space Lua introduces a few new features on top core Lua: 1. [[Space Lua/Lua Integrated Query]], embedding a query language into Lua itself 2. Thread locals ## Thread locals + There's a magic `_CTX` global variable available from which you can access useful context-specific values. Currently the following keys are available: * `_CTX.currentPage` providing access (in the client only) to the currently open page (PageMeta object) * `_CTX._GLOBAL` providing access to the global scope # API + ![[API]] # Lua implementation notes + Space Lua is intended to be a more or less complete implementation of [Lua 5.4](https://www.lua.org/manual/5.4/). However, a few features are (still) missing: * `goto` and labels (not planned, goto considered harmful) @@ -136,8 +143,11 @@ Space Lua is intended to be a more or less complete implementation of [Lua 5.4]( * Hexadecimal numeric constants with a fractional part, or binary exponents (not supported by JavaScript number parser either) # Frequently Asked Questions + ## Why Lua? + Lua is purpose-designed to be a simple, [easy to learn](https://www.lua.org/manual/5.4/), yet powerful language for extending existing applications. It is commonly used in the gaming industry, but to extend many other applications. If you know any other programming language, you will be able to learn Lua within hours or less. ## Why a custom Lua runtime? + Rather than using a WebAssembly or other implementation of Lua that could run in the browser and server, we have opted for a custom implementation. This is achievable because Lua is a relatively simple and small language to implement and allows for deep integration in the custom Lua runtime. The thing that triggered a custom implementation was the need to call asynchronous (JavaScipt) APIs from Lua, without having to resort to ugly asynchronous callback-style API design (Lua does not support async-await). In SilverBullet’s Lua implementation, the differences between asynchronous and synchronous APIs is fully abstracted away, which makes for a very clean development experience. diff --git a/website/Special Pages.md b/website/Special Pages.md index 86838492..4e5ed087 100644 --- a/website/Special Pages.md +++ b/website/Special Pages.md @@ -5,4 +5,3 @@ All special pages except [[CONFIG]] are optional: if they don’t exist, well, t Here are the current list of “special pages” known to humankind: * [[CONFIG]] for setting various settings -* [[VIMRC]] for tweaking [[Vim]] mode diff --git a/website/VIMRC.md b/website/VIMRC.md deleted file mode 100644 index 6da7cbf1..00000000 --- a/website/VIMRC.md +++ /dev/null @@ -1,7 +0,0 @@ -As part of SilverBullet’s [[Vim]] support, the [[VIMRC]] page allows you to run a set of _ex_ commands on boot. To use this functionality, create a page in your space named [[VIMRC]] and put a fenced code block (as demonstrated below) with one ex command per line, for example: - -``` -imap jj -``` - -To manually reload your [[VIMRC]] you can use the ${widgets.commandButton("Editor: Vim: Load VIMRC")} command. \ No newline at end of file diff --git a/website/Vim.md b/website/Vim.md index 088bae55..77ea88af 100644 --- a/website/Vim.md +++ b/website/Vim.md @@ -3,16 +3,13 @@ ${widgets.commandButton("Editor: Toggle Vim Mode")} command. In addition, it supports various ex commands that you can run as you would expect, for instance: `:imap jj `. -These commands can be configured in a [[VIMRC]] file placed in the root directory. -Alternatively, the [[CONFIG]] file can also be used to define and extend these commands. It supports the following: +The [[CONFIG]] file can also be used to define and extend these commands. It supports the following: + - **Key unmapping** - disable existing keybindings - **Custom mappings** - using `map` and `noremap` - **Ex command definitions** - map custom ex commands to built-in or custom SilverBullet commands -Both the [[VIMRC]] and [[CONFIG]] files will run on boot and work alongside each other. - -To manually reload the `vim` section of your [[CONFIG]], use the -${widgets.commandButton("Editor: Vim: Load Vim Config")} command. +To manually reload the `vim` section of your [[CONFIG]], use the ${widgets.commandButton("Editor: Vim: Load Vim Config")} command. # Configuration Using Space Lua: