M1.6: tabs and CodeMirror editor

- Editor area with tab bar, CodeMirror 6 view, close question and notices
  (ui/src/components/editor/, ui/src/stores/editor.ts), mounted in App.vue;
  the project tree opens files through the editor store.
- BufferSync: local edits to buffer.edit against the confirmed version,
  one call in flight, resync on stale_version or newer bufferChanged with
  rebase of unsent changes; EngineText maps CodeMirror positions to engine
  UTF-16 offsets for CRLF text.
- Save, save all and close from engine default shortcuts via listCommands.
- Dirty marker, Save / Don't Save / Cancel, non-blocking notice when a
  dirty file changes or disappears on disk.
- Vitest: keystroke bursts with stale versions and remote edits (LF and
  CRLF), mapping, store and component tests against a fake engine.
- Progress docs: Editor core 8% (est.), depth ~1.4%, G2, ui-parity tabs,
  M1 row, architecture, README status.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-15 18:26:32 +02:00
parent 0fb7e33fc7
commit 9fa6028335
25 changed files with 2958 additions and 22 deletions

View file

@ -0,0 +1,135 @@
<script setup lang="ts">
/**
* The question shown when a tab with unsaved changes closes: Save,
* Don't Save or Cancel. Escape cancels; Save has the focus.
*/
import { nextTick, ref, watch } from "vue";
import { useEditorStore } from "../../stores/editor";
const editor = useEditorStore();
/** The Save button, focused when the question appears. */
const saveButton = ref<HTMLButtonElement | null>(null);
watch(
() => editor.closePrompt,
async (prompt) => {
if (prompt) {
await nextTick();
saveButton.value?.focus();
}
},
{ immediate: true },
);
/**
* Cancels on Escape.
*
* @param event - the key event inside the dialog.
*/
function onKeydown(event: KeyboardEvent): void {
if (event.key === "Escape") {
event.preventDefault();
void editor.resolveClose("cancel");
}
}
</script>
<template>
<div
v-if="editor.closePrompt"
class="close-prompt"
data-test="close-prompt"
>
<div
class="close-prompt__dialog"
role="alertdialog"
aria-modal="true"
aria-labelledby="lt-close-prompt-title"
@keydown="onKeydown"
>
<p
id="lt-close-prompt-title"
class="close-prompt__text"
>
Save changes to {{ editor.closePrompt.name }} before closing?
</p>
<div class="close-prompt__buttons">
<button
ref="saveButton"
type="button"
class="close-prompt__button close-prompt__button--primary"
data-test="close-save"
@click="editor.resolveClose('save')"
>
Save
</button>
<button
type="button"
class="close-prompt__button"
data-test="close-discard"
@click="editor.resolveClose('discard')"
>
Don't Save
</button>
<button
type="button"
class="close-prompt__button"
data-test="close-cancel"
@click="editor.resolveClose('cancel')"
>
Cancel
</button>
</div>
</div>
</div>
</template>
<style scoped>
.close-prompt {
position: absolute;
inset: 0;
display: flex;
align-items: flex-start;
justify-content: center;
padding-top: 15%;
background: color-mix(in srgb, var(--lt-bg) 50%, transparent);
z-index: 10;
}
.close-prompt__dialog {
min-width: 320px;
padding: 16px;
background: var(--lt-bg);
color: var(--lt-fg);
border: 1px solid var(--lt-border);
border-radius: 6px;
}
.close-prompt__text {
margin: 0 0 16px;
}
.close-prompt__buttons {
display: flex;
justify-content: flex-end;
gap: 8px;
}
.close-prompt__button {
padding: 4px 12px;
font: inherit;
color: var(--lt-fg);
background: var(--lt-editor-bg);
border: 1px solid var(--lt-border);
border-radius: 4px;
}
.close-prompt__button--primary {
border-color: var(--lt-accent);
}
.close-prompt__button:focus-visible {
outline: 1px solid var(--lt-accent);
}
</style>

View file

@ -0,0 +1,96 @@
<script setup lang="ts">
/**
* The CodeMirror view of the active tab.
*
* One view serves every tab: switching tabs swaps in the tab's editor state
* (kept by its {@link BufferSync}), so undo history, selection and scroll
* anchor survive. Every transaction goes through the sync, which forwards
* local edits to the engine.
*/
import { EditorView } from "@codemirror/view";
import { onBeforeUnmount, onMounted, ref, watch } from "vue";
import type { BufferSync } from "./bufferSync";
import { useEditorStore } from "../../stores/editor";
const editor = useEditorStore();
/** Element the view is mounted in. */
const host = ref<HTMLElement | null>(null);
/** The view, null before mount and after unmount. */
let view: EditorView | null = null;
/** Sync of the buffer shown, null if none. */
let attached: BufferSync | null = null;
/**
* Shows a buffer in the view.
*
* @param id - buffer id, or null for none.
*/
function show(id: number | null): void {
attached?.detach();
attached = null;
const sync = id === null ? undefined : editor.syncOf(id);
if (!view || !sync || id === null) {
return;
}
attached = sync;
sync.attach(view);
view.focus();
requestAnimationFrame(() => {
editor.markShown(id);
});
}
onMounted(() => {
if (!host.value) {
return;
}
view = new EditorView({
parent: host.value,
dispatchTransactions: (transactions, target) => {
if (attached) {
attached.applyTransactions(transactions);
} else {
target.update(transactions);
}
},
});
show(editor.activeId);
});
watch(
() => editor.activeId,
(id) => {
show(id);
},
);
onBeforeUnmount(() => {
attached?.detach();
attached = null;
view?.destroy();
view = null;
});
</script>
<template>
<div
ref="host"
class="code-editor"
data-test="code-editor"
:data-buffer="editor.activeId ?? undefined"
/>
</template>
<style scoped>
.code-editor {
flex: 1;
min-height: 0;
overflow: hidden;
user-select: text;
}
.code-editor :deep(.cm-editor) {
height: 100%;
}
</style>

