Files
plainleaf/plug-api/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

507 lines
13 KiB
TypeScript

import { syscall } from "../syscall.ts";
import type {
FilterOption,
UploadFile,
} from "@silverbulletmd/silverbullet/type/client";
import type { Path, Ref } from "../lib/ref.ts";
import type { PageMeta } from "../../type/index.ts";
/**
* Exposes various editor utilities.
* Important: These syscalls are only available in the client.
* @module
*/
/**
* Returns the name of the page or document currently open in the editor.
* @returns the current page name
*/
export function getCurrentPage(): Promise<string> {
return syscall("editor.getCurrentPage");
}
/**
* Returns the meta data of the page or document currently open in the editor.
* @returns the current page meta data
*/
export function getCurrentPageMeta(): Promise<PageMeta | undefined> {
return syscall("editor.getCurrentPageMeta");
}
/**
* Returns the path of the page or document currently open in the editor.
* @returns the current page path
*/
export function getCurrentPath(): Promise<Path> {
return syscall("editor.getCurrentPath");
}
/**
* Returns the names of the pages that have been recently opened
* @returns the names of the recently opened pages
*/
export function getRecentlyOpenedPages(): Promise<PageMeta[]> {
return syscall("editor.getRecentlyOpenedPages");
}
/**
* Returns the name of the currently open editor.
* @returns the name of the current editor
*/
export function getCurrentEditor(): Promise<string> {
return syscall("editor.getCurrentEditor");
}
/**
* Returns the full text of the currently open page
*/
export function getText(): Promise<string> {
return syscall("editor.getText");
}
/**
* This updates the editor text, but in a minimal-diff way:
* it compares the current editor text with the new text, and only sends the changes to the editor, thereby preserving cursor location
*/
export function setText(
newText: string,
isolateHistory = false,
): Promise<void> {
return syscall("editor.setText", newText, isolateHistory);
}
/**
* Returns the position (in # of characters from the beginning of the file) of the cursor in the editor
*/
export function getCursor(): Promise<number> {
return syscall("editor.getCursor");
}
/**
* Returns the line number and column number of the cursor in the editor
*/
export function getSelection(): Promise<
{ from: number; to: number; text: string }
> {
return syscall("editor.getSelection");
}
/**
* Sets the position of the cursor in the editor
* @param from the start position of the selection
* @param to the end position of the selection
*/
export function setSelection(from: number, to: number): Promise<void> {
return syscall("editor.setSelection", from, to);
}
/**
* Invoke a client command by name
* Note: only available on the client
* @param name name of the command
* @param args arguments to pass to the command
*/
export function invokeCommand(name: string, args?: string[]): Promise<any> {
return syscall("editor.invokeCommand", name, args);
}
/**
* Forces a save of the current page
*/
export function save(): Promise<void> {
return syscall("editor.save");
}
/**
* Navigates to the specified page reference
* @param pageRef the page reference to navigate to
* @param replaceState whether to replace the current history state in the browser history
* @param newWindow whether to open the page in a new window
*/
export function navigate(
ref: Ref | string,
replaceState = false,
newWindow = false,
): Promise<void> {
return syscall("editor.navigate", ref, replaceState, newWindow);
}
/**
* Opens the page navigator
* @param mode the mode to open the navigator in
*/
export function openPageNavigator(
mode: "page" | "meta" | "document" | "all" = "page",
): Promise<void> {
return syscall("editor.openPageNavigator", mode);
}
/**
* Opens the command palette
*/
export function openCommandPalette(): Promise<void> {
return syscall("editor.openCommandPalette");
}
/**
* Force reloads the current page
*/
export function reloadPage(): Promise<void> {
return syscall("editor.reloadPage");
}
/**
* Force reloads the browser UI
*/
export function reloadUI(): Promise<void> {
return syscall("editor.reloadUI");
}
/**
* Rebuilds the editor state to ensure the dispatch updates the state.
*/
export function rebuildEditorState(): Promise<void> {
return syscall("editor.rebuildEditorState");
}
/**
* Reloads the config and commands, also in the server
*/
export function reloadConfigAndCommands(): Promise<void> {
return syscall("editor.reloadConfigAndCommands");
}
/**
* Opens the specified URL in the browser
* @param url the URL to open
* @param existingWindow whether to open the URL in an existing window
*/
export function openUrl(url: string, existingWindow = false): Promise<void> {
return syscall("editor.openUrl", url, existingWindow);
}
export function newWindow(): Promise<void> {
return syscall("editor.newWindow");
}
/**
* This is calling the `go()` method from the History Web API.
* @param delta Position in history to move to relative to the current page,
* where a negative value moves backwards, and positive forwards
*/
export function goHistory(delta: number): Promise<void> {
return syscall("editor.goHistory", delta);
}
/**
* Force the client to download the file in dataUrl with filename as file name
* @param filename the name of the file to download
* @param dataUrl the dataUrl of the file to download
*/
export function downloadFile(filename: string, dataUrl: string): Promise<void> {
return syscall("editor.downloadFile", filename, dataUrl);
}
/**
* Triggers the browser's native file upload dialog/popup
* @param accept the file types to accept
* @param capture the capture mode for the file input
*/
export function uploadFile(
accept?: string,
capture?: string,
): Promise<UploadFile> {
return syscall("editor.uploadFile", accept, capture);
}
/**
* Shows a flash notification to the user (top right corner)
* @param message the message to show
* @param type the type of notification to show
*/
export function flashNotification(
message: string,
type: "info" | "error" = "info",
): Promise<void> {
return syscall("editor.flashNotification", message, type);
}
/**
* Exposes a filter box UI (similar to the page navigator and command palette)
* @param label the label to show left of the input box
* @param options the options to show and to filter on
* @param helpText the help text to show below the input box
* @param placeHolder the placeholder text to show in the input box
*/
export function filterBox(
label: string,
options: FilterOption[],
helpText = "",
placeHolder = "",
): Promise<FilterOption | undefined> {
return syscall("editor.filterBox", label, options, helpText, placeHolder);
}
/**
* Shows a panel in the editor
* @param id the location of the panel to show
* @param mode the mode or "size" of the panel
* @param html the html content of the panel
* @param script the script content of the panel
*/
export function showPanel(
id: "lhs" | "rhs" | "bhs" | "modal",
mode: number,
html: string,
script = "",
): Promise<void> {
return syscall("editor.showPanel", id, mode, html, script);
}
/**
* Hides a panel in the editor
* @param id the location of the panel to hide
*/
export function hidePanel(
id: "lhs" | "rhs" | "bhs" | "modal",
): Promise<void> {
return syscall("editor.hidePanel", id);
}
export function showProgress(
progressPercentage?: number,
progressType?: string,
): Promise<void> {
return syscall("editor.showProgress", progressPercentage, progressType);
}
/**
* Insert text at the specified position into the editor
* @param text the text to insert
* @param pos
*/
export function insertAtPos(text: string, pos: number): Promise<void> {
return syscall("editor.insertAtPos", text, pos);
}
/**
* Replace the text in the specified range in the editor
* @param from the start position of the range
* @param to the end position of the range
* @param text the text to replace with
*/
export function replaceRange(
from: number,
to: number,
text: string,
): Promise<void> {
return syscall("editor.replaceRange", from, to, text);
}
/**
* Move the cursor to the specified position in the editor
* @param pos the position to move the cursor to
* @param center whether to center the cursor in the editor after moving
*/
export function moveCursor(pos: number, center = false): Promise<void> {
return syscall("editor.moveCursor", pos, center);
}
/**
* Move the cursor to the specified line and column in the editor
* @param line the line number to move the cursor to
* @param column the column number to move the cursor to
* @param center whether to center the cursor in the editor after moving
*/
export function moveCursorToLine(
line: number,
column = 1,
center = false,
): Promise<void> {
return syscall("editor.moveCursorToLine", line, column, center);
}
/**
* Insert text at the cursor position in the editor
* @param text the text to insert
*/
export function insertAtCursor(
text: string,
scrollIntoView = false,
cursorPlaceHolder = false,
): Promise<void> {
return syscall(
"editor.insertAtCursor",
text,
scrollIntoView,
cursorPlaceHolder,
);
}
/**
* Dispatch a CodeMirror transaction: https://codemirror.net/docs/ref/#state.Transaction
*/
export function dispatch(change: any): Promise<void> {
return syscall("editor.dispatch", change);
}
/**
* Prompt the user for text input
* @param message the message to show in the prompt
* @param defaultValue a default value pre-filled in the prompt
* @returns
*/
export function prompt(
message: string,
defaultValue = "",
): Promise<string | undefined> {
return syscall("editor.prompt", message, defaultValue);
}
/**
* Prompt the user for confirmation
* @param message the message to show in the confirmation dialog
* @returns
*/
export function confirm(
message: string,
): Promise<boolean> {
return syscall("editor.confirm", message);
}
/**
* Prompt the user for confirmation
* @param message the message to show in the confirmation dialog
* @returns
*/
export function alert(
message: string,
): Promise<boolean> {
return syscall("editor.alert", message);
}
/**
* Get the value of a UI option
* @param key the key of the UI option to get
* @returns
*/
export function getUiOption(key: string): Promise<any> {
return syscall("editor.getUiOption", key);
}
/**
* Set the value of a UI option
* @param key the key of the UI option to set
* @param value the value to set the UI option to
*/
export function setUiOption(key: string, value: any): Promise<void> {
return syscall("editor.setUiOption", key, value);
}
/**
* Perform a fold at the current cursor position
*/
export function fold(): Promise<void> {
return syscall("editor.fold");
}
/**
* Perform an unfold at the current cursor position
*/
export function unfold(): Promise<void> {
return syscall("editor.unfold");
}
/**
* Toggle the fold at the current cursor position
*/
export function toggleFold(): Promise<void> {
return syscall("editor.toggleFold");
}
/**
* Fold all code blocks in the editor
*/
export function foldAll(): Promise<void> {
return syscall("editor.foldAll");
}
/**
* Unfold all code blocks in the editor
*/
export function unfoldAll(): Promise<void> {
return syscall("editor.unfoldAll");
}
/**
* Perform an undo operation of the last edit in the editor
*/
export function undo(): Promise<void> {
return syscall("editor.undo");
}
/**
* Perform a redo operation of the last undo in the editor
*/
export function redo(): Promise<void> {
return syscall("editor.redo");
}
/**
* Open the editor's native search panel
*/
export function openSearchPanel(): Promise<void> {
return syscall("editor.openSearchPanel");
}
/**
* Copy the specified data to the clipboard
* @param data the data to copy
*/
export function copyToClipboard(data: string | Blob): Promise<void> {
return syscall("editor.copyToClipboard", data);
}
/**
* Delete the current line in the editor
*/
export function deleteLine(): Promise<void> {
return syscall("editor.deleteLine");
}
export function moveLineUp(): Promise<void> {
return syscall("editor.moveLineUp");
}
export function moveLineDown(): Promise<void> {
return syscall("editor.moveLineDown");
}
// Vim-mode specific syscalls
/**
* Execute a Vim ex command
* @param exCommand the ex command to execute
*/
export function vimEx(exCommand: string): Promise<any> {
return syscall("editor.vimEx", exCommand);
}
/**
* Execute a vim config using the CodeMirror Vim Mode API
*/
export function configureVimMode(): Promise<any> {
return syscall("editor.configureVimMode");
}
// Document editor specific syscalls
/**
* Send a message - or event if you will - to the currently used document editor
* @param type the message type, which can be listend to
* @param data data attached to the message
*/
export function sendMessage(type: string, data?: any): Promise<void> {
return syscall("editor.sendMessage", type, data);
}