1
0
silverbullet/web/editor.tsx

916 lines
26 KiB
TypeScript
Raw Normal View History

2022-10-25 16:50:07 +00:00
import {
preactRender,
useEffect,
useReducer,
yUndoManagerKeymap,
} from "./deps.ts";
2022-04-25 08:33:38 +00:00
import {
autocompletion,
closeBrackets,
closeBracketsKeymap,
2022-04-25 08:33:38 +00:00
completionKeymap,
CompletionResult,
2022-04-04 13:25:07 +00:00
drawSelection,
dropCursor,
EditorSelection,
EditorState,
2022-04-04 13:25:07 +00:00
EditorView,
highlightSpecialChars,
history,
historyKeymap,
indentOnInput,
indentWithTab,
javascriptLanguage,
2022-04-04 13:25:07 +00:00
KeyBinding,
keymap,
LanguageDescription,
LanguageSupport,
2022-05-17 09:53:17 +00:00
runScopeHandlers,
searchKeymap,
standardKeymap,
StreamLanguage,
syntaxHighlighting,
syntaxTree,
typescriptLanguage,
2022-04-04 13:25:07 +00:00
ViewPlugin,
2022-04-25 08:33:38 +00:00
ViewUpdate,
yamlLanguage,
} from "../common/deps.ts";
import { SilverBulletHooks } from "../common/manifest.ts";
// import { markdown } from "../common/_markdown/index.ts";
import { markdown } from "../common/deps.ts";
import { loadMarkdownExtensions, MDExt } from "../common/markdown_ext.ts";
import buildMarkdown from "../common/parser.ts";
import { Space } from "../common/spaces/space.ts";
import { markdownSyscalls } from "../common/syscalls/markdown.ts";
import { FilterOption, PageMeta } from "../common/types.ts";
import { safeRun, throttle } from "../common/util.ts";
2022-10-21 15:06:14 +00:00
import { createSandbox } from "../plugos/environments/webworker_sandbox.ts";
import { EventHook } from "../plugos/hooks/event.ts";
import { eventSyscalls } from "../plugos/syscalls/event.ts";
import sandboxSyscalls from "../plugos/syscalls/sandbox.ts";
import { System } from "../plugos/system.ts";
2022-10-14 13:11:33 +00:00
import { AppEvent, ClickEvent } from "../plug-api/app_event.ts";
import { CommandPalette } from "./components/command_palette.tsx";
import { FilterList } from "./components/filter.tsx";
import { PageNavigator } from "./components/page_navigator.tsx";
import { Panel } from "./components/panel.tsx";
import { TopBar } from "./components/top_bar.tsx";
import { attachmentExtension, pasteLinkExtension } from "./editor_paste.ts";
import { CommandHook } from "./hooks/command.ts";
import { SlashCommandHook } from "./hooks/slash_command.ts";
import { inlineImagesPlugin } from "./inline_image.ts";
import { lineWrapper } from "./line_wrapper.ts";
import { PathPageNavigator } from "./navigator.ts";
import reducer from "./reducer.ts";
import { smartQuoteKeymap } from "./smart_quotes.ts";
import customMarkdownStyle from "./style.ts";
import { clientStoreSyscalls } from "./syscalls/clientStore.ts";
import { editorSyscalls } from "./syscalls/editor.ts";
import { fulltextSyscalls } from "./syscalls/fulltext.ts";
import { indexerSyscalls } from "./syscalls/index.ts";
import { spaceSyscalls } from "./syscalls/space.ts";
import { storeSyscalls } from "./syscalls/store.ts";
import { systemSyscalls } from "./syscalls/system.ts";
import { Action, AppViewState, initialViewState } from "./types.ts";
import assetSyscalls from "../plugos/syscalls/asset.ts";
2022-10-25 16:50:07 +00:00
import { CollabState } from "./collab.ts";
import { collabSyscalls } from "./syscalls/collab.ts";
2022-04-03 16:12:16 +00:00
class PageState {
2022-04-26 17:04:36 +00:00
constructor(
readonly scrollTop: number,
readonly selection: EditorSelection,
2022-04-26 17:04:36 +00:00
) {}
}
2022-04-07 13:21:30 +00:00
const saveInterval = 1000;
export class Editor {
2022-03-29 10:13:46 +00:00
readonly commandHook: CommandHook;
readonly slashCommandHook: SlashCommandHook;
2022-03-23 14:41:12 +00:00
openPages = new Map<string, PageState>();
editorView?: EditorView;
viewState: AppViewState;
viewDispatch: React.Dispatch<Action>;
2022-04-07 13:21:30 +00:00
space: Space;
2022-03-28 13:25:05 +00:00
pageNavigator: PathPageNavigator;
eventHook: EventHook;
saveTimeout: any;
2022-04-04 13:25:07 +00:00
debouncedUpdateEvent = throttle(() => {
this.eventHook
.dispatchEvent("editor:updated")
.catch((e) => console.error("Error dispatching editor:updated event", e));
2022-04-04 13:25:07 +00:00
}, 1000);
private system = new System<SilverBulletHooks>("client");
2022-04-11 18:34:09 +00:00
private mdExtensions: MDExt[] = [];
2022-07-22 11:44:28 +00:00
urlPrefix: string;
2022-08-02 10:43:39 +00:00
indexPage: string;
2022-10-25 16:50:07 +00:00
collabState?: CollabState;
2022-08-02 10:43:39 +00:00
constructor(
space: Space,
parent: Element,
urlPrefix: string,
indexPage: string,
2022-08-02 10:43:39 +00:00
) {
this.space = space;
2022-07-22 11:44:28 +00:00
this.urlPrefix = urlPrefix;
this.viewState = initialViewState;
this.viewDispatch = () => {};
2022-08-02 10:43:39 +00:00
this.indexPage = indexPage;
2022-03-25 11:03:06 +00:00
// Event hook
this.eventHook = new EventHook();
this.system.addHook(this.eventHook);
// Command hook
this.commandHook = new CommandHook();
this.commandHook.on({
commandsUpdated: (commandMap) => {
this.viewDispatch({
type: "update-commands",
commands: commandMap,
});
},
});
this.system.addHook(this.commandHook);
// Slash command hook
this.slashCommandHook = new SlashCommandHook(this);
this.system.addHook(this.slashCommandHook);
2022-03-25 11:03:06 +00:00
this.render(parent);
2022-10-25 16:50:07 +00:00
this.editorView = new EditorView({
state: this.createEditorState("", ""),
2022-07-22 11:44:28 +00:00
parent: document.getElementById("sb-editor")!,
});
2022-08-02 10:43:39 +00:00
this.pageNavigator = new PathPageNavigator(indexPage, urlPrefix);
2022-03-21 14:21:34 +00:00
2022-04-11 18:34:09 +00:00
this.system.registerSyscalls(
[],
eventSyscalls(this.eventHook),
2022-05-09 12:59:12 +00:00
editorSyscalls(this),
spaceSyscalls(this),
indexerSyscalls(this.space),
2022-09-14 07:40:11 +00:00
fulltextSyscalls(this.space),
systemSyscalls(this, this.system),
2022-05-09 12:59:12 +00:00
markdownSyscalls(buildMarkdown(this.mdExtensions)),
clientStoreSyscalls(),
storeSyscalls(this.space),
sandboxSyscalls(this.system),
assetSyscalls(this.system),
2022-10-25 16:50:07 +00:00
collabSyscalls(this),
2022-04-11 18:34:09 +00:00
);
2022-05-13 12:36:26 +00:00
2022-05-17 09:53:17 +00:00
// Make keyboard shortcuts work even when the editor is in read only mode or not focused
globalThis.addEventListener("keydown", (ev) => {
2022-05-17 09:53:17 +00:00
if (!this.editorView?.hasFocus) {
2022-07-19 11:49:54 +00:00
if ((ev.target as any).classList.contains("cm-textfield")) {
// Search & replace feature, ignore this
return;
}
2022-05-17 09:53:17 +00:00
if (runScopeHandlers(this.editorView!, ev, "editor")) {
ev.preventDefault();
}
}
});
globalThis.addEventListener("touchstart", (ev) => {
// Launch the command palette using a three-finger tap
if (ev.touches.length > 2) {
ev.stopPropagation();
ev.preventDefault();
this.viewDispatch({ type: "show-palette" });
}
});
}
get currentPage(): string | undefined {
return this.viewState.currentPage;
}
async init() {
this.focus();
2022-08-30 08:44:20 +00:00
this.pageNavigator.subscribe(async (pageName, pos: number | string) => {
2022-09-13 06:41:01 +00:00
console.log("Now navigating to", pageName);
if (!this.editorView) {
return;
}
const stateRestored = await this.loadPage(pageName);
2022-03-28 13:25:05 +00:00
if (pos) {
2022-08-30 08:44:20 +00:00
if (typeof pos === "string") {
2022-10-24 17:40:52 +00:00
console.log("Navigating to anchor", pos);
2022-08-30 08:44:20 +00:00
// We're going to look up the anchor through a direct page store query...
const posLookup = await this.system.localSyscall(
"core",
"index.get",
[
pageName,
2022-10-24 17:40:52 +00:00
`a:${pageName}:${pos}`,
],
);
2022-08-30 08:44:20 +00:00
if (!posLookup) {
return this.flashNotification(
`Could not find anchor @${pos}`,
"error",
2022-08-30 08:44:20 +00:00
);
} else {
pos = +posLookup;
}
}
2022-03-28 13:25:05 +00:00
this.editorView.dispatch({
selection: { anchor: pos },
2022-08-30 08:44:20 +00:00
scrollIntoView: true,
2022-03-28 13:25:05 +00:00
});
2022-09-06 14:33:00 +00:00
} else if (!stateRestored) {
this.editorView.dispatch({
selection: { anchor: 0 },
scrollIntoView: true,
});
2022-03-28 13:25:05 +00:00
}
});
const globalModules: any = await (
2022-07-22 11:44:28 +00:00
await fetch(`${this.urlPrefix}/global.plug.json`)
).json();
this.system.on({
plugLoaded: async (plug) => {
for (
const [modName, code] of Object.entries(
globalModules.dependencies,
)
) {
await plug.sandbox.loadDependency(modName, code as string);
}
},
});
this.space.on({
pageChanged: (meta) => {
if (this.currentPage === meta.name) {
console.log("Page changed on disk, reloading");
this.flashNotification("Page changed on disk, reloading");
this.reloadPage();
}
},
pageListUpdated: (pages) => {
this.viewDispatch({
type: "pages-listed",
pages: pages,
});
},
});
2022-06-14 14:55:50 +00:00
await this.reloadPlugs();
2022-07-11 07:08:22 +00:00
await this.dispatchAppEvent("editor:init");
}
save(immediate = false): Promise<void> {
return new Promise((resolve, reject) => {
if (this.saveTimeout) {
clearTimeout(this.saveTimeout);
}
this.saveTimeout = setTimeout(
() => {
if (this.currentPage) {
2022-10-22 18:23:54 +00:00
if (!this.viewState.unsavedChanges || this.viewState.forcedROMode) {
// No unsaved changes, or read-only mode, not gonna save
2022-10-21 17:02:00 +00:00
return resolve();
}
console.log("Saving page", this.currentPage);
this.space
.writePage(
this.currentPage,
this.editorView!.state.sliceDoc(0),
true,
)
.then(() => {
this.viewDispatch({ type: "page-saved" });
resolve();
})
2022-07-19 15:21:11 +00:00
.catch((e) => {
this.flashNotification(
"Could not save page, retrying again in 10 seconds",
"error",
2022-07-19 15:21:11 +00:00
);
this.saveTimeout = setTimeout(this.save.bind(this), 10000);
reject(e);
});
} else {
resolve();
}
},
immediate ? 0 : saveInterval,
);
});
}
flashNotification(message: string, type: "info" | "error" = "info") {
const id = Math.floor(Math.random() * 1000000);
this.viewDispatch({
type: "show-notification",
notification: {
id,
type,
message,
date: new Date(),
},
});
setTimeout(
() => {
this.viewDispatch({
type: "dismiss-notification",
id: id,
});
},
type === "info" ? 2000 : 5000,
);
}
filterBox(
label: string,
options: FilterOption[],
helpText = "",
placeHolder = "",
): Promise<FilterOption | undefined> {
return new Promise((resolve) => {
this.viewDispatch({
type: "show-filterbox",
label,
options,
placeHolder,
helpText,
onSelect: (option) => {
this.viewDispatch({ type: "hide-filterbox" });
this.focus();
resolve(option);
},
});
});
}
dispatchAppEvent(name: AppEvent, data?: any): Promise<any[]> {
return this.eventHook.dispatchEvent(name, data);
}
createEditorState(pageName: string, text: string): EditorState {
const commandKeyBindings: KeyBinding[] = [];
for (const def of this.commandHook.editorCommands.values()) {
if (def.command.key) {
commandKeyBindings.push({
key: def.command.key,
mac: def.command.mac,
run: (): boolean => {
if (def.command.contexts) {
const context = this.getContext();
if (!context || !def.command.contexts.includes(context)) {
return false;
}
}
Promise.resolve()
2022-03-28 13:25:05 +00:00
.then(def.run)
.catch((e: any) => {
console.error(e);
this.flashNotification(
`Error running command: ${e.message}`,
"error",
);
})
.then(() => {
// Always be focusing the editor after running a command
editor.focus();
2022-03-28 13:25:05 +00:00
});
return true;
},
});
}
}
// deno-lint-ignore no-this-alias
const editor = this;
return EditorState.create({
2022-10-25 16:50:07 +00:00
doc: this.collabState ? this.collabState.ytext.toString() : text,
extensions: [
2022-06-14 07:45:22 +00:00
markdown({
base: buildMarkdown(this.mdExtensions),
codeLanguages: [
LanguageDescription.of({
name: "yaml",
alias: ["meta", "data"],
support: new LanguageSupport(StreamLanguage.define(yamlLanguage)),
}),
LanguageDescription.of({
name: "javascript",
alias: ["js"],
support: new LanguageSupport(javascriptLanguage),
}),
LanguageDescription.of({
name: "typescript",
alias: ["ts"],
support: new LanguageSupport(typescriptLanguage),
}),
],
addKeymap: true,
2022-06-14 07:45:22 +00:00
}),
2022-06-13 16:31:36 +00:00
syntaxHighlighting(customMarkdownStyle(this.mdExtensions)),
autocompletion({
override: [
this.completer.bind(this),
this.slashCommandHook.slashCommandCompleter.bind(
this.slashCommandHook,
),
],
}),
2022-09-13 06:41:01 +00:00
inlineImagesPlugin(),
highlightSpecialChars(),
history(),
drawSelection(),
dropCursor(),
indentOnInput(),
EditorView.lineWrapping,
lineWrapper([
2022-08-02 12:40:04 +00:00
{ selector: "ATXHeading1", class: "sb-line-h1" },
{ selector: "ATXHeading2", class: "sb-line-h2" },
{ selector: "ATXHeading3", class: "sb-line-h3" },
{ selector: "ListItem", class: "sb-line-li", nesting: true },
{ selector: "Blockquote", class: "sb-line-blockquote" },
{ selector: "Task", class: "sb-line-task" },
{ selector: "CodeBlock", class: "sb-line-code" },
{ selector: "FencedCode", class: "sb-line-fenced-code" },
{ selector: "Comment", class: "sb-line-comment" },
{ selector: "BulletList", class: "sb-line-ul" },
{ selector: "OrderedList", class: "sb-line-ol" },
{ selector: "TableHeader", class: "sb-line-tbl-header" },
{ selector: "FrontMatter", class: "sb-frontmatter" },
]),
keymap.of([
...smartQuoteKeymap,
...closeBracketsKeymap,
...standardKeymap,
...searchKeymap,
...historyKeymap,
...completionKeymap,
2022-10-25 16:50:07 +00:00
...(this.collabState ? yUndoManagerKeymap : []),
indentWithTab,
...commandKeyBindings,
{
key: "Ctrl-k",
mac: "Cmd-k",
run: (): boolean => {
this.viewDispatch({ type: "start-navigate" });
2022-04-26 17:04:36 +00:00
this.space.updatePageList();
return true;
},
},
{
key: "Ctrl-/",
mac: "Cmd-/",
run: (): boolean => {
this.viewDispatch({
type: "show-palette",
context: this.getContext(),
});
return true;
},
},
2022-04-05 15:02:17 +00:00
{
key: "Ctrl-l",
mac: "Cmd-l",
run: (): boolean => {
this.editorView?.dispatch({
effects: [
EditorView.scrollIntoView(
this.editorView.state.selection.main.anchor,
{
y: "center",
},
2022-04-05 15:02:17 +00:00
),
],
});
return true;
},
},
]),
2022-03-30 13:16:22 +00:00
EditorView.domEventHandlers({
click: (event: MouseEvent, view: EditorView) => {
safeRun(async () => {
const clickEvent: ClickEvent = {
2022-03-28 13:25:05 +00:00
page: pageName,
ctrlKey: event.ctrlKey,
metaKey: event.metaKey,
altKey: event.altKey,
pos: view.posAtCoords(event)!,
};
await this.dispatchAppEvent("page:click", clickEvent);
});
},
}),
ViewPlugin.fromClass(
class {
update(update: ViewUpdate): void {
if (update.docChanged) {
editor.viewDispatch({ type: "page-changed" });
2022-04-04 13:25:07 +00:00
editor.debouncedUpdateEvent();
editor.save().catch((e) => console.error("Error saving", e));
}
}
},
),
2022-03-30 13:16:22 +00:00
pasteLinkExtension,
attachmentExtension(this),
2022-06-14 07:45:22 +00:00
closeBrackets(),
2022-10-25 16:50:07 +00:00
...[this.collabState ? this.collabState.collabExtension() : []],
],
});
}
2022-04-26 17:04:36 +00:00
async reloadPlugs() {
console.log("Loading plugs");
2022-04-26 17:04:36 +00:00
await this.space.updatePageList();
await this.system.unloadAll();
console.log("(Re)loading plugs");
2022-10-21 14:48:48 +00:00
await Promise.all((await this.space.listPlugs()).map(async (plugName) => {
const { data } = await this.space.readAttachment(plugName, "string");
2022-10-21 15:06:14 +00:00
await this.system.load(JSON.parse(data as string), createSandbox);
2022-10-21 14:48:48 +00:00
}));
2022-04-26 17:04:36 +00:00
this.rebuildEditorState();
2022-07-11 07:08:22 +00:00
await this.dispatchAppEvent("plugs:loaded");
2022-04-26 17:04:36 +00:00
}
2022-03-31 15:25:34 +00:00
rebuildEditorState() {
const editorView = this.editorView;
2022-06-14 14:55:50 +00:00
console.log("Rebuilding editor state");
2022-03-31 15:25:34 +00:00
if (editorView && this.currentPage) {
2022-06-14 14:55:50 +00:00
console.log("Getting all syntax extensions");
2022-04-11 18:34:09 +00:00
this.mdExtensions = loadMarkdownExtensions(this.system);
// And reload the syscalls to use the new syntax extensions
this.system.registerSyscalls(
[],
markdownSyscalls(buildMarkdown(this.mdExtensions)),
2022-04-11 18:34:09 +00:00
);
2022-09-06 14:33:00 +00:00
this.saveState(this.currentPage);
2022-04-26 17:04:36 +00:00
2022-03-31 15:25:34 +00:00
editorView.setState(
this.createEditorState(this.currentPage, editorView.state.sliceDoc()),
2022-03-31 15:25:34 +00:00
);
if (editorView.contentDOM) {
2022-05-17 09:53:17 +00:00
this.tweakEditorDOM(
editorView.contentDOM,
this.viewState.perm === "ro",
2022-05-17 09:53:17 +00:00
);
}
2022-04-26 17:04:36 +00:00
this.restoreState(this.currentPage);
2022-03-31 15:25:34 +00:00
}
}
async completer(): Promise<CompletionResult | null> {
const results = await this.dispatchAppEvent("page:complete");
let actualResult = null;
for (const result of results) {
if (result) {
if (actualResult) {
console.error(
"Got completion results from multiple sources, cannot deal with that",
);
return null;
}
actualResult = result;
}
}
return actualResult;
}
2022-10-10 16:19:08 +00:00
async reloadPage() {
console.log("Reloading page");
2022-10-10 16:19:08 +00:00
clearTimeout(this.saveTimeout);
await this.loadPage(this.currentPage!);
}
focus() {
this.editorView!.focus();
}
async navigate(
name: string,
pos?: number | string,
replaceState = false,
newWindow = false,
) {
2022-08-02 10:43:39 +00:00
if (!name) {
name = this.indexPage;
}
if (newWindow) {
const win = window.open(`${location.origin}/${name}`, "_blank");
if (win) {
win.focus();
}
return;
}
await this.pageNavigator.navigate(name, pos, replaceState);
}
2022-09-06 14:33:00 +00:00
async loadPage(pageName: string): Promise<boolean> {
const loadingDifferentPage = pageName !== this.currentPage;
const editorView = this.editorView;
if (!editorView) {
2022-09-06 14:33:00 +00:00
return false;
}
2022-09-06 14:33:00 +00:00
const previousPage = this.currentPage;
// Persist current page state and nicely close page
2022-09-06 14:33:00 +00:00
if (previousPage) {
this.saveState(previousPage);
this.space.unwatchPage(previousPage);
2022-10-10 16:19:08 +00:00
if (previousPage !== pageName) {
await this.save(true);
2022-10-25 16:50:07 +00:00
// And stop the collab session
if (this.collabState) {
this.collabState.stop();
this.collabState = undefined;
}
2022-10-10 16:19:08 +00:00
}
}
2022-09-12 12:50:37 +00:00
this.viewDispatch({
type: "page-loading",
name: pageName,
});
// Fetch next page to open
let doc;
try {
doc = await this.space.readPage(pageName);
} catch (e: any) {
// Not found, new page
console.log("Creating new page", pageName);
doc = {
text: "",
2022-05-17 09:53:17 +00:00
meta: { name: pageName, lastModified: 0, perm: "rw" } as PageMeta,
};
}
const editorState = this.createEditorState(pageName, doc.text);
editorView.setState(editorState);
if (editorView.contentDOM) {
2022-05-17 09:53:17 +00:00
this.tweakEditorDOM(editorView.contentDOM, doc.meta.perm === "ro");
}
const stateRestored = this.restoreState(pageName);
this.space.watchPage(pageName);
this.viewDispatch({
type: "page-loaded",
2022-05-17 09:53:17 +00:00
meta: doc.meta,
});
2022-04-04 13:25:07 +00:00
if (loadingDifferentPage) {
await this.eventHook.dispatchEvent("editor:pageLoaded", pageName);
2022-07-18 14:48:36 +00:00
} else {
await this.eventHook.dispatchEvent("editor:pageReloaded", pageName);
}
2022-09-06 14:33:00 +00:00
return stateRestored;
}
2022-05-17 09:53:17 +00:00
tweakEditorDOM(contentDOM: HTMLElement, readOnly: boolean) {
2022-05-09 08:45:36 +00:00
contentDOM.spellcheck = true;
contentDOM.setAttribute("autocorrect", "on");
contentDOM.setAttribute("autocapitalize", "on");
2022-09-16 12:26:47 +00:00
contentDOM.setAttribute(
"contenteditable",
readOnly || this.viewState.forcedROMode ? "false" : "true",
2022-09-16 12:26:47 +00:00
);
if (isMobileSafari() && readOnly) {
console.log("Safari read only hack");
contentDOM.classList.add("ios-safari-readonly");
} else {
contentDOM.classList.remove("ios-safari-readonly");
}
function isMobileSafari() {
return (
navigator.userAgent.match(/(iPod|iPhone|iPad)/) &&
navigator.userAgent.match(/AppleWebKit/)
);
}
2022-05-09 08:45:36 +00:00
}
2022-09-06 14:33:00 +00:00
private restoreState(pageName: string): boolean {
const pageState = this.openPages.get(pageName);
2022-04-26 17:04:36 +00:00
const editorView = this.editorView!;
if (pageState) {
// Restore state
// console.log("Restoring selection state", pageState);
editorView.scrollDOM.scrollTop = pageState!.scrollTop;
2022-04-26 17:04:36 +00:00
editorView.dispatch({
selection: pageState.selection,
2022-07-06 10:18:33 +00:00
scrollIntoView: true,
2022-04-26 17:04:36 +00:00
});
} else {
editorView.scrollDOM.scrollTop = 0;
editorView.dispatch({
selection: { anchor: 0 },
scrollIntoView: true,
});
2022-04-26 17:04:36 +00:00
}
editorView.focus();
2022-09-06 14:33:00 +00:00
return !!pageState;
2022-04-26 17:04:36 +00:00
}
2022-09-06 14:33:00 +00:00
private saveState(currentPage: string) {
2022-04-26 17:04:36 +00:00
this.openPages.set(
2022-09-06 14:33:00 +00:00
currentPage,
2022-04-26 17:04:36 +00:00
new PageState(
this.editorView!.scrollDOM.scrollTop,
this.editorView!.state.selection,
),
2022-04-26 17:04:36 +00:00
);
}
ViewComponent() {
const [viewState, dispatch] = useReducer(reducer, initialViewState);
this.viewState = viewState;
this.viewDispatch = dispatch;
// deno-lint-ignore no-this-alias
const editor = this;
useEffect(() => {
if (viewState.currentPage) {
document.title = viewState.currentPage;
}
}, [viewState.currentPage]);
2022-09-16 12:26:47 +00:00
useEffect(() => {
if (editor.editorView) {
editor.tweakEditorDOM(
editor.editorView.contentDOM,
viewState.perm === "ro",
2022-09-16 12:26:47 +00:00
);
}
}, [viewState.forcedROMode]);
return (
2022-04-04 16:33:13 +00:00
<>
{viewState.showPageNavigator && (
<PageNavigator
allPages={viewState.allPages}
currentPage={this.currentPage}
onNavigate={(page) => {
dispatch({ type: "stop-navigate" });
editor.focus();
if (page) {
safeRun(async () => {
await editor.navigate(page);
});
}
}}
/>
)}
{viewState.showCommandPalette && (
<CommandPalette
onTrigger={(cmd) => {
dispatch({ type: "hide-palette" });
editor.focus();
if (cmd) {
2022-05-16 13:09:36 +00:00
dispatch({ type: "command-run", command: cmd.command.name });
cmd
.run()
.catch((e: any) => {
console.error("Error running command", e.message);
})
.then(() => {
// Always be focusing the editor after running a command
editor.focus();
});
}
}}
commands={viewState.commands}
2022-05-16 13:09:36 +00:00
recentCommands={viewState.recentCommands}
/>
)}
{viewState.showFilterBox && (
<FilterList
label={viewState.filterBoxLabel}
placeholder={viewState.filterBoxPlaceHolder}
options={viewState.filterBoxOptions}
allowNew={false}
helpText={viewState.filterBoxHelpText}
onSelect={viewState.filterBoxOnSelect}
/>
)}
<TopBar
pageName={viewState.currentPage}
notifications={viewState.notifications}
unsavedChanges={viewState.unsavedChanges}
isLoading={viewState.isLoading}
onClick={() => {
dispatch({ type: "start-navigate" });
}}
2022-08-26 22:32:40 +00:00
onThemeClick={() => {
2022-08-30 07:30:36 +00:00
if (localStorage.theme === "dark") localStorage.theme = "light";
else localStorage.theme = "dark";
2022-08-26 22:32:40 +00:00
document.documentElement.dataset.theme = localStorage.theme;
}}
2022-07-04 09:38:16 +00:00
onHomeClick={() => {
2022-08-02 10:43:39 +00:00
editor.navigate("");
2022-07-04 09:38:16 +00:00
}}
onActionClick={() => {
dispatch({ type: "show-palette" });
}}
rhs={!!viewState.panels.rhs.mode && (
<div
className="panel"
style={{ flex: viewState.panels.rhs.mode }}
/>
)}
lhs={!!viewState.panels.lhs.mode && (
<div
className="panel"
style={{ flex: viewState.panels.lhs.mode }}
/>
)}
/>
2022-07-22 11:44:28 +00:00
<div id="sb-main">
{!!viewState.panels.lhs.mode && (
<Panel config={viewState.panels.lhs} editor={editor} />
2022-04-04 16:33:13 +00:00
)}
2022-07-22 11:44:28 +00:00
<div id="sb-editor" />
{!!viewState.panels.rhs.mode && (
<Panel config={viewState.panels.rhs} editor={editor} />
2022-04-04 16:33:13 +00:00
)}
</div>
{!!viewState.panels.modal.mode && (
<div
className="sb-modal"
style={{ inset: `${viewState.panels.modal.mode}px` }}
>
<Panel config={viewState.panels.modal} editor={editor} />
</div>
)}
{!!viewState.panels.bhs.mode && (
2022-08-02 12:40:04 +00:00
<div className="sb-bhs">
<Panel config={viewState.panels.bhs} editor={editor} />
2022-04-26 17:04:36 +00:00
</div>
)}
2022-04-04 16:33:13 +00:00
</>
);
}
2022-07-11 07:08:22 +00:00
async runCommandByName(name: string) {
const cmd = this.viewState.commands.get(name);
if (cmd) {
await cmd.run();
} else {
throw new Error(`Command ${name} not found`);
}
}
render(container: Element) {
const ViewComponent = this.ViewComponent.bind(this);
// console.log(<ViewComponent />);
preactRender(<ViewComponent />, container);
}
private getContext(): string | undefined {
const state = this.editorView!.state;
const selection = state.selection.main;
if (selection.empty) {
return syntaxTree(state).resolveInner(selection.from).name;
}
return;
}
2022-10-25 16:50:07 +00:00
startCollab(serverUrl: string, token: string, username: string) {
if (this.collabState) {
// Clean up old collab state
this.collabState.stop();
}
const initialText = this.editorView!.state.sliceDoc();
this.collabState = new CollabState(serverUrl, token, username);
this.collabState.collabProvider.once("sync", (synced: boolean) => {
if (this.collabState?.ytext.toString() === "") {
console.log("Synced value is empty, putting back original text");
this.collabState?.ytext.insert(0, initialText);
}
});
this.rebuildEditorState();
}
}