Refactor closing and make Mod+W close

This commit is contained in:
Quinten Kock 2025-11-10 22:37:45 +01:00
parent bde88881b2
commit cfb7d5cea0
3 changed files with 36 additions and 20 deletions

View File

@ -42,6 +42,7 @@ const fixedHeightEditor = EditorView.theme({
export class Editor {
view: EditorView;
file: OpenFile;
deleteFn?: () => void;
dispatch(tr: Transaction, inhibitSync = false) {
this.view.update([tr]);
@ -65,6 +66,7 @@ export class Editor {
return true;
},
},
{ key: "Mod-w", run: () => this.close() },
]);
this.view = new EditorView({
doc: file.rootState.val.doc,
@ -103,4 +105,21 @@ export class Editor {
get dom() {
return this.view.dom;
}
focus() {
this.view.dom.scrollIntoView();
this.view.focus();
}
close() {
if (this.deleteFn) {
this.file.removeEditor(this, this.deleteFn);
return true;
}
return false;
}
setDeleteFunction(fn: () => void) {
this.deleteFn = fn;
}
}

View File

@ -1,12 +1,20 @@
import van from "vanjs-core";
import van, { State } from "vanjs-core";
import * as vanX from "vanjs-ext";
const v = van.tags;
import { OpenFile } from "./filestate";
import * as u from "./utils";
import { Editor } from "./editor";
const EditorWrapper = (editor: any, del: any, k: any) =>
v.div(
const EditorWrapper = (editor: State<Editor>, del: () => void, k: number) => {
// Set the delete function on the editor when it's created
van.derive(() => {
if (editor.val) {
editor.val.setDeleteFunction(del);
}
});
return v.div(
{ class: "flex flex-col" },
v.div(
{ class: "flex" },
@ -16,21 +24,11 @@ const EditorWrapper = (editor: any, del: any, k: any) =>
editor.val.file.filePath.val +
(editor.val.file.isDirty() ? "*" : ""),
),
u.InlineButton(
async () => {
const canClose = await editor.val.file.removeEditor(
editor.val,
);
if (canClose) {
del();
}
},
"Close",
"❌",
),
u.InlineButton(() => editor.val.close(), "Close", "❌"),
),
v.div({ class: "flex-auto h-4" }, editor.val.dom),
);
};
const editors = vanX.reactive([[]]);
const currentTab = van.state(0);
@ -40,8 +38,7 @@ export function addEditor(file: OpenFile) {
console.log("Adding editor to tab ", currentTab.val, editors);
const editor = file.createEditor();
editors[currentTab.val].push(vanX.noreactive(editor));
editor.view.dom.scrollIntoView();
editor.view.focus();
editor.focus();
}
export function addTab(file?: OpenFile) {

View File

@ -74,7 +74,7 @@ export class OpenFile {
}
// Function to remove an editor and clean up if no more editors exist
async removeEditor(editor: Editor): Promise<boolean> {
async removeEditor(editor: Editor, callback: () => void) {
const index = this.editors.indexOf(editor);
if (index > -1) {
this.editors.splice(index, 1);
@ -86,7 +86,7 @@ export class OpenFile {
if (!confirmed) {
// Re-add the editor if user cancelled
this.editors.push(editor);
return false;
return;
}
}
@ -95,7 +95,7 @@ export class OpenFile {
delete openFiles[this.filePath.val];
}
return true;
callback();
}
// Function to confirm closing of dirty file