View file

@ -0,0 +1,158 @@
<script setup lang="ts">
/**
* The editor area: tab bar, a notice line for the active tab, the editor
* and the close question. Without open tabs it shows the default slot.
*
* Shortcuts come from the engine's command specs (see `shortcuts.ts`); the
* area listens on the window in the capture phase so they also work while
* CodeMirror has the focus.
*/
import { onBeforeUnmount, onMounted } from "vue";
import { useEditorStore } from "../../stores/editor";
import ClosePrompt from "./ClosePrompt.vue";
import CodeEditor from "./CodeEditor.vue";
import EditorTabs from "./EditorTabs.vue";
import { commandFor, loadEditorKeymap, type EditorKeymap } from "./shortcuts";
const editor = useEditorStore();
/** Keymap loaded from the engine, empty until loaded. */
let keymap: EditorKeymap = [];
/**
* Runs the editor command bound to a key press.
*
* @param event - a key press anywhere in the window.
*/
function onKeydown(event: KeyboardEvent): void {
const command = commandFor(keymap, event);
if (command === null) {
return;
}
event.preventDefault();
event.stopPropagation();
switch (command) {
case "file.save":
void editor.save();
break;
case "file.saveAll":
void editor.saveAll();
break;
case "buffer.close":
void editor.requestClose();
break;
}
}
onMounted(() => {
editor.start();
window.addEventListener("keydown", onKeydown, true);
void loadEditorKeymap().then((result) => {
if (result.ok) {
keymap = result.value;
} else {
editor.lastError = result.error;
}
});
});
onBeforeUnmount(() => {
window.removeEventListener("keydown", onKeydown, true);
editor.stop();
});
</script>
<template>
<div
class="editor-area"
data-test="editor-area"
>
<template v-if="editor.tabs.length > 0">
<EditorTabs />
<div
v-if="editor.activeTab?.notice"
class="editor-area__notice"
:class="{ 'editor-area__notice--error': editor.activeTab.notice.kind === 'error' }"
role="status"
data-test="editor-notice"
>
<span>{{ editor.activeTab.notice.message }}</span>
<button
type="button"
class="editor-area__dismiss"
data-test="notice-dismiss"
@click="editor.dismissNotice(editor.activeTab.id)"
>
Dismiss
</button>
</div>
<CodeEditor />
</template>
<div
v-else
class="editor-area__empty"
>
<slot />
</div>
<div
v-if="editor.lastError"
class="editor-area__notice editor-area__notice--error"
role="alert"
data-test="editor-error"
>
<span>{{ editor.lastError.message }}</span>
<button
type="button"
class="editor-area__dismiss"
@click="editor.lastError = null"
>
Dismiss
</button>
</div>
<ClosePrompt />
</div>
</template>
<style scoped>
.editor-area {
position: relative;
display: flex;
flex-direction: column;
flex: 1;
align-self: stretch;
min-width: 0;
min-height: 0;
}
.editor-area__empty {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
}
.editor-area__notice {
display: flex;
align-items: center;
gap: 12px;
padding: 4px 12px;
flex-shrink: 0;
color: var(--lt-fg);
background: var(--lt-notice-bg, color-mix(in srgb, var(--lt-accent) 15%, var(--lt-bg)));
border-bottom: 1px solid var(--lt-border);
}
.editor-area__notice--error {
background: color-mix(in srgb, var(--lt-error) 15%, var(--lt-bg));
}
.editor-area__dismiss {
margin-left: auto;
padding: 0 8px;
font: inherit;
color: var(--lt-fg);
background: transparent;
border: 1px solid var(--lt-border);
border-radius: 3px;
}
</style>

View file

