Skip to content

Connect, collaborate, and grow with a community of TypeScript developers

feat(editor): support inline queries (#1618)

bautistaaa7bc810b6e15f
diff --git a/packages/monaco/package.json b/packages/monaco/package.json
index c157a441..d83d91ee 100644
--- a/packages/monaco/package.json
+++ b/packages/monaco/package.json
@@ -7,7 +7,7 @@
"./code-editor": "./src/code-editor.tsx",
"./settings-store": "./src/settings-store.ts",
"./vim-mode": "./src/vim-mode.tsx",
- "./twoslash": "./src/twoslash.ts",
+ "./twoslash": "./src/twoslash/provider.ts",
"./prettier": "./src/prettier.ts",
"./editor-hooks": "./src/editor-hooks.ts",
"./utils": "./src/utils.ts"
@@ -27,7 +27,7 @@
"./src/vim-mode.tsx"
],
"twoslash": [
- "./src/twoslash.ts"
+ "./src/twoslash/provider.ts"
],
"prettier": [
"./src/prettier.ts"
diff --git a/packages/monaco/src/split-editor.tsx b/packages/monaco/src/split-editor.tsx
index 2ad30597..64def758 100644
--- a/packages/monaco/src/split-editor.tsx
+++ b/packages/monaco/src/split-editor.tsx
@@ -1,7 +1,5 @@
'use client';
-import { createTwoslashInlayProvider } from './twoslash';
-
import { type OnChange, type OnMount, type OnValidate } from '@monaco-editor/react';
import { setupTypeAcquisition } from '@typescript/ata';
import clsx from 'clsx';
@@ -16,6 +14,7 @@ import { PrettierFormatProvider } from './prettier';
import { useEditorSettingsStore } from './settings-store';
import { getEventDeltas } from './utils';
import { useToast } from '@repo/ui/components/use-toast';
+import { createTwoslashInlayProvider } from './twoslash/provider';
function preventSelection(event: Event) {
event.preventDefault();
@@ -27,6 +26,8 @@ const VimStatusBar = dynamic(() => import('./vim-mode'), {
const MIN_HEIGHT = 150;
const COLLAPSE_THRESHOLD = MIN_HEIGHT / 2;
+const USER_FILE_PATH = 'node_modules/@types/user.d.ts';
+const TEST_FILE_PATH = 'node_modules/@types/test.d.ts';
export const TESTS_PATH = 'file:///tests.ts';
export const USER_CODE_PATH = 'file:///user.ts';
@@ -57,8 +58,7 @@ export interface SplitEditorProps {
}
export const hasImports = (code: string) => {
- const x = code.split('\n').filter((line) => line.trim().startsWith('import'));
- return x.length > 0;
+ return code.split('\n').some((line) => line.trim().startsWith('import'));
};
const getActualCode = (code: string) =>
@@ -92,7 +92,6 @@ export default function SplitEditor({
const testPanelSection = useRef<HTMLDivElement>(null);
const monacoRef = useRef<typeof import('monaco-editor')>();
const editorRef = useRef<monacoType.editor.IStandaloneCodeEditor>();
- const inlayHintsProviderDisposableRef = useRef<monacoType.IDisposable>();
useEffect(() => {
const saveHandler = (e: KeyboardEvent) => {
@@ -117,7 +116,6 @@ export default function SplitEditor({
return () => {
document.removeEventListener('keydown', saveHandler);
- inlayHintsProviderDisposableRef.current?.dispose();
};
}, [editorRef]);
@@ -128,7 +126,7 @@ export default function SplitEditor({
editorRef.current = userEditorState;
}, [userEditorState]);
- // i moved this into onMount to avpid the monacoRef stuff but then you can really debounce it
+ // i moved this into onMount to avoid the monacoRef stuff but then you can really debounce it
const [ata] = useState(() =>
setupTypeAcquisition({
projectName: 'TypeHero Playground',
@@ -162,14 +160,14 @@ export default function SplitEditor({
if (hasImports(userCode)) {
monacoRef.current.languages.typescript.typescriptDefaults.addExtraLib(
getActualCode(userCode),
- 'file:///node_modules/@types/user.d.ts',
+ USER_FILE_PATH,
);
}
if (hasImports(testCode)) {
monacoRef.current.languages.typescript.typescriptDefaults.addExtraLib(
getActualCode(testCode),
- 'file:///node_modules/@types/test.d.ts',
+ TEST_FILE_PATH,
);
}
@@ -304,6 +302,7 @@ export default function SplitEditor({
defaultPath={USER_CODE_PATH}
onMount={async (editor, monaco) => {
// this just does the typechecking so the UI can update
+ // it also makes the monaco instance available outside of this callback by setting state in parent
onMount?.user?.(editor, monaco);
typeCheck(monaco);
monaco.languages.typescript.typescriptDefaults.setEagerModelSync(true);
@@ -331,13 +330,11 @@ export default function SplitEditor({
const getTsWorker = await monaco.languages.typescript.getTypeScriptWorker();
const tsWorker = await getTsWorker(model.uri);
- const inlayHintsProviderDisposable = monaco.languages.registerInlayHintsProvider(
+ monaco.languages.registerInlayHintsProvider(
'typescript',
createTwoslashInlayProvider(monaco, tsWorker),
);
- inlayHintsProviderDisposableRef.current = inlayHintsProviderDisposable;
-
if (hasImports(code)) {
const actualCode = code
.split('\n')
@@ -347,7 +344,7 @@ export default function SplitEditor({
monaco.languages.typescript.typescriptDefaults.setExtraLibs([
{
content: actualCode,
- filePath: 'file:///node_modules/@types/user.d.ts',
+ filePath: USER_FILE_PATH,
},
]);
}
@@ -368,7 +365,7 @@ export default function SplitEditor({
monaco?.languages.typescript.typescriptDefaults.setExtraLibs([
{
content: actualCode,
- filePath: 'file:///node_modules/@types/user.d.ts',
+ filePath: USER_FILE_PATH,
},
]);
}
@@ -382,10 +379,7 @@ export default function SplitEditor({
// we want to blow away the user.d.ts because
// 1. its no longer needed
// 2. so you dont get duplicate type errors if you add imports back in
- monaco?.languages.typescript.typescriptDefaults.addExtraLib(
- '',
- 'file:///node_modules/@types/user.d.ts',
- );
+ monaco?.languages.typescript.typescriptDefaults.addExtraLib('', USER_FILE_PATH);
}
onChange?.user?.(value, changeEvent);
typeCheck(monaco!);
@@ -417,7 +411,7 @@ export default function SplitEditor({
renderValidationDecorations: 'on',
readOnly: isTestsReadonly,
}}
- onMount={(editor, monaco) => {
+ onMount={async (editor, monaco) => {
// this just does the typechecking so the UI can update
onMount?.tests?.(editor, monaco);
const testModel = monaco.editor.getModel(monaco.Uri.parse(TESTS_PATH))!;
@@ -433,7 +427,7 @@ export default function SplitEditor({
monaco.languages.typescript.typescriptDefaults.setExtraLibs([
{
content: actualCode,
- filePath: 'file:///node_modules/@types/test.d.ts',
+ filePath: TEST_FILE_PATH,
},
]);
}
@@ -454,7 +448,7 @@ export default function SplitEditor({
monaco?.languages.typescript.typescriptDefaults.setExtraLibs([
{
content: actualCode,
- filePath: 'file:///node_modules/@types/test.d.ts',
+ filePath: TEST_FILE_PATH,
},
]);
}
diff --git a/packages/monaco/src/twoslash.ts b/packages/monaco/src/twoslash.ts
deleted file mode 100644
index 9beaa6ed..00000000
--- a/packages/monaco/src/twoslash.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-// based on: https://github.com/microsoft/TypeScript-Website/blob/v2/packages/playground/src/twoslashInlays.ts
-import type * as monaco from 'monaco-editor';
-
-export const TWOSLASH_INLAY_HINTS_PROVIDER = 'twoslash inlay hints provider';
-
-export const createTwoslashInlayProvider = (
- m: typeof monaco,
- worker: monaco.languages.typescript.TypeScriptWorker,
-) => {
- const provider: monaco.languages.InlayHintsProvider = {
- displayName: TWOSLASH_INLAY_HINTS_PROVIDER,
- provideInlayHints: async (model, _, cancel) => {
- const text = model.getValue();
-
- let match;
- const results: monaco.languages.InlayHint[] = [];
- if (model.isDisposed()) {
- return {
- hints: [],
- dispose: () => {},
- };
- }
-
- const queryRegex = /^\s*\/\/\s*\^\?$/gm;
- while ((match = queryRegex.exec(text)) !== null) {
- const end = match.index + match[0].length - 1;
- const endPos = model.getPositionAt(end);
- const inspectionPos = new m.Position(endPos.lineNumber - 1, endPos.column);
- const inspectionOff = model.getOffsetAt(inspectionPos);
-
- if (cancel.isCancellationRequested) {
- return {
- hints: [],
- dispose: () => {},
- };
- }
-
- const hint = (await worker.getQuickInfoAtPosition(model.uri.toString(), inspectionOff)) as {
- displayParts: { text: string }[];
- };
- if (!hint || !hint.displayParts) continue;
-
- // Make a one-liner
- let text = hint.displayParts
- .map((d: { text: string }) => d.text)
- .join('')
- .replace(/\r?\n\s*/g, ' ');
- if (text.length > 120) text = `${text.slice(0, 119)}...`;
-
- const inlay: monaco.languages.InlayHint = {
- // @ts-expect-error undocumented kind
- kind: 0,
- position: new m.Position(endPos.lineNumber, endPos.column + 1),
- label: text,
- paddingLeft: true,
- };
-
- results.push(inlay);
- }
-
- return {
- hints: results,
- dispose: () => {},
- };
- },
- };
-
- return provider;
-};
diff --git a/packages/monaco/src/twoslash/helpers.ts b/packages/monaco/src/twoslash/helpers.ts
new file mode 100644
index 00000000..09e67a8a
--- /dev/null
+++ b/packages/monaco/src/twoslash/helpers.ts
@@ -0,0 +1,77 @@
+import type * as monaco from 'monaco-editor';
+
+interface InlayHintInfo {
+ hint: QuickInfoResponse | undefined;
+ monaco: typeof monaco;
+ position: monaco.Position;
+}
+
+type QuickInfoResponse = Awaited<ReturnType<typeof quickInfoRequest>>;
+/** Leverages the `tsserver` protocol to try to get the type info at the given `position`. */
+export async function quickInfoRequest({
+ fileName,
+ offset,
+ worker,
+}: {
+ fileName: string;
+ offset: number;
+ worker: monaco.languages.typescript.TypeScriptWorker;
+}) {
+ return (await worker.getQuickInfoAtPosition(fileName, offset)) as {
+ displayParts: { text: string }[];
+ };
+}
+
+export async function createInlayHint({ hint, monaco, position }: InlayHintInfo) {
+ if (!hint || !hint.displayParts) return;
+ // Make a one-liner
+ let text = hint.displayParts
+ .map((d: { text: string }) => d.text)
+ .join('')
+ .replace(/\r?\n\s*/g, ' ');
+ if (text.length > 120) text = `${text.slice(0, 119)}...`;
+
+ const inlay: monaco.languages.InlayHint = {
+ // @ts-expect-error undocumented kind
+ kind: 0,
+ position: new monaco.Position(position.lineNumber, position.column + 1),
+ label: text,
+ paddingLeft: true,
+ };
+
+ return inlay;
+}
+
+const range = (num: number) => [...Array(num).keys()];
+interface LineInfo {
+ model: monaco.editor.ITextModel;
+ position: monaco.Position;
+ lineLength: number;
+ worker: monaco.languages.typescript.TypeScriptWorker;
+ monaco: typeof monaco;
+}
+/** Gets the first `QuickInfo` response in a given line, if available. */
+export async function getLeftMostHintOfLine({
+ model,
+ position,
+ lineLength,
+ monaco,
+ worker,
+}: LineInfo) {
+ for (const i of range(lineLength)) {
+ const newPosition: monaco.Position = new monaco.Position(position.lineNumber + 1, i);
+ const offset = model.getOffsetAt(newPosition);
+
+ const hint = await quickInfoRequest({
+ fileName: model.uri.toString(),
+ offset,
+ worker,
+ });
+
+ if (!hint || !hint.displayParts) {
+ continue;
+ }
+
+ return hint;
+ }
+}
diff --git a/packages/monaco/src/twoslash/provider.ts b/packages/monaco/src/twoslash/provider.ts
new file mode 100644
index 00000000..f3a26c44
--- /dev/null
+++ b/packages/monaco/src/twoslash/provider.ts
@@ -0,0 +1,19 @@
+// based on: https://github.com/microsoft/TypeScript-Website/blob/v2/packages/playground/src/twoslashInlays.ts
+import type * as monaco from 'monaco-editor';
+import { getHintsFromQueries } from './queries';
+
+export const TWOSLASH_INLAY_HINTS_PROVIDER = 'twoslash inlay hints provider';
+
+export const createTwoslashInlayProvider = (
+ m: typeof monaco,
+ worker: monaco.languages.typescript.TypeScriptWorker,
+) => {
+ const provider: monaco.languages.InlayHintsProvider = {
+ displayName: TWOSLASH_INLAY_HINTS_PROVIDER,
+ provideInlayHints: async (model, range, cancel) => {
+ return await getHintsFromQueries({ model, range, cancel, monaco: m, worker });
+ },
+ };
+
+ return provider;
+};
diff --git a/packages/monaco/src/twoslash/queries.ts b/packages/monaco/src/twoslash/queries.ts
new file mode 100644
index 00000000..e5b04ecc
--- /dev/null
+++ b/packages/monaco/src/twoslash/queries.ts
@@ -0,0 +1,137 @@
+// based on https://github.com/orta/vscode-twoslash-queries
+import type * as monaco from 'monaco-editor';
+import { createInlayHint, getLeftMostHintOfLine, quickInfoRequest } from './helpers';
+
+/** Strongly-typed RegExp groups (https://github.com/microsoft/TypeScript/issues/32098#issuecomment-1279645368) */
+type RegExpGroups<T extends string> = {
+ groups: Record<string, string> | { [name in T]: string };
+}[] &
+ IterableIterator<RegExpMatchArray>;
+const twoslashQueryRegex = /^\s*\/\/\s*\^\?$/gm;
+// https://regex101.com/r/6Jb8h2/1
+const inlineQueryRegex = new RegExp(
+ `${/^[^\S\r\n]*(?<start>\S).*\/\/\s*(?<end>=>)/.source}$`,
+ 'gm',
+); // symbol: =>
+type InlineQueryMatches = RegExpGroups<'end' | 'start'>;
+
+type InlayHintsPromise = Promise<monaco.languages.InlayHint[]>;
+interface Query {
+ cancel: monaco.CancellationToken;
+ model: monaco.editor.ITextModel;
+ monaco: typeof monaco;
+ range: monaco.Range;
+ worker: monaco.languages.typescript.TypeScriptWorker;
+}
+
+export async function checkTwoslashQuery({
+ model,
+ cancel,
+ monaco,
+ worker,
+}: Query): InlayHintsPromise {
+ const results: monaco.languages.InlayHint[] = [];
+ const text = model.getValue();
+ const m = text.matchAll(twoslashQueryRegex);
+
+ for (const match of m) {
+ if (match.index === undefined) {
+ break;
+ }
+
+ if (cancel.isCancellationRequested) {
+ return [];
+ }
+
+ const end = match.index + match[0].length - 1;
+ const endPos = model.getPositionAt(end);
+ const inspectionPos = new monaco.Position(endPos.lineNumber - 1, endPos.column);
+ const inspectionOff = model.getOffsetAt(inspectionPos);
+
+ const hint = await quickInfoRequest({
+ fileName: model.uri.toString(),
+ offset: inspectionOff,
+ worker,
+ });
+ const inlayHint = await createInlayHint({
+ hint,
+ monaco,
+ position: endPos,
+ });
+
+ if (inlayHint) {
+ results.push(inlayHint);
+ }
+ }
+
+ return results;
+}
+
+export async function checkInlineTwoslashQuery({
+ model,
+ cancel,
+ monaco,
+ worker,
+ range,
+}: Query): InlayHintsPromise {
+ const results: monaco.languages.InlayHint[] = [];
+ const text = model.getValue();
+ const m = text.matchAll(inlineQueryRegex) as InlineQueryMatches;
+
+ for (const match of m) {
+ if (match.index === undefined) {
+ break;
+ }
+
+ if (cancel.isCancellationRequested) {
+ return [];
+ }
+
+ const [line] = match;
+ const { start, end: querySymbol } = match.groups;
+ const startIndex = line.indexOf(start);
+ const offset = model.getOffsetAt(range.getStartPosition());
+
+ const endIndex = line.lastIndexOf(querySymbol) + 2;
+ const endPos = model.getPositionAt(endIndex + offset + match.index);
+
+ const inspectionPos = new monaco.Position(endPos.lineNumber - 1, endPos.column);
+
+ const hint = await getLeftMostHintOfLine({
+ model,
+ position: inspectionPos,
+ lineLength: endIndex - startIndex - 2,
+ worker,
+ monaco,
+ });
+
+ const inlayHint = await createInlayHint({
+ hint,
+ monaco,
+ position: endPos,
+ });
+
+ if (inlayHint) {
+ results.push(inlayHint);
+ }
+ }
+
+ return results;
+}
+export async function getHintsFromQueries(queryInfo: Query): Promise<{
+ hints: monaco.languages.InlayHint[];
+ dispose: () => void;
+}> {
+ const queries = [checkTwoslashQuery, checkInlineTwoslashQuery];
+ const results: monaco.languages.InlayHint[] = [];
+
+ for (const query of queries) {
+ const queryResults = await query(queryInfo);
+ results.push(...queryResults);
+ }
+
+ return {
+ hints: results,
+ dispose: () => {},
+ };
+}