Skip to content

.d.ts support on manaco editor (Auto types fetching support) #150

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

Merged
merged 3 commits into from
Apr 18, 2022
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
58 changes: 1 addition & 57 deletions editor-packages/editor-services-esbuild/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
import { Monaco } from "@monaco-editor/react";
import { nanoid } from "nanoid";
import { build, initialize, Loader } from "esbuild-wasm";
import { fetchPlugin } from "./fetch.plugin";
import { unpkgPathPlugin } from "./unpkg-path.plugin";

declare const window: {
monaco: Monaco;
};
import { loadTypes } from "@code-editor/estypes-resolver";

let serviceLoaded: boolean | null = null;

Expand Down Expand Up @@ -66,55 +62,3 @@ export const normalizeCss = (data: string) => {
};

export default bundler;

let typesWorker;

const loadTypes = (types) => {
const disposables: any = [];
const monaco = window && window.monaco;

const dependencies = types.map((e) => ({ name: e, version: "latest" })) || [];

if (!typesWorker) {
typesWorker = new Worker(
new URL("./workers/fetch-types.worker.js", import.meta.url)
);
}

dependencies.forEach((dep) => {
typesWorker.postMessage({
name: dep.name,
version: dep.version,
});
});

typesWorker.addEventListener("message", (event) => {
// name,
// version,
// typings: result,
const key = `node_modules/${event.data.name}/index.d.ts`;
const source = event.data.typings[key];

// const path = `${MONACO_LIB_PREFIX}${event.data.name}`;
const libUri = `file:///node_modules/@types/${event.data.name}/index.d.ts`;

disposables.push(
monaco.languages.typescript.javascriptDefaults.addExtraLib(source, libUri)
);
disposables.push(
monaco.languages.typescript.typescriptDefaults.addExtraLib(source, libUri)
);

// When resolving definitions and references, the editor will try to use created models.
// Creating a model for the library allows "peek definition/references" commands to work with the library.
});

return {
dispose() {
disposables.forEach((d) => d.dispose());
if (typesWorker) {
typesWorker.terminate();
}
},
};
};
57 changes: 57 additions & 0 deletions editor-packages/editor-services-estypes-resolver/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { Monaco } from "@monaco-editor/react";

declare const window: {
monaco: Monaco;
};

let typesWorker;

