Skip to content

EditorView ​

EditorView (EditorViewProps) mounts an editor, attaches the language features of a project to it, and draws their cards. It is the component most apps need.

tsx
<EditorView
    engine={engine}
    options={{ text, language: 'typescript', path: '/shop/src/order.ts', theme: 'github-light' }}
    project={project}
    uri="file:///shop/src/order.ts"
    languageId="typescript"
    onMount={(editor) => editor.onSave(() => save(editor.getText()))}
    className="h-96"
/>
PropTypeMeaning
engineEditorEngineThe engine that mounts the editor
optionsEditorOptionsThe mount options
projectProjectLanguageOptional; without it, or without uri or languageId, the editor has no features
uristringThe document's file: URI
languageIdstringThe LSP language id, such as typescript or php
timersTimersThe clock of the language features, such as ManualTimers in a test
languageOptionsEditorLanguageOptionsWhat the app tunes about the features, as the last argument of EditorLanguage
onMount(editor, language) => void | (() => void)Called after mounting with the Editor and the EditorLanguage, or null; the function it returns runs before the editor goes
contextMenuItems(language) => ReactNodeA group of the app in the context menu
hoverFooter(view, language) => ReactNodeSections of the app at the foot of the hover card
className, refOn the outer element, which needs a height

Changing engine, project, uri or languageId remounts the editor with a fresh document and undo history. The view reads everything else at mount, so inline options and onMount cost nothing per render. Later changes of theme, readOnly, readOnlyReason, wrap, indentation, smartKeys, guides, stickyScroll, whitespace, rightMargin, foldOutline, label and messages apply in place; other options only count at mount. On unmount it runs the onMount cleanup, then disposes the EditorLanguage and the editor. It never disposes the project.

EditorLanguage ​

new EditorLanguage(project, editor, uri, languageId, timers?, options?) attaches every feature to an editor the app mounted itself. It acquires the document from the project and holds the features as fields: completion, signature, snippets, hover, diagnostics, highlights, navigation, peek, callHierarchy, pick, symbolPicker, rename, codeActions, contextMenu, history, definitionLink, symbols, codeVision, formatOnType and renderedDocs. Semantic tokens, inlay hints, folds and selection ranges run without a field.

ts
const editor = engine.mount(element, options);
const language = new EditorLanguage(project, editor, uri, 'typescript');

await language.document.ready;

// Later, in this order:
language.dispose();
editor.dispose();

Attach one EditorLanguage per editor; EditorView already makes one. language.goTo(location) and language.jump(position) move the caret and record where it was; visit(place) moves it without a record. language.onDispose(callback) runs a callback when the language goes.

Keys ​

The features see keys through language.onKey(handler, priority?), which returns the function that removes the handler. Higher priorities go first, ties in order of adding, and the first handler to return true takes the key. KEY_PRIORITY holds each feature's priority, from highest to lowest: suggestionAccept (Tab on a suggestion), pick, diagnostics, hover, completion, snippets, templates, markup, signature, highlights, codeActions, rename, navigation, peek, callHierarchy, symbolPicker, history, renderedDocs, pasteHistory and inlineCompletion. A handler without a priority comes after every feature.

language.onServedKey(handler, priority?) is the same for a feature that needs a server behind the document: an editor whose document no server serves never gives it a key.

To see a key before a feature, register with a higher priority from the features option below:

ts
const language = new EditorLanguage(project, editor, uri, languageId, realTimers, {
    features: (built) => {
        // Tab runs the app's own action before the suggestion list and the snippet fields see it.
        built.onKey((event) => event.key === 'Tab' && runAction(built), KEY_PRIORITY.pick + 1);
        return { runAction };
    }
});

Features of the app ​

EditorLanguageOptions.features(language) builds the app's own features for one editor, once the shared ones exist, so it may use every one of them. What it returns is language.app, typed by EditorLanguage<App>; it is not set yet while features runs. The app composes instead of subclassing: it wraps new EditorLanguage in a function that passes its features.

A feature that suggests code adds a source to language.inlineCompletion instead of drawing ghost text itself; see inline completions.

An editor.onKeyDown handler runs before these when added before the EditorLanguage, and after them when added later.

LanguagePopups ​

<LanguagePopups language={language} /> draws every card a feature opens: hover, suggestions, signature help, the pick list, rename, peek, the call hierarchy, the symbol picker, the context menu and the authors card. EditorView renders it; an app that mounts by hand renders it next to the editor. Cards follow their character as the editor scrolls or resizes.

An app adds its own parts through LanguagePopupsProps:

