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:
parent
0fb7e33fc7
commit
9fa6028335
25 changed files with 2958 additions and 22 deletions
|
|
@ -16,8 +16,11 @@
|
|||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codemirror/state": "^6.7.6",
|
||||
"@codemirror/view": "^6.43.14",
|
||||
"@lucide/vue": "^1.57.0",
|
||||
"@tauri-apps/api": "^2.12.3",
|
||||
"codemirror": "^6.0.2",
|
||||
"pinia": "^4.0.3",
|
||||
"vue": "^3.5.44"
|
||||
},
|
||||
|
|
|
|||
134
ui/pnpm-lock.yaml
generated
134
ui/pnpm-lock.yaml
generated
|
|
@ -8,12 +8,21 @@ importers:
|
|||
|
||||
.:
|
||||
dependencies:
|
||||
'@codemirror/state':
|
||||
specifier: ^6.7.6
|
||||
version: 6.7.6
|
||||
'@codemirror/view':
|
||||
specifier: ^6.43.14
|
||||
version: 6.43.14
|
||||
'@lucide/vue':
|
||||
specifier: ^1.57.0
|
||||
version: 1.57.0(vue@3.5.44(typescript@6.0.3))
|
||||
'@tauri-apps/api':
|
||||
specifier: ^2.12.3
|
||||
version: 2.12.3
|
||||
codemirror:
|
||||
specifier: ^6.0.2
|
||||
version: 6.0.2
|
||||
pinia:
|
||||
specifier: ^4.0.3
|
||||
version: 4.0.3(@vue/devtools-api@8.2.1)(typescript@6.0.3)(vue@3.5.44(typescript@6.0.3))
|
||||
|
|
@ -101,6 +110,30 @@ packages:
|
|||
'@cacheable/utils@2.5.0':
|
||||
resolution: {integrity: sha512-buipgOVDkkPXNR5+xBpDw7Zk2n1EvU7qBJCNUcL7rhQ//kfpOXPAvQ511Os0vpLYJ1pZnvudNytkQt2hst3wqA==}
|
||||
|
||||
'@codemirror/autocomplete@6.20.3':
|
||||
resolution: {integrity: sha512-tlosUqb+3BbxCxZdu4tKeRghPFC+QM7q4X5YhKV2eCmPG+1r2F3f4AaSz5sCrFqUtX4Jh20VFTKecl16MgiV9g==}
|
||||
|
||||
'@codemirror/commands@6.11.1':
|
||||
resolution: {integrity: sha512-O/4hG3SC1YwcmQ0d2UVNDs+AsaNWd1iHVxbTeEBuqH+6bExAiPK3iS/BvpY6rZGURALv4ZD3sIgcCmRvw3ehBg==}
|
||||
|
||||
'@codemirror/language@6.13.1':
|
||||
resolution: {integrity: sha512-zfvU2r3TyylQLMj/te+5CnQ0rSqZi8B1oTCBbQkagcLW4Xc6imab6qN+pEJhsuNOLaJqiRyBXp9UhWA1DhVvDw==}
|
||||
|
||||
'@codemirror/lint@6.9.7':
|
||||
resolution: {integrity: sha512-28/+iWLYxKxsvGYhSYL7zaCZqLz5+FFFDq9tVsvGv9kv8RY4fFAchJ5WX9M3YrrRlTIsECjsXPqeNgnSmNP2dg==}
|
||||
|
||||
'@codemirror/search@6.7.2':
|
||||
resolution: {integrity: sha512-gUYkYhT2+n/+VGZ+8EzE5WFkYZUZYm1VOKDudIsNqh42uRVQJ0a6Yss9sdKT3MeOYfuL1N6AZA57oza0Oyr0LA==}
|
||||
|
||||
'@codemirror/state@6.7.6':
|
||||
resolution: {integrity: sha512-kAz+AncRtKuIknedxT1bq4XwXv4UowhbkHU1myPrtVb/jZtImWuV5BXzv5vK6i3kYACsdiZiQKFQQ5Mq7elW8w==}
|
||||
|
||||
'@codemirror/streamparser@6.0.0':
|
||||
resolution: {integrity: sha512-JTFPF6xrfjt0mnfGPgzcLiMwYmvIyNaoizp8BYzv8FE8KrT6GBGDZ190rtt+O7Wke3gG/MFHyiY9YGNeimof4w==}
|
||||
|
||||
'@codemirror/view@6.43.14':
|
||||
resolution: {integrity: sha512-hC45YnmJNR1rz42OF57BLoQNFMV12/13drnvibDsR2quNDmldcb4WvYVV81hFQg56i9lcqQMEDqilhX2QDcGQQ==}
|
||||
|
||||
'@csstools/color-helpers@6.1.2':
|
||||
resolution: {integrity: sha512-grhRy3OKmniaAEKXMjua5z/EODX0MSqBGjunw8+j/3HQjOnahs2AGhvEOIYVUWcU6ScApbhLhVrQTX8XqrMrow==}
|
||||
engines: {node: '>=20.19.0'}
|
||||
|
|
@ -224,11 +257,23 @@ packages:
|
|||
'@keyv/serialize@1.1.1':
|
||||
resolution: {integrity: sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA==}
|
||||
|
||||
'@lezer/common@1.5.3':
|
||||
resolution: {integrity: sha512-H0iErY4e43LpXbYDyBci5W4v/RwTgGV3YzYOlJPiGZ8RY8w51kVE+xLn1tg3Z6UmSfyETvtsUK3r7YsgDQEI7Q==}
|
||||
|
||||
'@lezer/highlight@1.2.5':
|
||||
resolution: {integrity: sha512-O1GMVKgtf5YspFaRzpmqkVgMtIk2HG9uMAbH6wdAIdNh3TVzCsch/+cRi+6l2//UGDKe6NB9BW3cvuR5ezMQ0w==}
|
||||
|
||||
'@lezer/lr@1.4.11':
|
||||
resolution: {integrity: sha512-UwgZcl1R66H2hDzBrA7kWyYmX6s8p5TQ+e/t7CuvgCtBEPxbEPaHYHu+pJBvTvDotEJpuQkJjbXuHiw5Cixxgw==}
|
||||
|
||||
'@lucide/vue@1.57.0':
|
||||
resolution: {integrity: sha512-l/D9mr+8Wb8uHl2vzHfcGVRkunJnq0NDmv8HFwXAL3UiYYxuNpDSd1uaCVqeR8+I1XY70dWA+R5W/pSpXWilMw==}
|
||||
peerDependencies:
|
||||
vue: '>=3.0.1'
|
||||
|
||||
'@marijn/find-cluster-break@1.0.4':
|
||||
resolution: {integrity: sha512-Wy0V7+SGUjnF9/TkiM1hKVDPj7jKXduPNboMVtHTA8dySMURWqfg/JZ9E2Sq8JgSJmkl7k7Qe9FLeMSrSraWmQ==}
|
||||
|
||||
'@one-ini/wasm@0.2.1':
|
||||
resolution: {integrity: sha512-TUqERXGNTifZ9y2g3wPxQrw3HpHv/02DsW3D90T9x0hhonrL1ZqpSmNrU2XkoIq0fP1N6gZfVQzy2Fw1ZvGBNg==}
|
||||
|
||||
|
|
@ -541,6 +586,9 @@ packages:
|
|||
resolution: {integrity: sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
codemirror@6.0.2:
|
||||
resolution: {integrity: sha512-VhydHotNW5w1UGK0Qj96BwSk/Zqbp9WbnyK2W/eVMv4QyF41INRGpjUhFJY7/uDNuudSc33a/PKr4iDqRduvHw==}
|
||||
|
||||
commander@14.0.3:
|
||||
resolution: {integrity: sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==}
|
||||
engines: {node: '>=20'}
|
||||
|
|
@ -548,6 +596,9 @@ packages:
|
|||
config-chain@1.1.13:
|
||||
resolution: {integrity: sha512-qj+f8APARXHrM0hraqXYb2/bOVSV4PvJQlNZ/DVj0QrmNM2q2euizkeuVckQ57J+W0mRH6Hvi+k50M4Jul2VRQ==}
|
||||
|
||||
crelt@1.0.7:
|
||||
resolution: {integrity: sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA==}
|
||||
|
||||
cross-spawn@7.0.6:
|
||||
resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==}
|
||||
engines: {node: '>= 8'}
|
||||
|
|
@ -1031,6 +1082,9 @@ packages:
|
|||
std-env@4.3.0:
|
||||
resolution: {integrity: sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==}
|
||||
|
||||
style-mod@4.1.4:
|
||||
resolution: {integrity: sha512-XXWIQt633/EpAFx8aZDOTjBzrCaGmhvEQlQo6MVPfa2OzO2cWo+4hV9h+6UkHYlXGfy+ODXKUdP7Pthmcu5ATw==}
|
||||
|
||||
tinybench@6.2.2:
|
||||
resolution: {integrity: sha512-nIZ2N2dFpjBsg2hgitKu7mA+FvsIJuGJOwysRngmVRRmWgR/UyPjwJj8c/fT/dhm8EkHnF5EOogRf+0Z2qrimA==}
|
||||
engines: {node: '>=20.0.0'}
|
||||
|
|
@ -1203,6 +1257,9 @@ packages:
|
|||
typescript:
|
||||
optional: true
|
||||
|
||||
w3c-keyname@2.2.8:
|
||||
resolution: {integrity: sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==}
|
||||
|
||||
w3c-xmlserializer@6.0.0:
|
||||
resolution: {integrity: sha512-4Nsy8K5Tr6SPDH9jhKJOHf7ChDrc1zufZTVSF7x72hwuEXBqxqk9G6cK+K2NRUtB3iELRJqjXb4JPDMBjMTl2Q==}
|
||||
engines: {node: ^22.22.2 || ^24.15.0 || >=26.0.0}
|
||||
|
|
@ -1290,6 +1347,55 @@ snapshots:
|
|||
hashery: 1.5.1
|
||||
keyv: 5.6.0
|
||||
|
||||
'@codemirror/autocomplete@6.20.3':
|
||||
dependencies:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14
|
||||
'@lezer/common': 1.5.3
|
||||
|
||||
'@codemirror/commands@6.11.1':
|
||||
dependencies:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14
|
||||
'@lezer/common': 1.5.3
|
||||
|
||||
'@codemirror/language@6.13.1':
|
||||
dependencies:
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/streamparser': 6.0.0
|
||||
'@codemirror/view': 6.43.14
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
style-mod: 4.1.4
|
||||
|
||||
'@codemirror/lint@6.9.7':
|
||||
dependencies:
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14
|
||||
crelt: 1.0.7
|
||||
|
||||
'@codemirror/search@6.7.2':
|
||||
dependencies:
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14
|
||||
crelt: 1.0.7
|
||||
|
||||
'@codemirror/state@6.7.6':
|
||||
dependencies:
|
||||
'@marijn/find-cluster-break': 1.0.4
|
||||
|
||||
'@codemirror/streamparser@6.0.0': {}
|
||||
|
||||
'@codemirror/view@6.43.14':
|
||||
dependencies:
|
||||
'@codemirror/state': 6.7.6
|
||||
crelt: 1.0.7
|
||||
style-mod: 4.1.4
|
||||
w3c-keyname: 2.2.8
|
||||
|
||||
'@csstools/color-helpers@6.1.2': {}
|
||||
|
||||
'@csstools/css-calc@3.4.3(@csstools/css-parser-algorithms@4.0.2(@csstools/css-tokenizer@4.0.2))(@csstools/css-tokenizer@4.0.2)':
|
||||
|
|
@ -1383,10 +1489,22 @@ snapshots:
|
|||
|
||||
'@keyv/serialize@1.1.1': {}
|
||||
|
||||
'@lezer/common@1.5.3': {}
|
||||
|
||||
'@lezer/highlight@1.2.5':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
|
||||
'@lezer/lr@1.4.11':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
|
||||
'@lucide/vue@1.57.0(vue@3.5.44(typescript@6.0.3))':
|
||||
dependencies:
|
||||
vue: 3.5.44(typescript@6.0.3)
|
||||
|
||||
'@marijn/find-cluster-break@1.0.4': {}
|
||||
|
||||
'@one-ini/wasm@0.2.1': {}
|
||||
|
||||
'@oxc-project/types@0.153.0': {}
|
||||
|
|
@ -1706,6 +1824,16 @@ snapshots:
|
|||
|
||||
chai@6.3.0: {}
|
||||
|
||||
codemirror@6.0.2:
|
||||
dependencies:
|
||||
'@codemirror/autocomplete': 6.20.3
|
||||
'@codemirror/commands': 6.11.1
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/lint': 6.9.7
|
||||
'@codemirror/search': 6.7.2
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14
|
||||
|
||||
commander@14.0.3: {}
|
||||
|
||||
config-chain@1.1.13:
|
||||
|
|
@ -1713,6 +1841,8 @@ snapshots:
|
|||
ini: 1.3.8
|
||||
proto-list: 1.2.4
|
||||
|
||||
crelt@1.0.7: {}
|
||||
|
||||
cross-spawn@7.0.6:
|
||||
dependencies:
|
||||
path-key: 3.1.1
|
||||
|
|
@ -2166,6 +2296,8 @@ snapshots:
|
|||
|
||||
std-env@4.3.0: {}
|
||||
|
||||
style-mod@4.1.4: {}
|
||||
|
||||
tinybench@6.2.2: {}
|
||||
|
||||
tinyexec@1.3.1: {}
|
||||
|
|
@ -2285,6 +2417,8 @@ snapshots:
|
|||
optionalDependencies:
|
||||
typescript: 6.0.3
|
||||
|
||||
w3c-keyname@2.2.8: {}
|
||||
|
||||
w3c-xmlserializer@6.0.0:
|
||||
dependencies:
|
||||
xml-name-validator: 5.0.0
|
||||
|
|
|
|||
|
|
@ -1,9 +1,11 @@
|
|||
<script setup lang="ts">
|
||||
/**
|
||||
* Root component: mounts the main window layout with the editor area
|
||||
* placeholder. Loads product information from the engine on mount.
|
||||
* Root component: mounts the main window layout with the editor area; the
|
||||
* slogan shows while no tab is open. Loads product information from the
|
||||
* engine on mount.
|
||||
*/
|
||||
import { onMounted } from "vue";
|
||||
import EditorArea from "./components/editor/EditorArea.vue";
|
||||
import MainLayout from "./components/layout/MainLayout.vue";
|
||||
import { useAppStore } from "./stores/app";
|
||||
|
||||
|
|
@ -16,9 +18,11 @@ onMounted(() => {
|
|||
|
||||
<template>
|
||||
<MainLayout>
|
||||
<p class="workbench__hint">
|
||||
{{ app.about?.slogan ?? "" }}
|
||||
</p>
|
||||
<EditorArea>
|
||||
<p class="workbench__hint">
|
||||
{{ app.about?.slogan ?? "" }}
|
||||
</p>
|
||||
</EditorArea>
|
||||
</MainLayout>
|
||||
</template>
|
||||
|
||||
|
|
|
|||
135
ui/src/components/editor/ClosePrompt.vue
Normal file
135
ui/src/components/editor/ClosePrompt.vue
Normal 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>
|
||||
96
ui/src/components/editor/CodeEditor.vue
Normal file
96
ui/src/components/editor/CodeEditor.vue
Normal 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>
|
||||
158
ui/src/components/editor/EditorArea.vue
Normal file
158
ui/src/components/editor/EditorArea.vue
Normal 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>
|
||||
154
ui/src/components/editor/EditorTabs.vue
Normal file
154
ui/src/components/editor/EditorTabs.vue
Normal 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>
|
||||
386
ui/src/components/editor/bufferSync.ts
Normal file
386
ui/src/components/editor/bufferSync.ts
Normal 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
100
ui/src/components/editor/engineEvents.ts
Normal file
100
ui/src/components/editor/engineEvents.ts
Normal 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;
|
||||
}
|
||||
};
|
||||
}
|
||||
214
ui/src/components/editor/engineText.ts
Normal file
214
ui/src/components/editor/engineText.ts
Normal 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,
|
||||
);
|
||||
}
|
||||
97
ui/src/components/editor/extensions.ts
Normal file
97
ui/src/components/editor/extensions.ts
Normal 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];
|
||||
}
|
||||
155
ui/src/components/editor/shortcuts.ts
Normal file
155
ui/src/components/editor/shortcuts.ts
Normal 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;
|
||||
}
|
||||
|
|
@ -11,9 +11,11 @@
|
|||
import { ChevronDown, ChevronRight, File, FileCode, Folder, FolderOpen } from "@lucide/vue";
|
||||
import { computed, nextTick, ref } from "vue";
|
||||
import { parentOf, useProjectStore, type TreeRow } from "../../stores/project";
|
||||
import { useEditorStore } from "../../stores/editor";
|
||||
import type { TreeEntry } from "./engineEvents";
|
||||
|
||||
const project = useProjectStore();
|
||||
const editor = useEditorStore();
|
||||
|
||||
/** The tree element, for keeping the selected row in view. */
|
||||
const treeEl = ref<HTMLElement | null>(null);
|
||||
|
|
@ -108,7 +110,7 @@ function activate(entry: TreeEntry): void {
|
|||
if (entry.kind === "dir") {
|
||||
void project.toggle(entry.path);
|
||||
} else {
|
||||
void project.openFile(entry.path);
|
||||
void editor.openFile(entry.path);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
507
ui/src/stores/editor.ts
Normal file
507
ui/src/stores/editor.ts
Normal file
|
|
@ -0,0 +1,507 @@
|
|||
/**
|
||||
* Editor tabs: which engine buffers are open, which one is active, their
|
||||
* dirty state, notices, and the Save / Don't save / Cancel question when a
|
||||
* dirty tab closes.
|
||||
*
|
||||
* Fed by engine events (`bufferOpened`, `bufferChanged`, `dirtyChanged`,
|
||||
* `bufferClosed`, `fileChangedOnDisk`, project open/close) and by command
|
||||
* results. Text lives in the engine and in one {@link BufferSync} per tab,
|
||||
* kept outside reactive state. Command failures are stored and shown, never
|
||||
* thrown.
|
||||
*/
|
||||
import { defineStore } from "pinia";
|
||||
import { computed, ref, shallowRef } from "vue";
|
||||
import { run, type EngineError, type RunResult } from "../ipc";
|
||||
import { BufferSync, isBufferInfo, engineTransport, type BufferInfo, type SyncTransport } from "../components/editor/bufferSync";
|
||||
import { onEditorEvent, type EditorEvent } from "../components/editor/engineEvents";
|
||||
import { editorExtensions } from "../components/editor/extensions";
|
||||
import type { Extension } from "@codemirror/state";
|
||||
|
||||
/** Engine command ids used by the editor. */
|
||||
export const EDITOR_COMMANDS = {
|
||||
/** Opens a file: params `{ path }`, result {@link BufferInfo}. */
|
||||
open: "file.open",
|
||||
/** Describes a buffer: params `{ id }`, result {@link BufferInfo}. */
|
||||
get: "buffer.get",
|
||||
/** Saves a buffer: params `{ id }`. */
|
||||
save: "file.save",
|
||||
/** Saves every dirty buffer: result `{ saved, failed: [{ id, message }] }`. */
|
||||
saveAll: "file.saveAll",
|
||||
/** Closes a buffer: params `{ id, force }`; fails with `unsaved_changes`. */
|
||||
close: "buffer.close",
|
||||
} as const;
|
||||
|
||||
/** A notice shown above a tab's editor; it never blocks editing. */
|
||||
export interface EditorNotice {
|
||||
/** What happened. */
|
||||
kind: "changedOnDisk" | "removedOnDisk" | "error";
|
||||
/** Text for the user. */
|
||||
message: string;
|
||||
}
|
||||
|
||||
/** One editor tab. */
|
||||
export interface EditorTab {
|
||||
/** Engine buffer id. */
|
||||
id: number;
|
||||
/** Project-relative path. */
|
||||
path: string;
|
||||
/** File name shown on the tab. */
|
||||
name: string;
|
||||
/** Unsaved changes in the engine buffer. */
|
||||
dirty: boolean;
|
||||
/** Notice for this tab, null if none. */
|
||||
notice: EditorNotice | null;
|
||||
}
|
||||
|
||||
/** The pending question for closing a dirty tab. */
|
||||
export interface ClosePrompt {
|
||||
/** Buffer id of the tab. */
|
||||
id: number;
|
||||
/** File name, for the question. */
|
||||
name: string;
|
||||
}
|
||||
|
||||
/** Answer to a {@link ClosePrompt}. */
|
||||
export type CloseChoice = "save" | "discard" | "cancel";
|
||||
|
||||
/** Timing of the last file open, for the performance budget. */
|
||||
export interface OpenTiming {
|
||||
/** Path of the opened file. */
|
||||
path: string;
|
||||
/** Size of the text in UTF-16 code units. */
|
||||
length: number;
|
||||
/** Milliseconds from the request until the editor state existed. */
|
||||
stateMs: number;
|
||||
/** Milliseconds until the editor showed it, null until the view reports. */
|
||||
shownMs: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The file name of a project-relative path.
|
||||
*
|
||||
* @param path - for example `src/App.php`.
|
||||
*/
|
||||
export function baseName(path: string): string {
|
||||
const slash = path.lastIndexOf("/");
|
||||
return slash < 0 ? path : path.slice(slash + 1);
|
||||
}
|
||||
|
||||
/** Store of editor tabs. */
|
||||
export const useEditorStore = defineStore("editor", () => {
|
||||
/** Open tabs in display order. */
|
||||
const tabs = ref<EditorTab[]>([]);
|
||||
/** Buffer id of the active tab, null when no tab is open. */
|
||||
const activeId = ref<number | null>(null);
|
||||
/** Pending close question, null if none. */
|
||||
const closePrompt = ref<ClosePrompt | null>(null);
|
||||
/** Last failed editor command, null if none. */
|
||||
const lastError = ref<EngineError | null>(null);
|
||||
/** Timing of the last open, see {@link OpenTiming}. */
|
||||
const lastOpen = shallowRef<OpenTiming | null>(null);
|
||||
/** Syncs by buffer id; not reactive (they hold large editor states). */
|
||||
const syncs = new Map<number, BufferSync>();
|
||||
/** Start time of open requests by path, for {@link lastOpen}. */
|
||||
const openStarted = new Map<string, number>();
|
||||
/** Start time of the open measured in {@link lastOpen}. */
|
||||
let timedStart = 0;
|
||||
/** Engine transport for syncs, replaceable in tests. */
|
||||
let transport: SyncTransport = engineTransport;
|
||||
/** Extensions of new editor states, replaceable in tests. */
|
||||
let extensions: () => Extension = editorExtensions;
|
||||
/** Counter of tab adoptions, so only the newest open activates its tab. */
|
||||
let openSequence = 0;
|
||||
/** Unsubscribe function of the event subscription. */
|
||||
let unsubscribe: (() => void) | null = null;
|
||||
|
||||
/** The active tab, or null. */
|
||||
const activeTab = computed(() => tabs.value.find((t) => t.id === activeId.value) ?? null);
|
||||
|
||||
/**
|
||||
* The tab of a buffer.
|
||||
*
|
||||
* @param id - buffer id.
|
||||
*/
|
||||
function tabOf(id: number): EditorTab | undefined {
|
||||
return tabs.value.find((t) => t.id === id);
|
||||
}
|
||||
|
||||
/**
|
||||
* The sync of a buffer, for the editor view.
|
||||
*
|
||||
* @param id - buffer id.
|
||||
*/
|
||||
function syncOf(id: number): BufferSync | undefined {
|
||||
return syncs.get(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the engine transport and editor extensions (tests).
|
||||
*
|
||||
* @param next - transport for new syncs.
|
||||
* @param nextExtensions - extensions for new editor states.
|
||||
*/
|
||||
function configure(next: SyncTransport, nextExtensions?: () => Extension): void {
|
||||
transport = next;
|
||||
if (nextExtensions) {
|
||||
extensions = nextExtensions;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a tab for a buffer the engine described, unless it exists, and
|
||||
* activates it.
|
||||
*
|
||||
* @param info - the buffer.
|
||||
* @param activate - whether the tab becomes active.
|
||||
*/
|
||||
function adopt(info: BufferInfo, activate = true): void {
|
||||
if (!syncs.has(info.id)) {
|
||||
const started = openStarted.get(info.path);
|
||||
syncs.set(
|
||||
info.id,
|
||||
new BufferSync(info, extensions(), transport, (error) => {
|
||||
const tab = tabOf(info.id);
|
||||
if (tab) {
|
||||
tab.notice = { kind: "error", message: error.message };
|
||||
}
|
||||
}),
|
||||
);
|
||||
if (started !== undefined) {
|
||||
openStarted.delete(info.path);
|
||||
timedStart = started;
|
||||
lastOpen.value = {
|
||||
path: info.path,
|
||||
length: info.text.length,
|
||||
stateMs: performance.now() - started,
|
||||
shownMs: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
if (!tabOf(info.id)) {
|
||||
const index = tabs.value.findIndex((t) => t.id === activeId.value);
|
||||
const tab: EditorTab = {
|
||||
id: info.id,
|
||||
path: info.path,
|
||||
name: baseName(info.path),
|
||||
dirty: info.dirty,
|
||||
notice: null,
|
||||
};
|
||||
tabs.value.splice(index < 0 ? tabs.value.length : index + 1, 0, tab);
|
||||
}
|
||||
if (activate || activeId.value === null) {
|
||||
activeId.value = info.id;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Records that the view showed the buffer whose open is being timed.
|
||||
*
|
||||
* @param id - buffer id that became visible.
|
||||
*/
|
||||
function markShown(id: number): void {
|
||||
const timing = lastOpen.value;
|
||||
if (!timing || timing.shownMs !== null || tabOf(id)?.path !== timing.path) {
|
||||
return;
|
||||
}
|
||||
lastOpen.value = { ...timing, shownMs: performance.now() - timedStart };
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens a file in a tab (or activates its tab).
|
||||
*
|
||||
* @param path - project-relative path.
|
||||
*/
|
||||
async function openFile(path: string): Promise<void> {
|
||||
openStarted.set(path, performance.now());
|
||||
const result = await run<unknown>(EDITOR_COMMANDS.open, { path });
|
||||
if (!result.ok) {
|
||||
openStarted.delete(path);
|
||||
lastError.value = result.error;
|
||||
return;
|
||||
}
|
||||
if (!isBufferInfo(result.value)) {
|
||||
lastError.value = { code: "ipc", message: `unexpected result of ${EDITOR_COMMANDS.open}` };
|
||||
return;
|
||||
}
|
||||
lastError.value = null;
|
||||
openSequence += 1;
|
||||
adopt(result.value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Activates a tab.
|
||||
*
|
||||
* @param id - buffer id.
|
||||
*/
|
||||
function activate(id: number): void {
|
||||
if (tabOf(id)) {
|
||||
activeId.value = id;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a tab and its sync; the neighbour becomes active.
|
||||
*
|
||||
* @param id - buffer id.
|
||||
*/
|
||||
function removeTab(id: number): void {
|
||||
syncs.get(id)?.dispose();
|
||||
syncs.delete(id);
|
||||
const index = tabs.value.findIndex((t) => t.id === id);
|
||||
if (index < 0) {
|
||||
return;
|
||||
}
|
||||
tabs.value.splice(index, 1);
|
||||
if (activeId.value === id) {
|
||||
const next = tabs.value[Math.min(index, tabs.value.length - 1)];
|
||||
activeId.value = next ? next.id : null;
|
||||
}
|
||||
if (closePrompt.value?.id === id) {
|
||||
closePrompt.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits until local edits of a buffer reached the engine.
|
||||
*
|
||||
* @param id - buffer id.
|
||||
*/
|
||||
async function settled(id: number): Promise<void> {
|
||||
await syncs.get(id)?.idle();
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs `buffer.close`.
|
||||
*
|
||||
* @param id - buffer id.
|
||||
* @param force - discard unsaved changes.
|
||||
* @returns the command result.
|
||||
*/
|
||||
async function closeBuffer(id: number, force: boolean): Promise<RunResult<unknown>> {
|
||||
const result = await run<unknown>(EDITOR_COMMANDS.close, { id, force });
|
||||
if (result.ok) {
|
||||
removeTab(id);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes a tab; a dirty one asks Save / Don't save / Cancel first.
|
||||
*
|
||||
* @param id - buffer id; the active tab when omitted.
|
||||
*/
|
||||
async function requestClose(id: number | null = activeId.value): Promise<void> {
|
||||
if (id === null) {
|
||||
return;
|
||||
}
|
||||
const tab = tabOf(id);
|
||||
if (!tab) {
|
||||
return;
|
||||
}
|
||||
await settled(id);
|
||||
if (tab.dirty) {
|
||||
closePrompt.value = { id, name: tab.name };
|
||||
return;
|
||||
}
|
||||
const result = await closeBuffer(id, false);
|
||||
if (result.ok) {
|
||||
lastError.value = null;
|
||||
} else if (result.error.code === "unsaved_changes") {
|
||||
tab.dirty = true;
|
||||
closePrompt.value = { id, name: tab.name };
|
||||
} else {
|
||||
lastError.value = result.error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Answers the pending close question.
|
||||
*
|
||||
* @param choice - save and close, close without saving, or keep the tab.
|
||||
*/
|
||||
async function resolveClose(choice: CloseChoice): Promise<void> {
|
||||
const prompt = closePrompt.value;
|
||||
closePrompt.value = null;
|
||||
if (!prompt || choice === "cancel") {
|
||||
return;
|
||||
}
|
||||
if (choice === "save" && !(await save(prompt.id))) {
|
||||
return;
|
||||
}
|
||||
const result = await closeBuffer(prompt.id, choice === "discard");
|
||||
lastError.value = result.ok ? null : result.error;
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves a buffer after its local edits reached the engine.
|
||||
*
|
||||
* @param id - buffer id; the active tab when omitted.
|
||||
* @returns whether the save succeeded.
|
||||
*/
|
||||
async function save(id: number | null = activeId.value): Promise<boolean> {
|
||||
if (id === null || !tabOf(id)) {
|
||||
return false;
|
||||
}
|
||||
await settled(id);
|
||||
const result = await run<unknown>(EDITOR_COMMANDS.save, { id });
|
||||
lastError.value = result.ok ? null : result.error;
|
||||
if (result.ok) {
|
||||
const tab = tabOf(id);
|
||||
if (tab) {
|
||||
tab.dirty = false;
|
||||
if (tab.notice?.kind === "changedOnDisk") {
|
||||
tab.notice = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
return result.ok;
|
||||
}
|
||||
|
||||
/** Saves every buffer after all local edits reached the engine. */
|
||||
async function saveAll(): Promise<void> {
|
||||
await Promise.all(tabs.value.map((t) => settled(t.id)));
|
||||
const result = await run<{ failed?: { id?: unknown; message?: unknown }[] }>(
|
||||
EDITOR_COMMANDS.saveAll,
|
||||
);
|
||||
if (!result.ok) {
|
||||
lastError.value = result.error;
|
||||
return;
|
||||
}
|
||||
const failed = Array.isArray(result.value.failed) ? result.value.failed : [];
|
||||
lastError.value =
|
||||
failed.length > 0
|
||||
? {
|
||||
code: "save_failed",
|
||||
message: failed
|
||||
.map((f) => (typeof f.message === "string" ? f.message : "save failed"))
|
||||
.join("; "),
|
||||
}
|
||||
: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hides a tab's notice.
|
||||
*
|
||||
* @param id - buffer id.
|
||||
*/
|
||||
function dismissNotice(id: number): void {
|
||||
const tab = tabOf(id);
|
||||
if (tab) {
|
||||
tab.notice = null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Drops every tab (the project closed or changed). */
|
||||
function clear(): void {
|
||||
for (const sync of syncs.values()) {
|
||||
sync.dispose();
|
||||
}
|
||||
syncs.clear();
|
||||
tabs.value = [];
|
||||
activeId.value = null;
|
||||
closePrompt.value = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a tab for a buffer opened elsewhere (control channel, replay after
|
||||
* a reload), fetching its text first. When several open at once, the
|
||||
* last one opened becomes active, whatever order the fetches finish in.
|
||||
*
|
||||
* @param id - buffer id.
|
||||
*/
|
||||
async function adoptOpened(id: number): Promise<void> {
|
||||
if (syncs.has(id)) {
|
||||
return;
|
||||
}
|
||||
const sequence = ++openSequence;
|
||||
const result = await run<unknown>(EDITOR_COMMANDS.get, { id });
|
||||
if (!result.ok) {
|
||||
lastError.value = result.error;
|
||||
return;
|
||||
}
|
||||
if (isBufferInfo(result.value) && !syncs.has(id)) {
|
||||
adopt(result.value, sequence === openSequence);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies one editor event.
|
||||
*
|
||||
* @param event - the event.
|
||||
*/
|
||||
function handleEvent(event: EditorEvent): void {
|
||||
switch (event.kind) {
|
||||
case "projectOpened":
|
||||
case "projectClosed":
|
||||
clear();
|
||||
break;
|
||||
case "bufferOpened":
|
||||
void adoptOpened(event.id);
|
||||
break;
|
||||
case "bufferChanged":
|
||||
syncs.get(event.id)?.notifyVersion(event.version);
|
||||
break;
|
||||
case "dirtyChanged": {
|
||||
const tab = tabOf(event.id);
|
||||
if (tab) {
|
||||
tab.dirty = event.dirty;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "bufferClosed":
|
||||
removeTab(event.id);
|
||||
break;
|
||||
case "fileChangedOnDisk": {
|
||||
const tab = tabOf(event.id);
|
||||
if (!tab) {
|
||||
break;
|
||||
}
|
||||
if (event.removed) {
|
||||
tab.notice = {
|
||||
kind: "removedOnDisk",
|
||||
message: `${tab.name} was deleted on disk. Your text is kept; saving writes it again.`,
|
||||
};
|
||||
} else {
|
||||
tab.notice = {
|
||||
kind: "changedOnDisk",
|
||||
message: `${tab.name} changed on disk. Your unsaved changes are kept; saving overwrites the file.`,
|
||||
};
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Subscribes to engine events; calling it again has no effect. */
|
||||
function start(): void {
|
||||
unsubscribe ??= onEditorEvent(handleEvent);
|
||||
}
|
||||
|
||||
/** Ends the event subscription. */
|
||||
function stop(): void {
|
||||
unsubscribe?.();
|
||||
unsubscribe = null;
|
||||
}
|
||||
|
||||
return {
|
||||
tabs,
|
||||
activeId,
|
||||
activeTab,
|
||||
closePrompt,
|
||||
lastError,
|
||||
lastOpen,
|
||||
syncOf,
|
||||
configure,
|
||||
openFile,
|
||||
activate,
|
||||
requestClose,
|
||||
resolveClose,
|
||||
save,
|
||||
saveAll,
|
||||
dismissNotice,
|
||||
markShown,
|
||||
handleEvent,
|
||||
start,
|
||||
stop,
|
||||
};
|
||||
});
|
||||
|
|
@ -18,7 +18,13 @@ describe("App", () => {
|
|||
});
|
||||
|
||||
it("shows name and version in the status bar", async () => {
|
||||
invoke.mockResolvedValue({ name: "Lutra", version: "0.0.0", slogan: "An otterly perfect IDE" });
|
||||
invoke.mockImplementation((command: string) =>
|
||||
Promise.resolve(
|
||||
command === "engine_list_commands"
|
||||
? []
|
||||
: { name: "Lutra", version: "0.0.0", slogan: "An otterly perfect IDE" },
|
||||
),
|
||||
);
|
||||
const wrapper = mount(App);
|
||||
await flushPromises();
|
||||
expect(wrapper.get("[data-test=status-bar]").text()).toBe("Lutra 0.0.0");
|
||||
|
|
|
|||
430
ui/tests/editor/EditorArea.test.ts
Normal file
430
ui/tests/editor/EditorArea.test.ts
Normal file
|
|
@ -0,0 +1,430 @@
|
|||
/**
|
||||
* Tests for the editor area and the editor store: opening tabs (from the
|
||||
* tree and from engine events), editing through CodeMirror into
|
||||
* `buffer.edit`, the dirty marker, closing (middle click, shortcut, the
|
||||
* Save / Don't Save / Cancel question), saving through shortcuts loaded
|
||||
* from the engine's command list, and the notice for files changed on disk.
|
||||
* The engine is a fake behind the mocked Tauri `invoke`.
|
||||
*/
|
||||
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { createPinia, setActivePinia, type Pinia } from "pinia";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const invoke = vi.hoisted(() => vi.fn());
|
||||
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
|
||||
|
||||
import EditorArea from "../../src/components/editor/EditorArea.vue";
|
||||
import { emitEditorEvent } from "../../src/components/editor/engineEvents";
|
||||
import { emitEngineEvent } from "../../src/components/project/engineEvents";
|
||||
import ProjectToolWindow from "../../src/components/project/ProjectToolWindow.vue";
|
||||
import { useEditorStore } from "../../src/stores/editor";
|
||||
|
||||
/** A buffer of the fake engine. */
|
||||
interface FakeBuffer {
|
||||
path: string;
|
||||
text: string;
|
||||
version: number;
|
||||
saved: number;
|
||||
}
|
||||
|
||||
/** Fake engine state. */
|
||||
let buffers: Map<number, FakeBuffer>;
|
||||
/** Files on the fake disk. */
|
||||
let disk: Record<string, string>;
|
||||
/** Next buffer id. */
|
||||
let nextId: number;
|
||||
/** Every `engine_execute` call, in order. */
|
||||
let calls: { command: string; params: Record<string, unknown> }[];
|
||||
|
||||
/**
|
||||
* Describes a buffer as `file.open` and `buffer.get` do.
|
||||
*
|
||||
* @param id - buffer id.
|
||||
*/
|
||||
function describeBuffer(id: number): unknown {
|
||||
const b = buffers.get(id);
|
||||
return b
|
||||
? { id, path: b.path, text: b.text, version: b.version, dirty: b.version !== b.saved, lineEnding: "lf" }
|
||||
: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rejects like the shell does with an engine error.
|
||||
*
|
||||
* @param code - error code.
|
||||
*/
|
||||
function fail(code: string): Promise<never> {
|
||||
return Promise.reject(Object.assign(new Error(code), { code, message: code }));
|
||||
}
|
||||
|
||||
/**
|
||||
* The fake engine's command handler.
|
||||
*
|
||||
* @param command - command id.
|
||||
* @param p - params.
|
||||
*/
|
||||
function execute(command: string, p: Record<string, unknown>): Promise<unknown> {
|
||||
const id = typeof p.id === "number" ? p.id : -1;
|
||||
const b = buffers.get(id);
|
||||
switch (command) {
|
||||
case "file.open": {
|
||||
const path = String(p.path);
|
||||
for (const [existing, buffer] of buffers) {
|
||||
if (buffer.path === path) {
|
||||
return Promise.resolve(describeBuffer(existing));
|
||||
}
|
||||
}
|
||||
const text = disk[path];
|
||||
if (text === undefined) {
|
||||
return fail("not_found");
|
||||
}
|
||||
const newId = nextId++;
|
||||
buffers.set(newId, { path, text, version: 1, saved: 1 });
|
||||
return Promise.resolve(describeBuffer(newId));
|
||||
}
|
||||
case "buffer.get":
|
||||
return b ? Promise.resolve(describeBuffer(id)) : fail("failed");
|
||||
case "buffer.edit": {
|
||||
if (!b) {
|
||||
return fail("failed");
|
||||
}
|
||||
if (p.baseVersion !== b.version) {
|
||||
return fail("stale_version");
|
||||
}
|
||||
let out = "";
|
||||
let pos = 0;
|
||||
for (const e of p.edits as { from: number; to: number; insert: string }[]) {
|
||||
out += b.text.slice(pos, e.from) + e.insert;
|
||||
pos = e.to;
|
||||
}
|
||||
const wasDirty = b.version !== b.saved;
|
||||
b.text = out + b.text.slice(pos);
|
||||
b.version += 1;
|
||||
emitEditorEvent({ kind: "bufferChanged", id, version: b.version });
|
||||
if (!wasDirty) {
|
||||
emitEditorEvent({ kind: "dirtyChanged", id, dirty: true });
|
||||
}
|
||||
return Promise.resolve({ id, version: b.version, dirty: true });
|
||||
}
|
||||
case "file.save":
|
||||
if (!b) {
|
||||
return fail("failed");
|
||||
}
|
||||
disk[b.path] = b.text;
|
||||
b.saved = b.version;
|
||||
emitEditorEvent({ kind: "dirtyChanged", id, dirty: false });
|
||||
return Promise.resolve({ id, version: b.version });
|
||||
case "file.saveAll": {
|
||||
const saved: number[] = [];
|
||||
for (const [bid, buffer] of buffers) {
|
||||
if (buffer.version !== buffer.saved) {
|
||||
disk[buffer.path] = buffer.text;
|
||||
buffer.saved = buffer.version;
|
||||
saved.push(bid);
|
||||
}
|
||||
}
|
||||
return Promise.resolve({ saved, failed: [] });
|
||||
}
|
||||
case "buffer.close":
|
||||
if (!b) {
|
||||
return fail("failed");
|
||||
}
|
||||
if (b.version !== b.saved && p.force !== true) {
|
||||
return fail("unsaved_changes");
|
||||
}
|
||||
buffers.delete(id);
|
||||
emitEditorEvent({ kind: "bufferClosed", id });
|
||||
return Promise.resolve(null);
|
||||
case "project.children":
|
||||
return Promise.resolve({
|
||||
dir: "",
|
||||
entries: Object.keys(disk).map((path) => ({
|
||||
name: path,
|
||||
path,
|
||||
kind: "file",
|
||||
ignored: false,
|
||||
role: "normal",
|
||||
})),
|
||||
truncated: false,
|
||||
});
|
||||
default:
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
}
|
||||
|
||||
/** Pinia of the current test, installed in every mounted component. */
|
||||
let pinia: Pinia;
|
||||
|
||||
/** Mounted components to unmount after each test. */
|
||||
let mounted: VueWrapper[] = [];
|
||||
|
||||
/** Mounts the editor area. */
|
||||
async function mountArea(): Promise<VueWrapper> {
|
||||
const wrapper = mount(EditorArea, {
|
||||
attachTo: document.body,
|
||||
slots: { default: "empty" },
|
||||
global: { plugins: [pinia] },
|
||||
});
|
||||
mounted.push(wrapper);
|
||||
await flushPromises();
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
/** The CodeMirror view inside a wrapper. */
|
||||
function viewOf(wrapper: VueWrapper): EditorView {
|
||||
const el = wrapper.find(".cm-editor").element;
|
||||
const view = EditorView.findFromDOM(el as HTMLElement);
|
||||
if (!view) {
|
||||
throw new Error("no editor view");
|
||||
}
|
||||
return view;
|
||||
}
|
||||
|
||||
/**
|
||||
* Presses a key on the window.
|
||||
*
|
||||
* @param init - key event properties.
|
||||
*/
|
||||
async function press(init: KeyboardEventInit): Promise<void> {
|
||||
window.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, cancelable: true, ...init }));
|
||||
await flushPromises();
|
||||
}
|
||||
|
||||
/** Commands sent to the engine, without project and listing calls. */
|
||||
function commands(): string[] {
|
||||
return calls.map((c) => c.command).filter((c) => !c.startsWith("project."));
|
||||
}
|
||||
|
||||
/**
|
||||
* jsdom has no layout; CodeMirror measures text ranges, so give ranges
|
||||
* empty rectangles.
|
||||
*/
|
||||
function stubRangeGeometry(): void {
|
||||
const empty = (): DOMRectList => {
|
||||
const list: DOMRect[] = [];
|
||||
return Object.assign(list, { item: () => null });
|
||||
};
|
||||
Range.prototype.getClientRects = empty;
|
||||
Range.prototype.getBoundingClientRect = () => new DOMRect(0, 0, 0, 0);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
stubRangeGeometry();
|
||||
pinia = createPinia();
|
||||
setActivePinia(pinia);
|
||||
buffers = new Map();
|
||||
disk = { "a.php": "<?php\necho 1;\n", "b.txt": "bee\n" };
|
||||
nextId = 1;
|
||||
calls = [];
|
||||
invoke.mockReset();
|
||||
invoke.mockImplementation((cmd: string, args?: { command: string; params: Record<string, unknown> }) => {
|
||||
if (cmd === "engine_list_commands") {
|
||||
return Promise.resolve([
|
||||
{ id: "file.save", label: "Save", menuPath: null, defaultShortcut: "Mod+S", params: "", enabled: true },
|
||||
{ id: "file.saveAll", label: "Save All", menuPath: null, defaultShortcut: "Mod+Alt+S", params: "", enabled: true },
|
||||
{ id: "buffer.close", label: "Close", menuPath: null, defaultShortcut: "Mod+W", params: "", enabled: true },
|
||||
]);
|
||||
}
|
||||
if (cmd === "engine_execute" && args) {
|
||||
calls.push({ command: args.command, params: args.params });
|
||||
return execute(args.command, args.params);
|
||||
}
|
||||
return Promise.reject(new Error(`unexpected ${cmd}`));
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await flushPromises();
|
||||
for (const wrapper of mounted) {
|
||||
wrapper.unmount();
|
||||
}
|
||||
mounted = [];
|
||||
});
|
||||
|
||||
describe("EditorArea", () => {
|
||||
it("shows the slot without tabs and opens a file from the project tree", async () => {
|
||||
const area = await mountArea();
|
||||
expect(area.text()).toContain("empty");
|
||||
const tree = mount(ProjectToolWindow, { attachTo: document.body, global: { plugins: [pinia] } });
|
||||
mounted.push(tree);
|
||||
emitEngineEvent({ kind: "projectOpened", root: "/tmp/demo", name: "demo" });
|
||||
await flushPromises();
|
||||
await tree.find("[data-path='a.php']").trigger("dblclick");
|
||||
await flushPromises();
|
||||
const tabs = area.findAll("[data-test=editor-tab]");
|
||||
expect(tabs.map((t) => t.text())).toEqual(["a.php"]);
|
||||
expect(viewOf(area).state.doc.toString()).toBe("<?php\necho 1;\n");
|
||||
await tree.find("[data-path='a.php']").trigger("dblclick");
|
||||
await flushPromises();
|
||||
expect(area.findAll("[data-test=editor-tab]")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("sends typing to buffer.edit and marks the tab dirty", async () => {
|
||||
const area = await mountArea();
|
||||
const editor = useEditorStore(pinia);
|
||||
await editor.openFile("a.php");
|
||||
await flushPromises();
|
||||
const view = viewOf(area);
|
||||
view.dispatch({ changes: { from: 5, insert: " // hi" } });
|
||||
view.dispatch({ changes: { from: 0, insert: "#" } });
|
||||
await flushPromises();
|
||||
expect(buffers.get(1)?.text).toBe("#<?php // hi\necho 1;\n");
|
||||
expect(area.find("[data-test=tab-dirty]").exists()).toBe(true);
|
||||
});
|
||||
|
||||
it("applies engine edits made elsewhere to the open editor", async () => {
|
||||
const area = await mountArea();
|
||||
await useEditorStore(pinia).openFile("b.txt");
|
||||
await flushPromises();
|
||||
const b = buffers.get(1);
|
||||
if (!b) {
|
||||
throw new Error("no buffer");
|
||||
}
|
||||
b.text = "honey bee\n";
|
||||
b.version = 2;
|
||||
emitEditorEvent({ kind: "bufferChanged", id: 1, version: 2 });
|
||||
await flushPromises();
|
||||
expect(viewOf(area).state.doc.toString()).toBe("honey bee\n");
|
||||
});
|
||||
|
||||
it("switches tabs and closes a clean tab with a middle click", async () => {
|
||||
const area = await mountArea();
|
||||
const editor = useEditorStore(pinia);
|
||||
await editor.openFile("a.php");
|
||||
await editor.openFile("b.txt");
|
||||
await flushPromises();
|
||||
expect(editor.activeId).toBe(2);
|
||||
await area.findAll("[data-test=editor-tab]")[0]?.trigger("click");
|
||||
expect(viewOf(area).state.doc.toString()).toContain("<?php");
|
||||
await area.findAll("[data-test=editor-tab]")[1]?.trigger("auxclick", { button: 1 });
|
||||
await flushPromises();
|
||||
expect(area.findAll("[data-test=editor-tab]").map((t) => t.text())).toEqual(["a.php"]);
|
||||
expect(commands()).toContain("buffer.close");
|
||||
});
|
||||
|
||||
it("asks before closing a dirty tab: cancel, don't save, save", async () => {
|
||||
const area = await mountArea();
|
||||
const editor = useEditorStore(pinia);
|
||||
await editor.openFile("a.php");
|
||||
await flushPromises();
|
||||
viewOf(area).dispatch({ changes: { from: 0, insert: "x" } });
|
||||
await flushPromises();
|
||||
|
||||
await press({ key: "w", code: "KeyW", ctrlKey: true });
|
||||
expect(area.find("[data-test=close-prompt]").exists()).toBe(true);
|
||||
await area.find("[data-test=close-cancel]").trigger("click");
|
||||
await flushPromises();
|
||||
expect(area.find("[data-test=close-prompt]").exists()).toBe(false);
|
||||
expect(editor.tabs).toHaveLength(1);
|
||||
|
||||
await area.find("[data-test=tab-close]").trigger("click");
|
||||
await flushPromises();
|
||||
await area.find("[data-test=close-save]").trigger("click");
|
||||
await flushPromises();
|
||||
expect(disk["a.php"]).toBe("x<?php\necho 1;\n");
|
||||
expect(editor.tabs).toHaveLength(0);
|
||||
|
||||
await editor.openFile("b.txt");
|
||||
await flushPromises();
|
||||
viewOf(area).dispatch({ changes: { from: 0, insert: "lost " } });
|
||||
await flushPromises();
|
||||
await editor.requestClose();
|
||||
await flushPromises();
|
||||
await area.find("[data-test=close-discard]").trigger("click");
|
||||
await flushPromises();
|
||||
expect(disk["b.txt"]).toBe("bee\n");
|
||||
expect(calls.at(-1)).toEqual({ command: "buffer.close", params: { id: 2, force: true } });
|
||||
expect(editor.tabs).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("saves with the shortcuts the engine defines, after pending edits", async () => {
|
||||
const area = await mountArea();
|
||||
const editor = useEditorStore(pinia);
|
||||
await editor.openFile("a.php");
|
||||
await editor.openFile("b.txt");
|
||||
await flushPromises();
|
||||
viewOf(area).dispatch({ changes: { from: 0, insert: "B" } });
|
||||
await press({ key: "s", code: "KeyS", ctrlKey: true });
|
||||
expect(disk["b.txt"]).toBe("Bbee\n");
|
||||
expect(calls.at(-1)).toEqual({ command: "file.save", params: { id: 2 } });
|
||||
expect(area.find("[data-test=tab-dirty]").exists()).toBe(false);
|
||||
|
||||
await area.findAll("[data-test=editor-tab]")[0]?.trigger("click");
|
||||
viewOf(area).dispatch({ changes: { from: 0, insert: "A" } });
|
||||
await press({ key: "ß", code: "KeyS", ctrlKey: true, altKey: true });
|
||||
expect(disk["a.php"]).toBe("A<?php\necho 1;\n");
|
||||
expect(calls.at(-1)?.command).toBe("file.saveAll");
|
||||
|
||||
calls = [];
|
||||
await press({ key: "s", code: "KeyS", shiftKey: true });
|
||||
expect(calls).toEqual([]);
|
||||
});
|
||||
|
||||
it("adds a tab for a buffer opened elsewhere", async () => {
|
||||
const area = await mountArea();
|
||||
await execute("file.open", { path: "b.txt" });
|
||||
emitEditorEvent({ kind: "bufferOpened", id: 1, path: "b.txt" });
|
||||
await flushPromises();
|
||||
expect(area.findAll("[data-test=editor-tab]").map((t) => t.text())).toEqual(["b.txt"]);
|
||||
emitEditorEvent({ kind: "bufferClosed", id: 1 });
|
||||
await flushPromises();
|
||||
expect(area.findAll("[data-test=editor-tab]")).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("activates the last opened buffer even when its fetch finishes first", async () => {
|
||||
const area = await mountArea();
|
||||
await execute("file.open", { path: "a.php" });
|
||||
await execute("file.open", { path: "b.txt" });
|
||||
let releaseFirst: () => void = () => undefined;
|
||||
const fallback = invoke.getMockImplementation();
|
||||
invoke.mockImplementation((cmd: string, args?: { command: string; params: Record<string, unknown> }) => {
|
||||
if (args?.command === "buffer.get" && args.params.id === 1) {
|
||||
return new Promise((resolve) => {
|
||||
releaseFirst = () => {
|
||||
resolve(describeBuffer(1));
|
||||
};
|
||||
});
|
||||
}
|
||||
return fallback?.(cmd, args) as Promise<unknown>;
|
||||
});
|
||||
emitEditorEvent({ kind: "bufferOpened", id: 1, path: "a.php" });
|
||||
emitEditorEvent({ kind: "bufferOpened", id: 2, path: "b.txt" });
|
||||
await flushPromises();
|
||||
releaseFirst();
|
||||
await flushPromises();
|
||||
const editor = useEditorStore(pinia);
|
||||
expect(editor.tabs.map((t) => t.path).sort()).toEqual(["a.php", "b.txt"]);
|
||||
expect(editor.activeId).toBe(2);
|
||||
expect(area.find("[aria-selected=true]").text()).toBe("b.txt");
|
||||
});
|
||||
|
||||
it("shows a notice when a dirty file changes on disk, and an open error", async () => {
|
||||
const area = await mountArea();
|
||||
const editor = useEditorStore(pinia);
|
||||
await editor.openFile("a.php");
|
||||
await flushPromises();
|
||||
emitEditorEvent({ kind: "fileChangedOnDisk", id: 1, path: "a.php", removed: false });
|
||||
await flushPromises();
|
||||
expect(area.find("[data-test=editor-notice]").text()).toContain("changed on disk");
|
||||
await area.find("[data-test=notice-dismiss]").trigger("click");
|
||||
expect(area.find("[data-test=editor-notice]").exists()).toBe(false);
|
||||
|
||||
await editor.openFile("missing.php");
|
||||
await flushPromises();
|
||||
expect(area.find("[data-test=editor-error]").text()).toContain("not_found");
|
||||
});
|
||||
|
||||
it("opens a 1 MB file and records the time", async () => {
|
||||
const line = "<?php echo 'lutra otter tool use stone';\n";
|
||||
disk["big.php"] = line.repeat(Math.ceil((1024 * 1024) / line.length));
|
||||
const area = await mountArea();
|
||||
const editor = useEditorStore(pinia);
|
||||
await editor.openFile("big.php");
|
||||
await flushPromises();
|
||||
expect(viewOf(area).state.doc.length).toBe(disk["big.php"].length);
|
||||
const timing = editor.lastOpen;
|
||||
expect(timing?.path).toBe("big.php");
|
||||
expect(timing?.stateMs).toBeLessThan(2000);
|
||||
});
|
||||
});
|
||||
280
ui/tests/editor/bufferSync.test.ts
Normal file
280
ui/tests/editor/bufferSync.test.ts
Normal file
|
|
@ -0,0 +1,280 @@
|
|||
/**
|
||||
* Tests for the buffer sync: a fake engine with real versioning answers
|
||||
* `buffer.edit` and `buffer.get` after random delays and makes edits of its
|
||||
* own (as a reload from disk or the control channel would). Bursts of local
|
||||
* keystrokes must all reach the engine, and both sides must converge.
|
||||
*/
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
BufferSync,
|
||||
type BufferInfo,
|
||||
type EditParams,
|
||||
type EditResult,
|
||||
type SyncTransport,
|
||||
} from "../../src/components/editor/bufferSync";
|
||||
import type { RunResult } from "../../src/ipc";
|
||||
|
||||
/** Deterministic pseudo-random numbers (mulberry32). */
|
||||
function rng(seed: number): () => number {
|
||||
let a = seed >>> 0;
|
||||
return () => {
|
||||
a = (a + 0x6d2b79f5) >>> 0;
|
||||
let t = a;
|
||||
t = Math.imul(t ^ (t >>> 15), t | 1);
|
||||
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
|
||||
/** A fake engine buffer with the engine's edit protocol. */
|
||||
class FakeEngine implements SyncTransport {
|
||||
text: string;
|
||||
version = 1;
|
||||
readonly lineEnding: string;
|
||||
/** Answers waiting to be delivered. */
|
||||
private queue: (() => void)[] = [];
|
||||
/** Versions to report through `bufferChanged`. */
|
||||
events: number[] = [];
|
||||
editCalls = 0;
|
||||
staleRejections = 0;
|
||||
|
||||
constructor(text: string, lineEnding = "lf", private random: () => number = Math.random) {
|
||||
this.text = text;
|
||||
this.lineEnding = lineEnding;
|
||||
}
|
||||
|
||||
info(): BufferInfo {
|
||||
return {
|
||||
id: 1,
|
||||
path: "a.txt",
|
||||
text: this.text,
|
||||
version: this.version,
|
||||
dirty: this.version !== 1,
|
||||
lineEnding: this.lineEnding,
|
||||
};
|
||||
}
|
||||
|
||||
edit(params: EditParams): Promise<RunResult<EditResult>> {
|
||||
this.editCalls += 1;
|
||||
return this.later(() => {
|
||||
if (params.baseVersion !== this.version) {
|
||||
this.staleRejections += 1;
|
||||
return { ok: false, error: { code: "stale_version", message: "stale" } };
|
||||
}
|
||||
let out = "";
|
||||
let pos = 0;
|
||||
for (const e of params.edits) {
|
||||
expect(e.from).toBeGreaterThanOrEqual(pos);
|
||||
expect(e.to).toBeLessThanOrEqual(this.text.length);
|
||||
out += this.text.slice(pos, e.from) + e.insert;
|
||||
pos = e.to;
|
||||
}
|
||||
this.text = out + this.text.slice(pos);
|
||||
this.version += 1;
|
||||
this.events.push(this.version);
|
||||
return { ok: true, value: { id: 1, version: this.version, dirty: true } };
|
||||
});
|
||||
}
|
||||
|
||||
get(): Promise<RunResult<BufferInfo>> {
|
||||
return this.later(() => ({ ok: true, value: this.info() }));
|
||||
}
|
||||
|
||||
/**
|
||||
* An edit made outside the editor: inserts `text` at a line start.
|
||||
*
|
||||
* @param text - inserted text.
|
||||
* @param line - 0-based line; random when omitted.
|
||||
*/
|
||||
external(text: string, line?: number): void {
|
||||
const starts = [0];
|
||||
for (let i = 0; i < this.text.length; i += 1) {
|
||||
if (this.text[i] === "\n") {
|
||||
starts.push(i + 1);
|
||||
}
|
||||
}
|
||||
const at = starts[line ?? Math.floor(this.random() * starts.length)] ?? 0;
|
||||
this.text = this.text.slice(0, at) + text + this.text.slice(at);
|
||||
this.version += 1;
|
||||
this.events.push(this.version);
|
||||
}
|
||||
|
||||
/** Queues an answer; {@link step} delivers queued answers in random order. */
|
||||
private later<T>(answer: () => T): Promise<T> {
|
||||
return new Promise((resolve) => {
|
||||
this.queue.push(() => {
|
||||
resolve(answer());
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** Delivers one queued answer, if any. */
|
||||
step(): boolean {
|
||||
if (this.queue.length === 0) {
|
||||
return false;
|
||||
}
|
||||
const index = Math.floor(this.random() * this.queue.length);
|
||||
const [answer] = this.queue.splice(index, 1);
|
||||
answer?.();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/** Lets promise callbacks run. */
|
||||
async function tick(): Promise<void> {
|
||||
for (let i = 0; i < 5; i += 1) {
|
||||
await Promise.resolve();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delivers every pending answer and event until the sync is idle.
|
||||
*
|
||||
* @param engine - the fake engine.
|
||||
* @param sync - the sync under test.
|
||||
*/
|
||||
async function drain(engine: FakeEngine, sync: BufferSync): Promise<void> {
|
||||
for (let i = 0; i < 10_000; i += 1) {
|
||||
const events = engine.events.splice(0);
|
||||
for (const v of events) {
|
||||
sync.notifyVersion(v);
|
||||
}
|
||||
const stepped = engine.step();
|
||||
await tick();
|
||||
if (!stepped && events.length === 0 && !sync.pending) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new Error("sync did not settle");
|
||||
}
|
||||
|
||||
/**
|
||||
* The engine text with CodeMirror's line breaks, for comparison.
|
||||
*
|
||||
* @param text - engine text.
|
||||
*/
|
||||
function normalised(text: string): string {
|
||||
return text.replace(/\r\n?/g, "\n");
|
||||
}
|
||||
|
||||
describe("BufferSync", () => {
|
||||
it("sends local edits with the base version and tracks versions", async () => {
|
||||
const engine = new FakeEngine("hello\n");
|
||||
const sync = new BufferSync(engine.info(), [], engine);
|
||||
sync.dispatch({ changes: { from: 5, insert: " world" } });
|
||||
expect(sync.pending).toBe(true);
|
||||
await drain(engine, sync);
|
||||
expect(engine.text).toBe("hello world\n");
|
||||
expect(sync.baseVersion).toBe(2);
|
||||
expect(sync.pending).toBe(false);
|
||||
});
|
||||
|
||||
it("applies a change made in the engine", async () => {
|
||||
const engine = new FakeEngine("one\ntwo\n");
|
||||
const sync = new BufferSync(engine.info(), [], engine);
|
||||
engine.external("zero\n", 0);
|
||||
await drain(engine, sync);
|
||||
expect(sync.state.doc.toString()).toBe("zero\none\ntwo\n");
|
||||
expect(sync.baseVersion).toBe(engine.version);
|
||||
});
|
||||
|
||||
it("keeps the local cursor when a remote change lands before it", async () => {
|
||||
const engine = new FakeEngine("abc\n");
|
||||
const sync = new BufferSync(engine.info(), [], engine);
|
||||
sync.dispatch({ selection: { anchor: 2 } });
|
||||
engine.external("x\n", 0);
|
||||
await drain(engine, sync);
|
||||
expect(sync.state.selection.main.head).toBe(4);
|
||||
});
|
||||
|
||||
it("loses no keystroke in a burst with stale versions and remote edits", async () => {
|
||||
const random = rng(42);
|
||||
const engine = new FakeEngine("<?php\n\necho 1;\n", "lf", random);
|
||||
const sync = new BufferSync(engine.info(), [], engine);
|
||||
const typed: string[] = [];
|
||||
for (let i = 0; i < 400; i += 1) {
|
||||
const token = `[k${String(i)}]`;
|
||||
typed.push(token);
|
||||
const doc = sync.state.doc;
|
||||
const at = doc.line(1 + Math.floor(random() * doc.lines)).to;
|
||||
sync.dispatch({ changes: { from: at, insert: token } });
|
||||
if (random() < 0.15) {
|
||||
engine.external(`/*e${String(i)}*/\n`);
|
||||
}
|
||||
if (random() < 0.5) {
|
||||
engine.step();
|
||||
}
|
||||
if (random() < 0.3) {
|
||||
for (const v of engine.events.splice(0)) {
|
||||
sync.notifyVersion(v);
|
||||
}
|
||||
}
|
||||
await tick();
|
||||
}
|
||||
await drain(engine, sync);
|
||||
expect(sync.state.doc.toString()).toBe(engine.text);
|
||||
for (const token of typed) {
|
||||
expect(engine.text).toContain(token);
|
||||
}
|
||||
expect(engine.staleRejections).toBeGreaterThan(0);
|
||||
expect(engine.editCalls).toBeLessThan(400);
|
||||
});
|
||||
|
||||
it("converges with deletions and line breaks in a CRLF file", async () => {
|
||||
const random = rng(7);
|
||||
const engine = new FakeEngine("a\r\nbb\r\nccc\r\n", "crlf", random);
|
||||
const sync = new BufferSync(engine.info(), [], engine);
|
||||
for (let i = 0; i < 300; i += 1) {
|
||||
const len = sync.state.doc.length;
|
||||
const from = Math.floor(random() * (len + 1));
|
||||
const to = Math.min(len, from + Math.floor(random() * 3));
|
||||
const insert = random() < 0.3 ? "\n" : random() < 0.5 ? "é😀" : "";
|
||||
sync.dispatch({ changes: { from, to, insert } });
|
||||
if (random() < 0.1) {
|
||||
engine.external(`r${String(i)}\r\n`);
|
||||
}
|
||||
if (random() < 0.6) {
|
||||
engine.step();
|
||||
}
|
||||
if (random() < 0.3) {
|
||||
for (const v of engine.events.splice(0)) {
|
||||
sync.notifyVersion(v);
|
||||
}
|
||||
}
|
||||
await tick();
|
||||
}
|
||||
await drain(engine, sync);
|
||||
expect(sync.state.doc.toString()).toBe(normalised(engine.text));
|
||||
expect(engine.text.replace(/\r\n/g, "")).not.toMatch(/[\r\n]/);
|
||||
});
|
||||
|
||||
it("drops local changes and reports when the engine refuses them", async () => {
|
||||
const engine = new FakeEngine("keep\n");
|
||||
const errors: string[] = [];
|
||||
const refusing: SyncTransport = {
|
||||
edit: () =>
|
||||
Promise.resolve({ ok: false, error: { code: "invalid_params", message: "bad" } }),
|
||||
get: () => engine.get(),
|
||||
};
|
||||
const sync = new BufferSync(engine.info(), [], refusing, (e) => errors.push(e.code));
|
||||
sync.dispatch({ changes: { from: 0, insert: "lost " } });
|
||||
await drain(engine, sync);
|
||||
expect(errors).toEqual(["invalid_params"]);
|
||||
expect(sync.state.doc.toString()).toBe("keep\n");
|
||||
});
|
||||
|
||||
it("idle resolves after the engine confirmed every change", async () => {
|
||||
const engine = new FakeEngine("");
|
||||
const sync = new BufferSync(engine.info(), [], engine);
|
||||
sync.dispatch({ changes: { from: 0, insert: "x" } });
|
||||
let done = false;
|
||||
void sync.idle().then(() => {
|
||||
done = true;
|
||||
});
|
||||
await tick();
|
||||
expect(done).toBe(false);
|
||||
await drain(engine, sync);
|
||||
await tick();
|
||||
expect(done).toBe(true);
|
||||
});
|
||||
});
|
||||
58
ui/tests/editor/engineText.test.ts
Normal file
58
ui/tests/editor/engineText.test.ts
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
/**
|
||||
* Tests for the mapping between engine text (line breaks as on disk) and
|
||||
* CodeMirror documents (one position per line break).
|
||||
*/
|
||||
import { ChangeSet, Text } from "@codemirror/state";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { diffDocs, EngineText, separatorOf } from "../../src/components/editor/engineText";
|
||||
|
||||
describe("EngineText", () => {
|
||||
it("maps positions past CRLF breaks and keeps mixed endings", () => {
|
||||
const text = EngineText.fromEngine("a\r\nb\nc\rd\r\n");
|
||||
expect(text.doc.toString()).toBe("a\nb\nc\nd\n");
|
||||
expect(text.toEngine(0)).toBe(0);
|
||||
expect(text.toEngine(2)).toBe(3);
|
||||
expect(text.toEngine(4)).toBe(5);
|
||||
expect(text.toEngine(8)).toBe(10);
|
||||
expect(text.toEngine(99)).toBe(10);
|
||||
expect(text.engineString()).toBe("a\r\nb\nc\nd\r\n");
|
||||
});
|
||||
|
||||
it("is the identity for text without CRLF", () => {
|
||||
const text = EngineText.fromEngine("x😀\ny");
|
||||
expect(text.toEngine(4)).toBe(4);
|
||||
});
|
||||
|
||||
it("turns changes into engine edits with the buffer's line ending", () => {
|
||||
const text = EngineText.fromEngine("ab\r\ncd\r\n");
|
||||
const changes = ChangeSet.of(
|
||||
[
|
||||
{ from: 1, insert: "\n" },
|
||||
{ from: 3, to: 5, insert: "X" },
|
||||
],
|
||||
text.doc.length,
|
||||
);
|
||||
expect(text.edits(changes, "\r\n")).toEqual([
|
||||
{ from: 1, to: 1, insert: "\r\n" },
|
||||
{ from: 4, to: 6, insert: "X" },
|
||||
]);
|
||||
const after = text.apply(changes, "\r\n");
|
||||
expect(after.doc.toString()).toBe("a\nb\nX\n");
|
||||
expect(after.engineString()).toBe("a\r\nb\r\nX\r\n");
|
||||
});
|
||||
|
||||
it("diffs documents into one replacement", () => {
|
||||
const a = Text.of(["hello", "world"]);
|
||||
const b = Text.of(["hello", "brave", "world"]);
|
||||
const diff = diffDocs(a, b);
|
||||
expect(diff.apply(a).toString()).toBe(b.toString());
|
||||
expect(diffDocs(a, a).empty).toBe(true);
|
||||
});
|
||||
|
||||
it("names separators", () => {
|
||||
expect(separatorOf("crlf")).toBe("\r\n");
|
||||
expect(separatorOf("cr")).toBe("\r");
|
||||
expect(separatorOf("lf")).toBe("\n");
|
||||
expect(separatorOf("?")).toBe("\n");
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue