1
0
silverbullet/webapp/src/app.tsx

407 lines
11 KiB
TypeScript
Raw Normal View History

2022-02-21 08:32:36 +00:00
import { autocompletion, completionKeymap } from "@codemirror/autocomplete";
import { closeBrackets, closeBracketsKeymap } from "@codemirror/closebrackets";
import { indentWithTab, standardKeymap } from "@codemirror/commands";
import { history, historyKeymap } from "@codemirror/history";
import { indentOnInput } from "@codemirror/language";
import { bracketMatching } from "@codemirror/matchbrackets";
import { searchKeymap } from "@codemirror/search";
2022-02-21 10:27:30 +00:00
import { EditorState, StateField, Transaction } from "@codemirror/state";
2022-02-21 08:32:36 +00:00
import {
drawSelection,
dropCursor,
EditorView,
highlightSpecialChars,
keymap,
} from "@codemirror/view";
2022-02-21 10:27:30 +00:00
import React, { useEffect, useReducer, useRef } from "react";
import ReactDOM from "react-dom";
2022-02-21 08:32:36 +00:00
import * as commands from "./commands";
2022-02-22 13:18:37 +00:00
import { CommandPalette } from "./components/commandpalette";
import { NoteNavigator } from "./components/notenavigator";
2022-02-23 13:09:26 +00:00
import { FileSystem, HttpFileSystem } from "./fs";
2022-02-21 08:32:36 +00:00
import { lineWrapper } from "./lineWrapper";
2022-02-21 10:27:30 +00:00
import { markdown } from "./markdown";
2022-02-21 08:32:36 +00:00
import customMarkDown from "./parser";
2022-02-22 13:18:37 +00:00
import reducer from "./reducer";
2022-02-21 08:32:36 +00:00
import customMarkdownStyle from "./style";
2022-02-22 13:18:37 +00:00
import { Action, AppViewState } from "./types";
2022-02-21 08:32:36 +00:00
2022-02-22 13:18:37 +00:00
import { syntaxTree } from "@codemirror/language";
import * as util from "./util";
2022-02-22 16:36:24 +00:00
import { NoteMeta } from "./types";
2022-02-21 10:27:30 +00:00
2022-02-22 13:18:37 +00:00
const initialViewState: AppViewState = {
2022-02-21 10:27:30 +00:00
isSaved: false,
2022-02-22 13:18:37 +00:00
showNoteNavigator: false,
showCommandPalette: false,
2022-02-21 10:27:30 +00:00
allNotes: [],
2022-02-21 08:32:36 +00:00
};
2022-02-22 16:36:24 +00:00
import { CompletionContext, CompletionResult } from "@codemirror/autocomplete";
2022-02-23 13:09:26 +00:00
import { NavigationBar } from "./components/navigation_bar";
import { StatusBar } from "./components/status_bar";
class NoteState {
editorState: EditorState;
scrollTop: number;
constructor(editorState: EditorState, scrollTop: number) {
this.editorState = editorState;
this.scrollTop = scrollTop;
}
}
2022-02-22 16:36:24 +00:00
2022-02-21 08:32:36 +00:00
class Editor {
2022-02-23 13:09:26 +00:00
editorView?: EditorView;
viewState: AppViewState;
viewDispatch: React.Dispatch<Action>;
$hashChange?: () => void;
openNotes: Map<string, NoteState>;
fs: FileSystem;
constructor(fs: FileSystem, parent: Element) {
this.fs = fs;
this.viewState = initialViewState;
this.viewDispatch = () => {};
this.render(parent);
this.editorView = new EditorView({
state: this.createEditorState(""),
parent: document.getElementById("editor")!,
2022-02-21 08:32:36 +00:00
});
2022-02-23 13:09:26 +00:00
this.addListeners();
this.loadNoteList();
this.openNotes = new Map();
this.$hashChange!();
}
get currentNote(): string | undefined {
return this.viewState.currentNote;
2022-02-21 08:32:36 +00:00
}
2022-02-21 10:27:30 +00:00
createEditorState(text: string): EditorState {
2022-02-22 13:18:37 +00:00
const editor = this;
2022-02-21 08:32:36 +00:00
return EditorState.create({
doc: text,
extensions: [
highlightSpecialChars(),
history(),
drawSelection(),
dropCursor(),
indentOnInput(),
customMarkdownStyle,
bracketMatching(),
closeBrackets(),
2022-02-22 16:36:24 +00:00
autocompletion({
override: [this.noteCompleter.bind(this)],
}),
2022-02-21 08:32:36 +00:00
EditorView.lineWrapping,
lineWrapper([
{ selector: "ATXHeading1", class: "line-h1" },
{ selector: "ATXHeading2", class: "line-h2" },
{ selector: "ListItem", class: "line-li" },
{ selector: "Blockquote", class: "line-blockquote" },
{ selector: "CodeBlock", class: "line-code" },
{ selector: "FencedCode", class: "line-fenced-code" },
]),
keymap.of([
...closeBracketsKeymap,
...standardKeymap,
...searchKeymap,
...historyKeymap,
...completionKeymap,
indentWithTab,
{
key: "Ctrl-b",
mac: "Cmd-b",
run: commands.insertMarker("**"),
},
{
key: "Ctrl-i",
mac: "Cmd-i",
run: commands.insertMarker("_"),
},
{
key: "Ctrl-s",
mac: "Cmd-s",
run: (target: EditorView): boolean => {
Promise.resolve()
.then(async () => {
console.log("Saving");
await this.save();
})
.catch((e) => console.error(e));
return true;
},
},
2022-02-22 13:18:37 +00:00
{
key: "Ctrl-Enter",
mac: "Cmd-Enter",
run: (target): boolean => {
// TODO: Factor this and click handler into one action
let selection = target.state.selection.main;
if (selection.empty) {
let node = syntaxTree(target.state).resolveInner(
selection.from
);
if (node && node.name === "WikiLinkPage") {
let noteName = target.state.sliceDoc(node.from, node.to);
this.navigate(noteName);
return true;
}
}
return false;
},
},
2022-02-21 10:27:30 +00:00
{
key: "Ctrl-p",
mac: "Cmd-p",
run: (target): boolean => {
2022-02-23 13:09:26 +00:00
this.viewDispatch({ type: "start-navigate" });
2022-02-21 10:27:30 +00:00
return true;
},
},
2022-02-22 13:18:37 +00:00
{
key: "Ctrl-.",
mac: "Cmd-.",
run: (target): boolean => {
2022-02-23 13:09:26 +00:00
this.viewDispatch({ type: "show-palette" });
2022-02-22 13:18:37 +00:00
return true;
},
},
2022-02-21 08:32:36 +00:00
]),
EditorView.domEventHandlers({
2022-02-21 10:27:30 +00:00
click: this.click.bind(this),
2022-02-21 08:32:36 +00:00
}),
markdown({
base: customMarkDown,
}),
StateField.define({
create: () => null,
2022-02-21 10:27:30 +00:00
update: this.update.bind(this),
2022-02-21 08:32:36 +00:00
}),
],
});
}
2022-02-21 10:27:30 +00:00
2022-02-22 16:36:24 +00:00
noteCompleter(ctx: CompletionContext): CompletionResult | null {
let prefix = ctx.matchBefore(/\[\[\w*/);
if (!prefix) {
return null;
}
// TODO: Lots of optimization potential here
// TODO: put something in the cm-completionIcon-note style
return {
from: prefix.from + 2,
2022-02-23 13:09:26 +00:00
options: this.viewState.allNotes.map((noteMeta) => ({
2022-02-22 16:36:24 +00:00
label: noteMeta.name,
type: "note",
})),
};
}
2022-02-21 10:27:30 +00:00
update(value: null, transaction: Transaction): null {
if (transaction.docChanged) {
2022-02-23 13:09:26 +00:00
this.viewDispatch({
2022-02-22 13:18:37 +00:00
type: "note-updated",
2022-02-21 10:27:30 +00:00
});
}
return null;
}
click(event: MouseEvent, view: EditorView) {
if (event.metaKey || event.ctrlKey) {
2022-02-22 13:18:37 +00:00
let coords = view.posAtCoords(event)!;
let node = syntaxTree(view.state).resolveInner(coords);
if (node && node.name === "WikiLinkPage") {
let noteName = view.state.sliceDoc(node.from, node.to);
this.navigate(noteName);
}
2022-02-22 16:36:24 +00:00
if (node && node.name === "TaskMarker") {
let checkBoxText = view.state.sliceDoc(node.from, node.to);
if (checkBoxText === "[x]" || checkBoxText === "[X]") {
view.dispatch({
changes: { from: node.from, to: node.to, insert: "[ ]" },
});
} else {
view.dispatch({
changes: { from: node.from, to: node.to, insert: "[x]" },
});
}
}
2022-02-21 10:27:30 +00:00
return false;
}
}
async save() {
2022-02-23 13:09:26 +00:00
const editorState = this.editorView!.state;
if (!this.currentNote) {
return;
}
// Write to file system
const created = await this.fs.writeNote(
2022-02-22 13:18:37 +00:00
this.currentNote,
2022-02-23 13:09:26 +00:00
editorState.sliceDoc()
2022-02-22 13:18:37 +00:00
);
2022-02-23 13:09:26 +00:00
// Update in open note cache
this.openNotes.set(
this.currentNote,
new NoteState(editorState, this.editorView!.scrollDOM.scrollTop)
);
// Dispatch update to view
this.viewDispatch({ type: "note-saved" });
2022-02-22 13:18:37 +00:00
// If a new note was created, let's refresh the note list
if (created) {
await this.loadNoteList();
}
}
async loadNoteList() {
2022-02-23 13:09:26 +00:00
let notesMeta = await this.fs.listNotes();
this.viewDispatch({
2022-02-22 13:18:37 +00:00
type: "notes-listed",
notes: notesMeta,
});
2022-02-21 10:27:30 +00:00
}
focus() {
2022-02-23 13:09:26 +00:00
this.editorView!.focus();
2022-02-21 10:27:30 +00:00
}
2022-02-21 12:25:41 +00:00
2022-02-23 13:09:26 +00:00
async navigate(name: string) {
2022-02-21 12:25:41 +00:00
location.hash = encodeURIComponent(name);
}
2022-02-21 08:32:36 +00:00
2022-02-23 13:09:26 +00:00
hashChange() {
Promise.resolve()
.then(async () => {
await this.save();
const noteName = decodeURIComponent(location.hash.substring(1));
console.log("Now navigating to", noteName);
if (!this.editorView) {
return;
}
let noteState = this.openNotes.get(noteName);
if (!noteState) {
let text = await this.fs.readNote(noteName);
noteState = new NoteState(this.createEditorState(text), 0);
}
this.openNotes.set(noteName, noteState!);
this.editorView!.setState(noteState!.editorState);
this.editorView.scrollDOM.scrollTop = noteState!.scrollTop;
this.viewDispatch({
type: "note-loaded",
name: noteName,
});
})
.catch((e) => {
console.error(e);
});
}
2022-02-21 08:32:36 +00:00
2022-02-23 13:09:26 +00:00
addListeners() {
this.$hashChange = this.hashChange.bind(this);
window.addEventListener("hashchange", this.$hashChange);
2022-02-22 13:18:37 +00:00
}
2022-02-21 10:27:30 +00:00
2022-02-23 13:09:26 +00:00
dispose() {
if (this.$hashChange) {
window.removeEventListener("hashchange", this.$hashChange);
2022-02-21 12:25:41 +00:00
}
2022-02-23 13:09:26 +00:00
}
2022-02-21 10:27:30 +00:00
2022-02-23 13:09:26 +00:00
ViewComponent(): React.ReactElement {
const [viewState, dispatch] = useReducer(reducer, initialViewState);
this.viewState = viewState;
this.viewDispatch = dispatch;
2022-02-21 08:32:36 +00:00
2022-02-23 13:09:26 +00:00
useEffect(() => {
if (!location.hash) {
this.navigate("start");
2022-02-22 13:18:37 +00:00
}
2022-02-23 13:09:26 +00:00
}, []);
// Auto save
useEffect(() => {
const id = setTimeout(() => {
if (!viewState.isSaved) {
this.save();
}
}, 2000);
return () => {
clearTimeout(id);
};
}, [viewState.isSaved]);
let editor = this;
useEffect(() => {}, []);
return (
<>
{viewState.showNoteNavigator && (
<NoteNavigator
allNotes={viewState.allNotes}
onNavigate={(note) => {
dispatch({ type: "stop-navigate" });
editor!.focus();
if (note) {
editor
?.save()
.then(() => {
editor!.navigate(note);
})
.catch((e) => {
alert("Could not save note, not switching");
});
}
}}
/>
)}
{viewState.showCommandPalette && (
<CommandPalette
onTrigger={(cmd) => {
dispatch({ type: "hide-palette" });
editor!.focus();
if (cmd) {
console.log("Run", cmd);
}
}}
commands={[{ name: "My command", run: () => {} }]}
/>
)}
<NavigationBar
currentNote={viewState.currentNote}
onClick={() => {
dispatch({ type: "start-navigate" });
2022-02-22 13:18:37 +00:00
}}
/>
2022-02-23 13:09:26 +00:00
<div id="editor"></div>
<StatusBar isSaved={viewState.isSaved} editorView={this.editorView} />
</>
);
}
render(container: ReactDOM.Container) {
const ViewComponent = this.ViewComponent.bind(this);
ReactDOM.render(<ViewComponent />, container);
}
2022-02-21 08:32:36 +00:00
}
2022-02-23 13:09:26 +00:00
let ed = new Editor(
new HttpFileSystem("http://localhost:2222/fs"),
document.getElementById("root")!
);
ed.focus();
// @ts-ignore
window.editor = ed;