diff --git a/backend/examples/wikidata/example-012.rq b/backend/examples/wikidata/example-012.rq new file mode 100644 index 00000000..80245e24 --- /dev/null +++ b/backend/examples/wikidata/example-012.rq @@ -0,0 +1,13 @@ +#+ title: 'All predicates of Paris with name and #triples' + +PREFIX wd: +PREFIX wikibase: +PREFIX rdfs: +SELECT ?p (COUNT(?o) AS ?count) (SAMPLE(?label) AS ?pname) WHERE { + wd:Q90 ?p ?o . + ?x wikibase:claim ?p ; + rdfs:label ?label . + FILTER (LANG(?label) = "en") +} +GROUP BY ?p +ORDER BY DESC(?count) \ No newline at end of file diff --git a/backend/src/api/defaults/config.yaml b/backend/src/api/defaults/config.yaml index 71bc1780..850a7573 100644 --- a/backend/src/api/defaults/config.yaml +++ b/backend/src/api/defaults/config.yaml @@ -1,3 +1,143 @@ +uni: + preset: + - common_prefixes + - qlever_default + name: University + url: http://localhost:7019 + default: true + sort_key: A1 + prefix_map: + unio: http://uni-freiburg.de/ontology/ + coho: http://cohortdata.uni-freiburg.de/ontology/ + teachingUnit: http://uni-freiburg.de/resource/techingUnit/ + studypath: http://uni-freiburg.de/resource/studyPath/ + subject: http://uni-freiburg.de/resource/subject/ + subjectType: http://uni-freiburg.de/resource/subjectType/ + faculty: http://uni-freiburg.de/resource/faculty/ + degree: http://uni-freiburg.de/resource/degree/ + semester: http://uni-freiburg.de/resource/semester/ + metric: http://cohortdata.uni-freiburg.de/ontology/semesterMetric/ + query_templates: + subject_completion: | + #+ title: Qlue-ls subject completion query. + #+ description: This query was generated by the SPARQL language server Qlue-ls. + {% include "prefix_declarations" %} + + PREFIX skos: + PREFIX rdfs: + SELECT ?qls_entity + (SAMPLE(?name) AS ?qls_label) + (SAMPLE(?alias) AS ?qls_alias) + (COUNT(*) AS ?qls_count) WHERE { + { + SELECT ?qls_entity WHERE { + ?qls_entity rdfs:label ?name + FILTER(ql:prefix-match(?name,"{{ search_term }}")) + } + } + UNION { + SELECT ?qls_entity WHERE { + ?qls_entity skos:altLabel ?name + FILTER(ql:prefix-match(?name,"{{ search_term }}")) + } + } + ?qls_entity rdfs:label ?name ; + ?p ?o ; + OPTIONAL { + ?qls_entity skos:altLabel ?alias + FILTER(ql:prefix-match(?alias,"{{ search_term }}")) + } + } + GROUP BY ?qls_entity + ORDER BY DESC(?qls_count) + LIMIT {{ limit }} OFFSET {{ offset }} + predicate_completion_context_sensitive: |- + # predicate completion sensitive + {% for prefix in prefixes %} + PREFIX {{prefix.0}}: <{{prefix.1}}> + {% endfor %} + + PREFIX rdfs: + PREFIX skos: + SELECT ?qls_entity + (SAMPLE(?qls_name) as ?qls_label) + (SAMPLE(?count) as ?qls_count) WHERE { + { + SELECT ?qls_entity (COUNT(?qls_entity) AS ?count) WHERE { + {{ context }} {{ local_context }} + } + GROUP BY ?qls_entity + } + {% if not search_term %} + BIND (REPLACE(STR(?qls_entity), "^.*[#/]([^#/]*)", "$1") AS ?qls_name) + {% elif search_term_uncompressed %} + FILTER(ql:prefix-match(?qls_entity,"{{ search_term_uncompressed }}")) + {% else %} + BIND (REPLACE(STR(?qls_entity), "^.*[#/]([^#/]*)", "$1") AS ?qls_name) + FILTER(REGEX(?qls_name,"^{{ search_term }}(?:)")) + {% endif %} + } + GROUP BY ?qls_entity + ORDER BY DESC(?qls_count) + + LIMIT {{ limit }} OFFSET {{ offset }} + predicate_completion_context_insensitive: |- + {% include "prefix_declarations" %} + PREFIX rdfs: + SELECT ?qls_entity ?qls_label ?qls_alias ?qls_count WHERE { + { + SELECT ?qls_entity (COUNT(*) AS ?qls_count) WHERE { + {{ local_context }} + } + GROUP BY ?qls_entity + ORDER BY DESC(?qls_count) + } + BIND (REPLACE(STR(?qls_entity), "^.*[#/]([^#/]*)", "$1") AS ?qls_label) + FILTER (REGEX(?qls_label,"^type(?:)")) + } + LIMIT {{ limit }} + object_completion_context_sensitive: |- + #+ title: Qlue-ls object sensitive completion query. + #+ description: This query was generated by the SPARQL language server Qlue-ls. + {% include "prefix_declarations" %} + PREFIX rdfs: + SELECT ?qls_entity ?qls_label ?qls_alias ?qls_count WHERE { + { + SELECT ?qls_entity (COUNT(*) AS ?qls_count) WHERE { + {{ context }} {{ local_context }} + } + GROUP BY ?qls_entity + ORDER BY DESC(?qls_count) + } + OPTIONAL { + ?qls_entity rdfs:label ?qls_label_ + FILTER (LANG(?qls_label_) = "de" || LANG(?qls_label_) = "") + } + BIND (IF(ISLITERAL(?qls_entity), ?qls_entity, ?qls_label_) AS ?qls_label) + FILTER (REGEX(STR(?qls_label), "^{{ search_term }}")) + } + LIMIT {{ limit }} + object_completion_context_insensitive: |- + {% include "prefix_declarations" %} + PREFIX rdfs: + SELECT ?qls_entity ?qls_label ?qls_alias ?qls_count WHERE { + { + SELECT ?qls_entity (COUNT(*) AS ?qls_count) WHERE { + {{ local_context }} + } + GROUP BY ?qls_entity + ORDER BY DESC(?qls_count) + } + OPTIONAL { + ?qls_entity rdfs:label ?qls_label_ + FILTER (LANG(?qls_label_) = "de" || LANG(?qls_label_) = "") + } + BIND (IF(ISLITERAL(?qls_entity), ?qls_entity, ?qls_label_) AS ?qls_label) + {% if search_term %} + FILTER(ql:prefix-match(?qls_label,"{{ search_term }}")) + {% endif %} + } + LIMIT {{ limit }} dblp: preset: - common_prefixes @@ -5,15 +145,333 @@ dblp: name: DBLP url: https://qlever.dev/api/dblp default: false - sort_key: A2 + sort_key: '0' +eval: + preset: + - common_prefixes + - qlever_default + name: evaluationen + url: http://localhost:7029 + default: true + sort_key: A1 + prefix_map: + module: https://eva.uni-freiburg.de/module/ + lecture: https://eva.uni-freiburg.de/lecture/ + person: https://eva.uni-freiburg.de/person/ + uni: https://eva.uni-freiburg.de/ns# + po: https://eva.uni-freiburg.de/program/ + query_templates: + subject_completion: | + #+ title: Qlue-ls subject completion query. + #+ description: This query was generated by the SPARQL language server Qlue-ls. + {% include "prefix_declarations" %} + + PREFIX skos: + PREFIX rdfs: + SELECT ?qls_entity + (SAMPLE(?name) AS ?qls_label) + (SAMPLE(?alias) AS ?qls_alias) + (COUNT(*) AS ?qls_count) WHERE { + { + SELECT ?qls_entity WHERE { + ?qls_entity rdfs:label ?name + FILTER(ql:prefix(?name,"{{ search_term }}")) + } + } + UNION { + SELECT ?qls_entity WHERE { + ?qls_entity skos:altLabel ?name + FILTER(REGEX(?name,"^{{ search_term }}(?:)")) + } + } + ?qls_entity rdfs:label ?name ; + ?p ?o ; + OPTIONAL { + ?qls_entity skos:altLabel ?alias + FILTER(REGEX(?alias,"^{{ search_term }}(?:)")) + } + } + GROUP BY ?qls_entity + ORDER BY DESC(?qls_count) + LIMIT {{ limit }} OFFSET {{ offset }} + predicate_completion_context_sensitive: |- + # predicate completion sensitive + {% for prefix in prefixes %} + PREFIX {{prefix.0}}: <{{prefix.1}}> + {% endfor %} + {% if subject is not variable %} + PREFIX rdfs: + PREFIX skos: + SELECT ?qls_entity + (SAMPLE(?name) as ?qls_label) + (SAMPLE(?count) as ?qls_count) WHERE { + { + SELECT ?qls_entity (COUNT(?qls_entity) AS ?count) WHERE { + {{ local_context }} + } + GROUP BY ?qls_entity + } + {% if not search_term %} + BIND (REPLACE(STR(?qls_entity), "^.*#([^#/]*)", "$1") AS ?name) + {% elif search_term_uncompressed %} + FILTER(REGEX(?qls_entity,"^{{ search_term_uncompressed }}(?:)")) + {% else %} + BIND (REPLACE(STR(?qls_entity), "^.*#([^#/]*)", "$1") AS ?name) + FILTER(REGEX(?name,"^{{ search_term }}(?:)")) + {% endif %} + } + GROUP BY ?qls_entity + ORDER BY DESC(?qls_count) + {% else %} + PREFIX rdfs: + PREFIX skos: + SELECT ?qls_entity + (SAMPLE(?name) as ?qls_label) + (SAMPLE(?count) as ?qls_count) WHERE { + {% if not context %} + { + SELECT ?qls_entity (COUNT(?qls_entity) AS ?count) WHERE { + {{ local_context }} + } + GROUP BY ?qls_entity + } + {% else %} + { + SELECT ?qls_entity (COUNT(DISTINCT {{ subject }}) AS ?count) WHERE { + {{ context }} {{ local_context }} + } + GROUP BY ?qls_entity + } + {% endif %} + {% if not search_term %} + BIND (REPLACE(STR(?qls_entity), "^.*#([^#/]*)", "$1") AS ?name) + {% elif search_term_uncompressed %} + FILTER(REGEX(?qls_entity,"^{{ search_term_uncompressed }}(?:)")) + {% else %} + BIND (REPLACE(STR(?qls_entity), "^.*#([^#/]*)", "$1") AS ?name) + FILTER(REGEX(?name,"^{{ search_term }}(?:)")) + {% endif %} + } + GROUP BY ?qls_entity + ORDER BY DESC(?qls_count) + {% endif %} + LIMIT {{ limit }} OFFSET {{ offset }} + predicate_completion_context_insensitive: |- + {% include "prefix_declarations" %} + PREFIX rdfs: + SELECT ?qls_entity ?qls_label ?qls_alias ?qls_count WHERE { + { + SELECT ?qls_entity (COUNT(*) AS ?qls_count) WHERE { + {{ local_context }} + } + GROUP BY ?qls_entity + ORDER BY DESC(?qls_count) + } + BIND (REPLACE(STR(?qls_entity), ".*#([^#/]*)", "$1") AS ?name) + FILTER(REGEX(?name,"^{{ search_term }}(?:)")) + } + LIMIT {{ limit }} + object_completion_context_sensitive: |- + #+ title: Qlue-ls object sensitive completion query. + #+ description: This query was generated by the SPARQL language server Qlue-ls. + {% include "prefix_declarations" %} + PREFIX rdfs: + SELECT ?qls_entity ?qls_label ?qls_alias ?qls_count WHERE { + { + SELECT ?qls_entity (COUNT(*) AS ?qls_count) WHERE { + {{ context }} {{ local_context }} + } + GROUP BY ?qls_entity + ORDER BY DESC(?qls_count) + } + OPTIONAL { ?qls_entity rdfs:label ?qls_label1 } + BIND (IF(ISLITERAL(?qls_entity),?qls_entity,?qls_label1) AS ?qls_label) + {% if search_term %} + FILTER(ql:prefix-match(?qls_label,"{{ search_term }}")) + {% endif %} + } + LIMIT {{ limit }} + object_completion_context_insensitive: |- + {% include "prefix_declarations" %} + PREFIX rdfs: + SELECT ?qls_entity ?qls_label ?qls_alias ?qls_count WHERE { + { + SELECT ?qls_entity (COUNT(*) AS ?qls_count) WHERE { + {{ local_context }} + } + GROUP BY ?qls_entity + ORDER BY DESC(?qls_count) + } + OPTIONAL { ?qls_entity rdfs:label ?qls_label1 } + BIND (IF(ISLITERAL(?qls_entity),?qls_entity,?qls_label1) AS ?qls_label) + {% if search_term %} + FILTER(ql:prefix-match(?qls_label,"{{ search_term }}") || ql:prefix-match(?qls_alias, "{{ search_term }}")) + {% endif %} + } + LIMIT {{ limit }} wikidata: preset: - common_prefixes - qlever_default name: Wikidata - url: https://qlever.dev/api/wikidata + url: https://qlever.dev/api/wikidata-ianni default: true sort_key: A2 + query_templates: + subject_completion: | + #+ title: Qlue-ls subject completion query. + #+ description: This query was generated by the SPARQL language server Qlue-ls. + {% include "prefix_declarations" %} + + PREFIX skos: + PREFIX rdfs: + SELECT ?qls_entity + (SAMPLE(?name) AS ?qls_label) + (SAMPLE(?alias) AS ?qls_alias) + (COUNT(*) AS ?qls_count) WHERE { + { + SELECT ?qls_entity WHERE { + ?qls_entity rdfs:label ?name + FILTER (LANG(?name) = "mul") + FILTER (REGEX(STR(?name),"^{{ search_term }}")) + } + } + UNION { + SELECT ?qls_entity WHERE { + ?qls_entity skos:altLabel ?name + FILTER (LANG(?name) = "mul") + FILTER (REGEX(STR(?name),"^{{ search_term }}")) + } + } + ?qls_entity rdfs:label ?name ; + ?p ?o ; + OPTIONAL { + ?qls_entity skos:altLabel ?alias + FILTER (LANG(?alias) = "mul") + FILTER (REGEX(STR(?alias),"^{{ search_term }}")) + } + FILTER (LANG(?name) = "mul") + } + GROUP BY ?qls_entity + ORDER BY DESC(?qls_count) + LIMIT {{ limit }} OFFSET {{ offset }} + predicate_completion_context_sensitive: |- + # predicate completion sensitive + {% for prefix in prefixes %} + PREFIX {{prefix.0}}: <{{prefix.1}}> + {% endfor %} + {% if subject is not variable %} + PREFIX rdfs: + PREFIX skos: + SELECT ?qls_entity + (SAMPLE(?name) as ?qls_label) + (SAMPLE(?count) as ?qls_count) WHERE { + { + SELECT ?qls_entity (COUNT(?qls_entity) AS ?count) WHERE { + {{ local_context }} + } + GROUP BY ?qls_entity + } + {% if not search_term %} + ?qui_tmp_1 ?qui_tmp_2 ?qls_entity . + ?qui_tmp_1 rdfs:label ?name . FILTER (LANG(?name) = "en") + BIND (?name AS ?alias) + {% elif search_term_uncompressed %} + ?qui_tmp_1 ?qui_tmp_2 ?qls_entity . + ?qui_tmp_1 rdfs:label ?name FILTER (LANG(?name) = "en") + FILTER REGEX(STR(?qls_entity), "^{{ search_term_uncompressed }}", "i") + {% else %} + ?qui_tmp_1 ?qui_tmp_2 ?qls_entity . + ?qui_tmp_1 rdfs:label ?name FILTER (LANG(?name) = "en") + OPTIONAL { + ?qui_tmp_1 skos:altLabel ?alias FILTER (LANG(?alias) = "en") + } + FILTER (REGEX(STR(?name), "^{{ search_term }}", "i") || REGEX(STR(?alias), "^{{ search_term }}", "i")) + {% endif %} + } + GROUP BY ?qls_entity + ORDER BY DESC(?qls_count) + {% else %} + PREFIX rdfs: + PREFIX skos: + SELECT ?qls_entity + (SAMPLE(?name) as ?qls_label) + (SAMPLE(?count) as ?qls_count) WHERE { + {% if not context %} + { + SELECT ?qls_entity (COUNT(?qls_entity) AS ?count) WHERE { + {{ local_context }} + } + GROUP BY ?qls_entity + } + {% else %} + { + SELECT ?qls_entity (COUNT(DISTINCT {{ subject }}) AS ?count) WHERE { + {{ context }} {{ local_context }} + } + GROUP BY ?qls_entity + } + {% endif %} + {% if not search_term %} + ?qui_tmp_1 ?qui_tmp_2 ?qls_entity . + ?qui_tmp_1 rdfs:label ?name FILTER (LANG(?name) = "en") + BIND (?name AS ?alias) + {% elif search_term_uncompressed %} + ?qui_tmp_1 ?qui_tmp_2 ?qls_entity . + ?qui_tmp_1 rdfs:label ?name FILTER (LANG(?name) = "en") + FILTER REGEX(STR(?qls_entity), "^{{ search_term_uncompressed }}", "i") + {% else %} + ?qui_tmp_1 ?qui_tmp_2 ?qls_entity . + ?qui_tmp_1 rdfs:label ?name FILTER (LANG(?name) = "en") + OPTIONAL { + ?qui_tmp_1 skos:altLabel ?alias FILTER (LANG(?alias) = "en") + } + FILTER (REGEX(STR(?name), "^{{ search_term }}", "i") || REGEX(STR(?alias), "^{{ search_term }}", "i")) + {% endif %} + } + GROUP BY ?qls_entity + ORDER BY DESC(?qls_count) + {% endif %} + LIMIT {{ limit }} OFFSET {{ offset }} + object_completion_context_sensitive: |- + #+ title: Qlue-ls object sensitive completion query. + #+ description: This query was generated by the SPARQL language server Qlue-ls. + {% include "prefix_declarations" %} + PREFIX rdfs: + SELECT ?qls_entity ?qls_label ?qls_alias ?qls_count WHERE { + { + SELECT ?qls_entity (COUNT(*) AS ?qls_count) WHERE { + {{ context }} {{ local_context }} + } + GROUP BY ?qls_entity + ORDER BY DESC(?qls_count) + LIMIT {{ limit }} + } + OPTIONAL { ?qls_entity rdfs:label ?qls_label FILTER (LANG(?qls_label) = "en") } + OPTIONAL { ?qls_entity rdfs:comment ?qls_alias } + {% if search_term %} + FILTER(CONTAINS(LCASE(STR(?qls_label)), LCASE("{{ search_term }}")) || CONTAINS(LCASE(STR(?qls_alias)), LCASE("{{ search_term }}"))) + + {% endif %} + } + object_completion_context_insensitive: |- + {% include "prefix_declarations" %} + PREFIX rdfs: + SELECT ?qls_entity ?qls_label ?qls_alias ?qls_count WHERE { + { + SELECT ?qls_entity (COUNT(*) AS ?qls_count) WHERE { + {{ local_context }} + } + GROUP BY ?qls_entity + ORDER BY DESC(?qls_count) + LIMIT {{ limit }} + } + OPTIONAL { ?qls_entity rdfs:label ?qls_label FILTER (LANG(?qls_label) = "en") } + OPTIONAL { ?qls_entity rdfs:comment ?qls_alias } + {% if search_term %} + FILTER(CONTAINS(LCASE(STR(?qls_label)), LCASE("{{ search_term }}")) || CONTAINS(LCASE(STR(?qls_alias)), LCASE("{{ search_term }}"))) + {% endif %} + } osm-planet: preset: - common_prefixes diff --git a/backend/src/api/presets/qlever_default.yaml b/backend/src/api/presets/qlever_default.yaml index eebe5abf..af3a9cd3 100644 --- a/backend/src/api/presets/qlever_default.yaml +++ b/backend/src/api/presets/qlever_default.yaml @@ -10,7 +10,7 @@ query_templates: PREFIX rdfs: SELECT ?qls_entity (SAMPLE(?name) AS ?qls_label) - (GROUP_CONCAT(DISTINCT ?alias; SEPARATOR=", ") AS ?qls_alias) + (SAMPLE(?alias) AS ?qls_alias) (COUNT(*) AS ?qls_count) WHERE { { SELECT ?qls_entity WHERE { @@ -31,6 +31,7 @@ query_templates: OPTIONAL { ?qls_entity skos:altLabel ?alias FILTER (LANG(?alias) = "en") + FILTER (REGEX(STR(?alias),"^{{ search_term }}")) } FILTER (LANG(?name) = "en") } diff --git a/frontend/src/editor/commands.ts b/frontend/src/editor/commands.ts index 6bc17226..5b908af7 100644 --- a/frontend/src/editor/commands.ts +++ b/frontend/src/editor/commands.ts @@ -5,13 +5,14 @@ // └─────────────────────────────────┘ \\ import * as monaco from 'monaco-editor'; +import { triggerCompletion } from './completion'; import type { Editor } from './init'; -export function setup_commands(editor: Editor) { +export function setup_commands(_editor: Editor) { monaco.editor.addCommand({ id: 'triggerNewCompletion', run: () => { - editor.editorApp.getEditor()!.trigger('editor', 'editor.action.triggerSuggest', {}); + triggerCompletion(); }, }); } diff --git a/frontend/src/editor/completion/controller.ts b/frontend/src/editor/completion/controller.ts new file mode 100644 index 00000000..9c653734 --- /dev/null +++ b/frontend/src/editor/completion/controller.ts @@ -0,0 +1,806 @@ +// ┌─────────────────────────────────┐ \\ +// │ Copyright © 2026 Ioannis Nezis │ \\ +// ├─────────────────────────────────┤ \\ +// │ Licensed under the MIT license. │ \\ +// └─────────────────────────────────┘ \\ + +import * as monaco from 'monaco-editor'; +import { openSettings } from '../../settings/utils'; +import type { Range } from '../../types/lsp_messages'; +import type { Editor } from '../init'; +import { toMonacoRange } from '../utils'; +import { Trace, trace } from './trace'; +import { + AS_IS_MODE, + type CompletionItem, + type CompletionList, + type CompletionState, + type EntityData, + type LiteralData, + type RenderContent, + type RenderItem, + SNIPPET_FORMAT, + VALUE_KIND, +} from './types'; +import { CompletionWidget } from './widget'; + +/** JSON-RPC error code for a request the client itself cancelled. */ +const REQUEST_CANCELLED = -32800; +const DEBOUNCE_MS = 200; +/** + * How long a request may run with nothing on screen before the popup opens on + * a "Searching…" panel. + * + * An entity completion goes to the endpoint and can take seconds, which is a + * long time to type into silence. The grace period keeps the panel out of the + * way of the answers that come back promptly. + */ +const PENDING_PANEL_MS = 250; + +/** The bits of Monaco's `SnippetController2` that inserting a snippet needs. */ +interface SnippetController { + apply( + edits: { range: monaco.Range; template: string }[], + options?: Record + ): void; + insert(template: string, options?: Record): void; + isInSnippet(): boolean; +} + +/** A completely typed SPARQL variable, e.g. `?abc` — but not a bare `?`. */ +const VARIABLE_TERM = /^[?$]\w+$/; + +/** LSP `CompletionTriggerKind`. */ +enum TriggerKind { + Invoked = 1, + TriggerCharacter = 2, +} + +interface Session { + /** The term the server searched for, measured at the request position. */ + term: string; + /** All items the server returned, in server order. */ + items: RenderItem[]; + /** Whether the server wants a fresh request on every keystroke. */ + isIncomplete: boolean; + /** Where the popup is anchored. */ + anchor: monaco.IPosition; + /** + * Where the term being completed starts, when the server said so. + * + * NOTE: distinct from `anchor`, which falls back to the cursor at request + * time so the popup always has somewhere to sit. That fallback is not a term + * start — it sits *after* whatever was already typed — so it must not be + * used for filtering or highlighting. + */ + termStart: monaco.IPosition | undefined; +} + +export class CompletionController { + private readonly monacoEditor: monaco.editor.IStandaloneCodeEditor; + private readonly widget: CompletionWidget; + + private triggerCharacters: string[] = []; + private debounceHandle: number | undefined; + private pendingPanelHandle: number | undefined; + private tokenSource: { cancel(): void; dispose(): void; token: unknown } | undefined; + private requestVersion = 0; + private inFlight = 0; + private session: Session | undefined; + private state: CompletionState | undefined; + private selected = 0; + + constructor(private readonly editor: Editor) { + this.monacoEditor = editor.editorApp.getEditor()!; + this.widget = new CompletionWidget(this.monacoEditor, { + onAccept: (index) => this.accept(index), + onRetry: () => this.trigger(TriggerKind.Invoked), + onOpenSettings: () => { + this.hide(); + openSettings(); + }, + }); + + this.triggerCharacters = + (this.editor.languageClient.initializeResult?.capabilities?.completionProvider + ?.triggerCharacters as string[] | undefined) ?? []; + + this.monacoEditor.onDidChangeModelContent((event) => this.onContentChanged(event)); + this.monacoEditor.onDidChangeCursorPosition((event) => { + // NOTE: typing moves the cursor too (reason NotSet); only an explicit + // move — arrow keys outside the widget, a click — dismisses. + if (!this.widget.isVisible()) return; + if (event.reason === monaco.editor.CursorChangeReason.Explicit) this.hide(); + }); + this.monacoEditor.onDidBlurEditorWidget(() => this.hide()); + this.monacoEditor.onKeyDown((event) => this.onKeyDown(event)); + } + + /** Hides the widget and cancels any request in flight. */ + hide() { + if (this.widget.isVisible() || this.debounceHandle !== undefined) trace('hide'); + window.clearTimeout(this.debounceHandle); + this.debounceHandle = undefined; + window.clearTimeout(this.pendingPanelHandle); + this.pendingPanelHandle = undefined; + this.cancelPending(); + this.session = undefined; + this.state = undefined; + this.widget.hide(); + } + + /** Requests completions at the current cursor position. */ + trigger(triggerKind: TriggerKind = TriggerKind.Invoked, triggerCharacter?: string) { + trace('trigger', () => ({ triggerKind: TriggerKind[triggerKind], triggerCharacter })); + // NOTE: the server completes inside comments too, but "# blabla select" is + // prose — the words there are not a query being written. + if (this.isInComment()) { + this.hide(); + return; + } + window.clearTimeout(this.debounceHandle); + this.debounceHandle = window.setTimeout(() => { + // NOTE: cleared before the request goes out, so that the handle marks a + // queued request and nothing else — `isRequestPending` reads it. + this.debounceHandle = undefined; + this.request(triggerKind, triggerCharacter); + }, DEBOUNCE_MS); + // NOTE: after the handle is assigned, since that is what marks the queued + // request that `isRequestPending` reads. + this.syncHeader(); + } + + /** Accepts the currently highlighted item. Returns false when there is none. */ + acceptSelected(): boolean { + if (this.state?.kind !== 'items') return false; + this.accept(this.selected); + return true; + } + + private onContentChanged(event: monaco.editor.IModelContentChangedEvent) { + // NOTE: also checked here, not only in `trigger`, since an open list of a + // complete session is filtered locally without going through it. + if (this.isInComment()) { + this.hide(); + return; + } + // NOTE: deleting back past where the list was requested destroys the very + // thing it was computed for — the "FILTER (" whose parens the built in call + // list belongs inside, or the term an entity search ran on. Those lists are + // complete, so nothing would re-request them, and an empty term is a prefix + // of everything: without this the whole list survives being backspaced away. + if (this.session && this.isBeforeAnchor(this.session.anchor)) { + trace('cursor moved before anchor'); + this.hide(); + return; + } + const change = event.changes.at(-1); + // NOTE: a code action's edit arrives here exactly like a keystroke does, + // and its text is not something the user is typing — "Add to result" + // writing `?o` into the SELECT clause opened the popup on whatever the + // cursor happened to sit on, several lines away. Only a change that lands + // on the cursor is typing. + if (!change || !this.isChangeAtCursor(change)) return; + const text = change.text; + const triggerCharacter = this.triggerCharacters.find((char) => text.endsWith(char)); + if (triggerCharacter) { + this.trigger(TriggerKind.TriggerCharacter, triggerCharacter); + return; + } + // NOTE: entity lists are always `isIncomplete`, so they are re-requested on + // every keystroke; static lists are filtered locally instead. + if (this.session && !this.session.isIncomplete) { + this.renderSession(); + return; + } + if (this.widget.isVisible() || /[\w:?<]$/.test(text)) { + this.trigger(TriggerKind.Invoked); + } + } + + private cancelPending() { + this.tokenSource?.cancel(); + this.tokenSource?.dispose(); + this.tokenSource = undefined; + } + + private request(triggerKind: TriggerKind, triggerCharacter?: string) { + const model = this.monacoEditor.getModel(); + const position = this.monacoEditor.getPosition(); + if (!model || !position) return; + + this.cancelPending(); + const tokenSource = new monaco.CancellationTokenSource(); + this.tokenSource = tokenSource; + const version = ++this.requestVersion; + const requestTrace = Trace.start('textDocument/completion', () => ({ + version, + line: position.lineNumber - 1, + character: position.column - 1, + triggerKind: TriggerKind[triggerKind], + triggerCharacter, + term: this.currentTerm(this.session?.termStart), + })); + + this.inFlight++; + this.syncHeader(); + this.schedulePendingPanel(position); + const started = performance.now(); + this.editor.languageClient + .sendRequest( + 'textDocument/completion', + { + textDocument: { uri: this.editor.getDocumentUri() }, + position: { line: position.lineNumber - 1, character: position.column - 1 }, + context: { triggerKind, triggerCharacter }, + }, + tokenSource.token + ) + .then((response) => { + this.inFlight--; + this.syncHeader(); + requestTrace?.log('response', () => { + const items = Array.isArray(response) ? response : (response?.items ?? []); + return { + count: items.length, + isIncomplete: Array.isArray(response) ? false : response?.isIncomplete, + stale: version !== this.requestVersion, + items, + }; + }); + if (version !== this.requestVersion) return; + // NOTE: before the render, which is what puts the footer on screen. + this.widget.setTiming(performance.now() - started); + this.onResponse(response, position); + }) + .catch((error: unknown) => { + this.inFlight--; + this.syncHeader(); + requestTrace?.log(isCancellation(error) ? 'cancelled' : 'error', () => ({ error })); + if (version !== this.requestVersion) return; + // NOTE: a superseded request rejects as cancelled; showing the error + // panel for those would make it flash on every keystroke. + if (isCancellation(error)) return; + this.showError(error instanceof Error ? error.message : String(error)); + }); + } + + private onResponse( + response: CompletionList | CompletionItem[] | null, + position: monaco.IPosition + ) { + const list = Array.isArray(response) ? undefined : (response ?? undefined); + const items = Array.isArray(response) ? response : (list?.items ?? []); + const isIncomplete = list?.isIncomplete ?? false; + + if (items.length === 0) { + this.session = undefined; + this.render({ kind: 'empty', term: this.currentTerm() }, position); + return; + } + + // NOTE: the server sets `filterText` to the search term for every entity + // item so that ordering falls back to `sortText`. Preserve that order. + const sorted = [...items].sort((a, b) => + (a.sortText ?? a.label).localeCompare(b.sortText ?? b.label) + ); + // NOTE: the built-in call completions carry their snippet format on the + // list rather than on each item, so the defaults are folded in here and + // every item downstream is self-describing. + const defaults = list?.itemDefaults; + const rendered = sorted + .map((item) => ({ + ...item, + insertTextFormat: item.insertTextFormat ?? defaults?.insertTextFormat, + insertTextMode: item.insertTextMode ?? defaults?.insertTextMode, + })) + .map(toRenderItem); + const termStart = termStartOf(rendered); + const anchor = termStart ?? position; + this.session = { + term: this.currentTerm(termStart, position), + items: rendered, + isIncomplete, + anchor, + termStart, + }; + this.renderSession(); + } + + /** + * Renders the current session. + * + * Both kinds of list are filtered the same way — a prefix match, the rule + * the server itself filters by — but against a different term. + * + * A complete list (keywords, snippets) is never re-requested, so it is + * narrowed against the live term; that is what lets it be re-filtered on + * later keystrokes. + * + * An `isIncomplete` list is re-requested on every keystroke and is already + * narrowed by the server, so its order is kept untouched and it is matched + * against the term the server searched for. The server sets `filterText` to + * that very term on every entity item, so they all survive; the variable + * items merged into the same list keep their own name there, which is what + * drops a `?label` suggestion once the term is `Mathe`. Using the server's + * term rather than the live one keeps the entity items from all blinking out + * for the one round trip it takes a keystroke to come back. + */ + private renderSession() { + const session = this.session; + if (!session) return; + const term = this.currentTerm(session.termStart); + const matchTerm = session.isIncomplete ? session.term : term; + const items = session.items.filter((renderItem) => matchesTerm(renderItem, matchTerm)); + trace('local filter', () => ({ term, kept: items.length, of: session.items.length })); + if (items.length === 0) { + this.render({ kind: 'empty', term }, session.anchor); + return; + } + this.render({ kind: 'items', items, term }, session.anchor); + } + + private showError(message: string) { + // NOTE: the server reports a failure to localize the cursor for every + // position it has no completions for. That is not something the user can + // act on, so it dismisses rather than raising the error panel. + if (message.startsWith('Could not localize cursor')) { + this.hide(); + return; + } + const position = this.monacoEditor.getPosition(); + if (!position) return; + const term = this.currentTerm(this.session?.termStart); + this.session = undefined; + this.render({ kind: 'error', message, term }, position); + } + + /** + * Whether `change` landed on the cursor — the test for "the user typed this". + * + * NOTE: the span covers both the text the change inserted and the text it + * replaced, so that the cursor is inside it whether it is read before or + * after the edit moved it. Typing lands it at the far end of the insert, + * backspacing at the near end of the deletion. + */ + private isChangeAtCursor(change: monaco.editor.IModelContentChange): boolean { + const model = this.monacoEditor.getModel(); + const position = this.monacoEditor.getPosition(); + if (!model || !position) return false; + const offset = model.getOffsetAt(position); + const span = Math.max(change.rangeLength, change.text.length); + return offset >= change.rangeOffset && offset <= change.rangeOffset + span; + } + + /** + * Whether the cursor sits inside a `#` comment. + * + * NOTE: scanning the line is enough — a `#` opens a comment unless it is + * inside a string literal or an IRI, and neither of those starts on an + * earlier line. A `<` only opens an IRI when its `>` follows without a + * space, so a `<` comparison does not swallow the rest of the line. + */ + private isInComment(): boolean { + const model = this.monacoEditor.getModel(); + const position = this.monacoEditor.getPosition(); + if (!model || !position) return false; + const line = model.getLineContent(position.lineNumber).slice(0, position.column - 1); + let quote: string | undefined; + for (let index = 0; index < line.length; index++) { + const char = line[index]; + if (quote) { + if (char === '\\') index++; + else if (char === quote) quote = undefined; + continue; + } + if (char === '"' || char === "'") { + quote = char; + } else if (char === '<') { + const close = line.indexOf('>', index + 1); + if (close !== -1 && !/[\s#<]/.test(line.slice(index + 1, close))) index = close; + } else if (char === '#') { + return true; + } + } + return false; + } + + /** Whether the cursor sits before `anchor`, the start of what is completed. */ + private isBeforeAnchor(anchor: monaco.IPosition): boolean { + const position = this.monacoEditor.getPosition(); + if (!position) return false; + if (position.lineNumber !== anchor.lineNumber) return position.lineNumber < anchor.lineNumber; + return position.column < anchor.column; + } + + /** + * Mirrors the pending state and the live term onto the widget's header. + * + * NOTE: this is the only thing that updates between renders. An entity list + * is `isIncomplete`, so a keystroke re-requests rather than re-renders, and + * the header has to keep up with what is being typed on its own. + */ + private syncHeader() { + this.widget.setPending(this.isRequestPending()); + this.widget.setTerm(this.currentTerm(this.session?.termStart)); + this.widget.setStale(this.staleTerm()); + } + + /** + * The term the displayed rows answer, once it is no longer the live one. + * + * `null` while the list is current, or while nothing is on its way that + * could replace it — a list nobody is refreshing is not stale, it is just + * the answer. + */ + private staleTerm(): string | null { + const session = this.session; + if (!session || this.state?.kind !== 'items' || !this.isRequestPending()) return null; + return this.currentTerm(session.termStart) === session.term ? null : session.term; + } + + /** Whether a request is queued or waiting on the server. */ + private isRequestPending(): boolean { + return this.debounceHandle !== undefined || this.inFlight > 0; + } + + /** + * Opens the popup on a "Searching…" panel if this request is still running + * once the grace period is up and nothing has been displayed meanwhile. + */ + private schedulePendingPanel(position: monaco.IPosition) { + if (this.state) return; + // NOTE: a fully typed variable has nothing to wait for -- whatever comes + // back is dismissed rather than shown, so announcing a search for it would + // only flash the panel on the way to nothing. + if (VARIABLE_TERM.test(this.currentTerm())) return; + window.clearTimeout(this.pendingPanelHandle); + this.pendingPanelHandle = window.setTimeout(() => { + this.pendingPanelHandle = undefined; + if (this.state || !this.isRequestPending()) return; + this.render({ kind: 'pending', term: this.currentTerm() }, position); + }, PENDING_PANEL_MS); + } + + private render(state: CompletionState, position: monaco.IPosition) { + // NOTE: typing fast outruns the round trip, so a list can be momentarily + // empty — the server searched a shorter term than what is on screen, or an + // intermediate term genuinely matched nothing. Replacing the suggestions + // with "Nothing matches" for those few frames reads as a flicker, so the + // last list stays up until the answer that is already on its way lands. + if (state.kind === 'empty' && this.isRequestPending() && this.state?.kind === 'items') { + trace('empty suppressed', () => ({ term: state.term })); + return; + } + // NOTE: a fully typed variable has nothing left to suggest — the only + // candidates are the other variables in the query, and the server drops the + // one being typed. That empty list is truthful, but "Nothing matches" reads + // as an error for a name the user just finished writing, so it dismisses. + // Both the server's own empty response and an empty local re-filter land + // here, which is why the check sits in `render` rather than either caller. + if (state.kind === 'empty' && VARIABLE_TERM.test(state.term)) { + trace('variable dismissed', () => ({ term: state.term })); + this.hide(); + return; + } + // NOTE: the panel only fills the gap before the first answer, so anything + // that reaches the screen first cancels it. + window.clearTimeout(this.pendingPanelHandle); + this.pendingPanelHandle = undefined; + this.state = state.kind === 'pending' ? undefined : state; + this.selected = 0; + this.widget.show(state, position, this.selected); + // NOTE: typing can outrun the round trip, so the list that just landed may + // already be answering an older term than what is on screen. + this.widget.setStale(this.staleTerm()); + } + + /** + * The text being completed, used for filtering and highlighting. + * + * NOTE: the term is not necessarily a word. `?a rdfs:label Algorithmen und` + * completes on the whole label, spaces and all. So it runs from the start of + * the range the server replaces to the cursor — the same rule Monaco's own + * suggest widget uses. The word scan is only a fallback for before the first + * response has arrived, when no range is known yet. + * + * `end` measures the term to somewhere other than the cursor. A response is + * read with the position its request was made at, so that the term it is + * stored under is the one the server actually searched for rather than + * whatever has been typed since. + */ + private currentTerm(anchor?: monaco.IPosition, end?: monaco.IPosition): string { + const model = this.monacoEditor.getModel(); + const position = end ?? this.monacoEditor.getPosition(); + if (!model || !position) return ''; + const line = model.getLineContent(position.lineNumber).slice(0, position.column - 1); + if (anchor?.lineNumber === position.lineNumber && anchor.column <= position.column) { + return line.slice(anchor.column - 1); + } + return /[\w:?<]*$/.exec(line)?.[0] ?? ''; + } + + private move(delta: number) { + if (this.state?.kind !== 'items') return; + const count = this.state.items.length; + this.selected = (this.selected + delta + count) % count; + this.widget.select(this.selected); + } + + private accept(index: number) { + if (this.state?.kind !== 'items') return; + const item = this.state.items[index]?.item; + if (!item) return; + trace('accept', () => ({ index, item })); + this.hide(); + this.applyItem(item); + } + + private applyItem(item: CompletionItem) { + const model = this.monacoEditor.getModel(); + if (!model) return; + + const range = this.replaceRange(item); + const newText = item.textEdit?.newText ?? item.insertText ?? item.label; + const additionalEdits = (item.additionalTextEdits ?? []).map((edit) => ({ + range: toMonacoRange(edit.range), + text: edit.newText, + })); + + if (item.insertTextFormat !== SNIPPET_FORMAT) { + // NOTE: all ranges are against the current model, so one call applies the + // PREFIX insert and the replacement together with correct offsets. + this.monacoEditor.executeEdits('completion', [ + ...additionalEdits, + { range, text: newText, forceMoveMarkers: true }, + ]); + return this.runCommand(item); + } + + // NOTE: `SnippetController2.apply` gives every edit it is handed its own + // final tabstop, which would leave one cursor per additional edit. So the + // additional edits are applied first and only the snippet goes through the + // controller. A tracked decoration carries the snippet's range across that + // first edit, which shifts it down by the inserted PREFIX line. + const [markerId] = model.deltaDecorations([], [{ range, options: {} }]); + if (additionalEdits.length > 0) { + this.monacoEditor.executeEdits('completion', additionalEdits); + } + const snippetRange = model.getDecorationRange(markerId) ?? range; + model.deltaDecorations([markerId], []); + + const controller = this.monacoEditor.getContribution( + 'snippetController2' + ) as unknown as SnippetController | null; + // NOTE: a snippet is written relative to the line it lands on, so its own + // indentation is added to that line's -- except where the server says + // `AsIs`, which it does for the object suffix, whose indentation it already + // worked out from the brace nesting depth. + const options = { + adjustWhitespace: item.insertTextMode !== AS_IS_MODE, + undoStopBefore: true, + undoStopAfter: true, + }; + if (controller?.isInSnippet() && snippetRange.startLineNumber === snippetRange.endLineNumber) { + // NOTE: `apply` cancels a running session before inserting, which throws + // away the tabstops of the snippet being completed into -- accepting YEAR + // inside "BIND ($1 AS ?$0)" lost the variable stop. `insert` merges into + // the session instead, so the new snippet's stops nest inside the old + // ones. It takes no range, so the term is overwritten from the cursor. + this.monacoEditor.setPosition(snippetRange.getEndPosition()); + controller.insert(newText, { + ...options, + overwriteBefore: snippetRange.endColumn - snippetRange.startColumn, + overwriteAfter: 0, + }); + } else if (controller) { + controller.apply([{ range: snippetRange, template: newText }], options); + } else { + this.monacoEditor.executeEdits('completion', [ + { range: snippetRange, text: escapeSnippet(newText), forceMoveMarkers: true }, + ]); + } + + return this.runCommand(item); + } + + /** + * Runs an accepted item's `command`. + * + * Monaco's suggest controller used to do this; the server relies on it to + * chain a follow-up completion. + */ + private runCommand(item: CompletionItem) { + if (item.command?.command === 'triggerNewCompletion') { + this.trigger(TriggerKind.Invoked); + } else if (item.command) { + this.monacoEditor.trigger('completion', item.command.command, item.command.arguments); + } + } + + /** + * The range an accepted item replaces. + * + * NOTE: a complete list is filtered locally rather than re-requested, so by + * the time an item is accepted the server's range can be several keystrokes + * old and end before the cursor. Everything typed since belongs to the term + * the item was picked for, so the range is extended to the cursor — the same + * thing Monaco's own suggest controller does. + */ + private replaceRange(item: CompletionItem): monaco.Range { + if (!item.textEdit) return this.wordRange(); + const range = toMonacoRange(item.textEdit.range); + const position = this.monacoEditor.getPosition(); + if (!position) return range; + if (position.lineNumber !== range.endLineNumber) return range; + if (position.column <= range.endColumn) return range; + return range.setEndPosition(position.lineNumber, position.column); + } + + private wordRange(): monaco.Range { + const position = this.monacoEditor.getPosition()!; + const term = this.currentTerm(); + return new monaco.Range( + position.lineNumber, + position.column - term.length, + position.lineNumber, + position.column + ); + } + + private onKeyDown(event: monaco.IKeyboardEvent) { + // NOTE: Ctrl/Cmd + Enter executes the query, which ends the session. It is + // handled before the visibility guard below on purpose: a request queued by + // the keystroke just before would otherwise still land and open the popup + // over the running query. The event is deliberately left to travel on, so + // the Execute Query action takes over. + if (event.keyCode === monaco.KeyCode.Enter && (event.ctrlKey || event.metaKey)) { + this.hide(); + return; + } + if (!this.widget.isVisible()) return; + const consume = () => { + event.preventDefault(); + event.stopPropagation(); + }; + switch (event.keyCode) { + case monaco.KeyCode.DownArrow: + this.move(1); + return consume(); + case monaco.KeyCode.UpArrow: + this.move(-1); + return consume(); + case monaco.KeyCode.PageDown: + this.move(10); + return consume(); + case monaco.KeyCode.PageUp: + this.move(-10); + return consume(); + case monaco.KeyCode.Enter: + if (this.acceptSelected()) consume(); + return; + case monaco.KeyCode.Escape: + this.hide(); + return consume(); + case monaco.KeyCode.Tab: + // NOTE: Tab never accepts. It dismisses the popup and the event is + // deliberately left to travel on, so the jump command takes over. + this.hide(); + return; + default: + return; + } + } +} + +/** + * Whether an item survives `term`. + * + * A case insensitive prefix match on `filterText`, falling back to the label — + * the same rule `matches_search_term` applies on the server, so a list the + * server has already narrowed is never narrowed further by accident. + */ +function matchesTerm(renderItem: RenderItem, term: string): boolean { + const text = renderItem.item.filterText ?? renderItem.item.label; + return text.toLowerCase().startsWith(term.toLowerCase()); +} + +/** Monaco/JSON-RPC report a cancelled request in a few different shapes. */ +function isCancellation(error: unknown): boolean { + if (typeof error !== 'object' || error === null) return false; + const code = (error as { code?: unknown }).code; + if (code === REQUEST_CANCELLED) return true; + return (error as { name?: string }).name === 'Canceled'; +} + +/** Escapes text so `SnippetController2` inserts it literally. */ +function escapeSnippet(text: string): string { + return text.replace(/\$|}|\\/g, '\\$&'); +} + +function toRenderItem(item: CompletionItem): RenderItem { + const data = item.kind === VALUE_KIND ? item.data?.qlueLs : undefined; + if (data?.kind === 'literal') { + const content = literalContent(data); + return { + item, + content, + primary: content.value, + score: data.score ?? null, + range: rangeOf(item), + }; + } + if (data?.kind === 'entity') { + // NOTE: the item's own label is the curie, so the name leads and the curie + // sits underneath it. + const content = entityContent(data, item.label); + return { + item, + content, + primary: content.name, + score: data.score ?? null, + range: rangeOf(item), + }; + } + // NOTE: for a keyword, a snippet or a built-in call the label is already the + // name and `labelDetails.detail` is a signature. + const content: RenderContent = { + kind: 'plain', + label: item.label, + detail: item.labelDetails?.detail ?? null, + }; + return { item, content, primary: item.label, score: null, range: rangeOf(item) }; +} + +/** Datatypes that read as a number or a date rather than as quoted text. */ +const NUMBER_DATATYPES = ['integer', 'int', 'long', 'short', 'decimal', 'double', 'float']; +const DATE_DATATYPES = ['date', 'dateTime', 'dateTimeStamp', 'gYear', 'gYearMonth']; + +function literalContent(data: LiteralData): Extract { + // NOTE: the datatype arrives as a curie ("xsd:date") where the prefix map + // allowed one, and as a full IRI otherwise — the local name settles the + // colour either way. + const localName = data.datatype?.split(/[#/:]/).pop() ?? ''; + const valueKind = NUMBER_DATATYPES.includes(localName) + ? 'number' + : DATE_DATATYPES.includes(localName) + ? 'date' + : 'text'; + return { + kind: 'literal', + // NOTE: a number is written bare in SPARQL, everything else quoted, which + // is how the editor itself renders these. + value: valueKind === 'number' ? data.value : `"${data.value}"`, + suffix: data.language ? `@${data.language}` : data.datatype ? `^^${data.datatype}` : '', + valueKind, + }; +} + +function entityContent( + data: EntityData, + curie: string +): Extract { + return { + kind: 'entity', + name: data.label || curie, + curie, + iri: data.uri ?? null, + alias: data.alias ?? null, + }; +} + +function rangeOf(item: CompletionItem): Range | null { + return item.textEdit?.range ?? null; +} /** + * The start of the range the items replace, when any of them carries one. + * + * Doubles as the widget's anchor, so the popup sits at the start of the term + * and does not drift as the term grows. Items built from `insertText` alone — + * the solution modifier keywords, for one — carry no range at all, and there + * is then no term start to be had. + */ +function termStartOf(items: RenderItem[]): monaco.IPosition | undefined { + const range: Range | null = items.find((item) => item.range)?.range ?? null; + if (!range) return undefined; + return { lineNumber: range.start.line + 1, column: range.start.character + 1 }; +} diff --git a/frontend/src/editor/completion/index.ts b/frontend/src/editor/completion/index.ts new file mode 100644 index 00000000..2a5f0bf9 --- /dev/null +++ b/frontend/src/editor/completion/index.ts @@ -0,0 +1,47 @@ +// ┌─────────────────────────────────┐ \\ +// │ Copyright © 2026 Ioannis Nezis │ \\ +// ├─────────────────────────────────┤ \\ +// │ Licensed under the MIT license. │ \\ +// └─────────────────────────────────┘ \\ + +import * as monaco from 'monaco-editor'; +import type { Editor } from '../init'; +import { CompletionController } from './controller'; + +let controller: CompletionController | undefined; + +/** Replaces Monaco's suggest widget with our own completion popup. */ +export function setupCompletion(editor: Editor): CompletionController { + controller = new CompletionController(editor); + + // NOTE: Monaco's own trigger is unbound in `keys.ts`; this replaces it. + monaco.editor.addCommand({ + id: 'qlue.triggerCompletion', + run: () => controller?.trigger(), + }); + // NOTE: `WinCtrl` is the physical Ctrl key, which is what Monaco binds its own + // trigger to when it believes it runs on macOS — including under Playwright's + // WebKit, whose user agent says "Macintosh". + for (const keybinding of [ + monaco.KeyMod.CtrlCmd | monaco.KeyCode.Space, + monaco.KeyMod.WinCtrl | monaco.KeyCode.Space, + ]) { + monaco.editor.addKeybindingRule({ + command: 'qlue.triggerCompletion', + keybinding, + when: 'editorTextFocus && !editorReadonly', + }); + } + + return controller; +} + +/** Hides the completion popup, if one is open. */ +export function hideCompletion() { + controller?.hide(); +} + +/** Requests completions at the current cursor position. */ +export function triggerCompletion() { + controller?.trigger(); +} diff --git a/frontend/src/editor/completion/trace.ts b/frontend/src/editor/completion/trace.ts new file mode 100644 index 00000000..3d9e9ee3 --- /dev/null +++ b/frontend/src/editor/completion/trace.ts @@ -0,0 +1,66 @@ +// ┌─────────────────────────────────┐ \\ +// │ Copyright © 2026 Ioannis Nezis │ \\ +// ├─────────────────────────────────┤ \\ +// │ Licensed under the MIT license. │ \\ +// └─────────────────────────────────┘ \\ + +/** + * Completion tracing. + * + * Off by default. Turn it on from the devtools console with + * `completionTrace(true)`; the setting persists in `localStorage`. + * Every request gets an id so the outgoing params and the incoming + * response can be matched up, along with the round trip time. + */ + +const STORAGE_KEY = 'qlue.completionTrace'; + +let enabled = localStorage.getItem(STORAGE_KEY) === 'true'; +let nextId = 0; + +declare global { + interface Window { + completionTrace: (on?: boolean) => void; + } +} + +window.completionTrace = (on = true) => { + enabled = on; + localStorage.setItem(STORAGE_KEY, String(on)); + console.debug(`[completion] tracing ${on ? 'enabled' : 'disabled'}`); +}; + +/** + * Details are passed as a function so that nothing is computed while tracing + * is off — arguments are evaluated eagerly, so an inline object would run its + * lookups on every keystroke regardless. + */ +type Details = () => Record; + +/** A single request/response round trip. */ +export class Trace { + readonly id = ++nextId; + private readonly start = performance.now(); + + private constructor() {} + + /** Starts a trace, or returns `undefined` while tracing is off. */ + static start(label: string, details: Details): Trace | undefined { + if (!enabled) return undefined; + const trace = new Trace(); + console.debug(`[completion] #${trace.id} → ${label}`, details()); + return trace; + } + + /** Logs an event on this trace, with the elapsed time since it started. */ + log(label: string, details?: Details) { + const elapsed = (performance.now() - this.start).toFixed(1); + console.debug(`[completion] #${this.id} ← ${label} (${elapsed}ms)`, details?.() ?? ''); + } +} + +/** Logs an event that is not tied to a request. */ +export function trace(label: string, details?: Details) { + if (!enabled) return; + console.debug(`[completion] ${label}`, details?.() ?? ''); +} diff --git a/frontend/src/editor/completion/types.ts b/frontend/src/editor/completion/types.ts new file mode 100644 index 00000000..7edb381a --- /dev/null +++ b/frontend/src/editor/completion/types.ts @@ -0,0 +1,150 @@ +// ┌─────────────────────────────────┐ \\ +// │ Copyright © 2026 Ioannis Nezis │ \\ +// ├─────────────────────────────────┤ \\ +// │ Licensed under the MIT license. │ \\ +// └─────────────────────────────────┘ \\ + +import type { Range, TextEdit } from '../../types/lsp_messages'; + +/** `insertTextFormat` value marking an item whose text is a snippet template. */ +export const SNIPPET_FORMAT = 2; + +/** + * `insertTextMode` value marking text that must be inserted verbatim. + * + * The server sets it on the object completions, whose suffix already carries + * the absolute indentation it worked out from the brace nesting depth. + */ +export const AS_IS_MODE = 1; + +/** `CompletionItemKind.Value`, the kind the server uses for RDF entities. */ +export const VALUE_KIND = 12; + +export interface CompletionItemLabelDetails { + detail?: string; + description?: string; +} + +/** + * The structured payload the server sends for an entity completion. + * + * `label`, `labelDetails` and `sortText` carry the same values as presentation; + * this is the copy to read them back from, since `detail` and `documentation` + * are human fields the other completion kinds use for their own purposes. + */ +export interface EntityData { + kind: 'entity'; + label: string; + /** The alias the search term matched, absent when it matched the label. */ + alias?: string; + /** The absolute IRI the item's curie label stands for. */ + uri?: string; + /** Usage count, absent when the completion query reported none. */ + score?: number; +} + +/** + * The structured payload the server sends for a literal completion. + * + * `value` is the lexical form alone — the item's own label carries the literal + * as SPARQL writes it, quotes and tag included. + */ +export interface LiteralData { + kind: 'literal'; + value: string; + language?: string; + /** Datatype as a curie where the backend's prefix map allowed one. */ + datatype?: string; + /** Usage count, absent when the completion query reported none. */ + score?: number; +} + +/** `CompletionItem.data`, namespaced by the server that produced it. */ +export interface CompletionItemData { + qlueLs?: EntityData | LiteralData; +} + +export interface CompletionCommand { + title: string; + command: string; + arguments?: unknown[]; +} + +export interface CompletionItem { + label: string; + labelDetails?: CompletionItemLabelDetails; + kind?: number; + detail?: string; + documentation?: string; + sortText?: string; + filterText?: string; + insertText?: string; + textEdit?: TextEdit; + insertTextFormat?: number; + insertTextMode?: number; + additionalTextEdits?: TextEdit[]; + command?: CompletionCommand; + data?: CompletionItemData; +} + +/** Values a `CompletionList` applies to every item that does not set them. */ +export interface ItemDefaults { + insertTextFormat?: number; + insertTextMode?: number; +} + +export interface CompletionList { + isIncomplete: boolean; + itemDefaults?: ItemDefaults; + items: CompletionItem[]; +} + +/** What the widget currently displays. */ +export type CompletionState = + | { kind: 'items'; items: RenderItem[]; term: string } + | { kind: 'pending'; term: string } + | { kind: 'empty'; term: string } + | { kind: 'error'; message: string; term: string }; + +/** How a row is laid out, which follows from what the item is. */ +export type RenderContent = + /** + * A literal takes one line: the value has no readable-name-plus-curie split, + * so there is nothing to put on a second one. + */ + | { + kind: 'literal'; + /** The value as it reads in the editor, quoted when the type is quoted. */ + value: string; + /** The language tag or datatype trailing the value, `''` when neither. */ + suffix: string; + /** Which of the editor's syntax colours the value takes. */ + valueKind: 'text' | 'number' | 'date'; + } + /** An entity takes two: its name, and its curie underneath. */ + | { + kind: 'entity'; + name: string; + curie: string; + /** + * The absolute IRI the curie stands for, so the detail panel can link out + * to the entity. `null` for a blank node, which has none. + */ + iri: string | null; + /** The alias the search term matched, `null` when none did. */ + alias: string | null; + } + /** Keywords, snippets and built-in calls: a label and a signature. */ + | { kind: 'plain'; label: string; detail: string | null }; + +/** A completion item plus the presentation data derived from it. */ +export interface RenderItem { + item: CompletionItem; + content: RenderContent; + /** Text the search term is highlighted in, and the row is found by in tests. */ + primary: string; + /** Usage count, when the server reported one. */ + score: number | null; + /** Range this item replaces, used to anchor the widget. */ + range: Range | null; +} diff --git a/frontend/src/editor/completion/widget.ts b/frontend/src/editor/completion/widget.ts new file mode 100644 index 00000000..273e3ca3 --- /dev/null +++ b/frontend/src/editor/completion/widget.ts @@ -0,0 +1,715 @@ +// ┌─────────────────────────────────┐ \\ +// │ Copyright © 2026 Ioannis Nezis │ \\ +// ├─────────────────────────────────┤ \\ +// │ Licensed under the MIT license. │ \\ +// └─────────────────────────────────┘ \\ + +import * as monaco from 'monaco-editor'; +import { + escapeRegExp, + highlightMatches, + matchesAllKeywords, + parseKeywords, +} from '../../utils/fuzzy_filter'; +import { type CompletionState, type RenderContent, type RenderItem, VALUE_KIND } from './types'; + +const MAX_HEIGHT = '15rem'; + +/** Width of the list column; the detail column sits beside it at its own. */ +const LIST_WIDTH = '22rem'; +const DETAIL_WIDTH = '19rem'; + +const PANEL_CLASSES = [ + 'flex', + 'items-stretch', + 'rounded', + 'border', + 'border-neutral-300', + 'dark:border-neutral-700', + 'bg-white', + 'dark:bg-neutral-900', + 'text-neutral-900', + 'dark:text-neutral-100', + 'shadow-lg', + 'overflow-hidden', + 'text-sm', +]; + +const BAR_CLASSES = [ + 'flex', + 'items-center', + 'justify-between', + 'gap-3', + 'px-2', + 'py-1', + 'text-xs', + 'text-neutral-500', + 'dark:text-neutral-400', + 'bg-neutral-100', + 'dark:bg-neutral-800', +]; + +const HIGHLIGHT_CLASSES = ['text-amber-600', 'dark:text-amber-400', 'font-semibold']; + +/** Mono classes shared by the curie, by every literal value and by the timing. */ +const MONO_CLASSES = ['truncate', 'text-xs', 'font-mono']; + +const MUTED_CLASSES = ['text-neutral-500', 'dark:text-neutral-400']; + +const CURIE_CLASSES = ['text-teal-700', 'dark:text-teal-300']; + +// NOTE: the one cue that a row's text is an alias and not the entity's name. +// Warm, so it reads as kin to the amber the matched term is highlighted in, +// and darker than that highlight so the term still stands out inside it. +const ALIAS_CLASSES = ['text-amber-800', 'dark:text-amber-200']; + +// NOTE: the editor's own syntax colours for the three literal shapes, so a +// suggestion reads the way it will read once inserted. +const VALUE_CLASSES: Record['valueKind'], string[]> = { + text: ['text-orange-700', 'dark:text-orange-300'], + number: ['text-emerald-700', 'dark:text-emerald-300'], + date: ['text-yellow-700', 'dark:text-yellow-200'], +}; + +/** `CompletionItemKind` values, for the detail panel's Type field. */ +const KIND_LABELS: Record = { + 2: 'Method', + 3: 'Function', + 6: 'Variable', + [VALUE_KIND]: 'Value', + 14: 'Keyword', + 15: 'Snippet', +}; + +const SPINNER_CLASSES = [ + 'size-3', + 'shrink-0', + 'rounded-full', + 'border', + 'border-neutral-400', + 'dark:border-neutral-500', + 'border-t-transparent', + 'dark:border-t-transparent', + 'animate-spin', +]; + +function createSpinner(...extra: string[]): HTMLElement { + const spinner = document.createElement('span'); + spinner.setAttribute('role', 'status'); + spinner.setAttribute('aria-label', 'Loading suggestions'); + spinner.classList.add(...SPINNER_CLASSES, ...extra); + return spinner; +} + +/** + * The completion popup. + * + * One surface split in two columns: a list of one-line rows on the left, and a + * panel on the right holding everything about the selected row that is not the + * text it matched on. A row therefore never grows a second line, and the facts + * one consults *after* finding the row — its canonical name, score, type, + * documentation — are read in one place instead of being crammed into all of + * them. + * + * Rendered as a Monaco content widget so it inherits Monaco's anchoring and + * above/below flipping. Monaco caches the widget's measured size and only + * invalidates that cache on `layoutContentWidget`, so every render calls it. + */ +export class CompletionWidget implements monaco.editor.IContentWidget { + // NOTE: render outside the editor's overflow:hidden view node, matching the + // `fixedOverflowWidgets` setting used for the other widgets. + readonly allowEditorOverflow = true; + // NOTE: keeps a click on a row from stealing focus from the editor. + readonly suppressMouseDown = true; + + private readonly domNode: HTMLElement; + private readonly panel: HTMLElement; + private readonly header: HTMLElement; + private readonly headerTerm: HTMLElement; + private readonly headerCount: HTMLElement; + private readonly spinner: HTMLElement; + private readonly body: HTMLElement; + private readonly headerMeta: HTMLElement; + private readonly timingNote: HTMLElement; + private readonly headerSeparator: HTMLElement; + private readonly staleNote: HTMLElement; + private readonly detail: HTMLElement; + + private position: monaco.IPosition | null = null; + private visible = false; + private rows: HTMLElement[] = []; + private items: RenderItem[] = []; + + constructor( + private readonly editor: monaco.editor.IStandaloneCodeEditor, + private readonly callbacks: { + onAccept: (index: number) => void; + onRetry: () => void; + onOpenSettings: () => void; + } + ) { + // NOTE: Monaco writes `display: block` inline on a content widget's dom + // node, which would override a `flex` class on it. The layout therefore + // lives on an inner panel that Monaco does not touch. + this.domNode = document.createElement('div'); + this.domNode.dataset.testid = 'completion-widget'; + + this.panel = document.createElement('div'); + this.panel.classList.add(...PANEL_CLASSES); + this.panel.style.maxWidth = 'calc(100vw - 32px)'; + this.panel.style.maxHeight = MAX_HEIGHT; + + const list = document.createElement('div'); + list.classList.add('flex', 'flex-col', 'min-w-0', 'shrink-0'); + list.style.width = LIST_WIDTH; + + this.header = document.createElement('div'); + this.header.classList.add(...BAR_CLASSES, 'border-b', 'border-neutral-200'); + this.header.classList.add('dark:border-neutral-700'); + const status = document.createElement('span'); + status.classList.add('flex', 'items-center', 'gap-2', 'min-w-0'); + this.spinner = createSpinner(); + this.spinner.dataset.testid = 'completion-spinner'; + this.spinner.hidden = true; + this.headerTerm = document.createElement('span'); + this.headerTerm.classList.add('truncate'); + status.append(this.spinner, this.headerTerm); + // NOTE: the header's right half. Everything in it is toggled between + // renders — a keystroke re-requests without re-rendering the list — so it + // is built once and lives for the widget's lifetime. + this.headerCount = document.createElement('span'); + this.headerCount.classList.add('tabular-nums'); + this.timingNote = document.createElement('span'); + this.timingNote.dataset.testid = 'completion-timing'; + this.timingNote.classList.add('font-mono', 'tabular-nums'); + this.timingNote.hidden = true; + this.headerMeta = document.createElement('span'); + this.headerMeta.classList.add('flex', 'items-center', 'gap-2', 'shrink-0'); + const separator = document.createElement('span'); + separator.textContent = '·'; + separator.hidden = true; + this.headerSeparator = separator; + this.headerMeta.append(this.timingNote, separator, this.headerCount); + this.staleNote = document.createElement('span'); + this.staleNote.dataset.testid = 'completion-stale'; + this.staleNote.classList.add('truncate', 'min-w-0'); + this.staleNote.hidden = true; + this.header.append(status, this.headerMeta, this.staleNote); + + this.body = document.createElement('div'); + // NOTE: `min-h-0` lets the list shrink inside the flex column, so a long + // list scrolls rather than growing the panel past its maximum height. + this.body.classList.add('overflow-y-auto', 'overflow-x-hidden', 'flex-1', 'min-h-0'); + this.body.setAttribute('role', 'listbox'); + + this.detail = document.createElement('div'); + this.detail.dataset.testid = 'completion-detail'; + this.detail.classList.add( + 'flex', + 'flex-col', + 'gap-2', + 'shrink-0', + 'min-w-0', + 'px-3', + 'py-2', + 'overflow-y-auto', + 'border-l', + 'border-neutral-200', + 'dark:border-neutral-700', + 'bg-neutral-50', + 'dark:bg-neutral-800/40' + ); + this.detail.style.width = DETAIL_WIDTH; + this.detail.hidden = true; + + list.append(this.header, this.body); + this.panel.append(list, this.detail); + this.domNode.append(this.panel); + editor.addContentWidget(this); + } + + getId(): string { + return 'qlue.completionWidget'; + } + + getDomNode(): HTMLElement { + return this.domNode; + } + + getPosition(): monaco.editor.IContentWidgetPosition | null { + if (!this.visible || !this.position) return null; + return { + position: this.position, + preference: [ + monaco.editor.ContentWidgetPositionPreference.BELOW, + monaco.editor.ContentWidgetPositionPreference.ABOVE, + ], + }; + } + + isVisible(): boolean { + return this.visible; + } + + /** Shows or hides the spinner that marks a request in flight. */ + setPending(pending: boolean) { + if (this.spinner.hidden === !pending) return; + this.spinner.hidden = !pending; + // NOTE: Monaco caches the widget's measured size until it is told the + // widget changed, and the spinner is the only thing that changes outside a + // render. + this.editor.layoutContentWidget(this); + } + + /** + * Shows how long the round trip that produced the current list took. + * + * An entity completion goes to the endpoint, so the number is the one thing + * that says whether a slow popup is the network or the editor. + */ + setTiming(ms: number | null) { + const hidden = ms === null; + if (!hidden) this.timingNote.textContent = `${Math.round(ms).toLocaleString()} ms`; + if (this.timingNote.hidden === hidden) return; + this.timingNote.hidden = hidden; + this.syncHeaderMeta(); + this.editor.layoutContentWidget(this); + } + + /** + * Marks the list as belonging to an older term than the one being typed. + * + * The rows stay in place and stay selectable — a list the user is already + * reading must not be blanked — but they dim while the answer for the live + * term is on its way, and the header says which term they are answering. + */ + setStale(term: string | null) { + const stale = term !== null; + if (stale) { + this.staleNote.replaceChildren('showing results for ', termElement(term)); + } + if (this.staleNote.hidden === !stale) return; + this.staleNote.hidden = !stale; + // NOTE: the header is only as wide as the list column, so the timing and + // the count stand down for the stale mark rather than being overlapped by + // it — and neither describes the list that is on its way anyway. + this.headerMeta.hidden = stale; + // NOTE: opacity alone, so the rows keep their colours and stay readable; + // the pulse is what says the list is still moving. + this.body.classList.toggle('opacity-50', stale); + this.body.classList.toggle('animate-pulse', stale); + this.editor.layoutContentWidget(this); + } + + /** + * Updates the term in the header without rebuilding the list. + * + * NOTE: an entity list is re-requested on every keystroke and only re-renders + * once the answer lands, so the header would otherwise name the term the last + * response was for rather than the one on screen. + */ + setTerm(term: string) { + if (!this.applyTerm(term)) return; + this.editor.layoutContentWidget(this); + } + + /** Writes the header term, reporting whether it changed. */ + private applyTerm(term: string): boolean { + if (this.headerTerm.dataset.term === term) return false; + this.headerTerm.dataset.term = term; + this.headerTerm.replaceChildren(); + if (!term) { + this.headerTerm.textContent = 'Suggestions'; + return true; + } + this.headerTerm.append('matching ', termElement(term)); + return true; + } + + hide() { + if (!this.visible) return; + this.visible = false; + this.domNode.style.display = 'none'; + // NOTE: a hidden row is still in the DOM, and a dismissed list must not + // leave one behind for anything that counts rows rather than looks at them. + this.body.replaceChildren(); + this.rows = []; + this.items = []; + this.detail.replaceChildren(); + this.detail.hidden = true; + this.spinner.hidden = true; + this.setStale(null); + this.setTiming(null); + this.applyTerm(''); + this.editor.layoutContentWidget(this); + } + + /** Renders `state` at `position` and makes the widget visible. */ + show(state: CompletionState, position: monaco.IPosition, selected: number) { + this.position = position; + this.visible = true; + this.domNode.style.display = ''; + this.render(state, selected); + } + + /** Shows the separator only when it has something on both sides of it. */ + private syncHeaderMeta() { + this.headerSeparator.hidden = this.timingNote.hidden || !this.headerCount.textContent; + } + + /** Moves the highlight without rebuilding the list. */ + select(index: number) { + this.rows.forEach((row, i) => { + setRowSelected(row, i === index); + if (i === index) row.scrollIntoView({ block: 'nearest' }); + }); + this.body.setAttribute('aria-activedescendant', `completion-item-${index}`); + this.renderDetail(index); + } + + private render(state: CompletionState, selected: number) { + this.applyTerm(state.term); + this.body.replaceChildren(); + this.rows = []; + this.items = state.kind === 'items' ? state.items : []; + this.detail.replaceChildren(); + this.detail.hidden = state.kind !== 'items'; + this.headerCount.textContent = state.kind === 'items' ? String(state.items.length) : ''; + this.syncHeaderMeta(); + + if (state.kind === 'items') { + this.renderItems(state.items, state.term, selected); + this.renderDetail(selected); + } else if (state.kind === 'pending') { + this.renderMessage( + 'Searching…', + state.term ? `Looking for suggestions matching ${state.term}.` : 'Looking for suggestions.', + createSpinner('mt-1') + ); + } else if (state.kind === 'empty') { + this.renderMessage( + 'Nothing matches', + state.term + ? `No suggestion in this position matches ${state.term}.` + : 'No suggestion is available in this position.' + ); + } else { + const panel = this.renderMessage('Suggestions unavailable', state.message); + const actions = document.createElement('div'); + actions.classList.add('flex', 'gap-3', 'mt-2'); + actions.append( + linkButton('Try again', this.callbacks.onRetry), + linkButton('Completion settings', this.callbacks.onOpenSettings) + ); + panel.append(actions); + } + + this.editor.layoutContentWidget(this); + } + + /** + * The list: one line per candidate. + * + * A row leads with the string the term will highlight in: the label, or the + * alias where the label is not it. The highlight is therefore always in view + * and no row has to carry both strings. An alias is tinted warm, which is + * the only cue that the text is not the entity's canonical name; that name + * is in the panel, read on selection. Two entities can therefore sit in the + * list under near-identical text, told apart by their curies. + */ + private renderItems(items: RenderItem[], term: string, selected: number) { + // NOTE: the term is source text, not a search query — `?la` would otherwise + // be a broken regex and get dropped, leaving nothing highlighted. + const keywords = parseKeywords(escapeRegExp(term)); + items.forEach((renderItem, index) => { + const content = renderItem.content; + const row = document.createElement('div'); + row.id = `completion-item-${index}`; + row.dataset.testid = 'completion-item'; + row.setAttribute('role', 'option'); + row.classList.add( + 'flex', + 'items-baseline', + 'gap-2', + 'px-2', + 'py-0.5', + 'cursor-pointer', + 'border-l-2', + 'border-transparent' + ); + + // NOTE: the alias leads only where the label is not what the term + // highlights in. `matchesAllKeywords` is the predicate `highlightMatches` + // renders from, so the row cannot pick a string the highlight then fails + // to appear in — and how the completion query matched, prefix or + // substring or something else, is never guessed at here. + const alias = + content.kind === 'entity' && content.alias && !matchesAllKeywords(content.name, keywords) + ? content.alias + : null; + + const primary = document.createElement('span'); + // NOTE: the text gives way down to a floor that still shows a few + // characters, and the curie never shrinks at all, because it is what + // will be inserted. + primary.classList.add('flex-1', 'min-w-[82px]', 'truncate'); + if (content.kind === 'literal') { + primary.classList.add('font-mono', ...VALUE_CLASSES[content.valueKind]); + } else if (alias) { + primary.classList.add(...ALIAS_CLASSES); + } + primary.innerHTML = highlightMatches( + alias ?? primaryText(content), + keywords, + HIGHLIGHT_CLASSES + ); + row.append(primary); + + const trailing = trailingText(content); + if (trailing) { + const tail = document.createElement('span'); + tail.classList.add('shrink-0', 'text-xs', 'font-mono'); + tail.classList.add(...(content.kind === 'plain' ? SIGNATURE_CLASSES : CURIE_CLASSES)); + tail.textContent = trailing; + row.append(tail); + } + + setRowSelected(row, index === selected); + row.addEventListener('click', () => this.callbacks.onAccept(index)); + this.body.append(row); + this.rows.push(row); + }); + this.body.setAttribute('aria-activedescendant', `completion-item-${selected}`); + this.rows[selected]?.scrollIntoView({ block: 'nearest' }); + } + + /** + * The panel beside the list, describing the selected row alone. + * + * Every field is omitted when the server did not send it, so the panel says + * what is known and never states a placeholder — an entity list carries a + * score, a keyword carries documentation, and neither carries both. + */ + private renderDetail(index: number) { + const renderItem = this.items[index]; + if (!renderItem) { + this.detail.replaceChildren(); + return; + } + const content = renderItem.content; + + const title = document.createElement('div'); + title.classList.add('font-semibold', 'leading-tight', 'break-words'); + title.textContent = primaryText(content); + this.detail.replaceChildren(title); + + // NOTE: `detail` is the server's one line gloss ("Group the results"); the + // signature the row already trails lives in `labelDetails` and is not + // repeated here. + if (renderItem.item.detail) { + const summary = document.createElement('div'); + summary.classList.add('text-xs', '-mt-1', ...MUTED_CLASSES); + summary.textContent = renderItem.item.detail; + this.detail.append(summary); + } + + if (content.kind === 'entity') { + this.detail.append(identityLine(content)); + } + + const fields = document.createElement('div'); + fields.classList.add('flex', 'flex-col', 'gap-1', 'text-xs'); + if (renderItem.score !== null) { + fields.append(field('Score', monoValue(renderItem.score.toLocaleString()))); + } + const type = typeLabel(renderItem); + if (type) fields.append(field('Type', plainValue(type))); + // NOTE: stated whenever the server sent one, and stated as nothing more + // than the entity's alias — whether the row led with it or with the label + // is the row's business, not something the panel can claim. + if (content.kind === 'entity' && content.alias) { + fields.append(field('Alias', aliasValue(content.alias))); + } + if (fields.childElementCount > 0) this.detail.append(fields); + + const documentation = renderItem.item.documentation; + if (documentation) { + const doc = document.createElement('div'); + doc.classList.add( + 'text-xs', + 'leading-relaxed', + 'pt-2', + 'border-t', + 'border-neutral-200', + 'dark:border-neutral-700', + ...MUTED_CLASSES + ); + doc.textContent = documentation; + this.detail.append(doc); + } + } + + private renderMessage(title: string, message: string, icon?: HTMLElement): HTMLElement { + const panel = document.createElement('div'); + panel.classList.add('px-3', 'py-3'); + const heading = document.createElement('div'); + heading.classList.add('font-semibold'); + heading.textContent = title; + const body = document.createElement('div'); + body.classList.add('text-xs', 'text-neutral-500', 'dark:text-neutral-400', 'mt-1'); + body.textContent = message; + if (icon) { + // NOTE: the icon sits beside the text as a whole, so the heading and the + // body go in a column of their own rather than side by side with it. + const text = document.createElement('div'); + text.classList.add('min-w-0'); + text.append(heading, body); + const row = document.createElement('div'); + row.classList.add('flex', 'items-start', 'gap-2'); + row.append(icon, text); + panel.append(row); + } else { + panel.append(heading, body); + } + this.body.append(panel); + return panel; + } + + dispose() { + this.editor.removeContentWidget(this); + } +} + +const SIGNATURE_CLASSES = ['text-sky-700', 'dark:text-sky-400']; + +/** + * An item's canonical text, which for an entity found by an alias is not the + * text its row displayed. + */ +function primaryText(content: RenderContent): string { + if (content.kind === 'literal') return content.value; + if (content.kind === 'entity') return content.name; + return content.label; +} + +/** What trails the name on a row: the curie, the literal's tag, a signature. */ +function trailingText(content: RenderContent): string { + if (content.kind === 'literal') return content.suffix; + if (content.kind === 'entity') return content.curie; + return content.detail ?? ''; +} + +/** + * The Type field: what the completion is, in the terms the server describes it. + * + * A literal's type is its datatype or language tag — the thing that decides how + * it is written — rather than the word "literal", which every one of them is. + */ +function typeLabel(renderItem: RenderItem): string | null { + const content = renderItem.content; + if (content.kind === 'entity') return 'Entity'; + if (content.kind === 'literal') return content.suffix.replace('^^', '') || 'Literal'; + // NOTE: the keyword completions carry no kind at all, and naming them + // something generic would say less than saying nothing. + const kind = renderItem.item.kind; + return kind === undefined ? null : (KIND_LABELS[kind] ?? null); +} + +/** + * The entity's curie, linking out to the IRI it stands for. + * + * The IRI itself is what identifies the entity, but it is long and the curie is + * what the query will read, so the curie is the text and the IRI is where it + * goes — and the title attribute, for anyone who wants to see it without + * leaving the page. A blank node has no IRI, so it is plain text: there is + * nowhere for it to lead. + */ +function identityLine(content: Extract): HTMLElement { + const classes = ['text-xs', 'font-mono', 'break-all', ...CURIE_CLASSES]; + if (!content.iri) { + const curie = document.createElement('div'); + curie.classList.add(...classes); + curie.textContent = content.curie; + return curie; + } + const link = document.createElement('a'); + link.dataset.testid = 'completion-detail-iri'; + link.classList.add(...classes, 'hover:underline', 'cursor-pointer'); + link.href = content.iri; + link.title = content.iri; + link.target = '_blank'; + link.rel = 'noopener noreferrer'; + link.textContent = content.curie; + return link; +} + +function field(label: string, value: HTMLElement): HTMLElement { + const row = document.createElement('div'); + row.classList.add('flex', 'items-baseline', 'gap-2'); + const name = document.createElement('span'); + name.classList.add('w-12', 'shrink-0', ...MUTED_CLASSES); + name.textContent = label; + row.append(name, value); + return row; +} + +function monoValue(text: string): HTMLElement { + const value = document.createElement('span'); + value.classList.add(...MONO_CLASSES, 'tabular-nums'); + value.textContent = text; + return value; +} + +function plainValue(text: string): HTMLElement { + const value = document.createElement('span'); + value.classList.add('min-w-0', 'truncate'); + value.textContent = text; + return value; +} + +/** + * The Alias field's value, in the tint a row gives an alias it leads with. + * + * It wraps over as many lines as it needs rather than truncating: the panel is + * where you come when the row cut the alias short. + */ +function aliasValue(alias: string): HTMLElement { + const value = document.createElement('span'); + value.classList.add('min-w-0', 'break-words', ...ALIAS_CLASSES); + value.textContent = alias; + return value; +} + +/** + * A search term, in the amber the rows highlight it in — so the header names + * the same thing the rows are marking. + */ +function termElement(term: string): HTMLElement { + const value = document.createElement('span'); + value.classList.add('font-mono', 'text-amber-600', 'dark:text-amber-400'); + value.textContent = term; + return value; +} + +function setRowSelected(row: HTMLElement, selected: boolean) { + row.classList.toggle('bg-neutral-100', selected); + row.classList.toggle('dark:bg-neutral-800', selected); + row.classList.toggle('border-sky-500', selected); + row.classList.toggle('border-transparent', !selected); + row.setAttribute('aria-selected', String(selected)); +} + +function linkButton(label: string, onClick: () => void): HTMLElement { + const button = document.createElement('button'); + button.type = 'button'; + button.classList.add( + 'text-xs', + 'text-sky-700', + 'dark:text-sky-400', + 'hover:underline', + 'cursor-pointer' + ); + button.textContent = label; + button.addEventListener('click', onClick); + return button; +} diff --git a/frontend/src/editor/config/config.ts b/frontend/src/editor/config/config.ts index c65658be..5312fc6a 100644 --- a/frontend/src/editor/config/config.ts +++ b/frontend/src/editor/config/config.ts @@ -96,6 +96,12 @@ export function buildWrapperConfig(initial: string) { uri: Uri.parse('file:/'), }, progressOnInitialization: true, + // NOTE: starve Monaco's suggest widget even if something still triggers + // it. This only wraps the provider path; the custom widget's own + // `sendRequest` is unaffected. + middleware: { + provideCompletionItem: () => null, + }, diagnosticPullOptions: { onChange: true, onSave: false, @@ -126,17 +132,17 @@ export function buildWrapperConfig(initial: string) { }, }, editorOptions: { - tabCompletion: 'on', + // NOTE: Monaco's suggest widget is fully replaced by the custom + // completion widget (see `editor/completion/`), so every path that + // could open it is disabled here. + tabCompletion: 'off', + quickSuggestions: false, + suggestOnTriggerCharacters: false, + acceptSuggestionOnEnter: 'off', + acceptSuggestionOnCommitCharacter: false, + snippetSuggestions: 'none', + inlineSuggest: { enabled: false }, formatOnType: true, - suggestOnTriggerCharacters: true, - // NOTE: Pin the pre-v37 default; "offWhenInlineCompletions" delays quick suggestions - // and leaks disposables (DisposableStore warning) on every trigger. - quickSuggestions: { - other: 'on', - comments: 'off', - strings: 'off', - }, - quickSuggestionsDelay: 100, fontSize: 14, fontFamily: 'Source Code Pro', detectIndentation: false, @@ -161,13 +167,6 @@ export function buildWrapperConfig(initial: string) { folding: true, foldingImportsByDefault: false, wordBasedSuggestions: 'off', - snippetSuggestions: 'bottom', - suggest: { - filterGraceful: false, - localityBonus: false, - shareSuggestSelections: false, - showWords: false, - }, autoIndent: 'none', guides: { bracketPairsHorizontal: 'active', diff --git a/frontend/src/editor/init.ts b/frontend/src/editor/init.ts index 08853645..0b4cb120 100644 --- a/frontend/src/editor/init.ts +++ b/frontend/src/editor/init.ts @@ -12,6 +12,7 @@ import { LanguageClientWrapper } from 'monaco-languageclient/lcwrapper'; import { MonacoVscodeApiWrapper } from 'monaco-languageclient/vscodeApiWrapper'; import { initStep } from '../timing'; import { setup_commands } from './commands'; +import { setupCompletion } from './completion'; import { buildWrapperConfig, waitForLanguageServer } from './config/config'; import { setup_key_bindings } from './keys'; @@ -81,6 +82,8 @@ export async function setupEditor(container_id: string): Promise { setup_key_bindings(editor); setup_commands(editor); + // NOTE: after the keybindings, so the completion Tab rule wins over the jump rule. + const completion = setupCompletion(editor); setup_toggle_theme(); // NOTE: Initially focus the editor. @@ -105,7 +108,7 @@ export async function setupEditor(container_id: string): Promise { 'scroll', (e) => { if (editorContainer.contains(e.target as Node)) return; - monacoEditor.trigger('scroll', 'hideSuggestWidget', {}); + completion.hide(); monacoEditor.trigger('scroll', 'editor.action.hideHover', {}); }, { passive: true, capture: true } diff --git a/frontend/src/editor/keys.ts b/frontend/src/editor/keys.ts index 88599b10..5ac486c6 100644 --- a/frontend/src/editor/keys.ts +++ b/frontend/src/editor/keys.ts @@ -73,6 +73,18 @@ export function setup_key_bindings(editor: Editor) { when: '!inSnippetMode && editorTextFocus', }); + // NOTE: unbind every chord Monaco's suggest trigger holds; the custom + // completion widget rebinds Ctrl + Space to its own trigger in + // `completion/index.ts`. The `WinCtrl` variant is the one Monaco uses + // on macOS, so leaving it bound surfaced the built-in widget there. + for (const keybinding of [ + monaco.KeyMod.CtrlCmd | monaco.KeyCode.Space, + monaco.KeyMod.WinCtrl | monaco.KeyCode.Space, + monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyI, + ]) { + monaco.editor.addKeybindingRule({ command: null, keybinding }); + } + // NOTE:jump to next or prev position monaco.editor.addCommand({ id: 'jumpToNextPosition', diff --git a/frontend/src/editor/style.css b/frontend/src/editor/style.css index 43130886..33d9d51b 100644 --- a/frontend/src/editor/style.css +++ b/frontend/src/editor/style.css @@ -17,52 +17,6 @@ min-width: 250px; } -/* Responsive suggest widget */ -.monaco-editor .suggest-widget { - width: min(600px, calc(100vw - 32px)); - min-width: min(300px, calc(100vw - 32px)); - max-width: calc(100vw - 32px); -} - -/* Mobile adjustments for suggest widget */ -@media (max-width: 640px) { - .monaco-editor .suggest-widget { - width: calc(100vw - 24px); - min-width: calc(100vw - 24px); - left: 12px; - right: 12px; - } - - /* Tighter padding on mobile */ - .monaco-editor .suggest-widget .monaco-list-row { - padding-left: 4px; - padding-right: 4px; - } -} - -/* Right-align labelDetail in completion items */ -.monaco-editor .suggest-widget .monaco-icon-label-container { - display: flex; - justify-content: space-between; - width: 100%; -} - -.monaco-editor .suggest-widget .signature-label { - margin-left: auto; - padding-left: 12px; - padding-right: 0; - margin-right: -8px; - opacity: 0.7; - white-space: nowrap; -} - -/* Better contrast for labelDetail when selected (light mode) */ -.monaco-editor .suggest-widget .monaco-list-row.focused .signature-label, -.monaco-editor .suggest-widget .monaco-list-row.selected .signature-label { - opacity: 1; - font-weight: 500; -} - /* Parse tree hover highlight */ .parseTreeHighlight { background-color: rgba(59, 130, 246, 0.15); diff --git a/frontend/src/utils/fuzzy_filter.ts b/frontend/src/utils/fuzzy_filter.ts index 571ea9ac..da96f80a 100644 --- a/frontend/src/utils/fuzzy_filter.ts +++ b/frontend/src/utils/fuzzy_filter.ts @@ -61,3 +61,8 @@ export function highlightMatches(text: string, keywords: RegExp[], classes: stri return result; } + +/** Escapes regex metacharacters so a literal string can be used as a keyword. */ +export function escapeRegExp(text: string): string { + return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 00000000..508cbc11 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,18 @@ +{ + "name": "qlue-ui", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "dependencies": { + "qlue-ls": "^3.11.0" + } + }, + "node_modules/qlue-ls": { + "version": "3.11.0", + "resolved": "https://registry.npmjs.org/qlue-ls/-/qlue-ls-3.11.0.tgz", + "integrity": "sha512-XnT7dTrWGjWE8QlI59xvEdm4mYIr6PAqqCQFHPT8VtT6BYSMTRv4R/gykLsmlkoZ/WDr/DsczzgNBA5pK/EUaA==", + "license": "SEE LICENSE IN LICENSE" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 00000000..1c1f92f4 --- /dev/null +++ b/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "qlue-ls": "^3.11.0" + } +} diff --git a/testing/tests/completion.spec.ts b/testing/tests/completion.spec.ts new file mode 100644 index 00000000..24bf92d7 --- /dev/null +++ b/testing/tests/completion.spec.ts @@ -0,0 +1,436 @@ +import { expect, test } from '@playwright/test'; +import { ctrlCmd, getEditorContent, placeCursor, setEditorContent } from './utils'; + +// Regression tests for the custom completion controller +// (frontend/src/editor/completion/). Each test pins one bug that shipped, so +// the name says what must not happen again rather than what is exercised. + +const RDFS = 'PREFIX rdfs: '; +const EX = 'PREFIX ex: '; + +test.beforeEach(async ({ page }) => { + await page.goto('./test'); + await expect(page.locator('#loadingScreen')).toHaveCount(0, { timeout: 15000 }); +}); + +test.describe('completion', () => { + test('a term that is not a valid regex still filters', async ({ page }) => { + // "?abas" compiled to an invalid regex, was dropped, and an empty keyword + // list matched everything -- so the list never narrowed. + await setEditorContent(page, [RDFS, 'SELECT * WHERE {', ' ?a rdfs:label ', '}'].join('\n')); + await placeCursor(page, 3, 17); + + const editor = page.getByRole('textbox', { name: 'Editor content' }); + const widget = page.getByTestId('completion-widget'); + + await editor.pressSequentially('?la', { delay: 60 }); + await expect(widget).toBeVisible({ timeout: 10000 }); + await expect(widget.getByTestId('completion-item').filter({ hasText: '?label' })).toHaveCount( + 1, + ); + + await editor.pressSequentially('bas', { delay: 60 }); + await expect(widget.getByTestId('completion-item')).toHaveCount(0); + }); + + test('the matched part of the term is highlighted when typing from cold', async ({ page }) => { + // The widget anchor falls back to the cursor at request time, which sits + // after what was already typed. Using it as the term start yielded an empty + // term, so nothing highlighted -- but only when typing without a preceding + // explicit trigger, which is what made it easy to miss. + await setEditorContent(page, ['SELECT * WHERE {', '}', ''].join('\n')); + await placeCursor(page, 3, 1); + + const editor = page.getByRole('textbox', { name: 'Editor content' }); + const widget = page.getByTestId('completion-widget'); + + await editor.pressSequentially('G', { delay: 60 }); + await expect(widget).toBeVisible({ timeout: 10000 }); + + const item = widget.getByTestId('completion-item').filter({ hasText: 'GROUP BY' }).first(); + await expect(item.locator('.text-amber-600')).toHaveText('G'); + }); + + test('accepting replaces the whole term, not just what the server saw', async ({ page }) => { + // A complete list is filtered locally rather than re-requested, so the + // server's replace range is several keystrokes old by the time an item is + // accepted. Applying it verbatim left the typed "la" behind. + await setEditorContent(page, [RDFS, 'SELECT * WHERE {', ' ?a rdfs:label ', '}'].join('\n')); + await placeCursor(page, 3, 17); + + const editor = page.getByRole('textbox', { name: 'Editor content' }); + const widget = page.getByTestId('completion-widget'); + + await editor.pressSequentially('?la', { delay: 60 }); + await expect(widget).toBeVisible({ timeout: 10000 }); + await widget.getByTestId('completion-item').filter({ hasText: '?label' }).first().click(); + + await expect.poll(() => getEditorContent(page), { timeout: 5000 }).toContain( + '?a rdfs:label ?label', + ); + // The leftover showed up as a bare "la" on a line of its own. + expect(await getEditorContent(page)).not.toMatch(/^\s*la\s*$/m); + }); + + test('a variable suggestion drops out once the term cannot match it', async ({ + page, + browserName, + }) => { + // Variable items are merged into the entity list, which is isIncomplete and + // so was rendered unfiltered -- leaving "?acted_in" on screen next to + // entities matching a completely different term. + await setEditorContent(page, [EX, 'SELECT * WHERE {', ' ?a ex:actedIn ', '}'].join('\n')); + await placeCursor(page, 3, 17); + + const editor = page.getByRole('textbox', { name: 'Editor content' }); + const widget = page.getByTestId('completion-widget'); + + await page.keyboard.press(`${ctrlCmd(browserName)}+Space`); + await expect(widget).toBeVisible({ timeout: 15000 }); + await expect( + widget.getByTestId('completion-item').filter({ hasText: '?acted_in' }), + ).not.toHaveCount(0); + + // "The Iron Lady" is an object of ex:actedIn; "?acted_in" is not a prefix + // of it, so the variable suggestion has to go while the entities stay. + await editor.pressSequentially('The Iron', { delay: 60 }); + await expect( + widget.getByTestId('completion-item').filter({ hasText: 'The Iron Lady' }).first(), + ).toBeVisible({ timeout: 15000 }); + await expect(widget.getByTestId('completion-item').filter({ hasText: '?acted_in' })).toHaveCount( + 0, + ); + }); + + test('a freshly typed variable dismisses instead of reporting no match', async ({ page }) => { + // The server only suggests the other variables in the query and drops the + // one being typed, so "?abc" in an otherwise variable free query returns a + // truthful empty list -- which was rendered as "Nothing matches" for a name + // the user had just finished writing. + await setEditorContent(page, ['SELECT * WHERE {', ' ', '}'].join('\n')); + await placeCursor(page, 2, 3); + + const editor = page.getByRole('textbox', { name: 'Editor content' }); + const widget = page.getByTestId('completion-widget'); + + await editor.pressSequentially('?abc', { delay: 60 }); + // NOTE: the widget starts hidden, so it has to be given the time to come + // back with the empty response before "still hidden" means anything. + await page.waitForTimeout(2000); + await expect(widget).toBeHidden(); + }); + + test('an inserted snippet is indented onto the line it lands on', async ({ page }) => { + // The snippet carries its own relative indentation, which was inserted + // verbatim -- so the sub select came out flat against the left margin. + await setEditorContent(page, ['SELECT * WHERE {', ' ', '}'].join('\n')); + await placeCursor(page, 2, 3); + + const editor = page.getByRole('textbox', { name: 'Editor content' }); + const widget = page.getByTestId('completion-widget'); + + await editor.pressSequentially('Sub', { delay: 60 }); + await expect(widget).toBeVisible({ timeout: 10000 }); + await widget.getByTestId('completion-item').filter({ hasText: 'Sub select' }).first().click(); + + await expect + .poll(() => getEditorContent(page), { timeout: 5000 }) + .toBe( + [ + 'SELECT * WHERE {', + ' {', + ' SELECT * WHERE {', + ' ', + ' }', + ' }', + '}', + ].join('\n') + ); + }); + + test('the object suffix keeps the indentation the server gave it', async ({ page }) => { + // The suffix carries the absolute indentation the server worked out from + // the brace nesting depth, and says so with `insertTextMode: AsIs`. Adding + // the current line's indentation on top of it put the next triple 2 columns + // too far in. + await setEditorContent( + page, + [EX, 'SELECT * WHERE {', ' ?a ex:actedIn ', '}'].join('\n') + ); + await placeCursor(page, 3, 17); + + const editor = page.getByRole('textbox', { name: 'Editor content' }); + const widget = page.getByTestId('completion-widget'); + + await editor.pressSequentially('Th', { delay: 60 }); + await expect(widget).toBeVisible({ timeout: 15000 }); + await widget.getByTestId('completion-item').filter({ hasText: 'The Iron Lady' }).first().click(); + + await expect + .poll(() => getEditorContent(page), { timeout: 5000 }) + .toBe( + [EX, 'SELECT * WHERE {', ' ?a ex:actedIn ex:the_iron_lady .', ' ', '}'].join('\n') + ); + }); + + test('a snippet accepted inside a snippet keeps the outer tabstops', async ({ page }) => { + // Monaco's `apply` cancels a running snippet session before inserting, so + // accepting YEAR in the first stop of "BIND ($1 AS ?$0)" threw away the + // variable stop and Tab could no longer reach it. + await setEditorContent(page, ['SELECT * WHERE {', ' ?a ?B ?c .', ' ', '}'].join('\n')); + await placeCursor(page, 3, 3); + + const editor = page.getByRole('textbox', { name: 'Editor content' }); + const widget = page.getByTestId('completion-widget'); + + await editor.pressSequentially('B', { delay: 60 }); + await expect(widget).toBeVisible({ timeout: 10000 }); + await widget.getByTestId('completion-item').filter({ hasText: 'BIND' }).first().click(); + + await editor.pressSequentially('Ye', { delay: 60 }); + await expect(widget).toBeVisible({ timeout: 10000 }); + await widget.getByTestId('completion-item').filter({ hasText: 'YEAR' }).first().click(); + + // The outer stop is the one after "AS ?". + await editor.press('Tab'); + await editor.pressSequentially('year'); + + await expect + .poll(() => getEditorContent(page), { timeout: 5000 }) + .toContain('BIND (YEAR(datetime) AS ?year)'); + }); + + test('the header spins while a request is out', async ({ page }) => { + await setEditorContent(page, [EX, 'SELECT * WHERE {', ' ', '}'].join('\n')); + await placeCursor(page, 3, 3); + + const editor = page.getByRole('textbox', { name: 'Editor content' }); + const widget = page.getByTestId('completion-widget'); + const spinner = page.getByTestId('completion-spinner'); + + await editor.pressSequentially('Mery', { delay: 60 }); + await expect(widget).toBeVisible({ timeout: 15000 }); + await expect(spinner).toBeHidden(); + + // The keystroke queues a request synchronously, so the spinner is on for + // the debounce and the round trip, then off once the answer lands. + await editor.press('l'); + await expect(spinner).toBeVisible(); + await expect(spinner).toBeHidden({ timeout: 15000 }); + }); + + test('the header names the term as it is typed', async ({ page }) => { + // An entity list is isIncomplete, so a keystroke re-requests rather than + // re-renders. The header used to name the term the last response was for, + // catching up only once the round trip finished. + await page.route(/7878\/query/, async (route) => { + await new Promise((resolve) => setTimeout(resolve, 1500)); + await route.continue(); + }); + + await setEditorContent(page, [EX, 'SELECT * WHERE {', ' ', '}'].join('\n')); + await placeCursor(page, 3, 3); + + const editor = page.getByRole('textbox', { name: 'Editor content' }); + const widget = page.getByTestId('completion-widget'); + + await editor.pressSequentially('Mery', { delay: 60 }); + await expect(widget).toBeVisible({ timeout: 15000 }); + + // The header follows the keystroke, while the request for it is still out. + await editor.press('l'); + await expect(widget.getByTestId('completion-spinner')).toBeVisible(); + // NOTE: well inside the 1500ms route delay, so only the keystroke can have + // put this on screen. A generous timeout here would simply outlast the + // request and watch the stale header catch up on the answer instead. + await expect(widget).toContainText('matching Meryl', { timeout: 800 }); + }); + + test('a list answering an older term is marked stale', async ({ page }) => { + // An entity list is isIncomplete, so the rows on screen keep answering the + // term the last response was for. They used to look exactly as current as + // a fresh list while the answer for what had been typed since was still + // out. + await page.route(/7878\/query/, async (route) => { + await new Promise((resolve) => setTimeout(resolve, 1500)); + await route.continue(); + }); + + await setEditorContent(page, [EX, 'SELECT * WHERE {', ' ', '}'].join('\n')); + await placeCursor(page, 3, 3); + + const editor = page.getByRole('textbox', { name: 'Editor content' }); + const widget = page.getByTestId('completion-widget'); + const stale = widget.getByTestId('completion-stale'); + + await editor.pressSequentially('Mery', { delay: 60 }); + await expect(widget.getByTestId('completion-item').first()).toBeVisible({ timeout: 15000 }); + await expect(stale).toBeHidden(); + + // NOTE: well inside the 1500ms route delay, so the mark can only come from + // the keystroke. It names the term the rows still answer, not the live one. + await editor.press('l'); + await expect(stale).toBeVisible({ timeout: 800 }); + await expect(stale).toHaveText('showing results for Mery'); + // The rows stay put and stay selectable while their replacement is out. + await expect(widget.getByTestId('completion-item').filter({ hasText: 'Meryl Streep' })).toHaveCount(1); + + // And the answer for the live term clears the mark. + await expect(stale).toBeHidden({ timeout: 15000 }); + }); + + test('a slow first request opens on a searching panel', async ({ page }) => { + // An entity completion goes to the endpoint. Nothing was shown until the + // answer came back, so a slow endpoint meant typing into silence. + await page.route(/7878\/query/, async (route) => { + await new Promise((resolve) => setTimeout(resolve, 1500)); + await route.continue(); + }); + + await setEditorContent(page, [EX, 'SELECT * WHERE {', ' ', '}'].join('\n')); + await placeCursor(page, 3, 3); + + const editor = page.getByRole('textbox', { name: 'Editor content' }); + const widget = page.getByTestId('completion-widget'); + + // NOTE: "The" matches no keyword, so nothing reaches the screen ahead of + // the endpoint -- the panel is deliberately suppressed once something has. + await editor.pressSequentially('The', { delay: 60 }); + await expect(widget).toContainText('Searching…', { timeout: 5000 }); + await expect(widget.getByTestId('completion-spinner')).toBeVisible(); + + // And the answer replaces it. + await expect( + widget.getByTestId('completion-item').filter({ hasText: 'The Iron Lady' }), + ).toHaveCount(1, { timeout: 15000 }); + await expect(widget).not.toContainText('Searching…'); + }); + + test('backspacing out of an inserted snippet dismisses the list', async ({ page }) => { + // FILTER inserts "FILTER ($0)" and chains a request for the built in calls. + // That list is complete and carries no ranges, so it was filtered locally + // against a word scan forever. Deleting the "FILTER (" it belongs inside + // left it on screen -- and an empty term is a prefix of everything, so the + // full list came back and could still be accepted. + await setEditorContent(page, ['SELECT * WHERE {', ' ', '}'].join('\n')); + await placeCursor(page, 2, 3); + + const editor = page.getByRole('textbox', { name: 'Editor content' }); + const widget = page.getByTestId('completion-widget'); + + await editor.pressSequentially('F', { delay: 60 }); + await expect(widget).toBeVisible({ timeout: 10000 }); + await widget.getByTestId('completion-item').filter({ hasText: 'FILTER' }).first().click(); + + // The chained request for the built in calls. + await expect( + widget.getByTestId('completion-item').filter({ hasText: 'ABS' }).first(), + ).toBeVisible({ timeout: 10000 }); + + await editor.press('Backspace'); + await expect(widget).toBeHidden(); + + // And the dismissed list must not be acceptable on the way out. + await editor.press('Enter'); + expect(await getEditorContent(page)).not.toContain('ABS'); + }); + + test('ctrl+enter ends the session and executes', async ({ page, browserName }) => { + // Ctrl+Enter was handled below the "is the widget visible" guard, so a + // request queued by the keystroke just before it was never cancelled: the + // query ran and the popup then opened on top of it. Pressing Ctrl+Enter + // straight after a keystroke is what reproduces it -- once the widget is up + // and settled there is nothing in flight left to land. + await setEditorContent(page, [EX, 'SELECT * WHERE {', ' ?s ?p ?o', '}'].join('\n')); + await placeCursor(page, 3, 11); + + const editor = page.getByRole('textbox', { name: 'Editor content' }); + const widget = page.getByTestId('completion-widget'); + + await page.evaluate(() => { + (window as any).__executed = 0; + window.addEventListener('execute-started', () => { + (window as any).__executed++; + }); + }); + + await editor.press('a'); + await page.keyboard.press(`${ctrlCmd(browserName)}+Enter`); + + await expect.poll(() => page.evaluate(() => (window as any).__executed)).toBe(1); + // The queued request has to be gone, not merely late. + await expect(widget).toBeHidden(); + await page.waitForTimeout(1500); + await expect(widget).toBeHidden(); + }); + + // The first word of a multi word keyword lexes as that keyword's own token, + // so a space after it used to localize as Unknown and drop every completion. + // Needs the get_location fix from qlue-ls 3.4.4. + test('a partially typed multi word keyword keeps its completions', async ({ page }) => { + await setEditorContent(page, ['SELECT * WHERE {', ' ?a ?b ?c .', '}', ''].join('\n')); + await placeCursor(page, 4, 1); + + const editor = page.getByRole('textbox', { name: 'Editor content' }); + const widget = page.getByTestId('completion-widget'); + + await editor.pressSequentially('GROUP B', { delay: 60 }); + await expect(widget).toBeVisible({ timeout: 10000 }); + await expect( + widget.getByTestId('completion-item').filter({ hasText: 'GROUP BY' }), + ).toHaveCount(1); + + await widget.getByTestId('completion-item').filter({ hasText: 'GROUP BY' }).first().click(); + // The whole "GROUP B" is the term, so accepting must not double it. + await expect.poll(() => getEditorContent(page), { timeout: 5000 }).toContain('GROUP BY'); + expect(await getEditorContent(page)).not.toContain('GROUP BGROUP BY'); + }); + + // A code action's edit reaches the content-change handler exactly like a + // keystroke, and the trigger heuristic only looked at the last character of + // the inserted text: "Add to result" writing "?o" over the "*" ended in a + // word character, so the popup opened on whatever the cursor sat on. + test('a code action editing elsewhere does not open the popup', async ({ + page, + browserName, + }) => { + await setEditorContent(page, ['SELECT * WHERE {', ' ?s ?p ?o', '}'].join('\n')); + // Right after the "?" of "?o" -- where the bug found a term to complete. + await placeCursor(page, 2, 10); + + const widget = page.getByTestId('completion-widget'); + + await page.keyboard.press(`${ctrlCmd(browserName)}+Period`); + const action = page.locator('.action-widget .monaco-list-row.action'); + await expect(action.filter({ hasText: 'Add to result' })).toHaveCount(1, { timeout: 10000 }); + // NOTE: the rows sit under a pointer-blocking overlay, so they are reached + // by keyboard. "Add to result" is the first one and starts out focused. + await page.keyboard.press('Enter'); + + await expect.poll(() => getEditorContent(page), { timeout: 5000 }).toContain('SELECT ?o'); + await page.waitForTimeout(1500); + await expect(widget).toBeHidden(); + }); + + // The server completes inside comments too, so typing prose that happens to + // end in a keyword -- "# blabla select" -- opened the keyword list. + test('typing inside a comment does not open the popup', async ({ page }) => { + await setEditorContent(page, ['# blabla ', 'SELECT * WHERE {', ' ?s ?p ?o', '}'].join('\n')); + await placeCursor(page, 1, 10); + + const editor = page.getByRole('textbox', { name: 'Editor content' }); + const widget = page.getByTestId('completion-widget'); + + await editor.pressSequentially('select', { delay: 60 }); + await page.waitForTimeout(1500); + await expect(widget).toBeHidden(); + + // An open list is dismissed once the "#" turns the line into a comment. + await placeCursor(page, 3, 10); + await editor.pressSequentially('?', { delay: 60 }); + await expect(widget).toBeVisible({ timeout: 10000 }); + await placeCursor(page, 3, 1); + await editor.pressSequentially('# ', { delay: 60 }); + await expect(widget).toBeHidden(); + }); +}); diff --git a/testing/tests/editor-usage.spec.ts b/testing/tests/editor-usage.spec.ts index 8b2fe459..f9b8ac23 100644 --- a/testing/tests/editor-usage.spec.ts +++ b/testing/tests/editor-usage.spec.ts @@ -1,34 +1,37 @@ import { test, expect } from '@playwright/test'; -import { getEditorContent } from './utils'; +import { ctrlCmd, getEditorContent } from './utils'; // Builds a two-triple query purely through completions served by the local // Oxigraph endpoint (see testing/fixtures/). Exercises subject, predicate and // object completions, including context-sensitive predicate completion on a // variable subject. -test('query building with completions against the local endpoint', async ({ page }) => { +test('query building with completions against the local endpoint', async ({ + page, + browserName, +}) => { test.setTimeout(60_000); await page.goto('./test'); await expect(page.locator('#loadingScreen')).toHaveCount(0, { timeout: 15000 }); const editor = page.getByRole('textbox', { name: 'Editor content' }); - const suggestWidget = page.locator('.suggest-widget'); + const suggestWidget = page.getByTestId('completion-widget'); // Insert the "SELECT * WHERE {}" snippet, then Tab past the SelectClause stop // into the body. await editor.pressSequentially('sel', { delay: 100 }); await expect(suggestWidget).toBeVisible({ timeout: 10000 }); - await suggestWidget.locator('.monaco-list-row', { hasText: /SELECT/ }).first().click(); + await suggestWidget.getByTestId('completion-item').filter({ hasText: /SELECT/ }).first().click(); await editor.press('Tab'); // Subject completion: "Meryl" -> "Meryl Streep" (ex:meryl_streep). await editor.pressSequentially('Meryl'); await expect(suggestWidget).toBeVisible({ timeout: 15000 }); - await suggestWidget.locator('.monaco-list-row', { hasText: /Meryl Streep/ }).first().click(); + await suggestWidget.getByTestId('completion-item').filter({ hasText: /Meryl Streep/ }).first().click(); // Predicate completion -> ex:actedIn. await expect(suggestWidget).toBeVisible({ timeout: 15000 }); - await suggestWidget.locator('.monaco-list-row', { hasText: /actedIn/ }).first().click(); + await suggestWidget.getByTestId('completion-item').filter({ hasText: /actedIn/ }).first().click(); // Object is a fresh variable; dismiss any object completions and end the triple. await editor.pressSequentially('?movie .'); @@ -42,9 +45,9 @@ test('query building with completions against the local endpoint', async ({ page // Second triple, variable subject ?movie. Context-sensitive predicate // completion should suggest predicates of Meryl's movies -> ex:hasGenre. await editor.pressSequentially('?movie '); - await page.keyboard.press('Control+Space'); + await page.keyboard.press(`${ctrlCmd(browserName)}+Space`); await expect(suggestWidget).toBeVisible({ timeout: 15000 }); - await suggestWidget.locator('.monaco-list-row', { hasText: /hasGenre/ }).first().click(); + await suggestWidget.getByTestId('completion-item').filter({ hasText: /hasGenre/ }).first().click(); // Object is a fresh variable. await editor.pressSequentially('?genre'); diff --git a/testing/tests/utils.ts b/testing/tests/utils.ts index 5c2e5ba2..9264be3b 100644 --- a/testing/tests/utils.ts +++ b/testing/tests/utils.ts @@ -7,3 +7,37 @@ import { type Page } from '@playwright/test'; export async function getEditorContent(page: Page): Promise { return page.evaluate(() => (window as any).__editor.getContent()); } + +/** + * Replace the editor content. + * + * Lets a test start from an exact query instead of building one up through + * completions, which keeps a regression test focused on the one interaction + * it is about. + */ +export async function setEditorContent(page: Page, content: string): Promise { + await page.evaluate((text) => (window as any).__editor.setContent(text), content); +} + +/** Focus the editor and put the cursor at a 1-based line/column. */ +export async function placeCursor(page: Page, lineNumber: number, column: number): Promise { + await page.evaluate( + ([line, col]) => { + const editor = (window as any).__editor.editorApp.getEditor(); + editor.focus(); + editor.setPosition({ lineNumber: line, column: col }); + }, + [lineNumber, column], + ); +} + +/** + * The key that stands in for Monaco's `CtrlCmd` modifier. + * + * Monaco reads the platform off the user agent, and Playwright's WebKit build + * claims to be a Macintosh even on Linux -- so inside WebKit the editor's + * Ctrl + bindings answer to Meta, exactly as they would on a real Mac. + */ +export function ctrlCmd(browserName: string): 'Control' | 'Meta' { + return browserName === 'webkit' ? 'Meta' : 'Control'; +}