Skip to content

Build your personal knowledge base with Trilium Notes

refactor(codemirror): merge the vendored TypeScript extensions by feature

Elian Doraneab2da1cf5bc
diff --git a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete.spec.ts b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete.spec.ts
new file mode 100644
index 0000000000..57a6dead16
--- /dev/null
+++ b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete.spec.ts
@@ -0,0 +1,44 @@
+import { expect, test } from "vitest";
+import { ensureAnchor, getLineAtPosition, matchBefore } from "./autocomplete.js";
+
+test("matchBefore", () => {
+ expect(matchBefore("hi.", 0, /\./)).toEqual(null);
+ expect(matchBefore("hi.", 3, /\./)).toEqual({
+ from: 2,
+ text: ".",
+ to: 3,
+ });
+});
+
+test("ensureAnchor", () => {
+ expect(ensureAnchor(/hi/, false)).toEqual(/(?:hi)$/);
+ expect(ensureAnchor(/hi$/, false)).toEqual(/hi$/);
+ expect(ensureAnchor(/hi$/, true)).toEqual(/^(?:hi$)/);
+ expect(ensureAnchor(/^hi$/, true)).toEqual(/^hi$/);
+});
+
+test("getLineAtPosition", () => {
+ expect(getLineAtPosition("x", 0)).toEqual({
+ from: 0,
+ text: "x",
+ to: 1,
+ });
+
+ expect(getLineAtPosition("x", 10)).toEqual({
+ from: 0,
+ text: "x",
+ to: 1,
+ });
+
+ expect(getLineAtPosition("x", -10)).toEqual({
+ from: 0,
+ text: "x",
+ to: 1,
+ });
+
+ expect(getLineAtPosition("first line\nsecond line", 12)).toEqual({
+ from: 11,
+ text: "second line",
+ to: 22,
+ });
+});
diff --git a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete.ts b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete.ts
new file mode 100644
index 0000000000..157f0d5165
--- /dev/null
+++ b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete.ts
@@ -0,0 +1,170 @@
+import type {
+ Completion,
+ CompletionContext,
+ CompletionResult,
+ CompletionSource,
+} from "@codemirror/autocomplete";
+import ts from "typescript";
+import { type VirtualTypeScriptEnvironment } from "@typescript/vfs";
+import { tsFacet } from "./environment.js";
+import { AUTOCOMPLETION_SYMBOLS } from "./symbols.js";
+
+/**
+ * Create a `CompletionSource` that queries
+ * the _on-thread_ TypeScript environments for autocompletions
+ * at this character.
+ */
+export function tsAutocomplete(): CompletionSource {
+ return async (
+ context: CompletionContext,
+ ): Promise<CompletionResult | null> => {
+ const config = context.state.facet(tsFacet);
+ if (!config) return null;
+ return getAutocompletion({
+ ...config,
+ context,
+ });
+ };
+}
+
+const TS_COMPLETE_BLOCKLIST: ts.ScriptElementKind[] = [
+ ts.ScriptElementKind.warning,
+];
+
+export async function getAutocompletion({
+ env,
+ path,
+ context,
+ keepLegacyLimitationForAutocompletionSymbols = true,
+}: {
+ env: VirtualTypeScriptEnvironment;
+ path: string;
+ keepLegacyLimitationForAutocompletionSymbols?: boolean;
+ /**
+ * Allow this to be a subset of the full CompletionContext
+ * object, because the raw object isn't serializable.
+ */
+ context: Pick<CompletionContext, "pos" | "explicit">;
+}): Promise<CompletionResult | null> {
+ const { pos, explicit } = context;
+ const rawContents = env.getSourceFile(path)?.getFullText();
+
+ if (!rawContents) return null;
+
+ // If there's space behind the cursor, don't try and autocomplete.
+ // https://codemirror.net/examples/autocompletion/
+ let word = matchBefore(rawContents, pos, /\w*/);
+ if (!word?.text) {
+ word = matchBefore(rawContents, pos, /\./);
+ }
+
+ if (!word?.text && !explicit) return null;
+
+ const completionInfo = env.languageService.getCompletionsAtPosition(
+ path,
+ pos,
+ {},
+ {},
+ );
+
+ // TODO: build ATA support for a 'loading' state
+ // while types are being fetched
+ if (!completionInfo) return null;
+
+ const options = completionInfo.entries
+ .filter(
+ (entry) =>
+ !TS_COMPLETE_BLOCKLIST.includes(entry.kind) &&
+ (entry.sortText < "15" ||
+ (completionInfo.optionalReplacementSpan?.length &&
+ (!keepLegacyLimitationForAutocompletionSymbols || AUTOCOMPLETION_SYMBOLS.includes(entry.name)))),
+ )
+ .map((entry): Completion => {
+ const boost = -Number(entry.sortText) || 0;
+ let type = entry.kind ? String(entry.kind) : undefined;
+
+ if (type === "member") type = "property";
+
+ if (type && !DEFAULT_CODEMIRROR_TYPE_ICONS.has(type)) {
+ type = undefined;
+ }
+
+ return {
+ label: entry.name,
+ type,
+ boost,
+ };
+ });
+
+ return {
+ from: word ? (word.text === "." ? word.to : word.from) : pos,
+ options,
+ };
+}
+
+/**
+ * There is some overlap between CodeMirror's
+ * types and TypeScripts. This is all of the default
+ * icons for CodeMirror: if TypeScript gives us one
+ * of these, we pass it through.
+ */
+export const DEFAULT_CODEMIRROR_TYPE_ICONS = new Set([
+ `class`,
+ `constant`,
+ `enum`,
+ `function`,
+ `interface`,
+ `keyword`,
+ `method`,
+ `namespace`,
+ `property`,
+ `text`,
+ `type`,
+ `variable`,
+]);
+
+// From: https://github.com/codemirror/autocomplete/blob/53cc58393252659ac4a86162b40afef13eeb2241/src/completion.ts#L111
+// TODO: do we need to vendor this?
+export function matchBefore(code: string, pos: number, expr: RegExp) {
+ const line = getLineAtPosition(code, pos);
+ let start = Math.max(line.from, pos - 250);
+ let str = line.text.slice(start - line.from, pos - line.from);
+ let found = str.search(ensureAnchor(expr, false));
+ return found < 0
+ ? null
+ : { from: start + found, to: pos, text: str.slice(found) };
+}
+
+// From: https://github.com/codemirror/autocomplete/blob/53cc58393252659ac4a86162b40afef13eeb2241/src/completion.ts#L245
+// TODO: do we need this, or can use import it from codemirror?
+export function ensureAnchor(expr: RegExp, start: boolean) {
+ let { source } = expr;
+ let addStart = start && source[0] != "^",
+ addEnd = source[source.length - 1] != "$";
+ if (!addStart && !addEnd) return expr;
+ return new RegExp(
+ `${addStart ? "^" : ""}(?:${source})${addEnd ? "$" : ""}`,
+ expr.flags ?? (expr.ignoreCase ? "i" : ""),
+ );
+}
+
+/**
+ * TODO: confirm that this is necessary; it may be possible
+ * and more efficient to get the line from CodeMirror, though
+ * that would mean it probably doesn't mix well with the approach
+ * of persisting code in the TS enviroment.
+ */
+export function getLineAtPosition(code: string, position: number) {
+ // lineStart is the index of line break or zero
+ const from = code.lastIndexOf("\n", position - 1) + 1;
+ let to = code.indexOf("\n", position);
+ if (to === -1) {
+ to = code.length;
+ }
+ const text = code.slice(from, to);
+ return {
+ from,
+ to,
+ text,
+ };
+}
diff --git a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/ensureAnchor.test.ts b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/ensureAnchor.test.ts
deleted file mode 100644
index 66d917cff9..0000000000
--- a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/ensureAnchor.test.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import { test, expect } from "vitest";
-import { ensureAnchor } from "./ensureAnchor.js";
-
-test("ensureAnchor", () => {
- expect(ensureAnchor(/hi/, false)).toEqual(/(?:hi)$/);
- expect(ensureAnchor(/hi$/, false)).toEqual(/hi$/);
- expect(ensureAnchor(/hi$/, true)).toEqual(/^(?:hi$)/);
- expect(ensureAnchor(/^hi$/, true)).toEqual(/^hi$/);
-});
diff --git a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/ensureAnchor.ts b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/ensureAnchor.ts
deleted file mode 100644
index f0d48efbb1..0000000000
--- a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/ensureAnchor.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-// From: https://github.com/codemirror/autocomplete/blob/53cc58393252659ac4a86162b40afef13eeb2241/src/completion.ts#L245
-// TODO: do we need this, or can use import it from codemirror?
-export function ensureAnchor(expr: RegExp, start: boolean) {
- let { source } = expr;
- let addStart = start && source[0] != "^",
- addEnd = source[source.length - 1] != "$";
- if (!addStart && !addEnd) return expr;
- return new RegExp(
- `${addStart ? "^" : ""}(?:${source})${addEnd ? "$" : ""}`,
- expr.flags ?? (expr.ignoreCase ? "i" : ""),
- );
-}
diff --git a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/getAutocompletion.ts b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/getAutocompletion.ts
deleted file mode 100644
index 5d4f07d918..0000000000
--- a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/getAutocompletion.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-import type {
- CompletionContext,
- Completion,
- CompletionResult,
-} from "@codemirror/autocomplete";
-import ts from "typescript";
-import { type VirtualTypeScriptEnvironment } from "@typescript/vfs";
-import { AUTOCOMPLETION_SYMBOLS } from "./symbols.js";
-import { DEFAULT_CODEMIRROR_TYPE_ICONS } from "./icons.js";
-import { matchBefore } from "./matchBefore.js";
-
-const TS_COMPLETE_BLOCKLIST: ts.ScriptElementKind[] = [
- ts.ScriptElementKind.warning,
-];
-
-export async function getAutocompletion({
- env,
- path,
- context,
- keepLegacyLimitationForAutocompletionSymbols = true,
-}: {
- env: VirtualTypeScriptEnvironment;
- path: string;
- keepLegacyLimitationForAutocompletionSymbols?: boolean;
- /**
- * Allow this to be a subset of the full CompletionContext
- * object, because the raw object isn't serializable.
- */
- context: Pick<CompletionContext, "pos" | "explicit">;
-}): Promise<CompletionResult | null> {
- const { pos, explicit } = context;
- const rawContents = env.getSourceFile(path)?.getFullText();
-
- if (!rawContents) return null;
-
- // If there's space behind the cursor, don't try and autocomplete.
- // https://codemirror.net/examples/autocompletion/
- let word = matchBefore(rawContents, pos, /\w*/);
- if (!word?.text) {
- word = matchBefore(rawContents, pos, /\./);
- }
-
- if (!word?.text && !explicit) return null;
-
- const completionInfo = env.languageService.getCompletionsAtPosition(
- path,
- pos,
- {},
- {},
- );
-
- // TODO: build ATA support for a 'loading' state
- // while types are being fetched
- if (!completionInfo) return null;
-
- const options = completionInfo.entries
- .filter(
- (entry) =>
- !TS_COMPLETE_BLOCKLIST.includes(entry.kind) &&
- (entry.sortText < "15" ||
- (completionInfo.optionalReplacementSpan?.length &&
- (!keepLegacyLimitationForAutocompletionSymbols || AUTOCOMPLETION_SYMBOLS.includes(entry.name)))),
- )
- .map((entry): Completion => {
- const boost = -Number(entry.sortText) || 0;
- let type = entry.kind ? String(entry.kind) : undefined;
-
- if (type === "member") type = "property";
-
- if (type && !DEFAULT_CODEMIRROR_TYPE_ICONS.has(type)) {
- type = undefined;
- }
-
- return {
- label: entry.name,
- type,
- boost,
- };
- });
-
- return {
- from: word ? (word.text === "." ? word.to : word.from) : pos,
- options,
- };
-}
diff --git a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/getLineAtPosition.test.ts b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/getLineAtPosition.test.ts
deleted file mode 100644
index ef7e34a065..0000000000
--- a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/getLineAtPosition.test.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { test, expect } from "vitest";
-import { getLineAtPosition } from "./getLineAtPosition.js";
-
-test("getLineAtPosition", () => {
- expect(getLineAtPosition("x", 0)).toEqual({
- from: 0,
- text: "x",
- to: 1,
- });
-
- expect(getLineAtPosition("x", 10)).toEqual({
- from: 0,
- text: "x",
- to: 1,
- });
-
- expect(getLineAtPosition("x", -10)).toEqual({
- from: 0,
- text: "x",
- to: 1,
- });
-
- expect(getLineAtPosition("first line\nsecond line", 12)).toEqual({
- from: 11,
- text: "second line",
- to: 22,
- });
-});
diff --git a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/getLineAtPosition.ts b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/getLineAtPosition.ts
deleted file mode 100644
index 5940c707b4..0000000000
--- a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/getLineAtPosition.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-/**
- * TODO: confirm that this is necessary; it may be possible
- * and more efficient to get the line from CodeMirror, though
- * that would mean it probably doesn't mix well with the approach
- * of persisting code in the TS enviroment.
- */
-export function getLineAtPosition(code: string, position: number) {
- // lineStart is the index of line break or zero
- const from = code.lastIndexOf("\n", position - 1) + 1;
- let to = code.indexOf("\n", position);
- if (to === -1) {
- to = code.length;
- }
- const text = code.slice(from, to);
- return {
- from,
- to,
- text,
- };
-}
diff --git a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/icons.ts b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/icons.ts
deleted file mode 100644
index b917deb0ec..0000000000
--- a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/icons.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-/**
- * There is some overlap between CodeMirror's
- * types and TypeScripts. This is all of the default
- * icons for CodeMirror: if TypeScript gives us one
- * of these, we pass it through.
- */
-export const DEFAULT_CODEMIRROR_TYPE_ICONS = new Set([
- `class`,
- `constant`,
- `enum`,
- `function`,
- `interface`,
- `keyword`,
- `method`,
- `namespace`,
- `property`,
- `text`,
- `type`,
- `variable`,
-]);
diff --git a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/matchBefore.test.ts b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/matchBefore.test.ts
deleted file mode 100644
index efc868f237..0000000000
--- a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/matchBefore.test.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { expect, test } from "vitest";
-import { matchBefore } from "./matchBefore.js";
-
-test("matchBefore", () => {
- expect(matchBefore("hi.", 0, /\./)).toEqual(null);
- expect(matchBefore("hi.", 3, /\./)).toEqual({
- from: 2,
- text: ".",
- to: 3,
- });
-});
diff --git a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/matchBefore.ts b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/matchBefore.ts
deleted file mode 100644
index 8794fbcd93..0000000000
--- a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/matchBefore.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { ensureAnchor } from "./ensureAnchor.js";
-import { getLineAtPosition } from "./getLineAtPosition.js";
-
-// From: https://github.com/codemirror/autocomplete/blob/53cc58393252659ac4a86162b40afef13eeb2241/src/completion.ts#L111
-// TODO: do we need to vendor this?
-export function matchBefore(code: string, pos: number, expr: RegExp) {
- const line = getLineAtPosition(code, pos);
- let start = Math.max(line.from, pos - 250);
- let str = line.text.slice(start - line.from, pos - line.from);
- let found = str.search(ensureAnchor(expr, false));
- return found < 0
- ? null
- : { from: start + found, to: pos, text: str.slice(found) };
-}
diff --git a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/tsAutocomplete.ts b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/tsAutocomplete.ts
deleted file mode 100644
index a22558a539..0000000000
--- a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/tsAutocomplete.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import type {
- CompletionContext,
- CompletionResult,
- CompletionSource,
-} from "@codemirror/autocomplete";
-import { getAutocompletion } from "./getAutocompletion.js";
-import { tsFacet } from "../facet/tsFacet.js";
-
-/**
- * Create a `CompletionSource` that queries
- * the _on-thread_ TypeScript environments for autocompletions
- * at this character.
- */
-export function tsAutocomplete(): CompletionSource {
- return async (
- context: CompletionContext,
- ): Promise<CompletionResult | null> => {
- const config = context.state.facet(tsFacet);
- if (!config) return null;
- return getAutocompletion({
- ...config,
- context,
- });
- };
-}
diff --git a/packages/codemirror/src/type_completion/codemirror-ts/environment.ts b/packages/codemirror/src/type_completion/codemirror-ts/environment.ts
new file mode 100644
index 0000000000..365a400185
--- /dev/null
+++ b/packages/codemirror/src/type_completion/codemirror-ts/environment.ts
@@ -0,0 +1,69 @@
+import { combineConfig, Facet } from "@codemirror/state";
+import { EditorView } from "@codemirror/view";
+import type ts from "@typescript/vfs";
+import { type VirtualTypeScriptEnvironment } from "@typescript/vfs";
+
+/**
+ * This is how the ts-related extensions are
+ * configured: this facet sets the path of the file
+ * and the environment to use, and the rest of
+ * the extensions, like tsLint and tsAutocomplete,
+ * pull those settings automatically from editor state.
+ */
+export const tsFacet = Facet.define<
+ {
+ path: string;
+ env: ts.VirtualTypeScriptEnvironment;
+ keepLegacyLimitationForAutocompletionSymbols?: boolean;
+ },
+ {
+ path: string;
+ env: ts.VirtualTypeScriptEnvironment;
+ keepLegacyLimitationForAutocompletionSymbols?: boolean;
+ } | null
+>({
+ combine(configs) {
+ return combineConfig(configs, {});
+ },
+});
+
+/**
+ * Sync updates from CodeMirror to the TypeScript
+ * virtual environment. Note that this updates a file - it isn't
+ * responsible (yet) for deleting or renaming files if they
+ * do get deleted or renamed.
+ */
+export function tsSync() {
+ // TODO: this is a weak solution to the cold start problem.
+ // If you boot up a CodeMirror instance, we want the initial
+ // value to get loaded into CodeMirror. We do get a change event,
+ // but it surprisingly doesn't have `docChanged: true` on it,
+ // so this is a rough heuristic to just accept the first event
+ // regardless of whether it looks significant.
+ let first = true;
+ return EditorView.updateListener.of((update) => {
+ const config = update.view.state.facet(tsFacet);
+ if (!config) return;
+ if (!update.docChanged && !first) return;
+ first = false;
+ createOrUpdateFile(config.env, config.path, update.state.doc.toString() || ' ');
+ });
+}
+
+/**
+ * In TypeScript, updates are not like PUTs, you
+ * need to create a file before updating it.
+ *
+ * This method lets us treat the two as the same.
+ */
+export function createOrUpdateFile(
+ env: VirtualTypeScriptEnvironment,
+ path: string,
+ code: string,
+): void {
+ if (!env.getSourceFile(path)) {
+ env.createFile(path, code);
+ } else {
+ env.updateFile(path, code);
+ }
+}
diff --git a/packages/codemirror/src/type_completion/codemirror-ts/facet/tsFacet.ts b/packages/codemirror/src/type_completion/codemirror-ts/facet/tsFacet.ts
deleted file mode 100644
index 45ea18dd3f..0000000000
--- a/packages/codemirror/src/type_completion/codemirror-ts/facet/tsFacet.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { combineConfig, Facet } from "@codemirror/state";
-import type ts from "@typescript/vfs";
-
-/**
- * This is how the ts-related extensions are
- * configured: this facet sets the path of the file
- * and the environment to use, and the rest of
- * the extensions, like tsLint and tsAutocomplete,
- * pull those settings automatically from editor state.
- */
-export const tsFacet = Facet.define<
- {
- path: string;
- env: ts.VirtualTypeScriptEnvironment;
- keepLegacyLimitationForAutocompletionSymbols?: boolean;
- },
- {
- path: string;
- env: ts.VirtualTypeScriptEnvironment;
- keepLegacyLimitationForAutocompletionSymbols?: boolean;
- } | null
->({
- combine(configs) {
- return combineConfig(configs, {});
- },
-});
diff --git a/packages/codemirror/src/type_completion/codemirror-ts/hover.ts b/packages/codemirror/src/type_completion/codemirror-ts/hover.ts
new file mode 100644
index 0000000000..5816147967
--- /dev/null
+++ b/packages/codemirror/src/type_completion/codemirror-ts/hover.ts
@@ -0,0 +1,96 @@
+import { EditorView, hoverTooltip, Tooltip, TooltipView } from "@codemirror/view";
+import type ts from "typescript";
+import { type VirtualTypeScriptEnvironment } from "@typescript/vfs";
+import { tsFacet } from "./environment.js";
+
+/**
+ * This binds the CodeMirror `hoverTooltip` method
+ * with a code that pulls types and documentation
+ * from the TypeScript environment.
+ */
+export function tsHover({
+ renderTooltip = defaultRenderer,
+}: {
+ renderTooltip?: TooltipRenderer;
+} = {}) {
+ return hoverTooltip(async (view, pos): Promise<Tooltip | null> => {
+ const config = view.state.facet(tsFacet);
+ if (!config) return null;
+
+ const hoverData = getHover({
+ ...config,
+ pos,
+ });
+
+ if (!hoverData) return null;
+
+ return {
+ pos: hoverData.start,
+ end: hoverData.end,
+ create: () => renderTooltip(hoverData, view),
+ };
+ });
+}
+
+/**
+ * This information is passed to the API consumer to allow
+ * them to create tooltips however they wish.
+ */
+export interface HoverInfo {
+ start: number;
+ end: number;
+ typeDef: readonly ts.DefinitionInfo[] | undefined;
+ quickInfo: ts.QuickInfo | undefined;
+}
+
+export function getHover({
+ env,
+ path,
+ pos,
+}: {
+ env: VirtualTypeScriptEnvironment;
+ path: string;
+ pos: number;
+}): HoverInfo | null {
+ const sourcePos = pos;
+ if (sourcePos === null) return null;
+
+ const quickInfo = env.languageService.getQuickInfoAtPosition(path, sourcePos);
+ if (!quickInfo) return null;
+
+ const start = quickInfo.textSpan.start;
+
+ const typeDef =
+ env.languageService.getTypeDefinitionAtPosition(path, sourcePos) ??
+ env.languageService.getDefinitionAtPosition(path, sourcePos);
+
+ return {
+ start,
+ end: start + quickInfo.textSpan.length,
+ typeDef,
+ quickInfo,
+ };
+}
+
+export type TooltipRenderer = (
+ arg0: HoverInfo,
+ editorView: EditorView,
+) => TooltipView;
+
+/**
+ * Default, barebones tooltip renderer. Generates
+ * structure of a div, containing a series of
+ * span elements with the typescript `kind` as
+ * classes.
+ */
+export const defaultRenderer: TooltipRenderer = (info: HoverInfo) => {
+ const div = document.createElement("div");
+ if (info.quickInfo?.displayParts) {
+ for (let part of info.quickInfo.displayParts) {
+ const span = div.appendChild(document.createElement("span"));
+ span.className = `quick-info-${part.kind}`;
+ span.innerText = part.text;
+ }
+ }
+ return { dom: div };
+};
diff --git a/packages/codemirror/src/type_completion/codemirror-ts/hover/getHover.ts b/packages/codemirror/src/type_completion/codemirror-ts/hover/getHover.ts
deleted file mode 100644
index d2a7bcc65b..0000000000
--- a/packages/codemirror/src/type_completion/codemirror-ts/hover/getHover.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import type ts from "typescript";
-import { type VirtualTypeScriptEnvironment } from "@typescript/vfs";
-
-/**
- * This information is passed to the API consumer to allow
- * them to create tooltips however they wish.
- */
-export interface HoverInfo {
- start: number;
- end: number;
- typeDef: readonly ts.DefinitionInfo[] | undefined;
- quickInfo: ts.QuickInfo | undefined;
-}
-
-export function getHover({
- env,
- path,
- pos,
-}: {
- env: VirtualTypeScriptEnvironment;
- path: string;
- pos: number;
-}): HoverInfo | null {
- const sourcePos = pos;
- if (sourcePos === null) return null;
-
- const quickInfo = env.languageService.getQuickInfoAtPosition(path, sourcePos);
- if (!quickInfo) return null;
-
- const start = quickInfo.textSpan.start;
-
- const typeDef =
- env.languageService.getTypeDefinitionAtPosition(path, sourcePos) ??
- env.languageService.getDefinitionAtPosition(path, sourcePos);
-
- return {
- start,
- end: start + quickInfo.textSpan.length,
- typeDef,
- quickInfo,
- };
-}
diff --git a/packages/codemirror/src/type_completion/codemirror-ts/hover/renderTooltip.ts b/packages/codemirror/src/type_completion/codemirror-ts/hover/renderTooltip.ts
deleted file mode 100644
index 2c5f37c5fe..0000000000
--- a/packages/codemirror/src/type_completion/codemirror-ts/hover/renderTooltip.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { EditorView, TooltipView } from "@codemirror/view";
-import { HoverInfo } from "./getHover.js";
-
-export type TooltipRenderer = (
- arg0: HoverInfo,
- editorView: EditorView,
-) => TooltipView;
-
-/**
- * Default, barebones tooltip renderer. Generates
- * structure of a div, containing a series of
- * span elements with the typescript `kind` as
- * classes.
- */
-export const defaultRenderer: TooltipRenderer = (info: HoverInfo) => {
- const div = document.createElement("div");
- if (info.quickInfo?.displayParts) {
- for (let part of info.quickInfo.displayParts) {
- const span = div.appendChild(document.createElement("span"));
- span.className = `quick-info-${part.kind}`;
- span.innerText = part.text;
- }
- }
- return { dom: div };
-};
diff --git a/packages/codemirror/src/type_completion/codemirror-ts/hover/tsHover.ts b/packages/codemirror/src/type_completion/codemirror-ts/hover/tsHover.ts
deleted file mode 100644
index 6805379cea..0000000000
--- a/packages/codemirror/src/type_completion/codemirror-ts/hover/tsHover.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { hoverTooltip, Tooltip } from "@codemirror/view";
-import { getHover } from "./getHover.js";
-import { defaultRenderer, TooltipRenderer } from "./renderTooltip.js";
-import { tsFacet } from "../facet/tsFacet.js";
-
-/**
- * This binds the CodeMirror `hoverTooltip` method
- * with a code that pulls types and documentation
- * from the TypeScript environment.
- */
-export function tsHover({
- renderTooltip = defaultRenderer,
-}: {
- renderTooltip?: TooltipRenderer;
-} = {}) {
- return hoverTooltip(async (view, pos): Promise<Tooltip | null> => {
- const config = view.state.facet(tsFacet);
- if (!config) return null;
-
- const hoverData = getHover({
- ...config,
- pos,
- });
-
- if (!hoverData) return null;
-
- return {
- pos: hoverData.start,
- end: hoverData.end,
- create: () => renderTooltip(hoverData, view),
- };
- });
-}
diff --git a/packages/codemirror/src/type_completion/codemirror-ts/lint/utils.ts b/packages/codemirror/src/type_completion/codemirror-ts/lint.ts
similarity index 52%
rename from packages/codemirror/src/type_completion/codemirror-ts/lint/utils.ts
rename to packages/codemirror/src/type_completion/codemirror-ts/lint.ts
index bacaae0699..b798ae6a00 100644
--- a/packages/codemirror/src/type_completion/codemirror-ts/lint/utils.ts
+++ b/packages/codemirror/src/type_completion/codemirror-ts/lint.ts
@@ -1,5 +1,60 @@
+import { linter, Diagnostic } from "@codemirror/lint";
import ts from "typescript";
-import { type Diagnostic } from "@codemirror/lint";
+import type { DiagnosticWithLocation } from "typescript";
+import { type VirtualTypeScriptEnvironment } from "@typescript/vfs";
+import { tsFacet } from "./environment.js";
+
+/**
+ * Binds the TypeScript `lint()` method with TypeScript's
+ * semantic and syntactic diagnostics. You can use
+ * the `getLints` method for a lower-level interface
+ * to the same data.
+ */
+export function tsLinter({
+ diagnosticCodesToIgnore,
+}: { diagnosticCodesToIgnore?: number[] } = {}) {
+ return linter(async (view): Promise<readonly Diagnostic[]> => {
+ const config = view.state.facet(tsFacet);
+ return config
+ ? getLints({
+ ...config,
+ diagnosticCodesToIgnore: diagnosticCodesToIgnore || [],
+ })
+ : [];
+ });
+}
+
+/**
+ * Lower-level interface to get semantic and syntactic
+ * diagnostics from the TypeScript environment.
+ *
+ * This is used by tsLinter and tsLinterWorker,
+ * but you can use it directly to power other UI.
+ */
+export function getLints({
+ env,
+ path,
+ diagnosticCodesToIgnore,
+}: {
+ env: VirtualTypeScriptEnvironment;
+ path: string;
+ diagnosticCodesToIgnore: number[];
+}) {
+ // Don't crash if the relevant file isn't created yet.
+ const exists = env.getSourceFile(path);
+ if (!exists) return [];
+
+ const syntaticDiagnostics = env.languageService.getSyntacticDiagnostics(path);
+ const semanticDiagnostics = env.languageService.getSemanticDiagnostics(path);
+
+ const diagnostics = [...syntaticDiagnostics, ...semanticDiagnostics].filter(
+ (diagnostic): diagnostic is DiagnosticWithLocation =>
+ isDiagnosticWithLocation(diagnostic) &&
+ !diagnosticCodesToIgnore.includes(diagnostic.code),
+ );
+
+ return diagnostics.map(convertTSDiagnosticToCM);
+}
/**
* TypeScript has a set of diagnostic categories,
diff --git a/packages/codemirror/src/type_completion/codemirror-ts/lint/getLints.ts b/packages/codemirror/src/type_completion/codemirror-ts/lint/getLints.ts
deleted file mode 100644
index 8d6b534428..0000000000
--- a/packages/codemirror/src/type_completion/codemirror-ts/lint/getLints.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import type { DiagnosticWithLocation } from "typescript";
-import { convertTSDiagnosticToCM, isDiagnosticWithLocation } from "./utils.js";
-import { type VirtualTypeScriptEnvironment } from "@typescript/vfs";
-
-/**
- * Lower-level interface to get semantic and syntactic
- * diagnostics from the TypeScript environment.
- *
- * This is used by tsLinter and tsLinterWorker,
- * but you can use it directly to power other UI.
- */
-export function getLints({
- env,
- path,
- diagnosticCodesToIgnore,
-}: {
- env: VirtualTypeScriptEnvironment;
- path: string;
- diagnosticCodesToIgnore: number[];
-}) {
- // Don't crash if the relevant file isn't created yet.
- const exists = env.getSourceFile(path);
- if (!exists) return [];
-
- const syntaticDiagnostics = env.languageService.getSyntacticDiagnostics(path);
- const semanticDiagnostics = env.languageService.getSemanticDiagnostics(path);
-
- const diagnostics = [...syntaticDiagnostics, ...semanticDiagnostics].filter(
- (diagnostic): diagnostic is DiagnosticWithLocation =>
- isDiagnosticWithLocation(diagnostic) &&
- !diagnosticCodesToIgnore.includes(diagnostic.code),
- );
-
- return diagnostics.map(convertTSDiagnosticToCM);
-}
diff --git a/packages/codemirror/src/type_completion/codemirror-ts/lint/tsLinter.ts b/packages/codemirror/src/type_completion/codemirror-ts/lint/tsLinter.ts
deleted file mode 100644
index 58891a89dc..0000000000
--- a/packages/codemirror/src/type_completion/codemirror-ts/lint/tsLinter.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { linter, Diagnostic } from "@codemirror/lint";
-import { getLints } from "./getLints.js";
-import { tsFacet } from "../facet/tsFacet.js";
-
-/**
- * Binds the TypeScript `lint()` method with TypeScript's
- * semantic and syntactic diagnostics. You can use
- * the `getLints` method for a lower-level interface
- * to the same data.
- */
-export function tsLinter({
- diagnosticCodesToIgnore,
-}: { diagnosticCodesToIgnore?: number[] } = {}) {
- return linter(async (view): Promise<readonly Diagnostic[]> => {
- const config = view.state.facet(tsFacet);
- return config
- ? getLints({
- ...config,
- diagnosticCodesToIgnore: diagnosticCodesToIgnore || [],
- })
- : [];
- });
-}
diff --git a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/symbols.ts b/packages/codemirror/src/type_completion/codemirror-ts/symbols.ts
similarity index 100%
rename from packages/codemirror/src/type_completion/codemirror-ts/autocomplete/symbols.ts
rename to packages/codemirror/src/type_completion/codemirror-ts/symbols.ts
diff --git a/packages/codemirror/src/type_completion/codemirror-ts/sync/tsSync.ts b/packages/codemirror/src/type_completion/codemirror-ts/sync/tsSync.ts
deleted file mode 100644
index 0e99ba9ee5..0000000000
--- a/packages/codemirror/src/type_completion/codemirror-ts/sync/tsSync.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { EditorView } from "@codemirror/view";
-import { createOrUpdateFile } from "./update.js";
-import { tsFacet } from "../facet/tsFacet.js";
-
-/**
- * Sync updates from CodeMirror to the TypeScript
- * virtual environment. Note that this updates a file - it isn't
- * responsible (yet) for deleting or renaming files if they
- * do get deleted or renamed.
- */
-export function tsSync() {
- // TODO: this is a weak solution to the cold start problem.
- // If you boot up a CodeMirror instance, we want the initial
- // value to get loaded into CodeMirror. We do get a change event,
- // but it surprisingly doesn't have `docChanged: true` on it,
- // so this is a rough heuristic to just accept the first event
- // regardless of whether it looks significant.
- let first = true;
- return EditorView.updateListener.of((update) => {
- const config = update.view.state.facet(tsFacet);
- if (!config) return;
- if (!update.docChanged && !first) return;
- first = false;
- createOrUpdateFile(config.env, config.path, update.state.doc.toString() || ' ');
- });
-}
diff --git a/packages/codemirror/src/type_completion/codemirror-ts/sync/update.ts b/packages/codemirror/src/type_completion/codemirror-ts/sync/update.ts
deleted file mode 100644
index 844c0efec2..0000000000
--- a/packages/codemirror/src/type_completion/codemirror-ts/sync/update.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { type VirtualTypeScriptEnvironment } from "@typescript/vfs";
-
-/**
- * In TypeScript, updates are not like PUTs, you
- * need to create a file before updating it.
- *
- * This method lets us treat the two as the same.
- */
-export function createOrUpdateFile(
- env: VirtualTypeScriptEnvironment,
- path: string,
- code: string,
-): void {
- if (!env.getSourceFile(path)) {
- env.createFile(path, code);
- } else {
- env.updateFile(path, code);
- }
-}
diff --git a/packages/codemirror/src/type_completion/index.ts b/packages/codemirror/src/type_completion/index.ts
index 00b5abc8c7..fe615ed0f5 100644
--- a/packages/codemirror/src/type_completion/index.ts
+++ b/packages/codemirror/src/type_completion/index.ts
@@ -219,12 +219,11 @@ export async function buildTypeCompletion(mime: string, context: ScriptApiContex
}
const env = await createEnv(mime, context);
- const [ { tsFacet }, { tsSync }, { tsAutocomplete }, { tsLinter }, { tsHover } ] = await Promise.all([
- import("./codemirror-ts/facet/tsFacet.js"),
- import("./codemirror-ts/sync/tsSync.js"),
- import("./codemirror-ts/autocomplete/tsAutocomplete.js"),
- import("./codemirror-ts/lint/tsLinter.js"),
- import("./codemirror-ts/hover/tsHover.js")
+ const [ { tsFacet, tsSync }, { tsAutocomplete }, { tsLinter }, { tsHover } ] = await Promise.all([
+ import("./codemirror-ts/environment.js"),
+ import("./codemirror-ts/autocomplete.js"),
+ import("./codemirror-ts/lint.js"),
+ import("./codemirror-ts/hover.js")
]);
// `tsLinter` only underlines diagnostics inline; `lintGutter` adds the
// error/warning markers in the gutter (as the old ESLint integration did).
@@ -368,7 +367,7 @@ export async function getScriptLints(mime: string, code: string, context: Script
const env = await createEnv(mime, context);
const path = scriptPath(mime);
env.updateFile(path, code.length ? code : " ");
- const { getLints } = await import("./codemirror-ts/lint/getLints.js");
+ const { getLints } = await import("./codemirror-ts/lint.js");
return getLints({ env, path, diagnosticCodesToIgnore: ignoredDiagnosticCodes(mime) });
}