export function loadTypes(types: string[]) {
const disposables: any = [];
const monaco = window && window.monaco;

const dependencies = types.map((e) => ({ name: e, version: "latest" })) || [];

if (!typesWorker) {
typesWorker = new Worker(
new URL("./workers/fetch-types.worker.js", import.meta.url)
);
}

dependencies.forEach((dep) => {
typesWorker.postMessage({
name: dep.name,
version: dep.version,
});
});

typesWorker.addEventListener("message", (event) => {
// name,
// version,
// typings: result,
const key = `node_modules/${event.data.name}/index.d.ts`;
const source = event.data.typings[key];

// const path = `${MONACO_LIB_PREFIX}${event.data.name}`;
const libUri = `file:///node_modules/@types/${event.data.name}/index.d.ts`;

disposables.push(
monaco.languages.typescript.javascriptDefaults.addExtraLib(source, libUri)
);
disposables.push(
monaco.languages.typescript.typescriptDefaults.addExtraLib(source, libUri)
);

// When resolving definitions and references, the editor will try to use created models.
// Creating a model for the library allows "peek definition/references" commands to work with the library.
});

return {
dispose() {
disposables.forEach((d) => d.dispose());
if (typesWorker) {
typesWorker.terminate();
}
},
};
}
5 changes: 5 additions & 0 deletions editor-packages/editor-services-estypes-resolver/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"name": "@code-editor/estypes-resolver",
"version": "0.0.0",
"private": false
}
4 changes: 2 additions & 2 deletions editor/components/code-editor/code-editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ export function CodeEditor({
onChange={(v: string, e) => {
onChange?.(filekey, v, e);
}}
defaultLanguage={file.language}
defaultValue={file.raw}
language={file.language}
value={file.raw}
/>
</>
);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { loadTypes } from "@code-editor/estypes-resolver";

const react_preset_dependencies = [
"react",
"react-dom",
"prop-types",
"react-router",
"react-router-dom",
"styled-components",
"@emotion/styled",
"@emotion/react",
"axios",
];

/**
* load the preset dependencies on initial boot (e.g. react)
*/
export function registerPresetTypes() {
// load the react presets
loadTypes(react_preset_dependencies);
}
2 changes: 2 additions & 0 deletions editor/components/code-editor/monaco-utils/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ import * as monaco from "monaco-editor";
import { Monaco, OnMount } from "@monaco-editor/react";
import { registerDocumentPrettier } from "@code-editor/prettier-services";
import { registerJsxHighlighter } from "@code-editor/jsx-syntax-highlight-services";
import { registerPresetTypes } from "./register-preset-types";

type CompilerOptions = monaco.languages.typescript.CompilerOptions;

export const initEditor: OnMount = (editor, monaco) => {
registerJsxHighlighter(editor, monaco);
registerDocumentPrettier(editor, monaco);
registerPresetTypes();
};

export const initMonaco = (monaco: Monaco) => {
Expand Down
48 changes: 29 additions & 19 deletions editor/components/code-editor/monaco.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,16 @@
import React, { useRef, useEffect } from "react";
import Editor, {
useMonaco,
Monaco,
OnMount,
OnChange,
} from "@monaco-editor/react";
import React, { useRef } from "react";
import Editor, { OnMount, OnChange } from "@monaco-editor/react";
import * as monaco from "monaco-editor/esm/vs/editor/editor.api";
import { MonacoEmptyMock } from "./monaco-mock-empty";
import { register } from "./monaco-utils";
import { __dangerous__lastFormattedValue__global } from "@code-editor/prettier-services";
import { debounce } from "utils/debounce";

type ICodeEditor = monaco.editor.IStandaloneCodeEditor;

export interface MonacoEditorProps {
defaultValue?: string;
defaultLanguage?: string;
value?: string;
language?: string;
onChange?: OnChange;
width?: number | string;
height?: number | string;
Expand All @@ -23,16 +19,13 @@ export interface MonacoEditorProps {

export function MonacoEditor(props: MonacoEditorProps) {
const instance = useRef<{ editor: ICodeEditor; format: any } | null>(null);
const activeModel = useRef<any>();

const onMount: OnMount = (editor, monaco) => {
const format = editor.getAction("editor.action.formatDocument");
const rename = editor.getAction("editor.action.rename");

instance.current = { editor, format };

activeModel.current = editor.getModel();

register.initEditor(editor, monaco);

editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, function () {
Expand All @@ -41,6 +34,7 @@ export function MonacoEditor(props: MonacoEditorProps) {

// disabled. todo: find a way to format on new line, but also with adding new line.
// editor.addCommand(monaco.KeyCode.Enter, function () {
// // add new line via script, then run format
// format.run();
// });

Expand All @@ -50,9 +44,9 @@ export function MonacoEditor(props: MonacoEditorProps) {
rename.run();
});

editor.onDidChangeModelContent((e) => {
/* add here */
});
editor.onDidChangeModelContent(() =>
debounce(() => editor.saveViewState(), 200)
);
};

return (
Expand All @@ -61,11 +55,10 @@ export function MonacoEditor(props: MonacoEditorProps) {
onMount={onMount}
width={props.width}
height={props.height}
defaultLanguage={
pollyfill_language(props.defaultLanguage) ?? "typescript"
}
language={pollyfill_language(props.language) ?? "typescript"}
path={"app." + lang2ext(props.language)}
loading={<MonacoEmptyMock l={5} />}
defaultValue={props.defaultValue ?? "// no content"}
value={props.value ?? "// no content"}
theme="vs-dark"
onChange={(...v) => {
if (v[0] === __dangerous__lastFormattedValue__global) {
Expand All @@ -84,6 +77,23 @@ export function MonacoEditor(props: MonacoEditorProps) {
);
}

const lang2ext = (lang: string) => {
switch (lang) {
case "typescript":
return "ts";
case "javascript":
return "js";
case "tsx":
return "tsx";
case "jsx":
return "jsx";
case "dart":
return "dart";
default:
return lang;
}
};

const pollyfill_language = (lang: string) => {
switch (lang) {
case "tsx":
Expand Down
4 changes: 2 additions & 2 deletions editor/pages/figma/inspect-frame.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ export default function InspectAutolayout() {
<MonacoEditor
key={figma?.id}
height="100vh"
defaultLanguage="json"
defaultValue={JSON.stringify(inspectionTarget, null, 2)}
language="json"
value={JSON.stringify(inspectionTarget, null, 2)}
/>
</>
);
Expand Down
4 changes: 2 additions & 2 deletions editor/pages/figma/inspect-raw.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ export default function InspectRaw() {
<MonacoEditor
key={figma.id}
height="100vh"
defaultLanguage="json"
defaultValue={JSON.stringify(figma, null, 2)}
language="json"
value={JSON.stringify(figma, null, 2)}
/>
</>
);
Expand Down
5 changes: 3 additions & 2 deletions editor/scaffolds/code/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -193,10 +193,11 @@ export function CodeSegment() {
files={
code
? {
"index.tsx": {
// TODO: make this to match framework
"App.tsx": {
raw: code.raw,
language: framework_config.language,
name: "index.tsx",
name: "App.tsx",
},
}
: {
Expand Down