@ -0,0 +1,154 @@
<script setup lang="ts">
/**
* The tab bar of the editor area, following the WAI-ARIA tabs pattern.
*
* A click activates a tab, a middle click or the close button closes it,
* Left/Right move between tabs. A dot marks unsaved changes. Closing a
* dirty tab asks first (see the editor store).
*/
import { X } from "@lucide/vue";
import { useEditorStore } from "../../stores/editor";
const editor = useEditorStore();
/**
* Closes a tab on a middle click.
*
* @param event - the auxiliary click.
* @param id - buffer id of the tab.
*/
function onAuxClick(event: MouseEvent, id: number): void {
if (event.button === 1) {
event.preventDefault();
void editor.requestClose(id);
}
}
/**
* Keyboard navigation between tabs.
*
* @param event - the key event on the tab list.
*/
function onKeydown(event: KeyboardEvent): void {
const index = editor.tabs.findIndex((t) => t.id === editor.activeId);
const step = event.key === "ArrowRight" ? 1 : event.key === "ArrowLeft" ? -1 : 0;
if (step === 0 || editor.tabs.length === 0) {
return;
}
event.preventDefault();
const next = editor.tabs[(index + step + editor.tabs.length) % editor.tabs.length];
if (next) {
editor.activate(next.id);
}
}
</script>
<template>
<div
class="tabs"
role="tablist"
aria-label="Editor tabs"
data-test="editor-tabs"
@keydown="onKeydown"
>
<div
v-for="tab in editor.tabs"
:key="tab.id"
class="tabs__tab"
:class="{ 'tabs__tab--active': tab.id === editor.activeId }"
role="tab"
:tabindex="tab.id === editor.activeId ? 0 : -1"
:aria-selected="tab.id === editor.activeId"
:title="tab.path"
:data-id="tab.id"
data-test="editor-tab"
@click="editor.activate(tab.id)"
@mousedown.middle.prevent
@auxclick="onAuxClick($event, tab.id)"
>
<span class="tabs__name">{{ tab.name }}</span>
<span
v-if="tab.dirty"
class="tabs__dirty"
aria-label="unsaved changes"
data-test="tab-dirty"
/>
<button
class="tabs__close"
type="button"
tabindex="-1"
:aria-label="`Close ${tab.name}`"
data-test="tab-close"
@click.stop="editor.requestClose(tab.id)"
>
<X :size="12" />
</button>
</div>
</div>
</template>
<style scoped>
.tabs {
display: flex;
overflow-x: auto;
flex-shrink: 0;
background: var(--lt-bg);
border-bottom: 1px solid var(--lt-border);
scrollbar-width: thin;
}
.tabs__tab {
display: flex;
align-items: center;
gap: 6px;
padding: 0 6px 0 12px;
height: 30px;
flex-shrink: 0;
color: var(--lt-fg-muted);
border-right: 1px solid var(--lt-border);
border-bottom: 2px solid transparent;
cursor: default;
white-space: nowrap;
}
.tabs__tab:hover {
color: var(--lt-fg);
}
.tabs__tab--active {
color: var(--lt-fg);
background: var(--lt-tab-active-bg, var(--lt-editor-bg));
border-bottom-color: var(--lt-accent);
}
.tabs__tab:focus-visible {
outline: 1px solid var(--lt-accent);
outline-offset: -1px;
}
.tabs__dirty {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--lt-tab-modified, var(--lt-accent));
}
.tabs__close {
display: flex;
align-items: center;
justify-content: center;
width: 18px;
height: 18px;
padding: 0;
border: none;
border-radius: 3px;
background: transparent;
color: inherit;
opacity: 0.6;
}
.tabs__close:hover {
opacity: 1;
background: var(--lt-border);
}
</style>

View file

