Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Example of a portal-based React CodeMirror widget #1115

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 45 additions & 8 deletions src/editor/codemirror/CodeMirror.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,15 @@ import {
lineNumbers,
ViewUpdate,
} from "@codemirror/view";
import { useEffect, useMemo, useRef } from "react";
import React, {
ReactNode,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import { createPortal } from "react-dom";
import { useIntl } from "react-intl";
import { lineNumFromUint8Array } from "../../common/text-util";
import useActionFeedback from "../../common/use-action-feedback";
Expand Down Expand Up @@ -40,6 +48,7 @@ import { languageServer } from "./language-server/view";
import { lintGutter } from "./lint/lint";
import { codeStructure } from "./structure-highlighting";
import themeExtensions from "./themeExtensions";
import { reactWidgetExtension } from "./reactWidgetExtension";

interface CodeMirrorProps {
className?: string;
Expand All @@ -52,6 +61,20 @@ interface CodeMirrorProps {
parameterHelpOption: ParameterHelpOption;
}

interface PortalContent {
dom: HTMLElement;
content: ReactNode;
}

/**
* Creates a React portal for a CodeMirror dom element (e.g. for a widget) and
* returns a clean-up function to call when the widget is destroyed.
*/
export type PortalFactory = (
dom: HTMLElement,
content: ReactNode
) => () => void;

/**
* A React component for CodeMirror 6.
*
Expand Down Expand Up @@ -100,6 +123,13 @@ const CodeMirror = ({
[fontSize, codeStructureOption, parameterHelpOption]
);

const [portals, setPortals] = useState<PortalContent[]>([]);
const portalFactory: PortalFactory = useCallback((dom, content) => {
const portal = { dom, content };
setPortals((portals) => [...portals, portal]);
return () => setPortals((portals) => portals.filter((p) => p !== portal));
}, []);

useEffect(() => {
const initializing = !viewRef.current;
if (initializing) {
Expand All @@ -118,6 +148,7 @@ const CodeMirror = ({
extensions: [
notify,
editorConfig,
reactWidgetExtension(portalFactory),
// Extension requires external state.
dndSupport({ sessionSettings, setSessionSettings }),
// Extensions only relevant for editing:
Expand Down Expand Up @@ -172,6 +203,9 @@ const CodeMirror = ({
parameterHelpOption,
uri,
apiReferenceMap,
portals,
portalFactory,
setPortals,
]);
useEffect(() => {
// Do this separately as we don't want to destroy the view whenever options needed for initialization change.
Expand Down Expand Up @@ -260,13 +294,16 @@ const CodeMirror = ({
}, [routerState, setRouterState]);

return (
<section
data-testid="editor"
aria-label={intl.formatMessage({ id: "code-editor" })}
style={{ height: "100%" }}
className={className}
ref={elementRef}
/>
<>
<section
data-testid="editor"
aria-label={intl.formatMessage({ id: "code-editor" })}
style={{ height: "100%" }}
className={className}
ref={elementRef}
/>
{portals.map(({ content, dom }) => createPortal(content, dom))}
</>
);
};

Expand Down
112 changes: 112 additions & 0 deletions src/editor/codemirror/reactWidgetExtension.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import { Button, HStack, Text } from "@chakra-ui/react";
import { EditorState, Extension, StateField } from "@codemirror/state";
import {
Decoration,
DecorationSet,
EditorView,
WidgetType,
} from "@codemirror/view";
import { useCallback } from "react";
import { supportedLanguages, useSettings } from "../../settings/settings";
import { PortalFactory } from "./CodeMirror";

interface ExampleReactComponentProps {
view: EditorView;
}

/**
* An example react component that we use inside a CodeMirror widget as
* a proof of concept.
*/
const ExampleReactComponent = ({ view }: ExampleReactComponentProps) => {
console.log("We have access to the view here", view);

// This is a weird thing to do in a CodeMirror widget but proves the point that
// we can use React features to communicate with the rest of the app.
const [settings, setSettings] = useSettings();
const handleClick = useCallback(() => {
let { languageId } = settings;
while (languageId === settings.languageId) {
languageId =
supportedLanguages[
Math.floor(Math.random() * supportedLanguages.length)
].id;
}
setSettings({
...settings,
languageId,
});
}, [settings, setSettings]);
return (
<HStack fontFamily="body" spacing={5} py={3}>
<Button onClick={handleClick}>Pick random UI language</Button>
<Text fontWeight="semibold">Current language: {settings.languageId}</Text>
</HStack>
);
};

/**
* This widget will have its contents rendered by the code in CodeMirror.tsx
* which it communicates with via the portal factory.
*/
class ExampleReactBlockWidget extends WidgetType {
private portalCleanup: (() => void) | undefined;

constructor(private createPortal: PortalFactory) {
super();
}

toDOM(view: EditorView) {
const dom = document.createElement("div");
this.portalCleanup = this.createPortal(
dom,
<ExampleReactComponent view={view} />
);
return dom;
}

destroy(dom: HTMLElement): void {
if (this.portalCleanup) {
this.portalCleanup();
}
}

ignoreEvent() {
return true;
}
}

/**
* A toy extension that creates a wiget after the first line.
*/
export const reactWidgetExtension = (
createPortal: PortalFactory
): Extension => {
const decorate = (state: EditorState) => {
// Just put a widget at the start of the document.
// A more interesting example would look at the cursor (selection) and/or syntax tree.
const endOfFirstLine = state.doc.lineAt(0).to;
const widget = Decoration.widget({
block: true,
widget: new ExampleReactBlockWidget(createPortal),
side: 1,
});
return Decoration.set(widget.range(endOfFirstLine));
};

const stateField = StateField.define<DecorationSet>({
create(state) {
return decorate(state);
},
update(widgets, transaction) {
if (transaction.docChanged) {
return decorate(transaction.state);
}
return widgets.map(transaction.changes);
},
provide(field) {
return EditorView.decorations.from(field);
},
});
return [stateField];
};
Loading