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

feat(UI): SSR support #8915

Merged
merged 6 commits into from
Jul 25, 2024
Merged
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
7 changes: 7 additions & 0 deletions .bitmap
Original file line number Diff line number Diff line change
Expand Up @@ -1738,6 +1738,13 @@
"mainFile": "index.ts",
"rootDir": "components/ui/code-compare"
},
"ui/code-editor": {
"name": "ui/code-editor",
"scope": "teambit.code",
"version": "0.0.8",
"mainFile": "index.ts",
"rootDir": "components/ui/code-editor"
},
"ui/code-tab-page": {
"name": "ui/code-tab-page",
"scope": "teambit.code",
Expand Down
28 changes: 11 additions & 17 deletions components/renderers/api-node-details/api-node-details.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ import { APIRefQueryParams } from '@teambit/api-reference.hooks.use-api-ref-url'
import { useNavigate } from 'react-router-dom';
import { APINode } from '@teambit/api-reference.models.api-reference-model';
import { SchemaNodesIndex } from '@teambit/api-reference.renderers.schema-nodes-index';
import { OnMount, Monaco } from '@monaco-editor/react';
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';

import styles from './api-node-details.module.scss';

Expand Down Expand Up @@ -46,11 +44,11 @@ export function APINodeDetails({
const navigate = useNavigate();
const Editor = useCodeEditor();

const signatureEditorRef = useRef<monaco.editor.IStandaloneCodeEditor>();
const signatureMonacoRef = useRef<Monaco>();
const signatureEditorRef = useRef<any>();
const signatureMonacoRef = useRef<any>();

const exampleEditorRef = useRef<monaco.editor.IStandaloneCodeEditor>();
const exampleMonacoRef = useRef<Monaco>();
const exampleEditorRef = useRef<any>();
const exampleMonacoRef = useRef<any>();

const routeToAPICmdId = useRef<string | null>(null);
const apiUrlToRoute = useRef<string | null>(null);
Expand Down Expand Up @@ -153,11 +151,7 @@ export function APINodeDetails({
};

const updateEditorHeight =
(
editorRef: React.MutableRefObject<monaco.editor.IStandaloneCodeEditor | undefined>,
monacoRef: React.MutableRefObject<Monaco | undefined>
) =>
() => {
(editorRef: React.MutableRefObject<any | undefined>, monacoRef: React.MutableRefObject<any | undefined>) => () => {
if (!monacoRef.current) return undefined;

const editor = editorRef.current;
Expand Down Expand Up @@ -201,13 +195,13 @@ export function APINodeDetails({
// const updateEditorHeight = _.throttle<typeof _updateEditorHeight>(_updateEditorHeight, 300) as _.DebouncedFunc<any>;

const handleEditorDidMount: (
monacoRef: React.MutableRefObject<Monaco | undefined>,
editorRef: React.MutableRefObject<monaco.editor.IStandaloneCodeEditor | undefined>,
monacoRef: React.MutableRefObject<any | undefined>,
editorRef: React.MutableRefObject<any | undefined>,
containerRef: React.MutableRefObject<HTMLDivElement | null>,
setHeight?: React.Dispatch<React.SetStateAction<string | undefined>>,
onMount?: (monaco: Monaco, editor: monaco.editor.IStandaloneCodeEditor) => void,
onMount?: (monaco: any, editor: any) => void,
onUnMount?: () => void
) => OnMount = React.useCallback(
) => any = React.useCallback(
(monacoRef, editorRef, containerRef, setHeight, onMount, unMount) => (editor, _monaco) => {
/**
* disable syntax check
Expand All @@ -227,7 +221,7 @@ export function APINodeDetails({
esModuleInterop: true,
});

monaco.editor.defineTheme('bit', {
monacoRef.current.editor.defineTheme('bit', {
base: 'vs-dark',
inherit: true,
rules: [],
Expand All @@ -241,7 +235,7 @@ export function APINodeDetails({
},
});

monaco.editor.setTheme('bit');
monacoRef.current.editor.setTheme('bit');

onMount?.(monacoRef.current, editorRef.current);

Expand Down
32 changes: 32 additions & 0 deletions components/ui/code-editor/code-editor.provider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import React, { createContext, useContext, ReactNode, useEffect, useState } from 'react';
import { EditorProps } from '@monaco-editor/react';

const CodeEditorContext = createContext<React.FC<EditorProps> | null>(null);

type CodeEditorProviderProps = {
children: ReactNode;
};

export const CodeEditorProvider: React.FC<CodeEditorProviderProps> = ({ children }) => {
const [Editor, setEditor] = useState<React.FC<EditorProps> | null>(null);

useEffect(() => {
if (typeof window !== 'undefined') {
const loadEditor = async () => {
const { default: MonacoEditor } = await import('@monaco-editor/react');
setEditor(() => MonacoEditor);
};

loadEditor().catch((error) => {
// eslint-disable-next-line no-console
console.error('Failed to load Monaco Editor:', error);
});
}
}, []);

return <CodeEditorContext.Provider value={Editor}>{children}</CodeEditorContext.Provider>;
};

export const useCodeEditor = () => {
return useContext(CodeEditorContext);
};
89 changes: 89 additions & 0 deletions components/ui/code-editor/code-editor.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import React from 'react';
import classnames from 'classnames';
import { OnMount, BeforeMount, OnChange, EditorProps } from '@monaco-editor/react';
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
import { darkMode } from '@teambit/base-ui.theme.dark-theme';

export type CodeEditorProps = {
filePath?: string;
fileContent?: string;
language?: string;
height?: string;
className?: string;
options?: monaco.editor.IStandaloneEditorConstructionOptions;
beforeMount?: BeforeMount;
onMount?: OnMount;
onChange?: OnChange;
Loader?: React.ReactNode;
Editor?: React.FC<EditorProps> | null;
};

export const DEFAULT_EDITOR_OPTIONS: monaco.editor.IStandaloneEditorConstructionOptions = {
readOnly: true,
minimap: { enabled: false },
scrollbar: { alwaysConsumeMouseWheel: true, vertical: 'auto' },
scrollBeyondLastLine: false,
folding: false,
overviewRulerLanes: 0,
overviewRulerBorder: false,
wordWrap: 'off',
wrappingStrategy: undefined,
fixedOverflowWidgets: true,
renderLineHighlight: 'none',
lineHeight: 20,
padding: { top: 8, bottom: 8 },
hover: { enabled: false },
cursorBlinking: 'smooth',
};

// a translation list of specific monaco languages that are not the same as their file ending.
const languageOverrides = {
ts: 'typescript',
tsx: 'typescript',
js: 'javascript',
jsx: 'javascript',
mdx: 'markdown',
md: 'markdown',
};

export function CodeEditor({
fileContent,
filePath,
language,
beforeMount,
onMount,
onChange,
Loader,
options,
className,
height,
Editor,
}: CodeEditorProps) {
const defaultLang = React.useMemo(() => {
if (!filePath) return languageOverrides.ts;
const fileEnding = filePath?.split('.').pop();
return languageOverrides[fileEnding || ''] || fileEnding;
}, [filePath]);

if (!Editor) {
return <>{Loader ?? null}</>;
}

return (
<React.Suspense fallback={Loader ?? <></>}>
<Editor
path={filePath}
value={fileContent || undefined}
language={language || defaultLang}
height={height || '100%'}
onMount={onMount}
beforeMount={beforeMount}
onChange={onChange}
className={classnames(darkMode, className)}
theme={'vs-dark'}
options={options || DEFAULT_EDITOR_OPTIONS}
loading={Loader}
/>
</React.Suspense>
);
}
3 changes: 3 additions & 0 deletions components/ui/code-editor/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export { CodeEditor } from './code-editor';
export type { CodeEditorProps } from './code-editor';
export { useCodeEditor, CodeEditorProvider } from './code-editor.provider';