`;
- }
-
- 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/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/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/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")
+```
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: