From 64e537732ba84ecfe713cc79ea7236bd80ca3444 Mon Sep 17 00:00:00 2001 From: Zef Hemel Date: Fri, 28 Mar 2025 12:17:17 +0100 Subject: [PATCH 1/6] `Debug: Reset Client` is now called `System: Wipe Client` Merged two datastores into one (for both state and files), this will trigger a resync on upgrade --- common/syscalls/system.ts | 61 ++++++++++++++++++++++++++ deno.json | 6 +-- lib/data/indexeddb_kv_primitives.ts | 5 +-- plug-api/syscalls.ts | 1 - plug-api/syscalls/debug.ts | 19 -------- plug-api/syscalls/system.ts | 4 ++ plugs/editor/clean.ts | 14 ------ plugs/editor/debug.ts | 20 --------- plugs/editor/editor.plug.yaml | 22 ++++------ plugs/editor/system.ts | 31 +++++++++++++ scripts/build_website.sh | 31 +------------ web/client.ts | 44 ++++++++----------- web/client_system.ts | 2 - web/service_worker.ts | 64 ++++++++++++++++----------- web/sync_service.ts | 27 ++++++++++++ web/syscalls/debug.ts | 68 ----------------------------- web/syscalls/fetch.ts | 5 ++- website/API/debug.md | 20 --------- website/API/system.md | 10 +++++ 19 files changed, 206 insertions(+), 248 deletions(-) delete mode 100644 plug-api/syscalls/debug.ts delete mode 100644 plugs/editor/clean.ts delete mode 100644 plugs/editor/debug.ts create mode 100644 plugs/editor/system.ts delete mode 100644 web/syscalls/debug.ts delete mode 100644 website/API/debug.md diff --git a/common/syscalls/system.ts b/common/syscalls/system.ts index 9292b177..2da6ab7c 100644 --- a/common/syscalls/system.ts +++ b/common/syscalls/system.ts @@ -3,6 +3,7 @@ import type { SysCallMapping } from "../../lib/plugos/system.ts"; import type { Client } from "../../web/client.ts"; import type { CommandDef } from "$lib/command.ts"; import { version } from "../../version.ts"; +import { deleteDB } from "idb"; export function systemSyscalls( client: Client, @@ -98,6 +99,66 @@ export function systemSyscalls( } await client.loadCustomStyles(); }, + "system.wipeClient": async () => { + // Two tracks: + // 1. Service worker unregister + // 2. IndexedDB cleaning + if (navigator.serviceWorker) { + const registration = await navigator.serviceWorker.ready; + + if (registration?.active) { + // Disconnect the datastore in the service worker first + registration.active.postMessage({ type: "shutdown" }); + // Then flush the cache + registration.active.postMessage({ type: "flushCache" }); + await new Promise((resolve) => { + navigator.serviceWorker.addEventListener("message", (event) => { + if (event.data.type === "cacheFlushed") { + console.log("Cache flushed"); + navigator.serviceWorker.getRegistrations().then( + async (registrations) => { + for (const registration of registrations) { + await registration.unregister(); + } + resolve(); + }, + ); + } + }); + }); + } else { + console.info("No service worker active, so not unregistering"); + } + } else { + console.info("Service workers not supported, so not unregistering"); + } + console.log("Stop all the systems"); + client.space.unwatch(); + client.syncService.close(); + client.ds.kv.close(); + if (indexedDB.databases) { + // get a list of all existing IndexedDB databases + const databases = await indexedDB.databases(); + // loop through the list and delete each database + for (const database of databases) { + console.log("Deleting database", database.name); + await deleteDB(database.name!); + } + } else { + // Firefox doesn't support indexedDB.databases :( + console.info( + "Cannot delete local database, so go to empty them instead", + ); + const allKeys = []; + for await ( + const { key } of client.ds.kv.query({}) + ) { + allKeys.push(key); + } + await client.ds.batchDelete(allKeys); + } + alert("Client wiped, feel free to navigate elsewhere"); + }, // DEPRECATED "system.getEnv": () => { console.warn( diff --git a/deno.json b/deno.json index b687c007..2b580ffc 100644 --- a/deno.json +++ b/deno.json @@ -29,7 +29,7 @@ ] }, "tasks": { - "clean": "rm -rf dist dist_client_bundle dist_plug_bundle website_build", + "clean": "rm -rf dist dist_client_bundle dist_plug_bundle", "deep-clean-mac": "rm -f deno.lock && rm -rf $HOME/Library/Caches/deno && deno task clean", "install": "deno install -g -f -A --import-map deno.json silverbullet.ts", @@ -41,7 +41,7 @@ "test": "deno test -A", "bench": "deno bench", - "build": "deno run -A build_plugs.ts && deno run -A build_web.ts", + "build": "rm -rf dist dist_client_bundle dist_plug_bundle && deno run -A build_plugs.ts && deno run -A build_web.ts", "plugs": "deno run -A build_plugs.ts", "server": "deno run -A --check silverbullet.ts", "generate": "./scripts/generate.sh", @@ -76,7 +76,6 @@ "exclude": [ "dist*", "website", - "website_build", "test_space", "**/*.md", "**/*.html", @@ -151,6 +150,7 @@ "fast-diff": "https://esm.sh/fast-diff@1.3.0", "fuse": "https://deno.land/x/fuse@v6.4.1/dist/fuse.esm.min.js", "gitignore-parser": "https://esm.sh/gitignore-parser@0.0.2", + "idb": "https://esm.sh/idb@7.1.1/with-async-ittr", "hono": "jsr:@hono/hono@4.7.4", "hono/cookie": "jsr:@hono/hono@4.7.4/cookie", "hono/validator": "jsr:@hono/hono@4.7.4/validator", diff --git a/lib/data/indexeddb_kv_primitives.ts b/lib/data/indexeddb_kv_primitives.ts index d0708314..99ce29ea 100644 --- a/lib/data/indexeddb_kv_primitives.ts +++ b/lib/data/indexeddb_kv_primitives.ts @@ -1,9 +1,6 @@ import type { KV, KvKey } from "../../plug-api/types.ts"; import type { KvPrimitives, KvQueryOptions } from "./kv_primitives.ts"; -import { - type IDBPDatabase, - openDB, -} from "https://esm.sh/idb@7.1.1/with-async-ittr"; +import { type IDBPDatabase, openDB } from "idb"; const sep = "\0"; const objectStoreName = "data"; diff --git a/plug-api/syscalls.ts b/plug-api/syscalls.ts index b9b7e60c..c5df3dee 100644 --- a/plug-api/syscalls.ts +++ b/plug-api/syscalls.ts @@ -4,7 +4,6 @@ export * as space from "./syscalls/space.ts"; export * as system from "./syscalls/system.ts"; export * as clientStore from "./syscalls/clientStore.ts"; export * as sync from "./syscalls/sync.ts"; -export * as debug from "./syscalls/debug.ts"; export * as language from "./syscalls/language.ts"; export * as codeWidget from "./syscalls/code_widget.ts"; export * as asset from "./syscalls/asset.ts"; diff --git a/plug-api/syscalls/debug.ts b/plug-api/syscalls/debug.ts deleted file mode 100644 index a540aa3c..00000000 --- a/plug-api/syscalls/debug.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { syscall } from "../syscall.ts"; - -/** - * Exposes various debugging utilities. - */ - -/** - * Completely wipes the client state, both cached files as well as databases (best effort) - */ -export function resetClient(): Promise { - return syscall("debug.resetClient"); -} - -/** - * Wipes the entire state KV store and the entire space KV store. - */ -export function cleanup(): Promise { - return syscall("debug.cleanup"); -} diff --git a/plug-api/syscalls/system.ts b/plug-api/syscalls/system.ts index 379094e3..5c79c433 100644 --- a/plug-api/syscalls/system.ts +++ b/plug-api/syscalls/system.ts @@ -74,3 +74,7 @@ export function getConfig( ): Promise { return syscall("system.getConfig", key, defaultValue); } + +export function wipeClient(): Promise { + return syscall("system.wipeClient"); +} diff --git a/plugs/editor/clean.ts b/plugs/editor/clean.ts deleted file mode 100644 index 8a42690b..00000000 --- a/plugs/editor/clean.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { debug, editor } from "@silverbulletmd/silverbullet/syscalls"; - -export async function cleanCommand() { - if ( - !await editor.confirm( - "This will remove all your locally cached data and authentication cookies. Are you sure?", - ) - ) { - return; - } - await editor.flashNotification("Now wiping all state and logging out..."); - await debug.cleanup(); - await editor.alert("Cleanup done. Please close this window."); -} diff --git a/plugs/editor/debug.ts b/plugs/editor/debug.ts deleted file mode 100644 index 74c8a7de..00000000 --- a/plugs/editor/debug.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { debug, editor, markdown } from "@silverbulletmd/silverbullet/syscalls"; - -export async function parsePageCommand() { - console.log( - "AST", - JSON.stringify( - await markdown.parseMarkdown(await editor.getText()), - null, - 2, - ), - ); -} - -export async function resetClientCommand() { - await debug.resetClient(); -} - -export async function reloadUICommand() { - await editor.reloadUI(); -} diff --git a/plugs/editor/editor.plug.yaml b/plugs/editor/editor.plug.yaml index 9a88593a..ee7055bb 100644 --- a/plugs/editor/editor.plug.yaml +++ b/plugs/editor/editor.plug.yaml @@ -287,7 +287,7 @@ functions: # Debug commands parseCommand: - path: ./debug.ts:parsePageCommand + path: ./system.ts:parsePageCommand command: name: "Debug: Parse Document" requireEditor: page @@ -312,15 +312,16 @@ functions: command: name: "Stats: Show" requireEditor: page - reloadUICommand: - path: ./debug.ts:reloadUICommand - command: - name: "Debug: Reload UI" - resetClientCommand: - path: ./debug.ts:resetClientCommand + reloadUICommand: + path: ./system.ts:reloadUICommand command: - name: "Debug: Reset Client" + name: "System: Reload UI" + + wipeClientCommand: + path: ./system.ts:wipeClientCommand + command: + name: "System: Wipe Client" versionCommand: path: ./help.ts:versionCommand @@ -331,11 +332,6 @@ functions: command: name: "Help: Getting Started" - accountLogoutCommand: - path: clean.ts:cleanCommand - command: - name: "Clear Local Storage & Logout" - uploadFileCommand: path: ./upload.ts:uploadFile command: diff --git a/plugs/editor/system.ts b/plugs/editor/system.ts new file mode 100644 index 00000000..a47339fb --- /dev/null +++ b/plugs/editor/system.ts @@ -0,0 +1,31 @@ +import { + editor, + markdown, + system, +} from "@silverbulletmd/silverbullet/syscalls"; + +export async function parsePageCommand() { + console.log( + "AST", + JSON.stringify( + await markdown.parseMarkdown(await editor.getText()), + null, + 2, + ), + ); +} + +export async function wipeClientCommand() { + if ( + !await editor.confirm( + "Are you sure you want to wipe the client? This will clean the local cache.", + ) + ) { + return; + } + await system.wipeClient(); +} + +export async function reloadUICommand() { + await editor.reloadUI(); +} diff --git a/scripts/build_website.sh b/scripts/build_website.sh index 3c082a35..70dd9253 100755 --- a/scripts/build_website.sh +++ b/scripts/build_website.sh @@ -11,37 +11,8 @@ if [ "$1" != "local" ]; then fi deno task clean -mkdir -p website_build/_plug website_build/_client - -echo "Copying website content" -cp -r website/* website_build/ -#rm website_build/{_redirects,_headers} - -echo "Building silver bullet" deno task build - -echo "Copying silverbullet runtime files" -cp dist_client_bundle/* website_build/ -cp -r dist_client_bundle/.client/* website_build/_client/ - -echo "And all plugs" -cp -r dist_plug_bundle/_plug/* website_build/_plug/ -#echo "And additional ones" -curl https://raw.githubusercontent.com/silverbulletmd/silverbullet-mermaid/main/mermaid.plug.js > website_build/_plug/mermaid.plug.js -echo "But remove some plugs" -rm -rf website_build/_plug/{plugmd}.plug.js - - -# Generate random modified date, and replace in _headers too -export LAST_MODIFIED_TIMESTAMP=$(date +%s000) - -cat website/_headers | sed "s/12345/$LAST_MODIFIED_TIMESTAMP/g" > website_build/_headers -echo "Generating file listing" -deno run -A scripts/generate_fs_list.ts > website_build/index.json - - -#echo "Bundling..." deno task bundle +mkdir -p website_build cp dist/silverbullet.js website_build/ -cp web/images/logo.ico website_build/ cp install.sh website_build/ \ No newline at end of file diff --git a/web/client.ts b/web/client.ts index 01b8eba8..30b895ab 100644 --- a/web/client.ts +++ b/web/client.ts @@ -61,7 +61,6 @@ import { DataStoreMQ } from "$lib/data/mq.datastore.ts"; import { DataStoreSpacePrimitives } from "$common/spaces/datastore_space_primitives.ts"; import { ReadOnlySpacePrimitives } from "$common/spaces/ro_space_primitives.ts"; -import type { KvPrimitives } from "$lib/data/kv_primitives.ts"; import { LimitedMap } from "$lib/limited_map.ts"; import { plugPrefix } from "$common/spaces/constants.ts"; import { diffAndPrepareChanges } from "./cm_util.ts"; @@ -106,8 +105,7 @@ export class Client { httpSpacePrimitives!: HttpSpacePrimitives; ui!: MainUI; - stateDataStore!: DataStore; - spaceKV!: KvPrimitives; + ds!: DataStore; mq!: DataStoreMQ; config = new Config(); @@ -156,31 +154,31 @@ export class Client { * This is a separated from the constructor to allow for async initialization */ async init() { - // Setup the state data store - const stateKvPrimitives = new IndexedDBKvPrimitives( - `${this.dbPrefix}_state`, + // Setup the data store + const kvPrimitives = new IndexedDBKvPrimitives( + `${this.dbPrefix}`, ); - await stateKvPrimitives.init(); - this.stateDataStore = new DataStore(stateKvPrimitives); + await kvPrimitives.init(); + this.ds = new DataStore(kvPrimitives); // Setup message queue - this.mq = new DataStoreMQ(this.stateDataStore); + this.mq = new DataStoreMQ(this.ds); // Instantiate a PlugOS system this.clientSystem = new ClientSystem( this, this.mq, - this.stateDataStore, + this.ds, this.eventHook, this.clientConfig.readOnly, ); - const localSpacePrimitives = await this.initSpace(); + const localSpacePrimitives = this.initSpace(); this.syncService = new SyncService( localSpacePrimitives, this.plugSpaceRemotePrimitives, - this.stateDataStore, + this.ds, this.eventHook, (path) => { // isSyncCandidate // Exclude all plug space primitives paths @@ -449,7 +447,7 @@ export class Client { this.navigateWithinPage(locationState); // Persist this page as the last opened page, we'll use this for cold start PWA loads - await this.stateDataStore.set( + await this.ds.set( ["client", "lastOpenedPath"], locationState.page, ); @@ -457,7 +455,7 @@ export class Client { if (location.hash === "#boot") { // Cold start PWA load - const lastPath = await this.stateDataStore.get([ + const lastPath = await this.ds.get([ "client", "lastOpenedPath", ]); @@ -472,7 +470,7 @@ export class Client { }, 100); } - async initSpace(): Promise { + initSpace(): SpacePrimitives { this.httpSpacePrimitives = new HttpSpacePrimitives( location.origin, this.clientConfig.spaceFolderPath, @@ -492,18 +490,12 @@ export class Client { this.clientConfig.readOnly ? undefined : "client", ); - // We'll store the space files in a separate data store - const spaceKvPrimitives = new IndexedDBKvPrimitives( - `${this.dbPrefix}_synced_space`, - ); - await spaceKvPrimitives.init(); - const localSpacePrimitives = new EventedSpacePrimitives( // Using fallback space primitives here to allow (by default) local reads to "fall through" to HTTP when files aren't synced yet new FallbackSpacePrimitives( new DataStoreSpacePrimitives( new DataStore( - spaceKvPrimitives, + this.ds.kv, ), ), this.plugSpaceRemotePrimitives, @@ -511,8 +503,6 @@ export class Client { this.eventHook, ); - this.spaceKV = spaceKvPrimitives; - this.space = new Space( localSpacePrimitives, this.eventHook, @@ -1509,7 +1499,7 @@ export class Client { async loadCaches() { const [widgetHeightCache, widgetCache] = await this - .stateDataStore.batchGet([[ + .ds.batchGet([[ "cache", "widgetHeight", ], ["cache", "widgets"]]); @@ -1518,7 +1508,7 @@ export class Client { } debouncedWidgetHeightCacheFlush = throttle(() => { - this.stateDataStore.set( + this.ds.set( ["cache", "widgetHeight"], this.widgetHeightCache.toJSON(), ) @@ -1536,7 +1526,7 @@ export class Client { } debouncedWidgetCacheFlush = throttle(() => { - this.stateDataStore.set(["cache", "widgets"], this.widgetCache.toJSON()) + this.ds.set(["cache", "widgets"], this.widgetCache.toJSON()) .catch( console.error, ); diff --git a/web/client_system.ts b/web/client_system.ts index 1218f1eb..b9ac6ad4 100644 --- a/web/client_system.ts +++ b/web/client_system.ts @@ -12,7 +12,6 @@ import { CommandHook } from "$common/hooks/command.ts"; import { SlashCommandHook } from "./hooks/slash_command.ts"; import { SyscallHook } from "./hooks/syscall.ts"; import { clientStoreSyscalls } from "./syscalls/clientStore.ts"; -import { debugSyscalls } from "./syscalls/debug.ts"; import { editorSyscalls } from "./syscalls/editor.ts"; import { sandboxFetchSyscalls } from "./syscalls/fetch.ts"; import { markdownSyscalls } from "$common/syscalls/markdown.ts"; @@ -178,7 +177,6 @@ export class ClientSystem { mqSyscalls(this.mq), dataStoreReadSyscalls(this.ds, this), dataStoreWriteSyscalls(this.ds), - debugSyscalls(this.client), syncSyscalls(this.client), clientStoreSyscalls(this.ds), configSyscalls(this.client), diff --git a/web/service_worker.ts b/web/service_worker.ts index fb18ba57..13c33726 100644 --- a/web/service_worker.ts +++ b/web/service_worker.ts @@ -208,32 +208,44 @@ async function handleLocalFileRequest( } self.addEventListener("message", (event: any) => { - if (event.data.type === "skipWaiting") { - console.log( - "[Service worker]", - "Received skipWaiting message, activating immediately", - ); - // @ts-ignore: Skip waiting to activate this service worker immediately - self.skipWaiting(); - } - if (event.data.type === "flushCache") { - caches.delete(CACHE_NAME) - .then(() => { - console.log("[Service worker]", "Cache deleted"); - // ds?.close(); - event.source.postMessage({ type: "cacheFlushed" }); + switch (event.data.type) { + case "skipWaiting": { + console.log( + "[Service worker]", + "Received skipWaiting message, activating immediately", + ); + // @ts-ignore: Skip waiting to activate this service worker immediately + self.skipWaiting(); + break; + } + case "flushCache": { + caches.delete(CACHE_NAME) + .then(() => { + console.log("[Service worker]", "Cache deleted"); + // ds?.close(); + event.source.postMessage({ type: "cacheFlushed" }); + }); + break; + } + case "config": { + const spaceFolderPath = event.data.config.spaceFolderPath; + const dbPrefix = "" + simpleHash(spaceFolderPath); + + // Setup space + const kv = new IndexedDBKvPrimitives(`${dbPrefix}`); + kv.init().then(() => { + ds = new DataStore(kv); + console.log("Datastore in service worker initialized..."); }); - } - - if (event.data.type === "config") { - const spaceFolderPath = event.data.config.spaceFolderPath; - const dbPrefix = "" + simpleHash(spaceFolderPath); - - // Setup space - const kv = new IndexedDBKvPrimitives(`${dbPrefix}_synced_space`); - kv.init().then(() => { - ds = new DataStore(kv); - console.log("Datastore in service worker initialized..."); - }); + break; + } + case "shutdown": { + if (ds) { + console.log("[Service worker]", "Disconnecting datastore"); + ds.kv.close(); + ds = undefined; + } + break; + } } }); diff --git a/web/sync_service.ts b/web/sync_service.ts index 9b543e04..730f7370 100644 --- a/web/sync_service.ts +++ b/web/sync_service.ts @@ -41,6 +41,7 @@ export class SyncService { lastReportedSyncStatus = Date.now(); // If this is set to anything other than undefined, a file is currently saving savingTimeout: number | undefined; + enabled = true; constructor( readonly localSpacePrimitives: SpacePrimitives, @@ -64,6 +65,9 @@ export class SyncService { eventHook.addLocalListener( "editor:pageLoaded", (name, _prevPage, isSynced) => { + if (!this.enabled) { + return; + } if (!isSynced) { this.scheduleFileSync(`${name}.md`).catch(console.error); } @@ -71,6 +75,9 @@ export class SyncService { ); eventHook.addLocalListener("editor:documentLoaded", (name, _prevPage) => { + if (!this.enabled) { + return; + } this.scheduleFileSync(name).catch(console.error); }); @@ -85,6 +92,9 @@ export class SyncService { eventHook.addLocalListener("editor:documentSaving", setSavingTimeout); eventHook.addLocalListener("editor:pageSaved", (name) => { + if (!this.enabled) { + return; + } if (this.savingTimeout) { clearTimeout(this.savingTimeout); this.savingTimeout = undefined; @@ -96,6 +106,9 @@ export class SyncService { }); eventHook.addLocalListener("editor:documentSaved", (name) => { + if (!this.enabled) { + return; + } if (this.savingTimeout) { clearTimeout(this.savingTimeout); this.savingTimeout = undefined; @@ -201,6 +214,7 @@ export class SyncService { } filesScheduledForSync = new Set(); + async scheduleFileSync(path: string): Promise { if (this.filesScheduledForSync.has(path)) { // Already scheduled, no need to duplicate @@ -222,6 +236,9 @@ export class SyncService { this.syncSpace().catch(console.error); setInterval(async () => { + if (!this.enabled) { + return; + } try { if (!await this.isSyncing()) { const lastFullCycle = (await this.ds.get(syncLastFullCycleKey)) || 0; @@ -237,6 +254,9 @@ export class SyncService { } async syncSpace(): Promise { + if (!this.enabled) { + return 0; + } if (await this.isSyncing()) { console.log("Aborting space sync: already syncing"); return 0; @@ -264,6 +284,9 @@ export class SyncService { // Syncs a single file async syncFile(name: string) { + if (!this.enabled) { + return; + } // console.log("Checking if we can sync file", name); if (!this.isSyncCandidate(name)) { console.info("Requested sync, but not a sync candidate", name); @@ -337,6 +360,10 @@ export class SyncService { await this.ds.set(syncSnapshotKey, Object.fromEntries(snapshot)); } + close() { + this.enabled = false; + } + public async plugAwareConflictResolver( name: string, snapshot: Map, diff --git a/web/syscalls/debug.ts b/web/syscalls/debug.ts deleted file mode 100644 index ef0462cd..00000000 --- a/web/syscalls/debug.ts +++ /dev/null @@ -1,68 +0,0 @@ -import type { KvKey } from "../../plug-api/types.ts"; -import type { SysCallMapping } from "../../lib/plugos/system.ts"; -import type { Client } from "../client.ts"; - -export function debugSyscalls(client: Client): SysCallMapping { - return { - "debug.resetClient": async () => { - if (navigator.serviceWorker) { - const registration = await navigator.serviceWorker.ready; - - if (registration?.active) { - registration.active.postMessage({ type: "flushCache" }); - await new Promise((resolve) => { - navigator.serviceWorker.addEventListener("message", (event) => { - if (event.data.type === "cacheFlushed") { - console.log("Cache flushed"); - navigator.serviceWorker.getRegistrations().then( - async (registrations) => { - for (const registration of registrations) { - await registration.unregister(); - } - resolve(); - }, - ); - } - }); - }); - } else { - alert("No service worker active, so not unregistering"); - } - } else { - alert("Service workers not supported, so not unregistering"); - } - if (indexedDB.databases) { - // get a list of all existing IndexedDB databases - const databases = await indexedDB.databases(); - // loop through the list and delete each database - for (const database of databases) { - indexedDB.deleteDatabase(database.name!); - } - } else { - alert("Cannot flush local databases (Firefox user?)"); - } - - // And finally, reload the page - alert("Reset complete, now reloading the page..."); - location.reload(); - }, - "debug.cleanup": async () => { - console.log("Wiping the entire space KV store"); - // In sync mode, we can just delete the whole space - let allKeys: KvKey[] = []; - for await (const { key } of client.spaceKV.query({})) { - allKeys.push(key); - } - await client.spaceKV.batchDelete(allKeys); - localStorage.clear(); - console.log("Wiping the entire state KV store"); - allKeys = []; - for await ( - const { key } of client.stateDataStore.kv.query({}) - ) { - allKeys.push(key); - } - await client.stateDataStore.batchDelete(allKeys); - }, - }; -} diff --git a/web/syscalls/fetch.ts b/web/syscalls/fetch.ts index 2afcbb79..a4f907db 100644 --- a/web/syscalls/fetch.ts +++ b/web/syscalls/fetch.ts @@ -49,7 +49,10 @@ export function sandboxFetchSyscalls( let body: any; if (resp.headers.get("Content-Type")?.startsWith("application/json")) { body = await resp.json(); - } else if (resp.headers.get("Content-Type")?.startsWith("application/xml") || resp.headers.get("Content-Type")?.startsWith("text/")) { + } else if ( + resp.headers.get("Content-Type")?.startsWith("application/xml") || + resp.headers.get("Content-Type")?.startsWith("text/") + ) { body = await resp.text(); } else { body = new Uint8Array(await resp.arrayBuffer()); diff --git a/website/API/debug.md b/website/API/debug.md deleted file mode 100644 index aa3c2e97..00000000 --- a/website/API/debug.md +++ /dev/null @@ -1,20 +0,0 @@ -# Debug API - -The Debug API provides functions for debugging and resetting the application state. - -## debug.resetClient() -Completely wipes the client state, including cached files and databases. - -Example: -```lua -debug.resetClient() -print("Client state has been reset") -``` - -## debug.cleanup() -Wipes the entire state KV store and the entire space KV store. - -Example: -```lua -debug.cleanup() -print("All KV stores have been wiped") diff --git a/website/API/system.md b/website/API/system.md index 54f2ee6a..444fa591 100644 --- a/website/API/system.md +++ b/website/API/system.md @@ -99,3 +99,13 @@ Example: ```lua system.reloadPlugs() print("All plugs reloaded") + + +## system.wipeClient() +Completely wipes the client state, including cached files, service worker and databases. + +Example: +```lua +system.wipeClient() +print("Client state has been reset") +``` From 2787c40ebefbecf92e8e57ff404db26b0f1a1e6d Mon Sep 17 00:00:00 2001 From: Zef Hemel Date: Fri, 28 Mar 2025 12:50:35 +0100 Subject: [PATCH 2/6] Better Lua parse error reporting --- plug-api/lib/tree.test.ts | 6 ------ plug-api/lib/tree.ts | 25 +------------------------ plugs/index/lint.ts | 14 +++++++------- 3 files changed, 8 insertions(+), 37 deletions(-) diff --git a/plug-api/lib/tree.test.ts b/plug-api/lib/tree.test.ts index f5b967e4..32949c92 100644 --- a/plug-api/lib/tree.test.ts +++ b/plug-api/lib/tree.test.ts @@ -4,7 +4,6 @@ import { collectNodesMatching, findParentMatching, nodeAtPos, - parseTreeToAST, removeParentPointers, renderToText, replaceNodesMatching, @@ -69,8 +68,3 @@ Deno.test("Test parsing", () => { parse(extendedMarkdownLanguage, mdTest3); // console.log(JSON.stringify(mdTree3, null, 2)); }); - -Deno.test("AST functions", () => { - const mdTree = parse(extendedMarkdownLanguage, mdTest1); - console.log(JSON.stringify(parseTreeToAST(mdTree), null, 2)); -}); diff --git a/plug-api/lib/tree.ts b/plug-api/lib/tree.ts index c4b65ce3..a731face 100644 --- a/plug-api/lib/tree.ts +++ b/plug-api/lib/tree.ts @@ -214,33 +214,10 @@ export function cloneTree(tree: ParseTree): ParseTree { return newTree; } -export function parseTreeToAST(tree: ParseTree, omitTrimmable = true): AST { - if (tree.type === "⚠") { - // console.info("Parse error", JSON.stringify(tree, null, 2)); - throw new Error( - `Parse error in: ${renderToText(tree)}`, - ); - } - if (tree.text !== undefined) { - return tree.text; - } - const ast: AST = [tree.type!]; - for (const node of tree.children!) { - if (node.type && !node.type.endsWith("Mark") && node.type !== "Comment") { - ast.push(parseTreeToAST(node, omitTrimmable)); - } - if (node.text && (omitTrimmable && node.text.trim() || !omitTrimmable)) { - ast.push(node.text); - } - } - return ast; -} - export function cleanTree(tree: ParseTree, omitTrimmable = true): ParseTree { if (tree.type === "⚠") { - // console.info("Parse error", JSON.stringify(tree, null, 2)); throw new Error( - `Parse error in: ${renderToText(tree)}`, + `Parse error at pos ${tree.from}`, ); } if (tree.text !== undefined) { diff --git a/plugs/index/lint.ts b/plugs/index/lint.ts index ef3c4c95..57ed01a3 100644 --- a/plugs/index/lint.ts +++ b/plugs/index/lint.ts @@ -103,18 +103,18 @@ export async function lintLua({ tree }: LintEvent): Promise { const offset = codeText.from!; let from = codeText.from!; let to = codeText.to!; - if (e.message.includes("Parse error (")) { - const errorMatch = errorRegex.exec(e.message); - if (errorMatch) { - from = offset + parseInt(errorMatch[1], 10); - to = offset + parseInt(errorMatch[2], 10); - } + let message = e.message; + if (message.includes("Parse error")) { + const pos = +message.slice("Parse error at pos ".length); + from = offset + pos; + to = offset + pos; + message = "Parse error"; } diagnostics.push({ from, to, severity: "error", - message: e.message, + message, }); console.log("Lua error", e); } From 1703020a8abbddee206bb0cecdb72ee0a87bfc38 Mon Sep 17 00:00:00 2001 From: Zef Hemel Date: Fri, 28 Mar 2025 13:45:39 +0100 Subject: [PATCH 3/6] feat: Add logout option to client wipe functionality - Add optional logout parameter to system.wipeClient - Add new 'Clear Local Storage & Logout' command - Update API to support logout parameter - Clean up server code comments --- common/syscalls/system.ts | 8 ++++++-- plug-api/syscalls/system.ts | 4 ++-- plugs/editor/editor.plug.yaml | 5 +++++ plugs/editor/system.ts | 4 ++++ server/http_server.ts | 1 - 5 files changed, 17 insertions(+), 5 deletions(-) diff --git a/common/syscalls/system.ts b/common/syscalls/system.ts index 2da6ab7c..2aeffb2b 100644 --- a/common/syscalls/system.ts +++ b/common/syscalls/system.ts @@ -99,7 +99,7 @@ export function systemSyscalls( } await client.loadCustomStyles(); }, - "system.wipeClient": async () => { + "system.wipeClient": async (_ctx, logout = false) => { // Two tracks: // 1. Service worker unregister // 2. IndexedDB cleaning @@ -157,7 +157,11 @@ export function systemSyscalls( } await client.ds.batchDelete(allKeys); } - alert("Client wiped, feel free to navigate elsewhere"); + if (logout) { + location.href = "/.logout"; + } else { + alert("Client wiped, feel free to navigate elsewhere"); + } }, // DEPRECATED "system.getEnv": () => { diff --git a/plug-api/syscalls/system.ts b/plug-api/syscalls/system.ts index 5c79c433..8c5f7d2c 100644 --- a/plug-api/syscalls/system.ts +++ b/plug-api/syscalls/system.ts @@ -75,6 +75,6 @@ export function getConfig( return syscall("system.getConfig", key, defaultValue); } -export function wipeClient(): Promise { - return syscall("system.wipeClient"); +export function wipeClient(logout = false): Promise { + return syscall("system.wipeClient", logout); } diff --git a/plugs/editor/editor.plug.yaml b/plugs/editor/editor.plug.yaml index ee7055bb..30039963 100644 --- a/plugs/editor/editor.plug.yaml +++ b/plugs/editor/editor.plug.yaml @@ -323,6 +323,11 @@ functions: command: name: "System: Wipe Client" + wipeAndLogoutCommand: + path: ./system.ts:wipeAndLogoutCommand + command: + name: "Clear Local Storage & Logout" + versionCommand: path: ./help.ts:versionCommand command: diff --git a/plugs/editor/system.ts b/plugs/editor/system.ts index a47339fb..fca22872 100644 --- a/plugs/editor/system.ts +++ b/plugs/editor/system.ts @@ -26,6 +26,10 @@ export async function wipeClientCommand() { await system.wipeClient(); } +export async function wipeAndLogoutCommand() { + await system.wipeClient(true); +} + export async function reloadUICommand() { await editor.reloadUI(); } diff --git a/server/http_server.ts b/server/http_server.ts index d1f80674..58f7a6a3 100644 --- a/server/http_server.ts +++ b/server/http_server.ts @@ -238,7 +238,6 @@ export class HttpServer { ) : new LockoutTimer(0, 0); // disabled - // TODO: This should probably be a POST request this.app.get("/.logout", (c) => { const url = new URL(c.req.url); deleteCookie(c, authCookieName(url.host)); From c28e7aacf50957cca0c7164bdbad11f3039bdb39 Mon Sep 17 00:00:00 2001 From: Zef Hemel Date: Fri, 28 Mar 2025 15:57:46 +0100 Subject: [PATCH 4/6] Fixes #1311 --- Library/Std/Widgets.md | 77 ++++++++++++++++++++++++++++++++---------- 1 file changed, 59 insertions(+), 18 deletions(-) diff --git a/Library/Std/Widgets.md b/Library/Std/Widgets.md index c814b596..76dbf8ba 100644 --- a/Library/Std/Widgets.md +++ b/Library/Std/Widgets.md @@ -2,25 +2,47 @@ Some useful widgets. -# Button -A simple button. +# Buttons +Types of button widgets: + +* `widgets.button(text, callback)` renders a simple button running the callback when clicked +* `widgets.commandButton(commandName)` renders a button for a particular command (where the button text is the command name itself) +* `widgets.commandButton(text, commandName)` renders a button for a particular command with a custom button text +* `widgets.commandButton(text, commandName, args)` renders a button for a particular command and arguments (specified as a table list) with a custom button text ```space-lua -widgets = widgets or {} +-- priority: 10 function widgets.button(text, callback) - options = options or {} return widget.new { html = "", events = { click = callback } } end + +function widgets.commandButton(text, commandName, args) + if not commandName then + -- When only passed one argument, then let's assume it's a command name + commandName = text + end + return widget.new { + html = "", + events = { + click = function() + system.invokeCommand(commandName, args) + end + } + } +end ``` -Example: +Examples: + ${widgets.button("Hello", function() editor.flashNotification "Hi there!" end)} +${widgets.commandButton("System: Reload")} + # Table of contents ```space-lua widgets = widgets or {} @@ -42,23 +64,42 @@ function widgets.toc(options) local text = editor.getText() local pageName = editor.getCurrentPage() local lines = string.split(text, "\n") - local tocTexts = {} + local pos = 0 + -- Collect all headers + local headers = {} for _, line in ipairs(lines) do - local headerStart, headerEnd = string.find(line, "^(%#+%s+)") - if headerStart then - local headerText = line:sub(headerEnd + 1) - table.insert(tocTexts, string.rep(" ", (headerEnd-1) * 2) - .. "* [[" .. pageName .. "#" .. headerText .. "|" .. headerText .. "]]") + local headerSign, text = string.match(line, "^(%#+)%s+(.+)$") + if headerSign then + table.insert(headers, { + name = text, + pos = pos, + level = #headerSign, + }) + end + pos = pos + #line + 1 + end + if options.minHeaders and options.minHeaders > #headers then + return widget.new{} + end + -- Find min level + local minLevel = 6 + for _, header in ipairs(headers) do + if header.level < minLevel then + minLevel = header.level end end - if #tocTexts >= options.minHeaders then - local fullText = "# Table of Contents\n" .. table.concat(tocTexts, "\n") - return widget.new { - markdown = fullText - } - else - return "" + -- Build up markdown + local md = (options.header or "# Table of Contents") .. "\n" + for _, header in ipairs(headers) do + if not(options.maxHeader and header.level > options.maxHeader or + options.minLevel and header.level < options.minLevel) then + md = md .. string.rep(" ", (header.level - minLevel) * 2) + + "* [[" .. pageName .. "@" .. header.pos .. "|" .. header.name .. "]]\n" + end end + return widget.new { + markdown = md + } end event.listen { From 45b767fd3ca01d9f5c70a16f5935796169c1c03a Mon Sep 17 00:00:00 2001 From: Zef Hemel Date: Fri, 28 Mar 2025 17:38:32 +0100 Subject: [PATCH 5/6] Lua widgets: html can now also be a DOM node Encoding some more space lua priorities and documenting them --- Library/Std/Config.md | 1 + Library/Std/Embed.md | 2 +- Library/Std/Lua.md | 5 ++ Library/Std/Page Templates.md | 1 + Library/Std/Slash.md | 2 + Library/Std/Space Overview.md | 5 +- Library/Std/Template.md | 2 +- Library/Std/Widget.md | 11 +++- common/space_lua/stdlib/js.ts | 5 ++ web/cm_plugins/lua_widget.ts | 103 ++++++++++++++++++++++------------ website/API/command.md | 1 + website/SETTINGS.md | 87 ---------------------------- website/Shortcuts.md | 41 +++++++++----- website/Space Lua.md | 67 +++++++++------------- 14 files changed, 147 insertions(+), 186 deletions(-) delete mode 100644 website/SETTINGS.md diff --git a/Library/Std/Config.md b/Library/Std/Config.md index 714be890..16bb6141 100644 --- a/Library/Std/Config.md +++ b/Library/Std/Config.md @@ -3,6 +3,7 @@ This defines the [JSON schema](https://json-schema.org/) for built-in settings. ```space-lua +-- priority: 100 config.define("plugs", { description = "List of plugs to enable", oneOf = { diff --git a/Library/Std/Embed.md b/Library/Std/Embed.md index ce910ade..3b6ad57f 100644 --- a/Library/Std/Embed.md +++ b/Library/Std/Embed.md @@ -60,6 +60,6 @@ end # General implementation ```space-lua --- priority: 5 +-- priority: 50 embed = {} ``` diff --git a/Library/Std/Lua.md b/Library/Std/Lua.md index c24b987d..64652d07 100644 --- a/Library/Std/Lua.md +++ b/Library/Std/Lua.md @@ -4,6 +4,7 @@ Editor support for Lua, implemented in Lua. Of course. # Code complete support ```space-lua +-- priority: 10 local LUA_KEYWORDS = {"do", "if", "then", "for", "else", "end", "function", "local", "return"} -- Are we in a comment? @@ -121,6 +122,7 @@ event.listen { Ctrl/Cmd-click navigation to Lua function definition. ```space-lua +-- priority: 10 local function inLuaContext(parentNodes) for _, node in ipairs(parentNodes) do if node == "LuaDirective" @@ -192,6 +194,8 @@ Useful Lua slash commands for editing Lua files. ## In-lua slash commands ```space-lua +-- priority: 10 + slashcommand.define { name = "func", description = "Create a new function", @@ -251,6 +255,7 @@ slashcommand.define { ## Lua slash commands ```space-lua +-- priority: 10 -- Outside Space Lua contexts slashcommand.define { name = "space-lua", diff --git a/Library/Std/Page Templates.md b/Library/Std/Page Templates.md index 1c1be222..ede5e918 100644 --- a/Library/Std/Page Templates.md +++ b/Library/Std/Page Templates.md @@ -2,6 +2,7 @@ # Quick Note ```space-lua +-- priority: 10 command.define { name = "Quick Note", key = "Alt-Shift-n", diff --git a/Library/Std/Slash.md b/Library/Std/Slash.md index 410d1a6a..74ed498e 100644 --- a/Library/Std/Slash.md +++ b/Library/Std/Slash.md @@ -3,6 +3,8 @@ Some convenient slash commands for editing Markdown files. ```space-lua +-- priority: 10 + local function headerSlashCommand(level) local line = editor.getCurrentLine() local cleanText = string.gsub(line.textWithCursor, "^#+%s*", "") diff --git a/Library/Std/Space Overview.md b/Library/Std/Space Overview.md index 3e9c2f45..7a185811 100644 --- a/Library/Std/Space Overview.md +++ b/Library/Std/Space Overview.md @@ -11,8 +11,9 @@ These are all Space Lua scripts and the order in which they are loaded: ${template.each(query[[ from index.tag "space-lua" order by _.priority desc - select { name=ref } -]], templates.pageItem)} +]], template.new[==[ + * [[${ref}]] (priority: ${priority or "default"}) +]==])} # Active Space Style ${template.each(query[[ diff --git a/Library/Std/Template.md b/Library/Std/Template.md index 61dfc5c3..19cbab79 100644 --- a/Library/Std/Template.md +++ b/Library/Std/Template.md @@ -3,7 +3,7 @@ Implements useful template functions ```space-lua --- priority: 10 +-- priority: 50 -- Template API root table template = template or {} -- Template storage table diff --git a/Library/Std/Widget.md b/Library/Std/Widget.md index 298fab84..5f7f0b70 100644 --- a/Library/Std/Widget.md +++ b/Library/Std/Widget.md @@ -3,12 +3,12 @@ This implements the widget API. For a Lua Directive to be rendered as a widget, you need to return it via `widget.new`. ```space-lua --- priority: 5 +-- priority: 50 -- Widget APIs widget = {} --- Reusable set of widgets +-- Container for widgets widgets = {} -- Widget schema for validation @@ -16,7 +16,12 @@ local widgetSchema = { type = "object", properties = { markdown = { type = "string"}, - html = { type = "string"}, + html = { + anyOf = { + { type = "object"}, + { type = "string" } + } + }, cssClasses = { type = "array", items = { type = "string" }, diff --git a/common/space_lua/stdlib/js.ts b/common/space_lua/stdlib/js.ts index d0caf673..5d69e266 100644 --- a/common/space_lua/stdlib/js.ts +++ b/common/space_lua/stdlib/js.ts @@ -67,4 +67,9 @@ export const jsApi = new LuaTable({ * @returns The JSON string. */ stringify: new LuaBuiltinFunction((_sf, val) => JSON.stringify(val)), + + // Exposing DOM functions + createElement: new LuaBuiltinFunction((_sf, tag) => + document.createElement(tag) + ), }); diff --git a/web/cm_plugins/lua_widget.ts b/web/cm_plugins/lua_widget.ts index 4851bd27..41f17ad6 100644 --- a/web/cm_plugins/lua_widget.ts +++ b/web/cm_plugins/lua_widget.ts @@ -31,7 +31,7 @@ export type LuaWidgetContent = { // Magic marker _isWidget?: true; // Render as HTML - html?: string; + html?: string | HTMLElement; // Render as markdown markdown?: string; // CSS classes for wrapper @@ -62,18 +62,20 @@ export class LuaWidget extends WidgetType { wrapperSpan.appendChild(innerDiv); const cacheItem = this.client.getWidgetCache(this.cacheKey); if (cacheItem) { - innerDiv.innerHTML = this.wrapHtml(!!cacheItem.block, cacheItem.html); + // This is to make the initial render faster, will later be replaced by the actual content + innerDiv.replaceChildren( + this.wrapHtml(!!cacheItem.block, cacheItem.html), + ); } // Async kick-off of content renderer - this.renderContent(innerDiv, cacheItem?.html).catch(console.error); + this.renderContent(innerDiv).catch(console.error); this.dom = wrapperSpan; return wrapperSpan; } async renderContent( div: HTMLElement, - cachedHtml: string | undefined, ) { let widgetContent = await this.callback( this.bodyText, @@ -92,7 +94,7 @@ export class LuaWidget extends WidgetType { widgetContent = { markdown: "nil", _isWidget: true }; } - let html = ""; + let html: HTMLElement | undefined; let block = false; // Normalization @@ -108,7 +110,9 @@ export class LuaWidget extends WidgetType { div.className = widgetContent.cssClasses.join(" "); } if (widgetContent.html) { - html = widgetContent.html; + html = typeof widgetContent.html === "string" + ? parseHtmlString(widgetContent.html) + : widgetContent.html; block = widgetContent.display === "block"; if (block) { @@ -158,7 +162,7 @@ export class LuaWidget extends WidgetType { trimmedMarkdown, ); - html += renderMarkdownToHtml(mdTree, { + html = parseHtmlString(renderMarkdownToHtml(mdTree, { // Annotate every element with its position so we can use it to put // the cursor there when the user clicks on the table. annotationPositions: true, @@ -173,20 +177,16 @@ export class LuaWidget extends WidgetType { return url; }, preserveAttributes: true, - }, this.client.ui.viewState.allPages); - } - if (cachedHtml !== html) { - // If the content has changed, update the DOM - div.innerHTML = this.wrapHtml(block, html); + }, this.client.ui.viewState.allPages)); } if (html) { + div.replaceChildren(this.wrapHtml(block, html)); attachWidgetEventHandlers( div, this.client, this.inPage ? "${" + this.bodyText + "}" : undefined, widgetContent._isWidget && widgetContent.events, ); - this.attachHandlers(div); } // Let's give it a tick, then measure and cache @@ -195,7 +195,7 @@ export class LuaWidget extends WidgetType { this.cacheKey, { height: div.offsetHeight, - html, + html: html?.outerHTML || "", block, }, ); @@ -208,25 +208,23 @@ export class LuaWidget extends WidgetType { }); } - wrapHtml(isBlock: boolean, html: string): string { + wrapHtml(isBlock: boolean, html: string | HTMLElement): HTMLElement { + if (typeof html === "string") { + html = parseHtmlString(html); + } if (!isBlock) { return html; } - return `
- + const container = document.createElement("div"); + const buttonBar = document.createElement("div"); + buttonBar.className = "button-bar"; - ${ - this.inPage - ? ` - - ` - : "" - } -
${html}
`; - } - - attachHandlers(div: HTMLElement) { - div.querySelector(`button[data-button="reload"]`)?.addEventListener( + const reloadButton = document.createElement("button"); + reloadButton.setAttribute("data-button", "reload"); + reloadButton.setAttribute("title", "Reload"); + reloadButton.innerHTML = + ''; + reloadButton.addEventListener( "click", (e) => { e.stopPropagation(); @@ -236,14 +234,33 @@ export class LuaWidget extends WidgetType { ).catch(console.error); }, ); + buttonBar.appendChild(reloadButton); - div.querySelector(`button[data-button="edit"]`)?.addEventListener( - "click", - (e) => { - e.stopPropagation(); - moveCursorIntoText(this.client, "${" + this.bodyText + "}"); - }, - ); + if (this.inPage) { + const editButton = document.createElement("button"); + editButton.setAttribute("data-button", "edit"); + editButton.setAttribute("title", "Edit"); + editButton.innerHTML = + ''; + editButton.addEventListener( + "click", + (e) => { + e.stopPropagation(); + console.log("EDIT"); + moveCursorIntoText(this.client, "${" + this.bodyText + "}"); + }, + ); + buttonBar.appendChild(editButton); + } + + const content = document.createElement("div"); + content.className = "content"; + content.appendChild(html); + + container.appendChild(buttonBar); + container.appendChild(content); + + return container; } override get estimatedHeight(): number { @@ -255,7 +272,6 @@ export class LuaWidget extends WidgetType { return ( other instanceof LuaWidget && other.bodyText === this.bodyText && other.cacheKey === this.cacheKey - // && this.from === other.from ); } } @@ -288,3 +304,16 @@ export function renderExpressionResult(result: any): Promise { return Promise.resolve("" + result); } } + +export function parseHtmlString(html: string): HTMLElement { + const parser = new DOMParser(); + const doc = parser.parseFromString(html, "text/html"); + // Create a wrapper div to hold all elements + const wrapper = document.createElement("span"); + wrapper.className = "wrapper"; + // Move all body children into the wrapper + while (doc.body.firstChild) { + wrapper.appendChild(doc.body.firstChild); + } + return wrapper; +} diff --git a/website/API/command.md b/website/API/command.md index 243c05bc..7ce1f41f 100644 --- a/website/API/command.md +++ b/website/API/command.md @@ -22,3 +22,4 @@ command.define { editor.flashNotification "Triggered my custom command" end } +``` \ No newline at end of file diff --git a/website/SETTINGS.md b/website/SETTINGS.md deleted file mode 100644 index 12c8c486..00000000 --- a/website/SETTINGS.md +++ /dev/null @@ -1,87 +0,0 @@ -#meta - -This page contains configuration of SilverBullet and its plugs. Some of these changes will go into effect immediately, some require a page reload. - -```space-config -libraries: -# The "Core" library is recommended for all users -- import: "[[!silverbullet.md/Library/Core/*]]" - # You can exclude items from the import using exclude (also supports wildcards): - #exclude: - # - "[[!silverbullet.md/Table of Contents]]" - # - "[[!silverbullet.md/Library/Core/Widget/*]]"" - -## UI TWEAKS -# Hide the sync button -hideSyncButton: false -# Hide the edit button (available on mobile only) -hideEditButton: true # defaults to 'false' - -# Style the menu as a vertical fly-out on smaller screens (default) -# Use `mobileMenuStyle: "bottom-bar"` to style it as a bar on the bottom of the screen -# Use `mobileMenuStyle: null` to prevent mobile-specific styling -mobileMenuStyle: "hamburger" - -# In PWA mode, SilverBullet automatically reopens the last opened page on boot, this can be disabled -pwaOpenLastPage: true - -# Configure the shown action buttons (top right bar) -actionButtons: -- icon: home # Use any icon from https://feathericons.com - command: "{[Navigate: Home]}" - description: "Go to the index page" -- icon: activity - description: "What's new" - command: '{[Navigate: To Page]("CHANGELOG")}' -- icon: message-circle - description: "Community" - command: '{[Navigate: To URL]("https://community.silverbullet.md")}' -- icon: book - command: "{[Navigate: Page Picker]}" - description: Open page -- icon: terminal - command: "{[Open Command Palette]}" - description: Run command -#- icon: arrow-left -# command: "{[Navigate: Back in History]}" -# description: "Go to the previous page" -# mobile: true # Only show on mobile devices, set to false to show only on desktop - -# Create keyboard or slash command shortcuts for commands -shortcuts: -# Map a key to a command -- command: "{[Navigate: Center Cursor]}" - key: "Alt-x" -# Map a slash command (e.g. `/indent`) to a command -- command: "{[Outline: Move Right]}" - slashCommand: "indent" -# Bump a command's priority in the command palette -- command: "{[Upload: File]}" - priority: 1 - -# Choose which characters to auto-close -autoCloseBrackets: "([{`" -# Options for “smart” ‘quotes’ (left and right) used outside of code fragments, these are the defaults: -smartQuotes: - enabled: true # Set to false for "simple" 'quotes' (good ol' ASCII) - double: - left: '“' - right: '”' - single: - left: "‘" - right: "’" - -# Defines the maximum size of a file you can upload to the space (in MiB) -maximumDocumentSize: 10 - -# Add alternative names to emoji picker -emoji: - aliases: - smile: 😀 - sweat_smile: 😅 - -# Defines the indentation multiplier. -# SilverBullet's base indentation is 2 spaces. Actual indentation = 2 * indentMultiplier. -# So, using an indentMultiplier of 2 would make your indentation size 4, 3 would make it 6, etc. -indentMultiplier: 1 -``` diff --git a/website/Shortcuts.md b/website/Shortcuts.md index 3debb9b5..f82a6fdc 100644 --- a/website/Shortcuts.md +++ b/website/Shortcuts.md @@ -8,20 +8,31 @@ Supported types of shortcuts: * Priority shortcuts to tweak the ordering of commands in the [[Command Palette]] # Configuration -In [[SETTINGS]]: +Using Space Lua: -```yaml -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 +```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 336c43a9..ed6b5f16 100644 --- a/website/Space Lua.md +++ b/website/Space Lua.md @@ -1,30 +1,5 @@ -> **warning** Experimental -> This is an **experimental** feature still under active development. It is documented here primarily for the real early adopters as this feature develops. -> -> If you want to experiment, be sure to use the [edge builds](https://community.silverbullet.md/t/living-on-the-edge-builds/27/5). - Space Lua is a custom implementation of the [Lua programming language](https://lua.org/), embedded in SilverBullet. It aims to be a largely complete Lua implementation, and adds a few non-standard features while remaining syntactically compatible with “real” Lua. -```embed -url: https://youtu.be/t1oy_41bDAY -height: 400 -``` - - -# Goals -The introduction of Lua aims to unify and simplify a few SilverBullet features, specifically: - -* Scripting: replace [[Space Script]] (JavaScript) with a more controlled, simple and extensible language. -* Replace [[Expression Language]], [[Template Language]] and [[Query Language]] with Lua-based equivalents. -* (Potentially) provide an alternative way to specify [[Space Config]] - -# Strategy -This is a big effort. During its development, Space Lua will be offered as a kind of “alternative universe” to the things mentioned above. Existing [[Live Templates]], [[Live Queries]] and [[Space Script]] will continue to work as before, unaltered. - -Once these features stabilize and best practices are ironed out, old mechanisms will likely be deprecated and possibly removed at some point. - -We’re not there yet, though. - # Basics In its essence, Space Lua adds two features to its [[Markdown]] language: @@ -54,16 +29,36 @@ function stuff.adder(a, b) end ``` -> **note** Tip -> All your space-lua scripts are loaded on boot, to reload them without reloading the page, simply run the {[System: Reload]} command. +## Load order +It is possible to control load order of space lua scripts using a special `-- priority: ` comment in the Lua code. -## Expressions +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 helpfully part of your [[^Library/Std/Space Overview]]) page: + + query[[ + from index.tag "space-lua" + order by priority desc + ]] + +This means that the higher the priority, the earlier the script is loaded. That also means that if you want to override previously defined definitions you need to a set a _lower_ priority (or in most cases: simply omit the priority comment). + +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) + +> **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")} command. + +# Expressions A new syntax introduced with Space Lua is the `${lua expression}` syntax that you can use in your pages. This syntax will [[Live Preview]] to the evaluation of that expression. For example: 10 + 2 = ${adder(10, 2)} (Alt-click, or select to see the expression) is using the just defined `adder` function to this rather impressive calculation. Yes, this may as well be written as `${10 + 2}` (${10 + 2}), but... you know. ## Queries -Space Lua has a feature called [[Space Lua/Lua Integrated Query]], which integrate SQL-like queries into Lua. By using this feature, you can easily replicate [[Live Queries]]. More detail in [[Space Lua/Lua Integrated Query]], but here’s a small example querying the last 3 modifies pages: +Space Lua has a feature called [[Space Lua/Lua Integrated Query]], which integrate SQL-like queries into Lua. Here’s a small example querying the last 3 modifies pages: ${query[[ from index.tag "page" @@ -73,7 +68,7 @@ ${query[[ ]]} ## Widgets -The `${lua expression}` syntax can be used to implement simple widgets. If the Lua expression evaluates to a simple string, it will live preview as that string rendered as markdown. However, if the expression returns a `widget.new`-generated result value, you can do some cooler stuff. +The `${lua expression}` syntax can be used to implement custom widgets. If the Lua expression evaluates to a simple string, it will live preview as that string rendered as markdown. However, if the expression returns a `widget.new`-generated result value, you can do some cooler stuff. To render a widget, call `widget.new` with any of the following keys: @@ -125,7 +120,7 @@ command.define { } ``` -Try it: {[Hello World]} +Try it: ${widgets.commandButton("Hello World")} ## Event listeners You can listen to events using [[API/event#event.listen(listenerDef)]]: @@ -143,7 +138,7 @@ event.listen { # Space Lua Extensions Space Lua currently introduces a few new features on top core Lua: -1. [[Space Lua/Lua Integrated Query]], embedding a [[Query Language]]-like language into Lua itself +1. [[Space Lua/Lua Integrated Query]], embedding a query language into Lua itself 2. Thread locals ## Thread locals @@ -154,14 +149,6 @@ There's a magic `_CTX` global variable available from which you can access usefu # API ![[API]] -While in [[Space Script]] all syscalls are asynchronous and need to be called with `await`, this is happens transparently in Space Lua leading to cleaner code: - -```space-lua -local function callSomeThings() - local text = space.readPage(editor.getCurrentPage()) - print("Current page text", text) -end -``` # 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: From 5b9122eb62b576a79147735b8dd4b1d61afd6eee Mon Sep 17 00:00:00 2001 From: Zef Hemel Date: Fri, 28 Mar 2025 18:25:47 +0100 Subject: [PATCH 6/6] Fix very subtle Lua async bug --- common/space_lua/eval.test.ts | 19 ++++---- common/space_lua/eval.ts | 88 ++++++++++------------------------- common/space_lua/stdlib/js.ts | 3 ++ 3 files changed, 39 insertions(+), 71 deletions(-) diff --git a/common/space_lua/eval.test.ts b/common/space_lua/eval.test.ts index 389ad717..5d9bc97f 100644 --- a/common/space_lua/eval.test.ts +++ b/common/space_lua/eval.test.ts @@ -55,16 +55,19 @@ Deno.test("Evaluator test", async () => { true, ); // Tables - const tbl = evalExpr(`{3, 1, 2}`); + const tbl = await evalExpr(`{3, 1, 2}`); assertEquals(tbl.get(1), 3); assertEquals(tbl.get(2), 1); assertEquals(tbl.get(3), 2); assertEquals(luaValueToJS(tbl, sf), [3, 1, 2]); - assertEquals(luaValueToJS(evalExpr(`{name=test("Zef"), age=100}`, env), sf), { - name: "Zef", - age: 100, - }); + assertEquals( + luaValueToJS(await evalExpr(`{name=test("Zef"), age=100}`, env), sf), + { + name: "Zef", + age: 100, + }, + ); assertEquals( luaValueToJS(await evalExpr(`{name="Zef", age=asyncTest(100)}`, env), sf), @@ -74,12 +77,12 @@ Deno.test("Evaluator test", async () => { }, ); - const result = evalExpr(`{[3+2]=1, ["a".."b"]=2}`); + const result = await evalExpr(`{[3+2]=1, ["a".."b"]=2}`); assertEquals(result.get(5), 1); assertEquals(result.get("ab"), 2); - assertEquals(evalExpr(`#{}`), 0); - assertEquals(evalExpr(`#{1, 2, 3}`), 3); + assertEquals(await evalExpr(`#{}`), 0); + assertEquals(await evalExpr(`#{1, 2, 3}`), 3); // Unary operators assertEquals(await evalExpr(`-asyncTest(3)`, env), -3); diff --git a/common/space_lua/eval.ts b/common/space_lua/eval.ts index 4d300396..26db8619 100644 --- a/common/space_lua/eval.ts +++ b/common/space_lua/eval.ts @@ -71,57 +71,31 @@ async function handleVarargAsync( return []; } -function handleTableFieldSync( +async function handleTableFieldSync( table: LuaTable, field: any, env: LuaEnv, sf: LuaStackFrame, -): void | Promise { +): Promise { switch (field.type) { case "PropField": { - const value = evalExpression(field.value, env, sf); - if (value instanceof Promise) { - return value.then((v) => table.set(field.key, singleResult(v), sf)); - } + const value = await evalExpression(field.value, env, sf); table.set(field.key, singleResult(value), sf); break; } case "DynamicField": { - const key = evalExpression(field.key, env, sf); - const value = evalExpression(field.value, env, sf); - if (key instanceof Promise || value instanceof Promise) { - return Promise.all([ - key instanceof Promise ? key : Promise.resolve(key), - value instanceof Promise ? value : Promise.resolve(value), - ]).then(([k, v]) => { - table.set(singleResult(k), singleResult(v), sf); - }); - } + const key = await evalExpression(field.key, env, sf); + const value = await evalExpression(field.value, env, sf); + table.set(singleResult(key), singleResult(value), sf); break; } case "ExpressionField": { if (field.value.type === "Variable" && field.value.name === "...") { - const varargs = handleVarargSync(env); - if (varargs instanceof Promise) { - return varargs.then((args) => { - args.forEach((val, i) => table.set(i + 1, val, sf)); - }); - } + const varargs = await handleVarargSync(env); varargs.forEach((val, i) => table.set(i + 1, val, sf)); } else { - const value = evalExpression(field.value, env, sf); - if (value instanceof Promise) { - return value.then((v) => { - if (v instanceof LuaMultiRes) { - for (const val of v.values) { - table.set(table.length + 1, val, sf); - } - } else { - table.set(table.length + 1, singleResult(v), sf); - } - }); - } + const value = await evalExpression(field.value, env, sf); if (value instanceof LuaMultiRes) { for (const val of value.values) { table.set(table.length + 1, val, sf); @@ -249,37 +223,25 @@ export function evalExpression( case "PropertyAccess": return evalPrefixExpression(e, env, sf); case "TableConstructor": { - const table = new LuaTable(); - - if ( - e.fields.length === 1 && - e.fields[0].type === "ExpressionField" && - e.fields[0].value.type === "Variable" && - e.fields[0].value.name === "..." - ) { - const varargs = handleVarargSync(env); - if (varargs instanceof Promise) { - return varargs.then((args) => { - args.forEach((val, i) => table.set(i + 1, val, sf)); - return table; - }); + return Promise.resolve().then(async () => { + const table = new LuaTable(); + if ( + e.fields.length === 1 && + e.fields[0].type === "ExpressionField" && + e.fields[0].value.type === "Variable" && + e.fields[0].value.name === "..." + ) { + const varargs = await handleVarargSync(env); + varargs.forEach((val, i) => table.set(i + 1, val, sf)); + return table; } - varargs.forEach((val, i) => table.set(i + 1, val, sf)); + + for (const field of e.fields) { + await handleTableFieldSync(table, field, env, sf); + } + return table; - } - - const promises: Promise[] = []; - for (const field of e.fields) { - const result = handleTableFieldSync(table, field, env, sf); - if (result instanceof Promise) { - promises.push(result); - } - } - - if (promises.length > 0) { - return Promise.all(promises).then(() => table); - } - return table; + }); } case "FunctionDefinition": { return new LuaFunction(e.body, env); diff --git a/common/space_lua/stdlib/js.ts b/common/space_lua/stdlib/js.ts index 5d69e266..88f8ef82 100644 --- a/common/space_lua/stdlib/js.ts +++ b/common/space_lua/stdlib/js.ts @@ -72,4 +72,7 @@ export const jsApi = new LuaTable({ createElement: new LuaBuiltinFunction((_sf, tag) => document.createElement(tag) ), + createTextNode: new LuaBuiltinFunction((_sf, text) => + document.createTextNode(text) + ), });