@ -0,0 +1,386 @@
/**
* Keeps one CodeMirror editor state in step with one engine buffer.
*
* The engine is the source of truth. Local changes are sent with
* `buffer.edit {id, baseVersion, edits}`, at most one call at a time; changes
* typed while a call is in flight are composed and sent together next. The
* invariant is: local document = unsent(inflight(confirmed)), where
* `confirmed` is the engine text at `version`.
*
* Resync: when the engine rejects an edit with `stale_version`, or reports a
* newer version than ours through `bufferChanged` (a reload from disk, an
* edit from the control channel), the sync fetches the text with
* `buffer.get`, computes the remote change against `confirmed`, rebases the
* unsent local changes over it and applies the remote change to the editor.
* No local keystroke is lost; the rebased changes are then sent against the
* new version. Idea from https://codemirror.net/examples/collab/.
*/
import {
Annotation,
ChangeSet,
EditorState,
Transaction,
type Extension,
type TransactionSpec,
} from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
import { run, type EngineError, type RunResult } from "../../ipc";
import { diffDocs, EngineText, separatorOf, type EngineEdit } from "./engineText";
/** A buffer as `file.open` and `buffer.get` describe it. */
export interface BufferInfo {
/** Buffer id. */
id: number;
/** Project-relative path. */
path: string;
/** Full text as the engine holds it. */
text: string;
/** Current version. */
version: number;
/** Whether the buffer has unsaved changes. */
dirty: boolean;
/** Line ending the buffer saves with. */
lineEnding: string;
}
/** Result of `buffer.edit`. */
export interface EditResult {
/** Buffer id. */
id: number;
/** Version after the edit. */
version: number;
/** Whether the buffer is dirty now. */
dirty: boolean;
}
/** Params of `buffer.edit`. */
export interface EditParams {
/** Buffer id. */
id: number;
/** Version the edits refer to. */
baseVersion: number;
/** The edits, in engine UTF-16 offsets of the text at `baseVersion`. */
edits: EngineEdit[];
}
/** How the sync reaches the engine; replaced by a fake in tests. */
export interface SyncTransport {
/** Runs `buffer.edit`. */
edit(params: EditParams): Promise<RunResult<EditResult>>;
/** Runs `buffer.get`. */
get(id: number): Promise<RunResult<BufferInfo>>;
}
/** Transport through the engine IPC. */
export const engineTransport: SyncTransport = {
edit: (params) =>
run<EditResult>("buffer.edit", {
id: params.id,
baseVersion: params.baseVersion,
edits: params.edits.map((e) => ({ from: e.from, to: e.to, insert: e.insert })),
}),
get: (id) => run<BufferInfo>("buffer.get", { id }),
};
/** Marks transactions that carry engine changes, so they are not sent back. */
export const remoteChange = Annotation.define<boolean>();
/**
* Checks that a value looks like a {@link BufferInfo}.
*
* @param value - an untrusted command result.
*/
export function isBufferInfo(value: unknown): value is BufferInfo {
if (typeof value !== "object" || value === null) {
return false;
}
const v = value as Record<string, unknown>;
return (
typeof v.id === "number" &&
typeof v.path === "string" &&
typeof v.text === "string" &&
typeof v.version === "number" &&
typeof v.dirty === "boolean"
);
}
/** Synchronises one buffer; see the module documentation. */
export class BufferSync {
/** Engine buffer id. */
readonly id: number;
/** The local editor state, always current. */
private current: EditorState;
/** The view showing this buffer, null while another tab is active. */
private view: EditorView | null = null;
/** Engine text at {@link version}. */
private confirmed: EngineText;
/** Engine version of {@link confirmed}. */
private version: number;
/** Highest version the engine reported for this buffer. */
private latestKnown: number;
/** Changes sent and not yet answered, relative to {@link confirmed}. */
private inflight: ChangeSet | null = null;
/** Local changes not sent yet, relative to `inflight(confirmed)`. */
private unsent: ChangeSet | null = null;
/** Whether a `buffer.get` for a resync is running. */
private resyncing = false;
/** Line break used for inserted text. */
private separator: string;
/** Set once the buffer is closed; nothing is sent afterwards. */
private disposed = false;
/** Callbacks waiting for {@link idle}. */
private waiters: (() => void)[] = [];
/** Engine transport. */
private readonly transport: SyncTransport;
/** Receives errors that are not handled by a resync. */
private readonly onError: (error: EngineError) => void;
/**
* @param info - the buffer as the engine described it.
* @param extensions - editor extensions for the state.
* @param transport - how to reach the engine.
* @param onError - receives failures (shown by the editor store).
*/
constructor(
info: BufferInfo,
extensions: Extension,
transport: SyncTransport = engineTransport,
onError: (error: EngineError) => void = () => undefined,
) {
this.id = info.id;
this.confirmed = EngineText.fromEngine(info.text);
this.version = info.version;
this.latestKnown = info.version;
this.separator = separatorOf(info.lineEnding);
this.transport = transport;
this.onError = onError;
this.current = EditorState.create({ doc: this.confirmed.doc, extensions });
}
/** The current local editor state. */
get state(): EditorState {
return this.current;
}
/** Engine version the local document is based on. */
get baseVersion(): number {
return this.version;
}
/** Whether local changes have not reached the engine yet. */
get pending(): boolean {
return this.inflight !== null || this.unsent !== null || this.resyncing;
}
/**
* Shows this buffer in a view: the view takes over the local state and
* receives remote changes from now on.
*
* @param view - the editor view.
*/
attach(view: EditorView): void {
this.view = view;
view.setState(this.current);
}
/** Stops updating the view (another tab became active). */
detach(): void {
this.view = null;
}
/** Stops syncing; the buffer was closed. */
dispose(): void {
this.disposed = true;
this.view = null;
this.inflight = null;
this.unsent = null;
this.settle();
}
/**
* Creates and applies a transaction on the local state, as typing would.
*
* @param spec - the transaction.
*/
dispatch(spec: TransactionSpec): void {
this.applyTransactions([this.current.update(spec)]);
}
/**
* Applies transactions created from the current state (by the view or by
* {@link dispatch}). Local document changes are queued for the engine.
*
* @param transactions - the transactions, in order.
*/
applyTransactions(transactions: readonly Transaction[]): void {
const last = transactions[transactions.length - 1];
if (!last) {
return;
}
this.current = last.state;
for (const tr of transactions) {
if (tr.docChanged && tr.annotation(remoteChange) !== true) {
this.unsent = this.unsent ? this.unsent.compose(tr.changes) : tr.changes;
}
}
this.view?.update([...transactions]);
this.flush();
}
/**
* Notes a version reported by the engine (`bufferChanged`). A version
* newer than the local base starts a resync once nothing is in flight.
*
* @param version - the reported version.
*/
notifyVersion(version: number): void {
this.latestKnown = Math.max(this.latestKnown, version);
if (this.latestKnown > this.version && this.inflight === null) {
this.resync();
}
}
/** Resolves once every local change has reached the engine. */
idle(): Promise<void> {
if (!this.pending || this.disposed) {
return Promise.resolve();
}
return new Promise((resolve) => this.waiters.push(resolve));
}
/**
* Wakes {@link idle} callers when nothing is pending.
*
* @param force - wake them even with pending changes (the engine could not
* be reached, so waiting longer would hang the caller).
*/
private settle(force = false): void {
if (!force && this.pending && !this.disposed) {
return;
}
const waiters = this.waiters;
this.waiters = [];
for (const wake of waiters) {
wake();
}
}
/** Sends the unsent changes, unless a call or a resync is running. */
private flush(): void {
if (this.disposed || this.inflight !== null || this.resyncing || this.unsent === null) {
this.settle();
return;
}
const changes = this.unsent;
this.inflight = changes;
this.unsent = null;
const params: EditParams = {
id: this.id,
baseVersion: this.version,
edits: this.confirmed.edits(changes, this.separator),
};
void this.transport.edit(params).then((result) => {
this.onEditResult(changes, result);
});
}
/**
* Handles the answer to a `buffer.edit`.
*
* @param changes - the changes that were sent.
* @param result - the engine's answer.
*/
private onEditResult(changes: ChangeSet, result: RunResult<EditResult>): void {
if (this.disposed || this.inflight !== changes) {
return;
}
this.inflight = null;
if (result.ok) {
this.confirmed = this.confirmed.apply(changes, this.separator);
this.version = result.value.version;
this.latestKnown = Math.max(this.latestKnown, this.version);
if (this.latestKnown > this.version) {
this.resync();
} else {
this.flush();
}
return;
}
this.unsent = this.unsent ? changes.compose(this.unsent) : changes;
if (result.error.code === "stale_version") {
this.resync();
} else {
this.onError(result.error);
this.resync(true);
}
}
/**
* Fetches the engine text and rebases local changes onto it.
*
* @param dropLocal - discard unsent local changes instead of rebasing them
* (after the engine refused them for a reason other than a stale base).
*/
private resync(dropLocal = false): void {
if (this.disposed || this.resyncing || this.inflight !== null) {
return;
}
this.resyncing = true;
void this.transport.get(this.id).then((result) => {
this.resyncing = false;
if (this.disposed) {
return;
}
if (!result.ok || !isBufferInfo(result.value)) {
this.onError(
result.ok ? { code: "ipc", message: "unexpected result of buffer.get" } : result.error,
);
this.settle(true);
return;
}
this.rebase(result.value, dropLocal);
});
}
/**
* Moves the local document onto fresh engine text.
*
* @param info - the engine's current buffer.
* @param dropLocal - see {@link resync}.
*/
private rebase(info: BufferInfo, dropLocal: boolean): void {
const fresh = EngineText.fromEngine(info.text);
const remote = diffDocs(this.confirmed.doc, fresh.doc);
const local = this.unsent;
let toLocal: ChangeSet;
if (local === null) {
toLocal = remote;
} else if (dropLocal) {
toLocal = local.invert(this.confirmed.doc).compose(remote);
this.unsent = null;
} else {
toLocal = remote.map(local, true);
this.unsent = local.map(remote);
if (this.unsent.empty) {
this.unsent = null;
}
}
this.confirmed = fresh;
this.version = info.version;
this.latestKnown = Math.max(this.latestKnown, info.version);
this.separator = separatorOf(info.lineEnding);
if (!toLocal.empty) {
this.applyTransactions([
this.current.update({
changes: toLocal,
annotations: [remoteChange.of(true), Transaction.addToHistory.of(false)],
}),
]);
}
if (this.latestKnown > this.version) {
this.resync();
} else {
this.flush();
}
}
}