PropTypeMeaning
languageEditorLanguage<App>The editor's features; the callbacks below get the same type back
contextMenuItems(language) => ReactNodeA group of the app in the context menu
hoverFooter(view, language) => ReactNodeSections at the foot of the hover card, such as actions on its problems. view is the card's HoverView; each top-level element gets a divider, and null adds nothing
childrenReactNodeAn app layer over the editor, drawn above the cards and below the rename field, such as an inline prompt
tsx
<EditorRenderingProvider value={rendering}>
    <LanguagePopups
        language={language}
        hoverFooter={(view, language) =>
            view.problems.length === 0 ? null : (
                <div className="flex gap-1 px-3 py-2">
                    <Button size="xs" variant="secondary" onClick={() => explain(language, view.problems)}>
                        Explain
                    </Button>
                </div>
            )
        }
    >
        <InlinePrompt language={language} />
    </LanguagePopups>
</EditorRenderingProvider>

The cards render through portals, so a provider around LanguagePopups, such as EditorRenderingProvider, reaches all of them.

createHolder<T>() is the store EditorView uses to hand its EditorLanguage to React: get, set and subscribe, for useSyncExternalStore.

Drawing your own cards ​

The features keep what their cards show in language.popups, a Popups. language.popups.slot(name) is the PopupSlot of one card: get() returns its view, or null while the card is closed, and subscribe(listener) hears every change. Each slot has its own snapshot, so a card draws again only for a change of its own. LanguagePopups draws them all; a host that draws one card itself reads that slot and leaves the rest to LanguagePopups. The names and views are the PopupViews, which an app extends with declare module '@adecore/editor-react' { interface PopupViews { ... } } for a slot of its own.

SlotViewWhat it holds
hoverHoverViewThe anchor, the problems there and the info, a HoverInfo with the text and definition
completionCompletionViewThe rows as CompletionRows, the active one and its docs, a CompletionDocs
signatureSignatureViewThe anchor and the SignatureViewModel
pickPickViewThe title, the groups as PickGroups of PickRows, the query and chosen ids
renameRenameViewThe name, its occurrences and the preview, one RenameFileView per file
peekPeekViewReferences or definitions and the row the panel is drawn in
callHierarchyCallHierarchyViewThe tree of calls
symbolsSymbolsViewThe file's name and its symbols
menuMenuViewWhere the context menu opens and the refactorings on offer
authorsAuthorsViewThe code vision authors card
wrapWrapViewThe Wrap with Abbreviation field
tsx
const slot = language.popups.slot('completion');
const completion = useSyncExternalStore(
    (listener) => slot.subscribe(listener),
    () => slot.get()
);

The views are read-only; act through the feature, such as language.completion.accept(false).

AnchoredPopup ​

AnchoredPopup is the card every popup uses. It sits next to a rect from rectAt and stays inside the window. It renders into document.body, so it keeps the page's scale inside a scaled canvas.

tsx
import { AnchoredPopup } from '@adecore/editor-react';
import { formatNumber } from '@adecore/ui/format';
import { useEffect, useReducer, useState } from 'react';
import { EditorFrame } from '../shared/editor-frame.tsx';
import { SAMPLE, useEditor } from '../shared/editor.ts';

const OPTIONS = { text: SAMPLE, language: 'typescript', theme: 'demo', line: 5, column: 9 } as const;

/* A card that follows the caret: click in the editor, then move the caret or scroll. */
export default function AnchoredPopupDemo() {
    const { host, editor } = useEditor(OPTIONS);
    const [, redraw] = useReducer((count: number) => count + 1, 0);
    const [shown, setShown] = useState(false);

    useEffect(() => {
        if (editor === null) {
            return;
        }

        const stops = [
            editor.onCaret(() => {
                setShown(true);
                redraw();
            }),
            editor.onViewChange(redraw),
            editor.onBlur(() => setShown(false))
        ];

        return () => stops.forEach((stop) => stop());
    }, [editor]);

    const caret = shown ? (editor?.getCaret() ?? null) : null;
    const rect = caret === null ? null : editor!.rectAt(caret);

    return (
        <>
            <EditorFrame host={host} />
            {caret !== null && rect !== null && (
                <AnchoredPopup rect={rect} className="px-2.5 py-1.5 text-xs">
                    Line {formatNumber(caret.line + 1)}, column {formatNumber(caret.character + 1)}
                </AnchoredPopup>
            )}
        </>
    );
}
PropMeaning
rectThe box of the character, in page pixels
placementPlaceOptions: prefer 'above' or 'below', gap and margin
className, childrenThe card's content
overflow'scroll' by default, or 'clip' for content that scrolls
onPointerEnter, onPointerLeaveFor a card that stays while the pointer is on it

Render it again when the rect changes; it places itself on every render.

EditorRenderingProvider ​

Code in hover cards and peeks is plain text unless an EditorRenderingProvider colors it. Its value is an EditorRendering: the syntax theme and an optional highlight(code, language, theme) that resolves to HTML, such as Shiki's codeToHtml. The cards insert the HTML unescaped, so use a highlighter the app trusts.

tsx
<EditorRenderingProvider value={{ theme: 'github-light', highlight: (code, lang, theme) => highlighter.codeToHtml(code, { lang, theme }) }}>
    <App />
</EditorRenderingProvider>

Licenses and third-party notices are listed in each package.