Files
plainleaf/web/syscalls/editor.ts
T
aa0b95b31d The one about refs (#1496)
* [Major] Introduce a new `Ref` and `Path` type

This introduces a new `Ref` and `Path` type, which try to be as lightweight and rigorous as possible. More description in the PR

* [Minor] Updated Syntax

* [Minor] Updated Type

* [Minor] Renamed file

* [Minor] Updated type

* [Minor] Updated Syntax

* [Major] Rename css classes for wiki links

Previously all the parts of a wiki link were tagged with `sb-wiki-link-page`. This didn't make a whole lot of sense. Also the tag `sb-wiki-link` was could never render, because of the way `HighlightStyle` works. Now every part of a wiki link will be tagged with `sb-wiki-link` (i.e. the link, the alias, the dimensions). Invalid and missing links will be styled separately in a later commit.

* [Minor] Adjust to new API

* [Minor] Small changes

* [Minor] Function and file renames

* [Major] Syscall adjusments

Change behavior of `getCurrentPath` to actually return what's now considered a `Path`. `getCurrentPage(Meta)` now also correctly returns for documents. We could consider a rename to get rid of the `page` association

* [Major] Rework `Client`

Mostly minor adjustments for the new API. Some major changes in `navigateWithinPage` and some unecessary checks removed now

* [Major] Errors on navigate

This now throws an error when the user tries to navigate to a link that is invalid

* [Major] Minor adjustments and remove some old bulk

This does the typicall adjustments to the new API. A thing to consider is that invalid links aren't indexed. Also removed old code about template and query stuff. And reused a regex instead of copy pasting it.

* [Minor] Cleanup editor ui

* [Minor] Adjust to new API

* [Minor] Adjust to new API and reduce ugly regex

* [Minor] New API

* [Minor] Rework link cm plugin

* [Major] Rework wiki links

A lot of code cleanup, reworked for new APIs and also introduces "invalid links"

* [Minor] Part of the editor ui rework

* [Major] Adjust to new API

This also removes the `looksLikePathWithExtension` check. I don't think it was necessary.

* [Minor] PArt of editor ui rewrite

* [Minor] Adjust to new API

* [Major] Adjust renderer to new API

Invalid links now link to `#`

* [Major] Rewrite navigator

This still needs major rework, currently in a "got it working" state

* [Minor] Adjust file name

* [Minor] Mistake during rebase

* [Minor] Navigate to end of header

* [Minor] Remove `tweakEditorDOM` and use proper CM extensions

* [Major] Heavily clean up the navigation code

* [Minor] Make `PageNavigator` closable again

* [Minor] Small fixes to reduce errors bubbling up

* [Minor] Show error message if navigate fails

* [Major] Remove legacy `navigate({ kind = ` syntax

This removes the old navigation syntax. It's still supported but the user will be warned then using it. I also added some validation to editor.navigate for user provided refs.

* [Minor] Make notifications errors

* [Minor] Don't fail if header isn't found

* [Minor] Typo

* [Major] Remove cleanPageRef

* [Minor] Small bug

* [Minor] Align behavior between render and editor

* [Major] Remove `PageRef`. Pretty sure it's obsolete

* [Major] Remove pos from header as it's an invalid ref

* [Minor] Align with original behavior

* [Minor] Get tests working again

* [Minor] check that indexPage is valid

* [Major] Rewrite `resolve.ts` file

* [Minor] More tests, more fixes

* [Minor] Don't just append .md this is weird

* [Minor] More edge cases

* [Minor] Version bumping hono somehow fixes the `/` case

* [Minor] Smaller TODOs

* [Major] We can be a littler looser on the restrictions

* [Major] Change header indexing, to index with pos

* [Minor] More fixes for headers

* [Minor] Rename for clarity

* [Minor] Change more regexes to named groups

* [Major] Inline content rewrite

* [Minor] Fix TODO

* [Minor] Bump index version

* [Major] New Space Primitive to check paths

* [Minor] Fix #1214

* [Minor] Fix #1169

* [Minor] Remove TODO

This check is probably not needed anymore. Unsure. May look into it later

* [Minor] small bug

* [Minor] Not a good rebase without me needing to fix it afterwards

* [Minor] Improve fallback for file upload

* [Minor] Some fixes on the for resolving

* [Minor] Removed doubled test case

* [Minor] Resolve #860

* [Minor] Turn flash notification into an error

* [Minor] Change handling of `.` paths

* [Minor] Show empty URL for index page

* [Minor] Push correct ref to history

* [Major] Capture mini editor events in capture phase

This fixes the issue were when pressing arrowup or arrowdown changed the cursor position inside the editor

* [Major] Add prefix to `FilterList`

This now fixes issues were if you had a prefixed page you  con't properly search for it, because the search considered the prefix as part of the name

* [Minor] A little rigor for empty headers

* [Major] Fix #1404

* [Minor] `parseInt` returns `NaN` handle that

* [Minor] Use `fileName`

* [Minor] Fix comment

* [Minor] Fixes

* [Major] disallow `foo.png.md` and `/../`, etc. cases

* [Major] Change name of conflicted pages

* [Minor] Remove unecessary check

* [Minor] Remove some split code

* [Minor] Allow deletion of invalid files

* [Minor] Bug in the regex

* [Minor] Give some possibility of fixing incorrect names

* [Minor] Tiny bug with header completion

* [Major] Docs

* [Minor] Ignore errors for navigation inside of a page

This could be a problem when SB e.g. cached a scrollTop for a page, which, because e.g. the file is now deleted, doesn't exist anymore and thus CM throws an error, when trying to navigate

* Update conflicted copy regex in Maintenance.md

---------

Co-authored-by: Zef Hemel <zef@zef.me>
2025-08-24 16:16:19 +02:00

653 lines
19 KiB
TypeScript

import type { Client } from "../client.ts";
import {
foldAll,
foldCode,
toggleFold,
unfoldAll,
unfoldCode,
} from "@codemirror/language";
import {
deleteLine,
insertNewline,
insertNewlineAndIndent,
moveLineDown,
moveLineUp,
redo,
undo,
} from "@codemirror/commands";
import type { Transaction } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { getCM as vimGetCm, Vim } from "@replit/codemirror-vim";
import type { SysCallMapping } from "../../lib/plugos/system.ts";
import type {
FilterOption,
UploadFile,
} from "@silverbulletmd/silverbullet/type/client";
import { openSearchPanel } from "@codemirror/search";
import {
isValidPath,
parseToRef,
type Path,
type Ref,
} from "@silverbulletmd/silverbullet/lib/ref";
import { insertNewlineContinueMarkup } from "@codemirror/lang-markdown";
import type { VimConfig } from "../../type/config.ts";
import type { PageMeta } from "../../type/index.ts";
export function editorSyscalls(client: Client): SysCallMapping {
const syscalls: SysCallMapping = {
"editor.getCurrentPage": (): string => {
return client.currentName();
},
"editor.getCurrentPageMeta": (): PageMeta | undefined => {
return client.ui.viewState.current?.meta;
},
"editor.getCurrentPath": (_ctx): string => {
return client.currentPath();
},
"editor.getCurrentEditor": (): string => {
return client.documentEditor?.name || "page";
},
"editor.getRecentlyOpenedPages": (): PageMeta[] => {
return client.ui.viewState.allPages.sort((a, b) =>
(b.lastOpened || 0) - (a.lastOpened || 0)
);
},
"editor.getText": () => {
return client.editorView.state.sliceDoc();
},
"editor.getCurrentLine": (): {
from: number;
to: number;
text: string;
textWithCursor: string;
} => {
const pos = client.editorView.state.selection.main.from;
const line = client.editorView.state.doc.lineAt(pos);
return {
...line,
textWithCursor: line.text.slice(0, pos - line.from) + "|^|" +
line.text.slice(pos - line.from),
};
},
"editor.setText": (_ctx, newText: string, shouldIsolateHistory = false) => {
client.setEditorText(newText, shouldIsolateHistory);
},
"editor.getCursor": (): number => {
return client.editorView.state.selection.main.from;
},
"editor.getSelection": (): { from: number; to: number; text: string } => {
const selection = client.editorView.state.selection.main;
const text = client.editorView.state.sliceDoc(
selection.from,
selection.to,
);
return {
from: selection.from,
to: selection.to,
text,
};
},
"editor.save": () => {
return client.save(true);
},
"editor.navigate": async (
_ctx,
ref: Ref | string,
replaceState = false,
newWindow = false,
) => {
if (typeof ref === "string") {
const parsedRef = parseToRef(ref);
if (!parsedRef) {
throw new Error(
"Unable to parse string provided to `editor.navigate` as ref",
);
}
ref = parsedRef;
}
// @ts-ignore: Legacy support
if (ref.kind === "page" || ref.kind === "document") {
console.warn(
"You are using legacy navigation syntax with `editor.navigate()`, this will be phased out in the future",
);
const legacyRef = ref as unknown as {
kind: "page" | "document";
page: string;
pos?: number | { line: number; column: number };
header?: string;
meta?: boolean;
};
let details: Ref["details"] = undefined;
if (typeof legacyRef.pos === "number") {
details = {
type: "position",
pos: legacyRef.pos,
};
} else if (legacyRef.pos) {
details = {
type: "linecolumn",
line: legacyRef.pos.line,
column: legacyRef.pos.column,
};
} else if (legacyRef.header) {
details = {
type: "header",
header: legacyRef.header,
};
}
ref = {
path: (legacyRef.kind === "page"
? `${legacyRef.page}.md`
: legacyRef.page) as Path,
details,
meta: legacyRef.meta,
};
}
// This validation code should be connected to the Ref type. Ideally using
// some validation library. Didn't want to use jsonschemas here tho.
// Ideally this would be moved into a function too
if (!isValidPath(ref.path) && ref.path !== "") {
throw new Error(
"Path passed in ref to `editor.navigate` is invalid",
);
} else if (typeof ref.meta !== "boolean" && ref.meta !== undefined) {
throw new Error(
"ref.meta has to be of type `boolean`",
);
} else if (ref.details !== undefined && typeof ref.details !== "object") {
throw new Error(
"ref.details has to be of type `object` or `undefined`",
);
} else if (
ref.details &&
!["position", "linecolumn", "header"].includes(ref.details.type)
) {
throw new Error(
"ref.details.type has to be 'position', 'linecolumn' or 'header'",
);
}
if (
ref.details?.type === "position" && typeof ref.details.pos !== "number"
) {
throw new Error(
"ref.details.pos has to be of type `number`",
);
} else if (
ref.details?.type === "header" && typeof ref.details.header !== "string"
) {
throw new Error(
"ref.details.header has to be of type `string`",
);
} else if (
ref.details?.type === "linecolumn" &&
typeof ref.details.line !== "number" &&
typeof ref.details.column !== "number"
) {
throw new Error(
"ref.details.line and ref.details.column has to be of type `number`",
);
}
await client.navigate(ref, replaceState, newWindow);
},
"editor.reloadPage": async () => {
await client.reloadEditor();
},
"editor.reloadUI": () => {
location.reload();
},
"editor.rebuildEditorState": () => {
client.rebuildEditorState();
},
"editor.reloadConfigAndCommands": async () => {
await client.clientSystem.system.localSyscall(
"system.loadScripts",
[],
);
await client.clientSystem.system.localSyscall(
"system.loadSpaceStyles",
[],
);
},
"editor.invokeCommand": (_ctx, name: string, args?: string[]) => {
return client.runCommandByName(name, args);
},
"editor.openUrl": (_ctx, url: string, existingWindow = false) => {
client.openUrl(url, existingWindow);
},
"editor.newWindow": () => {
globalThis.open(
location.href,
"rnd" + Math.random(),
`width=${globalThis.innerWidth},heigh=${globalThis.innerHeight}`,
);
},
"editor.goHistory": (_ctx, delta: number) => {
globalThis.history.go(delta);
},
"editor.downloadFile": (_ctx, filename: string, dataUrl: string) => {
const link = document.createElement("a");
link.href = dataUrl;
link.download = filename;
link.click();
},
"editor.uploadFile": (
_ctx,
accept?: string,
capture?: string,
): Promise<UploadFile> => {
return new Promise<UploadFile>((resolve, reject) => {
const input = document.createElement("input");
input.type = "file";
if (accept) {
input.accept = accept;
}
if (capture) {
input.capture = capture;
}
input.onchange = () => {
const file = input.files?.item(0);
if (!file) {
reject(new Error("No file found"));
} else {
const reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onloadend = async (evt) => {
if (evt.target?.readyState == FileReader.DONE) {
resolve({
name: file.name,
contentType: file.type,
content: new Uint8Array(await file.arrayBuffer()),
});
}
};
reader.onabort = (e) => {
reject(e);
};
reader.onerror = (e) => {
reject(e);
};
}
};
input.onabort = (e) => {
reject(e);
};
input.click();
});
},
"editor.flashNotification": (
_ctx,
message: string,
type: "error" | "info" = "info",
) => {
client.flashNotification(message, type);
},
"editor.filterBox": (
_ctx,
label: string,
options: FilterOption[],
helpText = "",
placeHolder = "",
): Promise<FilterOption | undefined> => {
return client.filterBox(label, options, helpText, placeHolder);
},
"editor.showPanel": (
_ctx,
id: string,
mode: number,
html: string,
script: string,
) => {
client.ui.viewDispatch({
type: "show-panel",
id: id as any,
config: { html, script, mode },
});
setTimeout(() => {
// Dummy dispatch to rerender the editor and toggle the panel
client.editorView.dispatch({});
});
},
"editor.hidePanel": (_ctx, id: string) => {
client.ui.viewDispatch({
type: "hide-panel",
id: id as any,
});
setTimeout(() => {
// Dummy dispatch to rerender the editor and toggle the panel
client.editorView.dispatch({});
});
},
"editor.showProgress": (
_ctx,
progressPercentage?: number,
progressType?: "sync" | "index",
) => {
client.showProgress(progressPercentage, progressType);
},
"editor.insertAtPos": (
_ctx,
text: string,
pos: number,
cursorPlaceHolder = false,
) => {
let cursorPlaceholderPos = -1;
if (cursorPlaceHolder) {
cursorPlaceholderPos = text.indexOf("|^|");
if (cursorPlaceholderPos !== -1) {
text = text.slice(0, cursorPlaceholderPos) +
text.slice(cursorPlaceholderPos + 3);
} else {
cursorPlaceHolder = false;
}
}
client.editorView.dispatch({
changes: {
insert: text,
from: pos,
},
});
if (cursorPlaceHolder) {
const cursorPos = pos + cursorPlaceholderPos;
client.editorView.dispatch({
selection: {
anchor: cursorPos,
},
effects: [
EditorView.scrollIntoView(cursorPos),
],
});
}
},
"editor.replaceRange": (
_ctx,
from: number,
to: number,
text: string,
cursorPlaceHolder = false,
) => {
let cursorPlaceholderPos = -1;
if (cursorPlaceHolder) {
cursorPlaceholderPos = text.indexOf("|^|");
text = text.slice(0, cursorPlaceholderPos) +
text.slice(cursorPlaceholderPos + 3);
}
client.editorView.dispatch({
changes: {
insert: text,
from: from,
to: to,
},
});
if (cursorPlaceHolder) {
const cursorPos = from + cursorPlaceholderPos;
client.editorView.dispatch({
selection: {
anchor: cursorPos,
},
effects: [
EditorView.scrollIntoView(cursorPos),
],
});
}
},
"editor.moveCursor": (_ctx, pos: number, center = false) => {
client.editorView.dispatch({
selection: {
anchor: pos,
},
});
if (center) {
client.editorView.dispatch({
effects: [
EditorView.scrollIntoView(
pos,
{
y: "center",
},
),
],
});
}
client.editorView.focus();
},
"editor.moveCursorToLine": (
_ctx,
line: number,
column = 1,
center = false,
) => {
// CodeMirror already keeps information about lines
const cmLine = client.editorView.state.doc.line(line);
// How much to move inside the line, column number starts from 1
const offset = Math.max(0, Math.min(cmLine.length, column - 1));
// Just reuse the implementation above
syscalls["editor.moveCursor"](_ctx, cmLine.from + offset, center);
},
"editor.setSelection": (_ctx, from: number, to: number) => {
client.editorView.dispatch({
selection: {
anchor: from,
head: to,
},
});
},
"editor.insertAtCursor": (
_ctx,
text: string,
scrollIntoView = false,
cursorPlaceHolder = false,
) => {
const editorView = client.editorView;
const from = editorView.state.selection.main.from;
const cursorPlaceholderPos = text.indexOf("|^|");
if (cursorPlaceHolder && cursorPlaceholderPos !== -1) {
text = text.slice(0, cursorPlaceholderPos) +
text.slice(cursorPlaceholderPos + 3);
} else {
cursorPlaceHolder = false;
}
editorView.dispatch({
changes: {
insert: text,
from: from,
},
selection: {
anchor: cursorPlaceHolder
? from + cursorPlaceholderPos
: from + text.length,
},
scrollIntoView,
});
},
"editor.dispatch": (_ctx, change: Transaction) => {
client.editorView.dispatch(change);
},
"editor.prompt": (
_ctx,
message: string,
defaultValue = "",
): Promise<string | undefined> => {
return client.prompt(message, defaultValue);
},
"editor.confirm": (_ctx, message: string): Promise<boolean> => {
return client.confirm(message);
},
"editor.alert": (_ctx, message: string) => {
alert(message);
},
"editor.getUiOption": (_ctx, key: string): any => {
return (client.ui.viewState.uiOptions as any)[key];
},
"editor.setUiOption": (_ctx, key: string, value: any) => {
client.ui.viewDispatch({
type: "set-ui-option",
key,
value,
});
client.reloadEditor();
},
"editor.vimEx": (_ctx, exCommand: string) => {
const cm = vimGetCm(client.editorView);
if (cm && cm.state.vim) {
return Vim.handleEx(cm as any, exCommand);
} else {
throw new Error("Vim mode not active or not initialized.");
}
},
"editor.configureVimMode": () => {
// Override the default "o" binding to be more intelligent and follow the markdown editor's behavior
Vim.mapCommand("o", "action", "newline-continue-markup", {}, {});
Vim.mapCommand("O", "action", "back-newline-continue-markup", {}, {});
Vim.unmap("<C-q>", undefined as any);
Vim.defineAction("newline-continue-markup", (cm) => {
// Append at end of line
Vim.handleKey(cm, "A", "+input");
// Insert newline continuing markup where appropriate
insertNewlineContinueMarkup(client.editorView) ||
insertNewlineAndIndent(client.editorView);
});
Vim.defineAction("back-newline-continue-markup", (cm) => {
// Determine current line
const pos = client.editorView.state.selection.main.from;
const line = client.editorView.state.doc.lineAt(pos).number;
if (line === 1) {
// We're on the top line
// Go to 0:0
Vim.handleKey(cm, "0", "+input");
// Insert a newline
insertNewline(client.editorView);
// Go up to the new line
Vim.handleKey(cm, "k", "+input");
// Into insert mode
Vim.handleKey(cm, "i", "+input");
} else {
// We're elsewhere in the document
// Go up
Vim.handleKey(cm, "k", "+input");
// Append mode at the end of the line
Vim.handleKey(cm, "A", "+input");
// Insert a newline using the continue markup thing
insertNewlineContinueMarkup(client.editorView) ||
insertNewlineAndIndent(client.editorView);
}
});
// Load the config if any
const config = client.config.get<VimConfig>("vim", {});
if (config) {
config.unmap?.forEach((binding) => {
if (typeof binding === "string") {
console.log("Unmapping " + binding);
// @ts-ignore: unmap expects a string for the mode, this is problematic with Ex mappings which requires undefined or false
Vim.unmap(binding, undefined);
} else if (binding.key) {
console.log(
"Unmapping " + binding.key + " in " + (binding.mode ?? "normal"),
);
Vim.unmap(binding.key, binding.mode ?? "normal");
}
});
config.map?.forEach(({ map, to, mode }) => {
console.log(
"Mapping " + map + " to " + to + " for " + (mode ?? "normal"),
);
Vim.map(map, to, mode ?? "normal");
});
config.noremap?.forEach(({ map, to, mode }) => {
console.log(
"Noremapping " + map + " to " + to + " for " + (mode ?? "normal"),
);
Vim.noremap(map, to, mode ?? "normal");
});
config.commands?.forEach(({ ex, command }) => {
console.log("Mapping command '" + command + "' to Ex " + ex);
Vim.defineEx(ex, "", () => client.runCommandByName(command));
});
} else {
console.log("No vim config found");
}
},
"editor.openPageNavigator": (
_ctx,
mode: "page" | "meta" | "document" | "all" = "page",
) => {
client.startPageNavigate(mode);
},
"editor.openCommandPalette": () => {
client.ui.viewDispatch({
type: "show-palette",
context: client.getContext(),
});
},
"editor.deleteLine": () => {
deleteLine(client.editorView);
},
"editor.moveLineUp": () => {
return moveLineUp({
state: client.editorView.state,
dispatch: client.editorView.dispatch,
});
},
"editor.moveLineDown": () => {
return moveLineDown({
state: client.editorView.state,
dispatch: client.editorView.dispatch,
});
},
// Folding
"editor.fold": () => {
foldCode(client.editorView);
},
"editor.unfold": () => {
unfoldCode(client.editorView);
},
"editor.toggleFold": () => {
toggleFold(client.editorView);
},
"editor.foldAll": () => {
foldAll(client.editorView);
},
"editor.unfoldAll": () => {
unfoldAll(client.editorView);
},
"editor.undo": () => {
return undo(client.editorView);
},
"editor.redo": () => {
return redo(client.editorView);
},
"editor.openSearchPanel": () => {
openSearchPanel(client.editorView);
},
"editor.copyToClipboard": (_ctx, data: string | Blob) => {
if (typeof data === "string") {
navigator.clipboard.writeText(data);
} else {
navigator.clipboard.write([new ClipboardItem({ [data.type]: data })]);
}
},
"editor.sendMessage": (_ctx, type: string, data: any) => {
if (!client.isDocumentEditor()) return;
client.documentEditor.sendPublicMessage({
type,
data,
});
},
};
return syscalls;
}