View file

@ -0,0 +1,100 @@
/**
* Adapter between engine events and the editor store.
*
* Picks the events the editor needs from the engine's `engine://event`
* stream (see `docs/architecture.md` › Events), checks their fields (they
* cross the IPC boundary) and hands them to subscribers. One IPC
* subscription serves every subscriber. {@link emitEditorEvent} injects an
* event directly, which the tests use instead of the Tauri shell.
*/
import { onEngineEvent as onIpcEngineEvent, type EngineEventPayload } from "../../ipc";
/** An engine event as the editor store consumes it. */
export type EditorEvent =
| { kind: "projectOpened" }
| { kind: "projectClosed" }
| { kind: "bufferOpened"; id: number; path: string }
| { kind: "bufferChanged"; id: number; version: number }
| { kind: "dirtyChanged"; id: number; dirty: boolean }
| { kind: "bufferClosed"; id: number }
| { kind: "fileChangedOnDisk"; path: string; id: number; removed: boolean };
/** Callback receiving editor events. */
export type EditorEventHandler = (event: EditorEvent) => void;
/**
* Picks and checks an editor event from an engine event.
*
* @param payload - the engine event, untrusted.
* @returns the editor event, or null for other kinds and malformed events.
*/
export function toEditorEvent(payload: EngineEventPayload): EditorEvent | null {
const raw = payload as unknown as Record<string, unknown>;
const num = (key: string): number | null =>
typeof raw[key] === "number" && Number.isFinite(raw[key]) ? raw[key] : null;
const id = num("id");
switch (payload.kind) {
case "projectOpened":
case "projectClosed":
return { kind: payload.kind };
case "bufferOpened":
return id !== null && typeof raw.path === "string"
? { kind: "bufferOpened", id, path: raw.path }
: null;
case "bufferChanged": {
const version = num("version");
return id !== null && version !== null ? { kind: "bufferChanged", id, version } : null;
}
case "dirtyChanged":
return id !== null && typeof raw.dirty === "boolean"
? { kind: "dirtyChanged", id, dirty: raw.dirty }
: null;
case "bufferClosed":
return id !== null ? { kind: "bufferClosed", id } : null;
case "fileChangedOnDisk":
return id !== null && typeof raw.path === "string" && typeof raw.removed === "boolean"
? { kind: "fileChangedOnDisk", id, path: raw.path, removed: raw.removed }
: null;
default:
return null;
}
}
/** Current subscribers. */
const handlers = new Set<EditorEventHandler>();
/** Ends the IPC subscription; null while nobody listens. */
let stopIpc: (() => void) | null = null;
/**
* Delivers an engine event to every subscriber, if it is an editor event.
*
* @param payload - the engine event.
*/
export function emitEditorEvent(payload: EngineEventPayload): void {
const event = toEditorEvent(payload);
if (!event) {
return;
}
for (const handler of [...handlers]) {
handler(event);
}
}
/**
* Subscribes to editor events.
*
* @param handler - called for every editor event, in engine order.
* @returns a function that ends the subscription.
*/
export function onEditorEvent(handler: EditorEventHandler): () => void {
handlers.add(handler);
stopIpc ??= onIpcEngineEvent(emitEditorEvent);
return () => {
handlers.delete(handler);
if (handlers.size === 0) {
stopIpc?.();
stopIpc = null;
}
};
}

