M2.2: PHP highlighting, syntax colour tokens and editor.reveal
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
f13a49064d
commit
6c75c08d70
25 changed files with 1044 additions and 33 deletions
|
|
@ -16,8 +16,17 @@
|
|||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codemirror/lang-css": "^6.3.1",
|
||||
"@codemirror/lang-html": "^6.4.12",
|
||||
"@codemirror/lang-javascript": "^6.2.5",
|
||||
"@codemirror/lang-json": "^6.0.2",
|
||||
"@codemirror/lang-markdown": "^6.5.2",
|
||||
"@codemirror/lang-php": "^6.0.2",
|
||||
"@codemirror/lang-yaml": "^6.1.3",
|
||||
"@codemirror/language": "^6.13.1",
|
||||
"@codemirror/state": "^6.7.6",
|
||||
"@codemirror/view": "^6.43.14",
|
||||
"@lezer/highlight": "^1.2.5",
|
||||
"@lucide/vue": "^1.57.0",
|
||||
"@tauri-apps/api": "^2.12.3",
|
||||
"codemirror": "^6.0.2",
|
||||
|
|
|
|||
173
ui/pnpm-lock.yaml
generated
173
ui/pnpm-lock.yaml
generated
|
|
@ -8,12 +8,39 @@ importers:
|
|||
|
||||
.:
|
||||
dependencies:
|
||||
'@codemirror/lang-css':
|
||||
specifier: ^6.3.1
|
||||
version: 6.3.1
|
||||
'@codemirror/lang-html':
|
||||
specifier: ^6.4.12
|
||||
version: 6.4.12
|
||||
'@codemirror/lang-javascript':
|
||||
specifier: ^6.2.5
|
||||
version: 6.2.5
|
||||
'@codemirror/lang-json':
|
||||
specifier: ^6.0.2
|
||||
version: 6.0.2
|
||||
'@codemirror/lang-markdown':
|
||||
specifier: ^6.5.2
|
||||
version: 6.5.2
|
||||
'@codemirror/lang-php':
|
||||
specifier: ^6.0.2
|
||||
version: 6.0.2
|
||||
'@codemirror/lang-yaml':
|
||||
specifier: ^6.1.3
|
||||
version: 6.1.3
|
||||
'@codemirror/language':
|
||||
specifier: ^6.13.1
|
||||
version: 6.13.1
|
||||
'@codemirror/state':
|
||||
specifier: ^6.7.6
|
||||
version: 6.7.6
|
||||
'@codemirror/view':
|
||||
specifier: ^6.43.14
|
||||
version: 6.43.14
|
||||
'@lezer/highlight':
|
||||
specifier: ^1.2.5
|
||||
version: 1.2.5
|
||||
'@lucide/vue':
|
||||
specifier: ^1.57.0
|
||||
version: 1.57.0(vue@3.5.44(typescript@6.0.3))
|
||||
|
|
@ -116,6 +143,27 @@ packages:
|
|||
'@codemirror/commands@6.11.1':
|
||||
resolution: {integrity: sha512-O/4hG3SC1YwcmQ0d2UVNDs+AsaNWd1iHVxbTeEBuqH+6bExAiPK3iS/BvpY6rZGURALv4ZD3sIgcCmRvw3ehBg==}
|
||||
|
||||
'@codemirror/lang-css@6.3.1':
|
||||
resolution: {integrity: sha512-kr5fwBGiGtmz6l0LSJIbno9QrifNMUusivHbnA1H6Dmqy4HZFte3UAICix1VuKo0lMPKQr2rqB+0BkKi/S3Ejg==}
|
||||
|
||||
'@codemirror/lang-html@6.4.12':
|
||||
resolution: {integrity: sha512-pw2ReWKUqSkbvh76RAT4NYxiogRu+PWkR2ukAwO9uOgrm8uipkzjtKKtNpyeAQwHOqxEeSvAXZ6vr3AfyB9y/w==}
|
||||
|
||||
'@codemirror/lang-javascript@6.2.5':
|
||||
resolution: {integrity: sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A==}
|
||||
|
||||
'@codemirror/lang-json@6.0.2':
|
||||
resolution: {integrity: sha512-x2OtO+AvwEHrEwR0FyyPtfDUiloG3rnVTSZV1W8UteaLL8/MajQd8DpvUb2YVzC+/T18aSDv0H9mu+xw0EStoQ==}
|
||||
|
||||
'@codemirror/lang-markdown@6.5.2':
|
||||
resolution: {integrity: sha512-AwBOdkWYuA//WcM0xO5PfHPUcmz/O2i5o0Nsg1U69SII/loCJlFI1Romd9xp2HYb1kYJRGZotyqRghuHH5n8Kw==}
|
||||
|
||||
'@codemirror/lang-php@6.0.2':
|
||||
resolution: {integrity: sha512-ZKy2v1n8Fc8oEXj0Th0PUMXzQJ0AIR6TaZU+PbDHExFwdu+guzOA4jmCHS1Nz4vbFezwD7LyBdDnddSJeScMCA==}
|
||||
|
||||
'@codemirror/lang-yaml@6.1.3':
|
||||
resolution: {integrity: sha512-AZ8DJBuXGVHybpBQhmZtgew5//4hv3tdkXnr3vDmOUMJRuB6vn/uuwtmTOTlqEaQFg3hQSVeA90NmvIQyUV6FQ==}
|
||||
|
||||
'@codemirror/language@6.13.1':
|
||||
resolution: {integrity: sha512-zfvU2r3TyylQLMj/te+5CnQ0rSqZi8B1oTCBbQkagcLW4Xc6imab6qN+pEJhsuNOLaJqiRyBXp9UhWA1DhVvDw==}
|
||||
|
||||
|
|
@ -260,12 +308,33 @@ packages:
|
|||
'@lezer/common@1.5.3':
|
||||
resolution: {integrity: sha512-H0iErY4e43LpXbYDyBci5W4v/RwTgGV3YzYOlJPiGZ8RY8w51kVE+xLn1tg3Z6UmSfyETvtsUK3r7YsgDQEI7Q==}
|
||||
|
||||
'@lezer/css@1.3.9':
|
||||
resolution: {integrity: sha512-ZmzgvTOBdJWGIsY/ItAfN7UW8DV802oZG+jeG6E508SwEzz5YhuAajptpWPICvIyqYAD2+VjMdOS40GgGkyEOQ==}
|
||||
|
||||
'@lezer/highlight@1.2.5':
|
||||
resolution: {integrity: sha512-O1GMVKgtf5YspFaRzpmqkVgMtIk2HG9uMAbH6wdAIdNh3TVzCsch/+cRi+6l2//UGDKe6NB9BW3cvuR5ezMQ0w==}
|
||||
|
||||
'@lezer/html@1.3.13':
|
||||
resolution: {integrity: sha512-oI7n6NJml729m7pjm9lvLvmXbdoMoi2f+1pwSDJkl9d68zGr7a9Btz8NdHTGQZtW2DA25ybeuv/SyDb9D5tseg==}
|
||||
|
||||
'@lezer/javascript@1.5.6':
|
||||
resolution: {integrity: sha512-sEvOqpl4vJQca0NugSQK02vQPbc5KrvoojnYGoqqFgFO0MtcYhwGiHKVEB+LuXYJnfyXo4QPA8ztbrEa4Fw5NA==}
|
||||
|
||||
'@lezer/json@1.0.3':
|
||||
resolution: {integrity: sha512-BP9KzdF9Y35PDpv04r0VeSTKDeox5vVr3efE7eBbx3r4s3oNLfunchejZhjArmeieBH+nVOpgIiBJpEAv8ilqQ==}
|
||||
|
||||
'@lezer/lr@1.4.11':
|
||||
resolution: {integrity: sha512-UwgZcl1R66H2hDzBrA7kWyYmX6s8p5TQ+e/t7CuvgCtBEPxbEPaHYHu+pJBvTvDotEJpuQkJjbXuHiw5Cixxgw==}
|
||||
|
||||
'@lezer/markdown@1.8.0':
|
||||
resolution: {integrity: sha512-X6w3A2NpyhdtGqTWRJB8gR4QDXBaFMbTOs780ZdZ15KKCfBXOQTKcB3Vr+W6tqJHVlealt53tLmHRvOqPTQgYA==}
|
||||
|
||||
'@lezer/php@1.0.6':
|
||||
resolution: {integrity: sha512-QJ2xNXPmsm/Z3IpThq8fnJrEIVpxhsIoj6GZBW0JYEd/l9zxpJZW216X4fzqQY4vgpdGIumypvI4uQjd4tnYtw==}
|
||||
|
||||
'@lezer/yaml@1.0.4':
|
||||
resolution: {integrity: sha512-2lrrHqxalACEbxIbsjhqGpSW8kWpUKuY6RHgnSAFZa6qK62wvnPxA8hGOwOoDbwHcOFs5M4o27mjGu+P7TvBmw==}
|
||||
|
||||
'@lucide/vue@1.57.0':
|
||||
resolution: {integrity: sha512-l/D9mr+8Wb8uHl2vzHfcGVRkunJnq0NDmv8HFwXAL3UiYYxuNpDSd1uaCVqeR8+I1XY70dWA+R5W/pSpXWilMw==}
|
||||
peerDependencies:
|
||||
|
|
@ -1361,6 +1430,69 @@ snapshots:
|
|||
'@codemirror/view': 6.43.14
|
||||
'@lezer/common': 1.5.3
|
||||
|
||||
'@codemirror/lang-css@6.3.1':
|
||||
dependencies:
|
||||
'@codemirror/autocomplete': 6.20.3
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/css': 1.3.9
|
||||
|
||||
'@codemirror/lang-html@6.4.12':
|
||||
dependencies:
|
||||
'@codemirror/autocomplete': 6.20.3
|
||||
'@codemirror/lang-css': 6.3.1
|
||||
'@codemirror/lang-javascript': 6.2.5
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/css': 1.3.9
|
||||
'@lezer/html': 1.3.13
|
||||
|
||||
'@codemirror/lang-javascript@6.2.5':
|
||||
dependencies:
|
||||
'@codemirror/autocomplete': 6.20.3
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/lint': 6.9.7
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/javascript': 1.5.6
|
||||
|
||||
'@codemirror/lang-json@6.0.2':
|
||||
dependencies:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@lezer/json': 1.0.3
|
||||
|
||||
'@codemirror/lang-markdown@6.5.2':
|
||||
dependencies:
|
||||
'@codemirror/autocomplete': 6.20.3
|
||||
'@codemirror/lang-html': 6.4.12
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/markdown': 1.8.0
|
||||
|
||||
'@codemirror/lang-php@6.0.2':
|
||||
dependencies:
|
||||
'@codemirror/lang-html': 6.4.12
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/php': 1.0.6
|
||||
|
||||
'@codemirror/lang-yaml@6.1.3':
|
||||
dependencies:
|
||||
'@codemirror/autocomplete': 6.20.3
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
'@lezer/yaml': 1.0.4
|
||||
|
||||
'@codemirror/language@6.13.1':
|
||||
dependencies:
|
||||
'@codemirror/state': 6.7.6
|
||||
|
|
@ -1491,14 +1623,55 @@ snapshots:
|
|||
|
||||
'@lezer/common@1.5.3': {}
|
||||
|
||||
'@lezer/css@1.3.9':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
|
||||
'@lezer/highlight@1.2.5':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
|
||||
'@lezer/html@1.3.13':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
|
||||
'@lezer/javascript@1.5.6':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
|
||||
'@lezer/json@1.0.3':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
|
||||
'@lezer/lr@1.4.11':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
|
||||
'@lezer/markdown@1.8.0':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
|
||||
'@lezer/php@1.0.6':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
|
||||
'@lezer/yaml@1.0.4':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
|
||||
'@lucide/vue@1.57.0(vue@3.5.44(typescript@6.0.3))':
|
||||
dependencies:
|
||||
vue: 3.5.44(typescript@6.0.3)
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ export interface UiCommandSpec {
|
|||
|
||||
/** The frontend's UI commands. */
|
||||
export const UI_COMMANDS: readonly UiCommandSpec[] = [
|
||||
{ id: "editor.reveal", labelKey: "command.editor.reveal" },
|
||||
{ id: "palette.open", labelKey: "command.palette.open", defaultShortcut: "Mod+Shift+P" },
|
||||
{ id: "settings.open", labelKey: "command.settings.open", defaultShortcut: "Mod+," },
|
||||
{ id: "view.toggleProjectTree", labelKey: "command.view.toggleProjectTree", defaultShortcut: "Mod+1" },
|
||||
|
|
|
|||
|
|
@ -5,7 +5,8 @@
|
|||
*
|
||||
* Save, save all and close run through the global keymap and the
|
||||
* palette (`commands/store.ts`): the area supplies their behaviour with the
|
||||
* active buffer as context and says when they can run.
|
||||
* active buffer as context and says when they can run. It also supplies the
|
||||
* UI command `editor.reveal` (`reveal.ts`).
|
||||
*/
|
||||
import { onBeforeUnmount, onMounted } from "vue";
|
||||
import { useCommandsStore } from "../../commands/store";
|
||||
|
|
@ -14,6 +15,7 @@ import { useEditorStore } from "../../stores/editor";
|
|||
import ClosePrompt from "./ClosePrompt.vue";
|
||||
import CodeEditor from "./CodeEditor.vue";
|
||||
import EditorTabs from "./EditorTabs.vue";
|
||||
import { reveal, REVEAL_COMMAND } from "./reveal";
|
||||
|
||||
const editor = useEditorStore();
|
||||
const commands = useCommandsStore();
|
||||
|
|
@ -28,6 +30,7 @@ onMounted(() => {
|
|||
commands.provide("file.save", { run: async () => { await editor.save(); }, enabled: hasActive }),
|
||||
commands.provide("file.saveAll", { run: () => editor.saveAll(), enabled: () => editor.tabs.length > 0 }),
|
||||
commands.provide("buffer.close", { run: () => editor.requestClose(), enabled: hasActive }),
|
||||
commands.provide(REVEAL_COMMAND, { run: (params) => reveal(editor, params) }),
|
||||
];
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -212,3 +212,25 @@ export function diffDocs(from: Text, to: Text): ChangeSet {
|
|||
a.length,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The CodeMirror position of an engine `{line, column}` position.
|
||||
*
|
||||
* Engine lines are split at the same breaks CodeMirror recognises, and a
|
||||
* `\r\n` counts as one break on both sides, so line numbers carry over
|
||||
* unchanged; the column counts UTF-16 code units inside the line, which is
|
||||
* the same in both. A line past the end selects the last line, a column past
|
||||
* the line's end (into a `\r\n`, say) its end, and negative or fractional
|
||||
* values are clamped and truncated (non-finite ones count as 0). Converting the result back with
|
||||
* {@link EngineText.toEngine} yields the engine offset.
|
||||
*
|
||||
* @param doc - the CodeMirror document.
|
||||
* @param line - 0-based line.
|
||||
* @param column - 0-based column in UTF-16 code units.
|
||||
* @returns the position in `doc`.
|
||||
*/
|
||||
export function positionOf(doc: Text, line: number, column: number): number {
|
||||
const whole = (n: number): number => (Number.isFinite(n) ? Math.max(Math.trunc(n), 0) : 0);
|
||||
const target = doc.line(Math.min(whole(line) + 1, doc.lines));
|
||||
return target.from + Math.min(whole(column), target.length);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
/**
|
||||
* 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, including
|
||||
* history, selection, brackets, search), the file's language and syntax
|
||||
* highlighting (`language.ts`), and a theme that takes every colour from
|
||||
* `--lt-*` tokens, including the syntax tokens (`--lt-syntax-*`) and
|
||||
* the editor tokens (`--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`).
|
||||
|
|
@ -9,6 +10,25 @@
|
|||
import { EditorView } from "@codemirror/view";
|
||||
import type { Extension } from "@codemirror/state";
|
||||
import { basicSetup } from "codemirror";
|
||||
import { languageExtensions, type SYNTAX_CLASS, type SyntaxToken } from "./language";
|
||||
|
||||
/**
|
||||
* Colours of the highlight classes (`language.ts`), one `--lt-syntax-*`
|
||||
* token each, spelled out so the theme tests can check every token name.
|
||||
*/
|
||||
const syntaxColours: Record<`.${typeof SYNTAX_CLASS}${SyntaxToken}`, { color: string }> = {
|
||||
".lt-syntax-keyword": { color: "var(--lt-syntax-keyword)" },
|
||||
".lt-syntax-string": { color: "var(--lt-syntax-string)" },
|
||||
".lt-syntax-number": { color: "var(--lt-syntax-number)" },
|
||||
".lt-syntax-comment": { color: "var(--lt-syntax-comment)" },
|
||||
".lt-syntax-variable": { color: "var(--lt-syntax-variable)" },
|
||||
".lt-syntax-function": { color: "var(--lt-syntax-function)" },
|
||||
".lt-syntax-type": { color: "var(--lt-syntax-type)" },
|
||||
".lt-syntax-constant": { color: "var(--lt-syntax-constant)" },
|
||||
".lt-syntax-tag": { color: "var(--lt-syntax-tag)" },
|
||||
".lt-syntax-attribute": { color: "var(--lt-syntax-attribute)" },
|
||||
".lt-syntax-operator": { color: "var(--lt-syntax-operator)" },
|
||||
};
|
||||
|
||||
/** Editor theme built from theme tokens only. */
|
||||
export const lutraEditorTheme: Extension = EditorView.theme({
|
||||
|
|
@ -80,9 +100,15 @@ export const lutraEditorTheme: Extension = EditorView.theme({
|
|||
color: "var(--lt-fg)",
|
||||
border: "1px solid var(--lt-border)",
|
||||
},
|
||||
...syntaxColours,
|
||||
});
|
||||
|
||||
/** Every extension of an editor state. */
|
||||
export function editorExtensions(): Extension {
|
||||
return [basicSetup, lutraEditorTheme];
|
||||
/**
|
||||
* Every extension of an editor state.
|
||||
*
|
||||
* @param path - the file's path, which picks the language; plain text when
|
||||
* omitted or unknown.
|
||||
*/
|
||||
export function editorExtensions(path = ""): Extension {
|
||||
return [basicSetup, lutraEditorTheme, languageExtensions(path)];
|
||||
}
|
||||
|
|
|
|||
167
ui/src/components/editor/language.ts
Normal file
167
ui/src/components/editor/language.ts
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
/**
|
||||
* Language support of an editor tab, picked once from the file extension
|
||||
* when the tab opens.
|
||||
*
|
||||
* Every parser is a Lezer grammar from the `@codemirror/lang-*` packages
|
||||
* (MIT). PHP files use `@codemirror/lang-php`, which also parses the HTML
|
||||
* (with its CSS and JavaScript) around `<?php … ?>` blocks. Unknown
|
||||
* extensions stay plain text. The colours come from {@link lutraHighlighting}.
|
||||
*/
|
||||
import type { Extension } from "@codemirror/state";
|
||||
import { syntaxHighlighting } from "@codemirror/language";
|
||||
import { tagHighlighter, tags } from "@lezer/highlight";
|
||||
import { css } from "@codemirror/lang-css";
|
||||
import { html } from "@codemirror/lang-html";
|
||||
import { javascript } from "@codemirror/lang-javascript";
|
||||
import { json } from "@codemirror/lang-json";
|
||||
import { markdown } from "@codemirror/lang-markdown";
|
||||
import { php } from "@codemirror/lang-php";
|
||||
import { yaml } from "@codemirror/lang-yaml";
|
||||
|
||||
/** Languages the editor knows. */
|
||||
export type LanguageId = "php" | "html" | "css" | "javascript" | "typescript" | "json" | "yaml" | "markdown";
|
||||
|
||||
/** Language by lower-case file extension (without the dot). */
|
||||
const BY_EXTENSION: Readonly<Record<string, LanguageId>> = {
|
||||
php: "php",
|
||||
phtml: "php",
|
||||
php3: "php",
|
||||
php4: "php",
|
||||
php5: "php",
|
||||
php7: "php",
|
||||
php8: "php",
|
||||
phps: "php",
|
||||
inc: "php",
|
||||
html: "html",
|
||||
htm: "html",
|
||||
css: "css",
|
||||
js: "javascript",
|
||||
mjs: "javascript",
|
||||
cjs: "javascript",
|
||||
jsx: "javascript",
|
||||
ts: "typescript",
|
||||
mts: "typescript",
|
||||
cts: "typescript",
|
||||
tsx: "typescript",
|
||||
json: "json",
|
||||
yaml: "yaml",
|
||||
yml: "yaml",
|
||||
md: "markdown",
|
||||
markdown: "markdown",
|
||||
};
|
||||
|
||||
/**
|
||||
* The language of a file.
|
||||
*
|
||||
* @param path - the file's path; only the extension after the last `.` of
|
||||
* the file name counts, case-insensitively.
|
||||
* @returns the language, or null for plain text.
|
||||
*/
|
||||
export function languageOf(path: string): LanguageId | null {
|
||||
const name = path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1);
|
||||
const dot = name.lastIndexOf(".");
|
||||
if (dot <= 0) {
|
||||
return null;
|
||||
}
|
||||
return BY_EXTENSION[name.slice(dot + 1).toLowerCase()] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The CodeMirror support of a language.
|
||||
*
|
||||
* @param id - the language.
|
||||
*/
|
||||
function supportOf(id: LanguageId): Extension {
|
||||
switch (id) {
|
||||
case "php":
|
||||
return php();
|
||||
case "html":
|
||||
return html();
|
||||
case "css":
|
||||
return css();
|
||||
case "javascript":
|
||||
return javascript({ jsx: true });
|
||||
case "typescript":
|
||||
return javascript({ jsx: true, typescript: true });
|
||||
case "json":
|
||||
return json();
|
||||
case "yaml":
|
||||
return yaml();
|
||||
case "markdown":
|
||||
return markdown();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Highlight class prefix: a highlighted span carries `lt-syntax-<token>`,
|
||||
* and the editor theme colours it with the token `--lt-syntax-<token>`.
|
||||
*/
|
||||
export const SYNTAX_CLASS = "lt-syntax-";
|
||||
|
||||
/** Syntax token names, as `SYNTAX_TOKENS` in `crates/engine/src/theme.rs`. */
|
||||
export const SYNTAX_TOKENS = [
|
||||
"keyword",
|
||||
"string",
|
||||
"number",
|
||||
"comment",
|
||||
"variable",
|
||||
"function",
|
||||
"type",
|
||||
"constant",
|
||||
"tag",
|
||||
"attribute",
|
||||
"operator",
|
||||
] as const;
|
||||
|
||||
/** A syntax token name. */
|
||||
export type SyntaxToken = (typeof SYNTAX_TOKENS)[number];
|
||||
|
||||
/**
|
||||
* Lezer highlight tags and the token each one is drawn with. A tag that is
|
||||
* not listed falls back to its parent (`tags.controlKeyword` to
|
||||
* `tags.keyword`, `tags.function(tags.variableName)` to
|
||||
* `tags.variableName`); one without a listed ancestor keeps the text colour.
|
||||
*/
|
||||
const TAG_TOKENS: readonly [SyntaxToken, Parameters<typeof tagHighlighter>[0][number]["tag"]][] = [
|
||||
["keyword", [tags.keyword, tags.modifier, tags.self, tags.heading]],
|
||||
["string", [tags.string, tags.regexp, tags.character, tags.link, tags.url]],
|
||||
["number", [tags.number]],
|
||||
["comment", [tags.comment, tags.meta]],
|
||||
["variable", [tags.variableName, tags.propertyName, tags.labelName]],
|
||||
[
|
||||
"function",
|
||||
[
|
||||
tags.function(tags.variableName),
|
||||
tags.function(tags.propertyName),
|
||||
tags.function(tags.definition(tags.variableName)),
|
||||
tags.macroName,
|
||||
],
|
||||
],
|
||||
["type", [tags.typeName, tags.className, tags.namespace]],
|
||||
[
|
||||
"constant",
|
||||
[tags.bool, tags.null, tags.atom, tags.constant(tags.variableName), tags.constant(tags.propertyName), tags.escape],
|
||||
],
|
||||
["tag", [tags.tagName, tags.angleBracket, tags.processingInstruction]],
|
||||
["attribute", [tags.attributeName]],
|
||||
["operator", [tags.operator, tags.derefOperator]],
|
||||
];
|
||||
|
||||
/**
|
||||
* Highlighting that marks spans with `lt-syntax-<token>` classes only, so
|
||||
* every colour comes from a theme token.
|
||||
*/
|
||||
export const lutraHighlighting: Extension = syntaxHighlighting(
|
||||
tagHighlighter(TAG_TOKENS.map(([token, tag]) => ({ tag, class: `${SYNTAX_CLASS}${token}` }))),
|
||||
);
|
||||
|
||||
/**
|
||||
* Editor extensions for a file: its language support (if any) and the
|
||||
* Lutra highlighting.
|
||||
*
|
||||
* @param path - the file's path.
|
||||
*/
|
||||
export function languageExtensions(path: string): Extension {
|
||||
const id = languageOf(path);
|
||||
return id === null ? [] : [supportOf(id), lutraHighlighting];
|
||||
}
|
||||
88
ui/src/components/editor/reveal.ts
Normal file
88
ui/src/components/editor/reveal.ts
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
/**
|
||||
* The UI command `editor.reveal {path, line, column}`: shows a position in
|
||||
* the editor. It opens the file (`file.open`) unless a tab has it,
|
||||
* activates the tab, places the cursor and scrolls it to the centre.
|
||||
*
|
||||
* Positions follow the C3 contract: `line` is 0-based and `column` counts
|
||||
* UTF-16 code units inside the line, converted to a CodeMirror position by
|
||||
* {@link positionOf} (CRLF-safe). Out-of-range values are clamped. Without
|
||||
* a `path` it centres the cursor of the active tab, which is what running
|
||||
* it from the palette does. The Find, Go-to and Structure windows and
|
||||
* agents (`uiCommand`) call it.
|
||||
*/
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { nextTick } from "vue";
|
||||
import { t } from "../../i18n";
|
||||
import type { useEditorStore } from "../../stores/editor";
|
||||
import { positionOf } from "./engineText";
|
||||
|
||||
/** Command id of the reveal command. */
|
||||
export const REVEAL_COMMAND = "editor.reveal";
|
||||
|
||||
/** A position to reveal. */
|
||||
export interface RevealTarget {
|
||||
/** File path as `file.open` takes it; null for the active tab. */
|
||||
path: string | null;
|
||||
/** 0-based line; null keeps the cursor. */
|
||||
line: number | null;
|
||||
/** 0-based column in UTF-16 code units. */
|
||||
column: number;
|
||||
}
|
||||
|
||||
/** The editor store as reveal uses it. */
|
||||
type EditorStore = ReturnType<typeof useEditorStore>;
|
||||
|
||||
/**
|
||||
* Reads the params of `editor.reveal`.
|
||||
*
|
||||
* @param params - untrusted params from the engine, the palette or a caller.
|
||||
* @returns the target, or null if a field has the wrong type.
|
||||
*/
|
||||
export function parseReveal(params: unknown): RevealTarget | null {
|
||||
const p = typeof params === "object" && params !== null && !Array.isArray(params) ? (params as Record<string, unknown>) : {};
|
||||
const number = (value: unknown): number | null | undefined =>
|
||||
value === undefined || value === null ? null : typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
||||
const path = p.path === undefined || p.path === null ? null : typeof p.path === "string" && p.path !== "" ? p.path : undefined;
|
||||
const line = number(p.line);
|
||||
const column = number(p.column);
|
||||
if (path === undefined || line === undefined || column === undefined) {
|
||||
return null;
|
||||
}
|
||||
return { path, line, column: column ?? 0 };
|
||||
}
|
||||
|
||||
/**
|
||||
* Reveals a position.
|
||||
*
|
||||
* @param editor - the editor store.
|
||||
* @param params - the command params, see {@link parseReveal}.
|
||||
* @throws Error with a catalog message when the params are invalid or the
|
||||
* file cannot be opened; the command store shows it as an error toast.
|
||||
*/
|
||||
export async function reveal(editor: EditorStore, params: unknown): Promise<void> {
|
||||
const target = parseReveal(params);
|
||||
if (!target) {
|
||||
throw new Error(t("editor.reveal.invalidParams"));
|
||||
}
|
||||
let id = editor.activeId;
|
||||
if (target.path !== null) {
|
||||
const path = target.path;
|
||||
id = editor.tabs.find((tab) => tab.path === path)?.id ?? (await editor.openFile(path));
|
||||
if (id === null) {
|
||||
throw new Error(editor.lastError?.message ?? t("editor.reveal.openFailed", { path }));
|
||||
}
|
||||
editor.activate(id);
|
||||
await nextTick();
|
||||
}
|
||||
const sync = id === null ? undefined : editor.syncOf(id);
|
||||
if (!sync) {
|
||||
return;
|
||||
}
|
||||
const state = sync.state;
|
||||
const pos = target.line === null ? state.selection.main.head : positionOf(state.doc, target.line, target.column);
|
||||
sync.dispatch({
|
||||
selection: { anchor: pos },
|
||||
effects: EditorView.scrollIntoView(pos, { y: "center" }),
|
||||
userEvent: "select.reveal",
|
||||
});
|
||||
}
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
{
|
||||
"app.statusBar.version": "{name} {version}",
|
||||
"command.editor.reveal": "Reveal Cursor in Editor",
|
||||
"command.key.alt": "Alt",
|
||||
"command.key.cmd": "Cmd",
|
||||
"command.key.ctrl": "Ctrl",
|
||||
|
|
@ -21,6 +22,8 @@
|
|||
"editor.closePrompt.question": "Save changes to {name} before closing?",
|
||||
"editor.notice.changedOnDisk": "{name} changed on disk. Your unsaved changes are kept; saving overwrites the file.",
|
||||
"editor.notice.removedOnDisk": "{name} was deleted on disk. Your text is kept; saving writes it again.",
|
||||
"editor.reveal.invalidParams": "editor.reveal needs a path (string), line and column (numbers)",
|
||||
"editor.reveal.openFailed": "could not open {path}",
|
||||
"editor.saveFailed": "save failed",
|
||||
"editor.tabs.close": "Close {name}",
|
||||
"editor.tabs.label": "Editor tabs",
|
||||
|
|
|
|||
|
|
@ -107,8 +107,8 @@ export const useEditorStore = defineStore("editor", () => {
|
|||
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;
|
||||
/** Extensions of a new editor state for a file path, replaceable in tests. */
|
||||
let extensions: (path: string) => Extension = editorExtensions;
|
||||
/** Counter of tab adoptions, so only the newest open activates its tab. */
|
||||
let openSequence = 0;
|
||||
/** Unsubscribe function of the event subscription. */
|
||||
|
|
@ -139,9 +139,9 @@ export const useEditorStore = defineStore("editor", () => {
|
|||
* Replaces the engine transport and editor extensions (tests).
|
||||
*
|
||||
* @param next - transport for new syncs.
|
||||
* @param nextExtensions - extensions for new editor states.
|
||||
* @param nextExtensions - extensions for new editor states, by file path.
|
||||
*/
|
||||
function configure(next: SyncTransport, nextExtensions?: () => Extension): void {
|
||||
function configure(next: SyncTransport, nextExtensions?: (path: string) => Extension): void {
|
||||
transport = next;
|
||||
if (nextExtensions) {
|
||||
extensions = nextExtensions;
|
||||
|
|
@ -160,7 +160,7 @@ export const useEditorStore = defineStore("editor", () => {
|
|||
const started = openStarted.get(info.path);
|
||||
syncs.set(
|
||||
info.id,
|
||||
new BufferSync(info, extensions(), transport, (error) => {
|
||||
new BufferSync(info, extensions(info.path), transport, (error) => {
|
||||
const tab = tabOf(info.id);
|
||||
if (tab) {
|
||||
tab.notice = { kind: "error", message: error.message };
|
||||
|
|
@ -211,22 +211,25 @@ export const useEditorStore = defineStore("editor", () => {
|
|||
* Opens a file in a tab (or activates its tab).
|
||||
*
|
||||
* @param path - project-relative path.
|
||||
* @returns the buffer id of the tab, or null if the open failed
|
||||
* ({@link lastError} says why).
|
||||
*/
|
||||
async function openFile(path: string): Promise<void> {
|
||||
async function openFile(path: string): Promise<number | null> {
|
||||
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;
|
||||
return null;
|
||||
}
|
||||
if (!isBufferInfo(result.value)) {
|
||||
lastError.value = { code: "ipc", message: t("common.error.unexpectedResult", { command: EDITOR_COMMANDS.open }) };
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
lastError.value = null;
|
||||
openSequence += 1;
|
||||
adopt(result.value);
|
||||
return result.value.id;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -4,7 +4,8 @@
|
|||
* `buffer.edit`, the dirty marker, closing (middle click, shortcut, the
|
||||
* Save / Don't Save / Cancel question), saving through the global keymap
|
||||
* (`commands/store.ts`) with shortcuts loaded from the engine's command
|
||||
* list, and the notice for files changed on disk.
|
||||
* list, the notice for files changed on disk, and the UI command
|
||||
* `editor.reveal` (open and closed files, CRLF text, bad params).
|
||||
* The engine is a fake behind the mocked Tauri `invoke`.
|
||||
*/
|
||||
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
|
||||
|
|
@ -21,6 +22,7 @@ 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";
|
||||
import { useNotificationsStore } from "../../src/stores/notifications";
|
||||
|
||||
/** A buffer of the fake engine. */
|
||||
interface FakeBuffer {
|
||||
|
|
@ -47,7 +49,14 @@ let calls: { command: string; params: Record<string, unknown> }[];
|
|||
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" }
|
||||
? {
|
||||
id,
|
||||
path: b.path,
|
||||
text: b.text,
|
||||
version: b.version,
|
||||
dirty: b.version !== b.saved,
|
||||
lineEnding: b.text.includes("\r\n") ? "crlf" : "lf",
|
||||
}
|
||||
: null;
|
||||
}
|
||||
|
||||
|
|
@ -473,3 +482,96 @@ describe("EditorArea", () => {
|
|||
expect(timing?.stateMs).toBeLessThan(2000);
|
||||
});
|
||||
});
|
||||
|
||||
describe("editor.reveal", () => {
|
||||
beforeEach(() => {
|
||||
disk["c.php"] = "<?php\nfunction a() {}\n\n $x = 'ü😀z';\n";
|
||||
disk["w.php"] = "<?php\r\n$a = 1;\r\n$b = 2;\r\n";
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("opens a closed file, activates it, places the cursor and centres it", async () => {
|
||||
const scroll = vi.spyOn(EditorView, "scrollIntoView");
|
||||
const area = await mountArea();
|
||||
const editor = useEditorStore(pinia);
|
||||
await editor.openFile("a.php");
|
||||
await flushPromises();
|
||||
await useCommandsStore(pinia).dispatch("editor.reveal", { path: "c.php", line: 3, column: 9 });
|
||||
await flushPromises();
|
||||
expect(calls.filter((c) => c.command === "file.open").map((c) => c.params.path)).toEqual(["a.php", "c.php"]);
|
||||
expect(editor.activeTab?.path).toBe("c.php");
|
||||
const view = viewOf(area);
|
||||
const head = view.state.selection.main.head;
|
||||
expect(view.state.doc.lineAt(head).number).toBe(4);
|
||||
expect(view.state.sliceDoc(head, head + 3)).toBe("😀z");
|
||||
expect(scroll).toHaveBeenLastCalledWith(head, { y: "center" });
|
||||
});
|
||||
|
||||
it("activates an open tab without opening the file again", async () => {
|
||||
const area = await mountArea();
|
||||
const editor = useEditorStore(pinia);
|
||||
await editor.openFile("c.php");
|
||||
await editor.openFile("b.txt");
|
||||
await flushPromises();
|
||||
await useCommandsStore(pinia).execute("editor.reveal", { path: "c.php", line: 1, column: 9 });
|
||||
await flushPromises();
|
||||
expect(calls.filter((c) => c.command === "file.open")).toHaveLength(2);
|
||||
expect(editor.activeTab?.path).toBe("c.php");
|
||||
expect(viewOf(area).state.selection.main.head).toBe(6 + 9);
|
||||
});
|
||||
|
||||
it("maps positions in CRLF text through the engine line breaks", async () => {
|
||||
const area = await mountArea();
|
||||
const editor = useEditorStore(pinia);
|
||||
await useCommandsStore(pinia).dispatch("editor.reveal", { path: "w.php", line: 2, column: 1 });
|
||||
await flushPromises();
|
||||
const view = viewOf(area);
|
||||
const head = view.state.selection.main.head;
|
||||
expect(head).toBe(15);
|
||||
expect(view.state.sliceDoc(head, head + 1)).toBe("b");
|
||||
const engineText = disk["w.php"] ?? "";
|
||||
const crlfBefore = engineText.slice(0, 16).split("\r\n").length - 1;
|
||||
expect(engineText.charAt(head + crlfBefore)).toBe("b");
|
||||
expect(editor.activeTab?.path).toBe("w.php");
|
||||
});
|
||||
|
||||
it("clamps positions past the end", async () => {
|
||||
const area = await mountArea();
|
||||
await useCommandsStore(pinia).dispatch("editor.reveal", { path: "w.php", line: 0, column: 99 });
|
||||
await flushPromises();
|
||||
expect(viewOf(area).state.selection.main.head).toBe(5);
|
||||
await useCommandsStore(pinia).dispatch("editor.reveal", { path: "w.php", line: 99, column: 0 });
|
||||
await flushPromises();
|
||||
expect(viewOf(area).state.selection.main.head).toBe(viewOf(area).state.doc.length);
|
||||
});
|
||||
|
||||
it("centres the cursor of the active tab without a path (palette)", async () => {
|
||||
const scroll = vi.spyOn(EditorView, "scrollIntoView");
|
||||
const area = await mountArea();
|
||||
await useEditorStore(pinia).openFile("c.php");
|
||||
await flushPromises();
|
||||
viewOf(area).dispatch({ selection: { anchor: 8 } });
|
||||
await useCommandsStore(pinia).execute("editor.reveal");
|
||||
await flushPromises();
|
||||
expect(viewOf(area).state.selection.main.head).toBe(8);
|
||||
expect(scroll).toHaveBeenLastCalledWith(8, { y: "center" });
|
||||
});
|
||||
|
||||
it("reports bad params and files that cannot be opened", async () => {
|
||||
await mountArea();
|
||||
const commands = useCommandsStore(pinia);
|
||||
await commands.dispatch("editor.reveal", { path: 3, line: 0, column: 0 });
|
||||
await commands.dispatch("editor.reveal", { path: "c.php", line: "1" });
|
||||
await commands.dispatch("editor.reveal", { path: "missing.php", line: 0, column: 0 });
|
||||
await flushPromises();
|
||||
const texts = useNotificationsStore(pinia).toasts.map((t) => t.text);
|
||||
expect(texts).toHaveLength(3);
|
||||
expect(texts[0]).toContain("needs a path");
|
||||
expect(texts[1]).toContain("needs a path");
|
||||
expect(texts[2]).toContain("not_found");
|
||||
expect(useEditorStore(pinia).tabs).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@
|
|||
*/
|
||||
import { ChangeSet, Text } from "@codemirror/state";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { diffDocs, EngineText, separatorOf } from "../../src/components/editor/engineText";
|
||||
import { diffDocs, EngineText, positionOf, separatorOf } from "../../src/components/editor/engineText";
|
||||
|
||||
describe("EngineText", () => {
|
||||
it("maps positions past CRLF breaks and keeps mixed endings", () => {
|
||||
|
|
@ -56,3 +56,26 @@ describe("EngineText", () => {
|
|||
expect(separatorOf("?")).toBe("\n");
|
||||
});
|
||||
});
|
||||
|
||||
describe("positionOf", () => {
|
||||
it("maps engine line and UTF-16 column to the same text in CRLF and LF documents", () => {
|
||||
for (const engine of ["ab\r\ncd😀e\r\n\r\nf", "ab\ncd😀e\n\nf", "ab\rcd😀e\r\rf"]) {
|
||||
const text = EngineText.fromEngine(engine);
|
||||
const pos = positionOf(text.doc, 1, 4);
|
||||
expect(text.doc.sliceString(pos, pos + 1)).toBe("e");
|
||||
expect(engine.charAt(text.toEngine(pos))).toBe("e");
|
||||
const f = positionOf(text.doc, 3, 0);
|
||||
expect(engine.charAt(text.toEngine(f))).toBe("f");
|
||||
}
|
||||
});
|
||||
|
||||
it("clamps lines and columns into the document", () => {
|
||||
const doc = EngineText.fromEngine("ab\r\ncd").doc;
|
||||
expect(positionOf(doc, 0, 99)).toBe(2);
|
||||
expect(positionOf(doc, 99, 1)).toBe(4);
|
||||
expect(positionOf(doc, -3, -1)).toBe(0);
|
||||
expect(positionOf(doc, 1.8, 1.9)).toBe(4);
|
||||
expect(positionOf(doc, Number.NaN, Number.POSITIVE_INFINITY)).toBe(0);
|
||||
expect(positionOf(Text.empty, 4, 4)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
111
ui/tests/editor/highlightPerf.test.ts
Normal file
111
ui/tests/editor/highlightPerf.test.ts
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
/**
|
||||
* Keystroke-to-highlight on a 1 MB PHP file (budget: < 16 ms, C3 contract).
|
||||
*
|
||||
* Opt-in, since it measures rather than checks behaviour: run it with
|
||||
* `LUTRA_PERF=1 pnpm vitest run tests/editor/highlightPerf.test.ts` on an
|
||||
* idle machine. It builds a 1 MB PHP file, parses it completely once (as the
|
||||
* editor does in the background after opening), then types characters into
|
||||
* a view at the top and in the middle of the file. Each keystroke is one
|
||||
* `view.dispatch`, which runs the incremental Lezer reparse up to the
|
||||
* visible range and redraws the highlighted lines; it also times the
|
||||
* incremental reparse of the whole document after an edit (the background
|
||||
* work the editor spreads over idle time). jsdom has no layout or paint, so
|
||||
* the numbers are the JavaScript work of a keystroke, not the frame.
|
||||
*/
|
||||
import { ensureSyntaxTree, forceParsing, syntaxTree } from "@codemirror/language";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { editorExtensions } from "../../src/components/editor/extensions";
|
||||
|
||||
/** One class of the generated file, about 1 KB. */
|
||||
function chunk(n: number): string {
|
||||
const i = String(n);
|
||||
return [
|
||||
`/** Shop item ${i}. */`,
|
||||
`final class Item${i} extends Base implements \\JsonSerializable`,
|
||||
"{",
|
||||
` public const LIMIT = ${i};`,
|
||||
" private array $tags = ['otter', \"stone\", 'river'];",
|
||||
"",
|
||||
" public function __construct(private int $id, protected ?string $name = null) {}",
|
||||
"",
|
||||
" // Sums the price with tax.",
|
||||
" public function total(float $price, int $count = 1): float",
|
||||
" {",
|
||||
" $sum = $price * $count * 1.19;",
|
||||
" if ($sum > self::LIMIT && $this->name !== null) {",
|
||||
' return round($sum, 2) + strlen("{$this->name}");',
|
||||
" }",
|
||||
" foreach ($this->tags as $k => $tag) { $sum += \\count([$k, $tag]); }",
|
||||
" return $sum;",
|
||||
" }",
|
||||
"",
|
||||
" public function jsonSerialize(): mixed { return ['id' => $this->id, 'name' => $this->name]; }",
|
||||
"}",
|
||||
"",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
/** Median and 95th percentile of samples, in ms. */
|
||||
function stats(samples: number[]): { median: number; p95: number; max: number } {
|
||||
const sorted = [...samples].sort((a, b) => a - b);
|
||||
const at = (q: number): number => sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))] ?? 0;
|
||||
return { median: at(0.5), p95: at(0.95), max: sorted.at(-1) ?? 0 };
|
||||
}
|
||||
|
||||
/**
|
||||
* Types into a view of the text with the extensions of a path.
|
||||
*
|
||||
* @param path - picks the language (`big.php`, or `big.txt` for the plain
|
||||
* text baseline).
|
||||
* @param text - the document.
|
||||
* @returns timings in ms.
|
||||
*/
|
||||
function measure(path: string, text: string): Record<string, unknown> {
|
||||
const view = new EditorView({ state: EditorState.create({ doc: text, extensions: editorExtensions(path) }), parent: document.body });
|
||||
let started = performance.now();
|
||||
forceParsing(view, text.length, 60_000);
|
||||
const fullParseMs = performance.now() - started;
|
||||
const parsed = syntaxTree(view.state).length;
|
||||
const typing = (pos: number, count: number): number[] => {
|
||||
const samples: number[] = [];
|
||||
view.dispatch({ selection: { anchor: pos }, effects: EditorView.scrollIntoView(pos, { y: "center" }) });
|
||||
for (let i = 0; i < count; i += 1) {
|
||||
const at = view.state.selection.main.head;
|
||||
const t0 = performance.now();
|
||||
view.dispatch({ changes: { from: at, insert: i % 10 === 9 ? "\n" : "x" }, selection: { anchor: at + 1 }, userEvent: "input.type" });
|
||||
samples.push(performance.now() - t0);
|
||||
}
|
||||
return samples;
|
||||
};
|
||||
const lineStart = (n: number): number => view.state.doc.line(n).from + 8;
|
||||
typing(lineStart(20), 50);
|
||||
const top = stats(typing(lineStart(30), 300));
|
||||
const middleLine = Math.floor(view.state.doc.lines / 2);
|
||||
typing(lineStart(middleLine - 40), 50);
|
||||
const middle = stats(typing(lineStart(middleLine), 300));
|
||||
const edited = view.state.update({ changes: { from: lineStart(middleLine), insert: "$" } }).state;
|
||||
started = performance.now();
|
||||
ensureSyntaxTree(edited, edited.doc.length, 60_000);
|
||||
const reparseMs = performance.now() - started;
|
||||
view.destroy();
|
||||
return { fullParseMs, keystrokeTop: top, keystrokeMiddle: middle, fullIncrementalReparseMs: reparseMs, parsed };
|
||||
}
|
||||
|
||||
describe.runIf(process.env.LUTRA_PERF)("keystroke to highlight, 1 MB PHP", () => {
|
||||
it("stays within the frame budget", () => {
|
||||
Range.prototype.getClientRects = () => Object.assign([] as DOMRect[], { item: () => null });
|
||||
Range.prototype.getBoundingClientRect = () => new DOMRect(0, 0, 0, 0);
|
||||
let text = "<?php\n\nnamespace App\\Shop;\n\n";
|
||||
for (let i = 0; text.length < 1024 * 1024; i += 1) {
|
||||
text += chunk(i);
|
||||
}
|
||||
const php = measure("big.php", text);
|
||||
const plain = measure("big.txt", text);
|
||||
const round = (_k: string, v: unknown): unknown => (typeof v === "number" ? Math.round(v * 100) / 100 : v);
|
||||
console.log(JSON.stringify({ bytes: text.length, php, plainTextBaseline: plain }, round, 2));
|
||||
expect(php.parsed).toBe(text.length);
|
||||
expect((php.keystrokeMiddle as { median: number }).median).toBeLessThan(16);
|
||||
}, 120_000);
|
||||
});
|
||||
149
ui/tests/editor/language.test.ts
Normal file
149
ui/tests/editor/language.test.ts
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
/**
|
||||
* Tests of the editor's language support (`language.ts`): the language
|
||||
* picked per file extension, and the highlight classes (`lt-syntax-*`) on
|
||||
* the spans CodeMirror draws for PHP, embedded HTML and the other
|
||||
* languages, each coloured by its `--lt-syntax-*` token.
|
||||
*/
|
||||
import { ensureSyntaxTree } from "@codemirror/language";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { editorExtensions, lutraEditorTheme } from "../../src/components/editor/extensions";
|
||||
import { languageOf, SYNTAX_TOKENS } from "../../src/components/editor/language";
|
||||
|
||||
/** Views to destroy after each test. */
|
||||
let views: EditorView[] = [];
|
||||
|
||||
/** jsdom has no layout; give text ranges empty rectangles. */
|
||||
function stubRangeGeometry(): void {
|
||||
const empty = (): DOMRectList => Object.assign([] as DOMRect[], { item: () => null });
|
||||
Range.prototype.getClientRects = empty;
|
||||
Range.prototype.getBoundingClientRect = () => new DOMRect(0, 0, 0, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows a document in a view with the extensions of a file path, parsed
|
||||
* completely.
|
||||
*
|
||||
* @param path - the file path that picks the language.
|
||||
* @param doc - the text.
|
||||
*/
|
||||
function show(path: string, doc: string): EditorView {
|
||||
const state = EditorState.create({ doc, extensions: editorExtensions(path) });
|
||||
ensureSyntaxTree(state, state.doc.length, 5000);
|
||||
const view = new EditorView({ state, parent: document.body });
|
||||
views.push(view);
|
||||
return view;
|
||||
}
|
||||
|
||||
/**
|
||||
* The text of every span with a highlight class, by token.
|
||||
*
|
||||
* @param view - the view.
|
||||
*/
|
||||
function highlighted(view: EditorView): Record<string, string[]> {
|
||||
const out: Record<string, string[]> = {};
|
||||
for (const token of SYNTAX_TOKENS) {
|
||||
const spans = [...view.contentDOM.querySelectorAll(`.lt-syntax-${token}`)];
|
||||
if (spans.length > 0) {
|
||||
out[token] = spans.map((span) => span.textContent);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
stubRangeGeometry();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const view of views) {
|
||||
view.destroy();
|
||||
}
|
||||
views = [];
|
||||
});
|
||||
|
||||
describe("languageOf", () => {
|
||||
it.each([
|
||||
["src/Controller/Home.php", "php"],
|
||||
["templates/view.PHTML", "php"],
|
||||
["legacy\\lib.inc", "php"],
|
||||
["public/index.html", "html"],
|
||||
["assets/app.css", "css"],
|
||||
["assets/app.js", "javascript"],
|
||||
["assets/app.tsx", "typescript"],
|
||||
["composer.json", "json"],
|
||||
["config/services.yaml", "yaml"],
|
||||
[".github/ci.yml", "yaml"],
|
||||
["README.md", "markdown"],
|
||||
])("%s is %s", (path, id) => {
|
||||
expect(languageOf(path)).toBe(id);
|
||||
});
|
||||
|
||||
it.each(["Makefile", ".env", "notes.txt", "archive.tar.gz", "dir.php/file", ".php", ""])(
|
||||
"%s is plain text",
|
||||
(path) => {
|
||||
expect(languageOf(path)).toBeNull();
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("highlighting", () => {
|
||||
it("marks PHP tokens with lt-syntax classes", () => {
|
||||
const view = show(
|
||||
"a.php",
|
||||
[
|
||||
"<?php",
|
||||
"// a note",
|
||||
"namespace App;",
|
||||
"final class Shop extends Base {",
|
||||
" const LIMIT = 10;",
|
||||
" public function total(int $count): float {",
|
||||
' return $count * 4.5 + strlen("otter") + self::LIMIT;',
|
||||
" }",
|
||||
"}",
|
||||
"$ok = true;",
|
||||
].join("\n"),
|
||||
);
|
||||
const marks = highlighted(view);
|
||||
expect(marks.comment).toContain("// a note");
|
||||
expect(marks.keyword).toEqual(expect.arrayContaining(["namespace", "final", "class", "extends", "public", "function", "return"]));
|
||||
expect(marks.type).toEqual(expect.arrayContaining(["Shop", "int", "float"]));
|
||||
expect(marks.variable).toEqual(expect.arrayContaining(["$count", "$ok"]));
|
||||
expect(marks.number).toEqual(expect.arrayContaining(["10", "4.5"]));
|
||||
expect(marks.string).toContain('"otter"');
|
||||
expect(marks.function).toEqual(expect.arrayContaining(["total", "strlen"]));
|
||||
expect(marks.constant).toContain("true");
|
||||
expect(marks.operator).toEqual(expect.arrayContaining(["*", "+", "="]));
|
||||
});
|
||||
|
||||
it("marks the HTML around PHP blocks", () => {
|
||||
const marks = highlighted(show("view.php", '<div class="box"><?= $name ?></div>\n'));
|
||||
expect(marks.tag).toEqual(expect.arrayContaining(["div"]));
|
||||
expect(marks.attribute).toContain("class");
|
||||
expect(marks.variable).toContain("$name");
|
||||
});
|
||||
|
||||
it.each([
|
||||
["composer.json", '{"name": "lutra/demo", "n": 1}', "string", '"lutra/demo"'],
|
||||
["ci.yml", "on: push # build\n", "comment", "# build"],
|
||||
["app.ts", "const x: number = 1;\n", "keyword", "const"],
|
||||
["app.css", "a { color: red; }\n", "tag", "a"],
|
||||
["README.md", "# Lutra\n", "keyword", " Lutra"],
|
||||
])("highlights %s", (path, doc, token, text) => {
|
||||
expect(highlighted(show(path, doc))[token]).toContain(text);
|
||||
});
|
||||
|
||||
it("leaves plain text unmarked", () => {
|
||||
expect(highlighted(show("notes.txt", "class Foo { $x = 1; }"))).toEqual({});
|
||||
});
|
||||
|
||||
it("colours every highlight class with its theme token", () => {
|
||||
const view = new EditorView({ state: EditorState.create({ extensions: lutraEditorTheme }), parent: document.body });
|
||||
views.push(view);
|
||||
const css = [...document.querySelectorAll("style")].map((style) => style.textContent).join("\n");
|
||||
for (const token of SYNTAX_TOKENS) {
|
||||
expect(css).toMatch(new RegExp(`\\.lt-syntax-${token}\\s*\\{\\s*color:\\s*var\\(--lt-syntax-${token}\\)`));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
@ -262,6 +262,7 @@ describe("CommandPalette", () => {
|
|||
"palette.open",
|
||||
"project.openDialog",
|
||||
"app.quit",
|
||||
"editor.reveal",
|
||||
"settings.open",
|
||||
"view.toggleProjectTree",
|
||||
]);
|
||||
|
|
|
|||
|
|
@ -2,7 +2,9 @@
|
|||
* WCAG 2.1 contrast check of the built-in themes
|
||||
* (https://www.w3.org/TR/WCAG21/#contrast-minimum). Every token pair the
|
||||
* UI draws text with reaches AA: 4.5:1 for body text, 3:1 for non-text
|
||||
* marks (cursor, modified dot, settings switch knob; WCAG 1.4.11). The themes come from
|
||||
* marks (cursor, modified dot, settings switch knob; WCAG 1.4.11). Every
|
||||
* syntax colour (`--lt-syntax-*`) reaches 4.5:1 on the editor background
|
||||
* and on the active line. The themes come from
|
||||
* `themes.json`, a snapshot that the Rust test `ui_snapshot_is_current`
|
||||
* keeps equal to `lutra_engine::theme`.
|
||||
*/
|
||||
|
|
@ -42,6 +44,27 @@ const PAIRS: [string, string, number][] = [
|
|||
["tab-modified", "tab-active-bg", LARGE],
|
||||
];
|
||||
|
||||
/** Syntax token names (`--lt-syntax-<name>`), as `SYNTAX_TOKENS` in `theme.rs`. */
|
||||
export const SYNTAX = [
|
||||
"keyword",
|
||||
"string",
|
||||
"number",
|
||||
"comment",
|
||||
"variable",
|
||||
"function",
|
||||
"type",
|
||||
"constant",
|
||||
"tag",
|
||||
"attribute",
|
||||
"operator",
|
||||
] as const;
|
||||
|
||||
/** Every syntax token as text on the editor background and the active line. */
|
||||
const SYNTAX_PAIRS: [string, string, number][] = SYNTAX.flatMap((name): [string, string, number][] => [
|
||||
[`syntax-${name}`, "editor-bg", TEXT],
|
||||
[`syntax-${name}`, "editor-active-line-bg", TEXT],
|
||||
]);
|
||||
|
||||
/**
|
||||
* Relative luminance of a `#rrggbb` colour (WCAG 2.1 definition).
|
||||
*
|
||||
|
|
@ -90,7 +113,15 @@ describe.each(themes)("theme $id", (theme) => {
|
|||
return value;
|
||||
};
|
||||
|
||||
it.each(PAIRS)("%s on %s reaches %d:1", (fg, bg, min) => {
|
||||
it("checks every syntax token it defines", () => {
|
||||
const defined = Object.keys(tokens)
|
||||
.filter((name) => name.startsWith("--lt-syntax-"))
|
||||
.map((name) => name.slice("--lt-syntax-".length))
|
||||
.sort();
|
||||
expect(defined).toEqual([...SYNTAX].sort());
|
||||
});
|
||||
|
||||
it.each([...PAIRS, ...SYNTAX_PAIRS])("%s on %s reaches %d:1", (fg, bg, min) => {
|
||||
expect(contrast(token(fg), token(bg))).toBeGreaterThanOrEqual(min);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -25,6 +25,17 @@
|
|||
"--lt-notice-bg": "#3a3025",
|
||||
"--lt-statusbar-bg": "#24211f",
|
||||
"--lt-statusbar-fg": "#b8afa6",
|
||||
"--lt-syntax-attribute": "#cdb87e",
|
||||
"--lt-syntax-comment": "#958d84",
|
||||
"--lt-syntax-constant": "#c4a0d6",
|
||||
"--lt-syntax-function": "#e6c46f",
|
||||
"--lt-syntax-keyword": "#d39a5c",
|
||||
"--lt-syntax-number": "#e3a1a8",
|
||||
"--lt-syntax-operator": "#b8afa6",
|
||||
"--lt-syntax-string": "#a9bd7e",
|
||||
"--lt-syntax-tag": "#e08b70",
|
||||
"--lt-syntax-type": "#7fbac6",
|
||||
"--lt-syntax-variable": "#d8bba6",
|
||||
"--lt-tab-active-bg": "#191817",
|
||||
"--lt-tab-modified": "#d39a5c"
|
||||
}
|
||||
|
|
@ -55,6 +66,17 @@
|
|||
"--lt-notice-bg": "#e9dfd4",
|
||||
"--lt-statusbar-bg": "#ece7e0",
|
||||
"--lt-statusbar-fg": "#5a5149",
|
||||
"--lt-syntax-attribute": "#695d1a",
|
||||
"--lt-syntax-comment": "#6e665e",
|
||||
"--lt-syntax-constant": "#73479a",
|
||||
"--lt-syntax-function": "#7a5808",
|
||||
"--lt-syntax-keyword": "#965a22",
|
||||
"--lt-syntax-number": "#a03a4e",
|
||||
"--lt-syntax-operator": "#5a5149",
|
||||
"--lt-syntax-string": "#4e6a24",
|
||||
"--lt-syntax-tag": "#a5432a",
|
||||
"--lt-syntax-type": "#24697a",
|
||||
"--lt-syntax-variable": "#7f4a34",
|
||||
"--lt-tab-active-bg": "#fbfaf8",
|
||||
"--lt-tab-modified": "#965a22"
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue