mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-11-27 10:42:38 +01:00
Put Yaak Proxy's search on the shared query engine (#826)
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
1 parent
7453869ac6
commit
77226dbedb
58 files changed
+4754
-1594
No files matched your search
@@ -1,8 +1,5 @@
|
||||
import type { Completion, CompletionContext, CompletionResult } from "@codemirror/autocomplete";
|
||||
import { autocompletion, startCompletion } from "@codemirror/autocomplete";
|
||||
import { LanguageSupport, LRLanguage, syntaxTree } from "@codemirror/language";
|
||||
import type { SyntaxNode } from "@lezer/common";
|
||||
import { parser } from "./filter";
|
||||
|
||||
export interface FieldDef {
|
||||
name: string;
|
||||
@@ -87,17 +84,7 @@ function fieldCompletionFrom(
|
||||
return null;
|
||||
}
|
||||
|
||||
function inPhrase(ctx: CompletionContext): boolean {
|
||||
// Lezer node names from your grammar: Phrase is the quoted token
|
||||
let n: SyntaxNode | null = syntaxTree(ctx.state).resolveInner(ctx.pos, -1);
|
||||
while (n) {
|
||||
if (n.name === "Phrase") return true;
|
||||
n = n.parent;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// While typing an incomplete quote, there's no Phrase token yet.
|
||||
/** Inside a quote, opened and not yet closed */
|
||||
function inUnclosedQuote(doc: string, pos: number): boolean {
|
||||
let quotes = 0;
|
||||
for (let i = 0; i < pos; i++) {
|
||||
@@ -200,7 +187,7 @@ export function makeCompletionSource(opts: FilterOptions) {
|
||||
const { state, pos } = ctx;
|
||||
const doc = state.doc.toString();
|
||||
|
||||
if (inPhrase(ctx) || inUnclosedQuote(doc, pos)) {
|
||||
if (inUnclosedQuote(doc, pos)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -250,14 +237,6 @@ export function makeCompletionSource(opts: FilterOptions) {
|
||||
};
|
||||
}
|
||||
|
||||
const language = LRLanguage.define({
|
||||
name: "filter",
|
||||
parser,
|
||||
languageData: {
|
||||
autocompletion: {},
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Field and value suggestions, as the sidebar's filter offers them, for a field of another
|
||||
* language: a plain input of `host:` and `app:` entries, say
|
||||
@@ -265,9 +244,3 @@ const language = LRLanguage.define({
|
||||
export function filterAutocomplete(options: FilterOptions) {
|
||||
return autocompletion({ override: [makeCompletionSource(options)] });
|
||||
}
|
||||
|
||||
/** Public extension */
|
||||
export function filter(options: FilterOptions) {
|
||||
const source = makeCompletionSource(options);
|
||||
return new LanguageSupport(language, [autocompletion({ override: [source] })]);
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
@top Query { Expr }
|
||||
|
||||
@skip { space+ }
|
||||
@tokens {
|
||||
space { $[ \t\r\n]+ }
|
||||
|
||||
LParen { "(" }
|
||||
RParen { ")" }
|
||||
At { "@" }
|
||||
Colon { ":" }
|
||||
Not { "-" | "NOT" }
|
||||
|
||||
// Keywords (case-insensitive)
|
||||
And { "AND" }
|
||||
Or { "OR" }
|
||||
|
||||
// "quoted phrase" with simple escapes: \" and \\
|
||||
Phrase { '"' (!["\\] | "\\" _)* '"' }
|
||||
|
||||
// Bare words run until filter syntax or whitespace. Leading '-' remains unary
|
||||
// negation, but '-' may appear after the first character.
|
||||
Word { ![ \t\r\n():"@-] ![ \t\r\n():"@]* }
|
||||
FieldValueWord { ![ \t\r\n"] ![ \t\r\n]* }
|
||||
|
||||
@precedence { Not, And, Or, Word }
|
||||
}
|
||||
|
||||
@detectDelim
|
||||
|
||||
// Precedence: NOT (highest) > AND > OR (lowest)
|
||||
// We also allow implicit AND in your parser/evaluator, but for highlighting,
|
||||
// this grammar parses explicit AND/OR/NOT + adjacency as a sequence (Seq).
|
||||
Expr {
|
||||
OrExpr
|
||||
}
|
||||
|
||||
OrExpr {
|
||||
AndExpr (Or AndExpr)*
|
||||
}
|
||||
|
||||
AndExpr {
|
||||
Unary (And Unary | Unary)* // allow implicit AND by adjacency: Unary Unary
|
||||
}
|
||||
|
||||
Unary {
|
||||
Not Unary
|
||||
| Primary
|
||||
}
|
||||
|
||||
Primary {
|
||||
Group
|
||||
| Field
|
||||
| Phrase
|
||||
| Term
|
||||
}
|
||||
|
||||
Group {
|
||||
LParen Expr RParen
|
||||
}
|
||||
|
||||
Field {
|
||||
FieldName Colon FieldValue
|
||||
}
|
||||
|
||||
FieldName {
|
||||
At? Word
|
||||
}
|
||||
|
||||
FieldValue {
|
||||
Phrase
|
||||
| FieldValueWord
|
||||
}
|
||||
|
||||
Term {
|
||||
Word
|
||||
}
|
||||
|
||||
@external propSource highlight from "./highlight"
|
||||
@@ -1,42 +0,0 @@
|
||||
import { describe, expect, test } from "vite-plus/test";
|
||||
import { parser } from "./filter";
|
||||
|
||||
function getNodeNames(input: string): string[] {
|
||||
const tree = parser.parse(input);
|
||||
const nodes: string[] = [];
|
||||
const cursor = tree.cursor();
|
||||
do {
|
||||
if (cursor.name !== "Query") {
|
||||
nodes.push(cursor.name);
|
||||
}
|
||||
} while (cursor.next());
|
||||
return nodes;
|
||||
}
|
||||
|
||||
describe("filter grammar", () => {
|
||||
test("parses URL-like field values as one value", () => {
|
||||
const nodes = getNodeNames("@url:yaak.app/foo-bar");
|
||||
|
||||
expect(nodes).not.toContain("⚠");
|
||||
expect(nodes).toContain("FieldValue");
|
||||
expect(nodes).toContain("FieldValueWord");
|
||||
});
|
||||
|
||||
test("parses punctuation-heavy field values as one value", () => {
|
||||
const nodes = getNodeNames("@url:yaa$&#*@tsrna(*)");
|
||||
|
||||
expect(nodes).not.toContain("⚠");
|
||||
expect(nodes).toContain("FieldValue");
|
||||
expect(nodes).toContain("FieldValueWord");
|
||||
});
|
||||
|
||||
test("parses operator-looking field values as one value", () => {
|
||||
const negativeValueNodes = getNodeNames("@url:-foo");
|
||||
const operatorWordNodes = getNodeNames("@url:AND");
|
||||
|
||||
expect(negativeValueNodes).not.toContain("⚠");
|
||||
expect(negativeValueNodes).toContain("FieldValueWord");
|
||||
expect(operatorWordNodes).not.toContain("⚠");
|
||||
expect(operatorWordNodes).toContain("FieldValueWord");
|
||||
});
|
||||
});
|
||||
@@ -1,22 +0,0 @@
|
||||
// This file was generated by lezer-generator. You probably shouldn't edit it.
|
||||
import {LRParser} from "@lezer/lr"
|
||||
import {highlight} from "./highlight"
|
||||
export const parser = LRParser.deserialize({
|
||||
version: 14,
|
||||
states: "%WOVQPOOPhOPOOOVQPO'#CfOmQPO'#ChO!_QPO'#ChO!dQPO'#CgOOQO'#Cc'#CcOVQPO'#CaOOQO'#Ca'#CaO!iQPO'#C`O!yQPO'#C_OOQO'#C^'#C^QOQPOOPOOO'#Cr'#CrP#UOPO)C>lO#]QPO,59QOOQO,59S,59SO#bQQO,59ROOQO,58{,58{OVQPO'#CsOOQO'#Cs'#CsO#jQPO,58zOVQPO'#CtO#zQPO,58yPOOO-E6p-E6pOOQO1G.l1G.lOOQO'#Cl'#ClOOQO1G.m1G.mOOQO,59_,59_OOQO-E6q-E6qOOQO,59`,59`OOQO-E6r-E6r",
|
||||
stateData: "$]~OkPQ~OUVOXQO]SO^ROaUO~Ok]O~OUcXXcX]cX^cX_[XacXdcXecXicXWcX~O^`O~O_aO~OdcOeSXiSXWSX~PVOefOiRXWRX~Ok]O~Qj]WiO~OajObjO~OdcOeSaiSaWSa~PVOefOiRaWRa~OUde^e~",
|
||||
goto: "#^iPPjpt{P![PP!e!e!nPPP!wPP!ePP!z#Q#WQ[OR_QTZOQSYOQRnfUXOQfQbVSdXeRlc_WOQVXcef_UOQVXcef_TOQVXcefRkaQ^PRh^QeXRmeQgYRog",
|
||||
nodeNames: "⚠ Query Expr OrExpr AndExpr Unary Not Primary RParen LParen Group Field FieldName At Word Colon FieldValue Phrase FieldValueWord Term And Or",
|
||||
maxTerm: 27,
|
||||
nodeProps: [
|
||||
["openedBy", 8,"LParen"],
|
||||
["closedBy", 9,"RParen"]
|
||||
],
|
||||
propSources: [highlight],
|
||||
skippedNodes: [0,22],
|
||||
repeatNodeCount: 3,
|
||||
tokenData: "2h~RiOX!pXY$hYZ$hZ]!p]^$h^p!ppq$hqr!prs$ysx!pxy&gyz'Qz}!p}!O'k!OY!d!p!p!p!q,q!q!r0Y!r;'S!p;'S;=`$b<%lO!pR!w^bQ^POX!pZ]!p^p!pqr!prs#ssx!pxz#sz![!p![!]#s!]!b!p!b!c#s!c;'S!p;'S;=`$b<%lO!pQ#xUbQOX#sZ]#s^p#sq;'S#s;'S;=`$[<%lO#sQ$_P;=`<%l#sR$eP;=`<%l!p~$mSk~XY$hYZ$h]^$hpq$h~$|VOr$yrs%cs#O$y#O#P%h#P;'S$y;'S;=`&a<%lO$y~%hOa~~%kRO;'S$y;'S;=`%t;=`O$y~%wWOr$yrs%cs#O$y#O#P%h#P;'S$y;'S;=`&a;=`<%l$y<%lO$y~&dP;=`<%l$yR&nUbQXPOX#sZ]#s^p#sq;'S#s;'S;=`$[<%lO#sR'XUbQWPOX#sZ]#s^p#sq;'S#s;'S;=`$[<%lO#sR'rUbQUPOX#sZ]#s^p#sq;'S#s;'S;=`$[<%lO#sR(]U_PbQOX#sZ]#s^p#sq;'S#s;'S;=`$[<%lO#sR(vU]PbQOX#sZ]#s^p#sq;'S#s;'S;=`$[<%lO#sR)a`bQ^POX!pZ]!p^p!pqr!prs#ssx!pxz#sz![!p![!]#s!]!b!p!b!c#s!c!p!p!p!q*c!q;'S!p;'S;=`$b<%lO!pR*j`bQ^POX!pZ]!p^p!pqr!prs#ssx!pxz#sz![!p![!]#s!]!b!p!b!c#s!c!f!p!f!g+l!g;'S!p;'S;=`$b<%lO!pR+u^bQdP^POX!pZ]!p^p!pqr!prs#ssx!pxz#sz![!p![!]#s!]!b!p!b!c#s!c;'S!p;'S;=`$b<%lO!pR,x`bQ^POX!pZ]!p^p!pqr!prs#ssx!pxz#sz![!p![!]#s!]!b!p!b!c#s!c!q!p!q!r-z!r;'S!p;'S;=`$b<%lO!pR.R`bQ^POX!pZ]!p^p!pqr!prs#ssx!pxz#sz![!p![!]#s!]!b!p!b!c#s!c!v!p!v!w/T!w;'S!p;'S;=`$b<%lO!pR/^^bQUP^POX!pZ]!p^p!pqr!prs#ssx!pxz#sz![!p![!]#s!]!b!p!b!c#s!c;'S!p;'S;=`$b<%lO!pR0a`bQ^POX!pZ]!p^p!pqr!prs#ssx!pxz#sz![!p![!]#s!]!b!p!b!c#s!c!t!p!t!u1c!u;'S!p;'S;=`$b<%lO!pR1l^bQeP^POX!pZ]!p^p!pqr!prs#ssx!pxz#sz![!p![!]#s!]!b!p!b!c#s!c;'S!p;'S;=`$b<%lO!p",
|
||||
tokenizers: [0, 1],
|
||||
topRules: {"Query":[0,1]},
|
||||
tokenPrec: 145
|
||||
})
|
||||
@@ -1,22 +0,0 @@
|
||||
import { styleTags, tags as t } from "@lezer/highlight";
|
||||
|
||||
export const highlight = styleTags({
|
||||
// Boolean operators
|
||||
And: t.operatorKeyword,
|
||||
Or: t.operatorKeyword,
|
||||
Not: t.operatorKeyword,
|
||||
|
||||
// Structural punctuation
|
||||
LParen: t.paren,
|
||||
RParen: t.paren,
|
||||
Colon: t.punctuation,
|
||||
Minus: t.operator,
|
||||
|
||||
// Literals
|
||||
Phrase: t.string, // "quoted string"
|
||||
|
||||
// Fields
|
||||
"FieldName/At": t.attributeName,
|
||||
"FieldName/Word": t.attributeName,
|
||||
"FieldValue/FieldValueWord": t.attributeValue,
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, test } from "vite-plus/test";
|
||||
import { pathsAt } from "./extension";
|
||||
|
||||
describe("pathsAt", () => {
|
||||
const at = (text: string) => pathsAt(text, text.length);
|
||||
|
||||
test("is the field whose value is being typed, quoted values with spaces too", () => {
|
||||
expect(at("@host:api")).toEqual(["host"]);
|
||||
expect(at('x @app:"Google C')).toEqual(["app"]);
|
||||
expect(at('@app:"Google Chrome" ')).toEqual([]);
|
||||
expect(at("@header.content-type:")).toEqual(["header.content-type"]);
|
||||
});
|
||||
|
||||
test("is a map's name while its key is typed", () => {
|
||||
expect(at("@header.x-")).toEqual(["header"]);
|
||||
expect(at("@res.header.")).toEqual(["res.header"]);
|
||||
});
|
||||
|
||||
test("is nothing outside a field", () => {
|
||||
expect(at("stripe ")).toEqual([]);
|
||||
expect(at("")).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,264 @@
|
||||
import type { Completion, CompletionContext, CompletionResult } from "@codemirror/autocomplete";
|
||||
import { autocompletion, startCompletion } from "@codemirror/autocomplete";
|
||||
import { highlightingFor } from "@codemirror/language";
|
||||
import type { EditorState, Extension } from "@codemirror/state";
|
||||
import { RangeSetBuilder, StateEffect, StateField } from "@codemirror/state";
|
||||
import type { DecorationSet, ViewUpdate } from "@codemirror/view";
|
||||
import { Decoration, EditorView, ViewPlugin } from "@codemirror/view";
|
||||
import type { Tag } from "@lezer/highlight";
|
||||
import { tags as t } from "@lezer/highlight";
|
||||
import type { Schema, TokenKind } from "@yaakapp-internal/query";
|
||||
import { queryCompletions, queryTokens } from "@yaakapp-internal/query";
|
||||
|
||||
/** A term the search cannot run, to underline: `from` and `to` count UTF-16 units */
|
||||
export interface QueryProblem {
|
||||
from: number;
|
||||
to: number;
|
||||
/** Shown on hover, a few words */
|
||||
label: string;
|
||||
/** Searchable later rather than wrong: marked more quietly */
|
||||
quiet?: boolean;
|
||||
}
|
||||
|
||||
export interface QueryFilterOptions {
|
||||
schema: Schema;
|
||||
/** The values seen for each field path, offered after `@field:` */
|
||||
values?: Record<string, string[]>;
|
||||
/**
|
||||
* Values for field paths `values` lacks, read as completion opens: `host` for `@host:`, and a
|
||||
* map's name, `header`, for the keys after `@header.`. Null for a path with none to offer.
|
||||
*/
|
||||
loadValues?: (paths: string[]) => Promise<Record<string, string[]>>;
|
||||
/**
|
||||
* More completions for a bare word or an empty spot, after the engine's, such as saved
|
||||
* searches. `typed` is the word, and the completions replace it.
|
||||
*/
|
||||
moreCompletions?: (typed: string) => Completion[];
|
||||
/** The terms of a query the search cannot run, underlined as typing settles */
|
||||
problems?: (text: string) => Promise<QueryProblem[]>;
|
||||
}
|
||||
|
||||
const tokenTags: Record<TokenKind, Tag | null> = {
|
||||
field: t.attributeName,
|
||||
value: t.attributeValue,
|
||||
operator: t.operatorKeyword,
|
||||
quote: t.string,
|
||||
paren: t.paren,
|
||||
negation: t.operator,
|
||||
text: null,
|
||||
};
|
||||
|
||||
function buildDecorations(state: EditorState): DecorationSet {
|
||||
const builder = new RangeSetBuilder<Decoration>();
|
||||
for (const token of queryTokens(state.doc.toString())) {
|
||||
const tag = tokenTags[token.kind];
|
||||
const className = tag == null ? null : highlightingFor(state, [tag]);
|
||||
if (className == null || token.span.start === token.span.end) continue;
|
||||
builder.add(token.span.start, token.span.end, Decoration.mark({ class: className }));
|
||||
}
|
||||
return builder.finish();
|
||||
}
|
||||
|
||||
const highlight = ViewPlugin.fromClass(
|
||||
class {
|
||||
decorations: DecorationSet;
|
||||
|
||||
constructor(view: EditorView) {
|
||||
this.decorations = buildDecorations(view.state);
|
||||
}
|
||||
|
||||
update(update: ViewUpdate) {
|
||||
if (update.docChanged || update.viewportChanged) {
|
||||
this.decorations = buildDecorations(update.state);
|
||||
}
|
||||
}
|
||||
},
|
||||
{ decorations: (v) => v.decorations },
|
||||
);
|
||||
|
||||
/**
|
||||
* The field paths whose values the term at `pos` would offer: its field's, a quoted value with
|
||||
* spaces included, or its map's keys
|
||||
*/
|
||||
export function pathsAt(text: string, pos: number): string[] {
|
||||
const before = text.slice(0, pos);
|
||||
const value = /@([A-Za-z0-9_.-]+):(?:"(?:[^"\\]|\\.)*|[^\s()"]*)$/.exec(before);
|
||||
if (value?.[1] != null) return [value[1].toLowerCase()];
|
||||
const key = /@([A-Za-z0-9_.-]+)\.[A-Za-z0-9_-]*$/.exec(before);
|
||||
if (key?.[1] != null) return [key[1].toLowerCase()];
|
||||
return [];
|
||||
}
|
||||
|
||||
/** The bare word being typed at `pos`, or empty at the start of a term */
|
||||
function wordAt(text: string, pos: number): { word: string; from: number } | null {
|
||||
const before = text.slice(0, pos);
|
||||
const m = /(^|[\s(])([^\s()"@:-][^\s()":]*)?$/.exec(before);
|
||||
if (m == null) return null;
|
||||
const word = m[2] ?? "";
|
||||
return { word, from: pos - word.length };
|
||||
}
|
||||
|
||||
/** The panel beside a completion: what the field is, and a term using it */
|
||||
function infoOf(info: string | null, example: string | null): Completion["info"] {
|
||||
if (example == null) return undefined;
|
||||
return () => {
|
||||
const el = document.createElement("div");
|
||||
if (info != null) {
|
||||
const what = document.createElement("div");
|
||||
what.textContent = info;
|
||||
el.append(what);
|
||||
}
|
||||
const term = document.createElement("code");
|
||||
term.className = "cm-query-example";
|
||||
term.textContent = example;
|
||||
el.append(term);
|
||||
return el;
|
||||
};
|
||||
}
|
||||
|
||||
function completionSource({ schema, values, loadValues, moreCompletions }: QueryFilterOptions) {
|
||||
return async (ctx: CompletionContext): Promise<CompletionResult | null> => {
|
||||
const text = ctx.state.doc.toString();
|
||||
let known = values ?? {};
|
||||
const wanted = pathsAt(text, ctx.pos).filter((p) => known[p] == null);
|
||||
if (loadValues != null && wanted.length > 0) {
|
||||
known = { ...known, ...(await loadValues(wanted)) };
|
||||
if (ctx.aborted) return null;
|
||||
}
|
||||
const result = queryCompletions(text, ctx.pos, schema, known);
|
||||
|
||||
const options: Completion[] = (result?.items ?? []).map((item) => ({
|
||||
label: item.label,
|
||||
// Not a CodeMirror type: it names the kind for `onlyFields` below, and draws no icon
|
||||
type: item.kind === "field" ? "field" : "value",
|
||||
detail: item.info ?? undefined,
|
||||
info: infoOf(item.info, item.example),
|
||||
apply: (view, _completion, from, to) => {
|
||||
view.dispatch({
|
||||
changes: { from, to, insert: item.insert },
|
||||
selection: { anchor: from + item.insert.length },
|
||||
});
|
||||
if (item.reopen) startCompletion(view);
|
||||
},
|
||||
}));
|
||||
|
||||
let from = result?.span.start ?? ctx.pos;
|
||||
let to = result?.span.end ?? ctx.pos;
|
||||
const word = moreCompletions == null ? null : wordAt(text, ctx.pos);
|
||||
// On an empty spot, only when asked for
|
||||
if (moreCompletions != null && word != null && (word.word !== "" || ctx.explicit)) {
|
||||
const more = moreCompletions(word.word);
|
||||
if (more.length > 0) {
|
||||
// Both replace the word being typed
|
||||
if (options.length === 0) [from, to] = [word.from, ctx.pos];
|
||||
if (from === word.from) options.push(...more);
|
||||
}
|
||||
}
|
||||
if (options.length === 0) return null;
|
||||
|
||||
// Field names pop up for something typed; on an empty spot, only when asked for
|
||||
const onlyFields = options.every((o) => o.type === "field");
|
||||
if (onlyFields && from === to && !ctx.explicit) return null;
|
||||
|
||||
// The engine has already filtered and ranked the options
|
||||
return { from, to, options, filter: false };
|
||||
};
|
||||
}
|
||||
|
||||
const setProblems = StateEffect.define<QueryProblem[]>();
|
||||
|
||||
/** Underlines what the search cannot run, as `problems` last answered for the text */
|
||||
const problemField = StateField.define<DecorationSet>({
|
||||
create: () => Decoration.none,
|
||||
update(decorations, tr) {
|
||||
let next = decorations.map(tr.changes);
|
||||
for (const effect of tr.effects) {
|
||||
if (!effect.is(setProblems)) continue;
|
||||
const builder = new RangeSetBuilder<Decoration>();
|
||||
const length = tr.state.doc.length;
|
||||
for (const p of [...effect.value].sort((a, b) => a.from - b.from)) {
|
||||
const from = Math.min(p.from, length);
|
||||
// An empty value, `@size:`, marks the colon before it
|
||||
const to = Math.min(Math.max(p.to, p.from + 1), length);
|
||||
const at = p.to === p.from ? Math.max(0, from - 1) : from;
|
||||
if (at >= to) continue;
|
||||
const className = p.quiet ? "cm-query-quiet" : "cm-query-problem";
|
||||
builder.add(at, to, Decoration.mark({ class: className, attributes: { title: p.label } }));
|
||||
}
|
||||
next = builder.finish();
|
||||
}
|
||||
return next;
|
||||
},
|
||||
provide: (f) => EditorView.decorations.from(f),
|
||||
});
|
||||
|
||||
/** How long typing settles before the search's problems are asked for */
|
||||
const PROBLEMS_MS = 150;
|
||||
|
||||
function problemChecker(problems: (text: string) => Promise<QueryProblem[]>) {
|
||||
return ViewPlugin.fromClass(
|
||||
class {
|
||||
timer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
constructor(readonly view: EditorView) {
|
||||
this.check();
|
||||
}
|
||||
|
||||
update(update: ViewUpdate) {
|
||||
if (!update.docChanged) return;
|
||||
if (this.timer != null) clearTimeout(this.timer);
|
||||
this.timer = setTimeout(() => this.check(), PROBLEMS_MS);
|
||||
}
|
||||
|
||||
check() {
|
||||
this.timer = null;
|
||||
const text = this.view.state.doc.toString();
|
||||
problems(text)
|
||||
.then((found) => {
|
||||
// Answered for text since changed: the next check covers it
|
||||
if (this.view.state.doc.toString() !== text) return;
|
||||
this.view.dispatch({ effects: setProblems.of(found) });
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
destroy() {
|
||||
if (this.timer != null) clearTimeout(this.timer);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const problemTheme = EditorView.baseTheme({
|
||||
".cm-query-problem": {
|
||||
textDecoration: "underline wavy var(--color-danger)",
|
||||
textUnderlineOffset: "3px",
|
||||
},
|
||||
".cm-query-quiet": {
|
||||
textDecoration: "underline dotted var(--color-text-subtlest, currentColor)",
|
||||
textUnderlineOffset: "3px",
|
||||
},
|
||||
});
|
||||
|
||||
const completionTheme = EditorView.baseTheme({
|
||||
".cm-query-example": {
|
||||
display: "block",
|
||||
marginTop: "0.25rem",
|
||||
color: "var(--color-text)",
|
||||
whiteSpace: "pre",
|
||||
},
|
||||
});
|
||||
|
||||
/** Highlighting and completion for a search box written in Yaak's query language */
|
||||
export function queryFilter(options: QueryFilterOptions): Extension {
|
||||
const extensions: Extension[] = [
|
||||
highlight,
|
||||
// No type icons: the fields and values of a search have no kind the editor's icons name
|
||||
autocompletion({ override: [completionSource(options)], icons: false }),
|
||||
completionTheme,
|
||||
];
|
||||
if (options.problems != null) {
|
||||
extensions.push(problemField, problemChecker(options.problems), problemTheme);
|
||||
}
|
||||
return extensions;
|
||||
}
|
||||
Reference in new issue
Block a user