View file

@ -0,0 +1,214 @@
/**
* Mapping between engine buffer text and CodeMirror documents.
*
* The engine keeps a file's text as it is on disk, line breaks included, and
* counts offsets in UTF-16 code units of that text. CodeMirror splits the
* text into lines and counts every line break as one position. Positions
* therefore differ by one for every `\r\n` before them. {@link EngineText}
* remembers which breaks are `\r\n` and converts positions and change sets
* into engine edits. Text without `\r\n` needs no bookkeeping.
*/
import { ChangeSet, Text } from "@codemirror/state";
/** Line ending of a buffer as the engine names it. */
export type LineEndingName = "lf" | "crlf" | "cr";
/** One change of a `buffer.edit` call, in engine UTF-16 offsets. */
export interface EngineEdit {
/** Start offset in the text at the base version. */
from: number;
/** End offset (exclusive) in the text at the base version. */
to: number;
/** Inserted text, with the buffer's line ending. */
insert: string;
}
/** Line breaks the engine and CodeMirror both recognise. */
const LINE_BREAK = /\r\n|\r|\n/g;
/**
* The line break string for a line ending name.
*
* @param name - the engine's name; anything unknown counts as `lf`.
*/
export function separatorOf(name: string): string {
return name === "crlf" ? "\r\n" : name === "cr" ? "\r" : "\n";
}
/**
* A CodeMirror document together with the kind of each of its line breaks
* in the engine text.
*/
export class EngineText {
/** The document as CodeMirror sees it. */
readonly doc: Text;
/**
* For each line break (index `i` follows line `i`, 0-based) whether it is
* `\r\n` in the engine text; null when there is none.
*/
private readonly crlf: readonly boolean[] | null;
/** Number of `\r\n` breaks before each line; built on first use. */
private prefix: Uint32Array | null = null;
/**
* @param doc - the CodeMirror document.
* @param crlf - break kinds, see {@link EngineText.crlf}.
*/
private constructor(doc: Text, crlf: readonly boolean[] | null) {
this.doc = doc;
this.crlf = crlf;
}
/**
* Builds the mapping for text received from the engine.
*
* @param text - the engine's buffer text.
*/
static fromEngine(text: string): EngineText {
const lines: string[] = [];
const crlf: boolean[] = [];
let any = false;
let start = 0;
LINE_BREAK.lastIndex = 0;
for (let m = LINE_BREAK.exec(text); m !== null; m = LINE_BREAK.exec(text)) {
lines.push(text.slice(start, m.index));
const isCrlf = m[0] === "\r\n";
crlf.push(isCrlf);
any ||= isCrlf;
start = m.index + m[0].length;
}
lines.push(text.slice(start));
return new EngineText(Text.of(lines), any ? crlf : null);
}
/**
* The engine text this mapping stands for, for checks and tests. Only
* `\r\n` breaks are remembered, so a lone `\r` comes back as `\n` (both
* are one UTF-16 unit, so offsets are unaffected).
*/
engineString(): string {
if (this.crlf === null) {
return this.doc.sliceString(0);
}
const parts: string[] = [];
let line = 0;
for (const text of this.doc.iterLines()) {
parts.push(text);
if (line < this.crlf.length) {
parts.push(this.crlf[line] === true ? "\r\n" : "\n");
}
line += 1;
}
return parts.join("");
}
/**
* Converts a CodeMirror position into an engine offset.
*
* @param pos - a position in {@link doc}, clamped to its length.
* @returns the UTF-16 offset in the engine text.
*/
toEngine(pos: number): number {
const clamped = Math.max(0, Math.min(pos, this.doc.length));
if (this.crlf === null) {
return clamped;
}
const line = this.doc.lineAt(clamped).number - 1;
return clamped + (this.prefixTable()[line] ?? 0);
}
/** The table of `\r\n` counts before each line. */
private prefixTable(): Uint32Array {
if (this.prefix === null) {
const crlf = this.crlf ?? [];
const table = new Uint32Array(crlf.length + 1);
for (let i = 0; i < crlf.length; i += 1) {
table[i + 1] = (table[i] ?? 0) + (crlf[i] === true ? 1 : 0);
}
this.prefix = table;
}
return this.prefix;
}
/**
* Translates a change set on {@link doc} into engine edits.
*
* @param changes - changes whose start document is {@link doc}.
* @param separator - line break for inserted text (the buffer's ending).
*/
edits(changes: ChangeSet, separator: string): EngineEdit[] {
const out: EngineEdit[] = [];
changes.iterChanges((fromA, toA, _fromB, _toB, inserted) => {
out.push({
from: this.toEngine(fromA),
to: this.toEngine(toA),
insert: inserted.sliceString(0, inserted.length, separator),
});
});
return out;
}
/**
* The mapping after a change set, assuming the engine applied the same
* changes with inserted line breaks written as `separator`.
*
* @param changes - changes whose start document is {@link doc}.
* @param separator - line break used for inserted text.
*/
apply(changes: ChangeSet, separator: string): EngineText {
const doc = changes.apply(this.doc);
const newCrlf = separator === "\r\n";
if (this.crlf === null && !newCrlf) {
return new EngineText(doc, null);
}
const old = this.crlf;
const out: boolean[] = [];
let cursor = 0;
changes.iterChanges((fromA, toA, _fromB, _toB, inserted) => {
const fromLine = this.doc.lineAt(fromA).number - 1;
const toLine = this.doc.lineAt(toA).number - 1;
for (let i = cursor; i < fromLine; i += 1) {
out.push(old?.[i] === true);
}
for (let i = 1; i < inserted.lines; i += 1) {
out.push(newCrlf);
}
cursor = Math.max(cursor, toLine);
});
for (let i = cursor; i < this.doc.lines - 1; i += 1) {
out.push(old?.[i] === true);
}
return new EngineText(doc, out.includes(true) ? out : null);
}
}
/**
* A minimal change set turning `from` into `to`: one replacement between
* their common prefix and suffix.
*
* @param from - the old document.
* @param to - the new document.
*/
export function diffDocs(from: Text, to: Text): ChangeSet {
const a = from.sliceString(0);
const b = to.sliceString(0);
if (a === b) {
return ChangeSet.empty(a.length);
}
const max = Math.min(a.length, b.length);
let prefix = 0;
while (prefix < max && a.charCodeAt(prefix) === b.charCodeAt(prefix)) {
prefix += 1;
}
let suffix = 0;
while (
suffix < max - prefix &&
a.charCodeAt(a.length - 1 - suffix) === b.charCodeAt(b.length - 1 - suffix)
) {
suffix += 1;
}
return ChangeSet.of(
[{ from: prefix, to: a.length - suffix, insert: b.slice(prefix, b.length - suffix) }],
a.length,
);
}

View file

@ -0,0 +1,97 @@
/**
* CodeMirror extensions of the Lutra editor: the basic setup (line numbers,
* history, selection, brackets, search) without a language (PHP comes in
* M2), and a theme that takes every colour from `--lt-*` tokens.
*
* Tokens the theme does not define yet are read with a fallback derived from
* existing tokens (`var(--lt-editor-selection-bg, color-mix(…))`), so that a
* token added to the Rust theme later takes effect without code changes.
* Requested from design: `--lt-editor-selection-bg`,
* `--lt-editor-active-line-bg`, `--lt-editor-cursor`, `--lt-editor-gutter-bg`,
* `--lt-editor-gutter-fg`, `--lt-editor-match-bg`, `--lt-font-size-editor`.
*/
import { EditorView } from "@codemirror/view";
import type { Extension } from "@codemirror/state";
import { basicSetup } from "codemirror";
/** Editor theme built from theme tokens only. */
export const lutraEditorTheme: Extension = EditorView.theme({
"&": {
height: "100%",
color: "var(--lt-fg)",
backgroundColor: "var(--lt-editor-bg)",
fontSize: "var(--lt-font-size-editor, var(--lt-font-size-ui))",
},
"&.cm-focused": {
outline: "none",
},
".cm-scroller": {
fontFamily: "var(--lt-font-mono)",
lineHeight: "1.5",
},
".cm-content": {
caretColor: "var(--lt-editor-cursor, var(--lt-accent))",
},
".cm-cursor, .cm-dropCursor": {
borderLeftColor: "var(--lt-editor-cursor, var(--lt-accent))",
},
"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":
{
backgroundColor:
"var(--lt-editor-selection-bg, color-mix(in srgb, var(--lt-accent) 30%, transparent))",
},
".cm-activeLine": {
backgroundColor:
"var(--lt-editor-active-line-bg, color-mix(in srgb, var(--lt-fg) 5%, transparent))",
},
".cm-selectionMatch, .cm-searchMatch": {
backgroundColor:
"var(--lt-editor-match-bg, color-mix(in srgb, var(--lt-accent) 18%, transparent))",
},
"&.cm-focused .cm-matchingBracket": {
backgroundColor:
"var(--lt-editor-match-bg, color-mix(in srgb, var(--lt-accent) 18%, transparent))",
outline: "1px solid var(--lt-border)",
},
".cm-gutters": {
backgroundColor: "var(--lt-editor-gutter-bg, var(--lt-editor-bg))",
color: "var(--lt-editor-gutter-fg, var(--lt-fg-muted))",
borderRight: "1px solid var(--lt-border)",
},
".cm-activeLineGutter": {
backgroundColor:
"var(--lt-editor-active-line-bg, color-mix(in srgb, var(--lt-fg) 5%, transparent))",
color: "var(--lt-fg)",
},
".cm-panels": {
backgroundColor: "var(--lt-bg)",
color: "var(--lt-fg)",
},
".cm-panels-top": {
borderBottom: "1px solid var(--lt-border)",
},
".cm-panels-bottom": {
borderTop: "1px solid var(--lt-border)",
},
".cm-textfield": {
backgroundColor: "var(--lt-editor-bg)",
color: "var(--lt-fg)",
border: "1px solid var(--lt-border)",
},
".cm-button": {
backgroundImage: "none",
backgroundColor: "var(--lt-bg)",
color: "var(--lt-fg)",
border: "1px solid var(--lt-border)",
},
".cm-tooltip": {
backgroundColor: "var(--lt-bg)",
color: "var(--lt-fg)",
border: "1px solid var(--lt-border)",
},
});
/** Every extension of an editor state. */
export function editorExtensions(): Extension {
return [basicSetup, lutraEditorTheme];
}

View file

@ -0,0 +1,155 @@
/**
* Editor shortcuts, taken from the engine's command specs.
*
* The engine defines default shortcuts in Lutra notation (`Mod+Alt+S`,
* `Mod` = Cmd on macOS, Ctrl elsewhere). The editor area loads them with
* `listCommands` and maps key presses to the editor commands it handles
* with context (the active buffer): saving, saving all and closing a tab.
* Nothing here hard-codes a key.
*/
import { listCommands, type CommandInfo, type RunResult } from "../../ipc";
/** Engine commands the editor area runs with the active buffer as context. */
export const EDITOR_SHORTCUT_COMMANDS = ["file.save", "file.saveAll", "buffer.close"] as const;
/** One of {@link EDITOR_SHORTCUT_COMMANDS}. */
export type EditorShortcutCommand = (typeof EDITOR_SHORTCUT_COMMANDS)[number];
/** A parsed shortcut. */
export interface Shortcut {
/** Ctrl must be held. */
ctrl: boolean;
/** Meta (Cmd) must be held. */
meta: boolean;
/** Alt (Option) must be held. */
alt: boolean;
/** Shift must be held. */
shift: boolean;
/** The key, lower case (`s`, `f4`, `enter`). */
key: string;
}
/** Whether the frontend runs on macOS, where `Mod` means Cmd. */
export function isMac(): boolean {
return typeof navigator !== "undefined" && /Mac OS X|Macintosh|iPhone|iPad/.test(navigator.userAgent);
}
/**
* Parses a shortcut in Lutra notation.
*
* @param text - for example `Mod+Alt+S`.
* @param mac - whether `Mod` means Cmd.
* @returns the shortcut, or null when the text has no key or an unknown modifier.
*/
export function parseShortcut(text: string, mac: boolean): Shortcut | null {
const parts = text.split("+").map((part) => part.trim().toLowerCase());
const key = parts.pop();
if (key === undefined || key === "") {
return null;
}
const shortcut: Shortcut = { ctrl: false, meta: false, alt: false, shift: false, key };
for (const part of parts) {
switch (part) {
case "mod":
if (mac) {
shortcut.meta = true;
} else {
shortcut.ctrl = true;
}
break;
case "ctrl":
shortcut.ctrl = true;
break;
case "cmd":
case "meta":
shortcut.meta = true;
break;
case "alt":
shortcut.alt = true;
break;
case "shift":
shortcut.shift = true;
break;
default:
return null;
}
}
return shortcut;
}
/**
* The key of an event, independent of keyboard layout effects of Alt and
* Shift for letters and digits (`Alt+S` on macOS types `ß`).
*
* @param event - the key event.
*/
function eventKey(event: KeyboardEvent): string {
const code = event.code;
if (/^Key[A-Z]$/.test(code)) {
return code.slice(3).toLowerCase();
}
if (/^Digit[0-9]$/.test(code)) {
return code.slice(5);
}
return event.key.toLowerCase();
}
/**
* Whether a key event matches a shortcut exactly.
*
* @param event - the key event.
* @param shortcut - the shortcut.
*/
export function matches(event: KeyboardEvent, shortcut: Shortcut): boolean {
return (
event.ctrlKey === shortcut.ctrl &&
event.metaKey === shortcut.meta &&
event.altKey === shortcut.alt &&
event.shiftKey === shortcut.shift &&
eventKey(event) === shortcut.key
);
}
/** Shortcuts of the editor commands, by command. */
export type EditorKeymap = { command: EditorShortcutCommand; shortcut: Shortcut }[];
/**
* Loads the default shortcuts of the editor commands from the engine.
*
* @param mac - whether `Mod` means Cmd.
* @returns the keymap, or the error of `listCommands`.
*/
export async function loadEditorKeymap(mac = isMac()): Promise<RunResult<EditorKeymap>> {
const result = await listCommands();
if (!result.ok) {
return result;
}
const list: unknown = result.value;
if (!Array.isArray(list)) {
return { ok: false, error: { code: "ipc", message: "unexpected result of listCommands" } };
}
const commands = (list as unknown[]).filter(
(c): c is CommandInfo => typeof c === "object" && c !== null && "id" in c,
);
const keymap: EditorKeymap = [];
for (const command of EDITOR_SHORTCUT_COMMANDS) {
const info = commands.find((c) => c.id === command);
const raw: unknown = info?.defaultShortcut;
const shortcut = typeof raw === "string" ? parseShortcut(raw, mac) : null;
if (shortcut) {
keymap.push({ command, shortcut });
}
}
return { ok: true, value: keymap };
}
/**
* The editor command a key event triggers.
*
* @param keymap - the loaded keymap.
* @param event - the key event.
* @returns the command, or null.
*/
export function commandFor(keymap: EditorKeymap, event: KeyboardEvent): EditorShortcutCommand | null {
return keymap.find((entry) => matches(event, entry.shortcut))?.command ?? null;
}