Skip to content

Commit

Permalink
feat: restore run op action
Browse files Browse the repository at this point in the history
  • Loading branch information
acao committed Apr 29, 2020
1 parent 85ccd0d commit 8be3e24
Show file tree
Hide file tree
Showing 16 changed files with 116 additions and 36 deletions.
16 changes: 10 additions & 6 deletions packages/graphiql/resources/webpack.config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
const path = require('path');
// const webpack = require('webpack');
// const MonacoEditorWebpackPlugin = require('monaco-editor-webpack-plugin');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
Expand Down Expand Up @@ -47,6 +46,9 @@ const resultConfig = {
react: 'React',
'react-dom': 'ReactDOM',
},
optimization: {
splitChunks: { name: 'vendor' },
},
module: {
rules: [
// for graphql module, which uses .mjs
Expand Down Expand Up @@ -113,9 +115,10 @@ const resultConfig = {
async: isDev,
tsconfig: rootPath('tsconfig.json'),
}),
// new MonacoEditorWebpackPlugin({
// languages: ['json'],
// }),
// TODO: reduces bundle size, but then we lose the JSON grammar
// new webpack.IgnorePlugin({
// contextRegExp: /monaco-editor\/esm\/vs\/language\/css\/$/
// })
],
resolve: {
extensions: ['.mjs', '.js', '.json', '.jsx', '.css', '.ts', '.tsx'],
Expand All @@ -133,7 +136,8 @@ const cssLoaders = [
if (!isDev) {
cssLoaders.push('postcss-loader');
} else {
// resultConfig.plugins.push(new ErrorOverlayPlugin());
// TODO: This worked, but somehow this ended up totally busted
// resultConfig.plugins.push(new ErrorOverlayPlugin());
}

if (process.env.ANALYZE) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React, { useCallback } from 'react';

import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';

import {
Expand All @@ -12,7 +13,7 @@ import EditorWorker from 'worker-loader!monaco-editor/esm/vs/editor/editor.worke
// @ts-ignore
import JSONWorker from 'worker-loader!monaco-editor/esm/vs/language/json/json.worker';
// @ts-ignore
import GraphQLWorker from 'worker-loader!monaco-graphql/esm/graphql.worker';
import GraphQLWorker from 'worker-loader!../../workers/graphql.worker';

// @ts-ignore
window.MonacoEnvironment = {
Expand Down
10 changes: 5 additions & 5 deletions packages/graphiql/src/api/providers/GraphiQLSchemaProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
/* global monaco */

import React, { useCallback } from 'react';
import { GraphQLSchema } from 'graphql';
import { SchemaConfig, Fetcher } from '../../types';

import { buildSchemaFromResponse } from 'graphql-languageservice';

import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';

import {
SchemaAction,
SchemaActionTypes,
Expand Down Expand Up @@ -121,9 +121,9 @@ export function SchemaProvider({
dispatch(schemaRequestedAction());
try {
// @ts-ignore
if (monaco.languages.graphql.getSchema) {
if (monaco.languages.graphql?.api.getSchema) {
// @ts-ignore
const schema: GraphQLSchema = await monaco.languages.graphql.getSchema();
const schema: GraphQLSchema = await monaco.languages.graphql.api.getSchema();
console.log('schema fetched');
// @ts-ignore
dispatch(schemaSucceededAction(buildSchemaFromResponse(schema)));
Expand All @@ -137,7 +137,7 @@ export function SchemaProvider({
React.useEffect(() => {
if (state.config) {
// @ts-ignore
monaco.languages.graphql.graphqlDefaults.setSchemaConfig(state.config);
monaco.languages?.graphql?.graphqlDefaults.setSchemaConfig(state.config);
}
setTimeout(() => {
loadCurrentSchema()
Expand Down
16 changes: 16 additions & 0 deletions packages/graphiql/src/api/providers/GraphiQLSessionProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* global monaco */
import * as React from 'react';
import { Fetcher } from '../../types';

Expand All @@ -16,6 +17,7 @@ import {
} from '../actions/sessionActions';

import { observableToPromise } from '../../utility/observableToPromise';
// import { KeyMod, KeyCode } from 'monaco-editor';

export type SessionReducer = React.Reducer<SessionState, SessionAction>;
export interface SessionHandlers {
Expand Down Expand Up @@ -184,6 +186,20 @@ export function SessionProvider({
],
);

React.useEffect(() => {
if (editorsState.editors.operation) {
editorsState.editors.operation.editor.addAction({
id: 'run-command',
label: 'Run Operation',
// eslint-disable-next-line no-bitwise
keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.Enter],
run: async () => {
return executeOperation();
},
});
}
}, [editorsState.editors.operation, executeOperation]);

return (
<SessionContext.Provider
value={{
Expand Down
12 changes: 7 additions & 5 deletions packages/graphiql/src/components/QueryEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,9 @@ type QueryEditorProps = {
readOnly?: boolean;
onHintInformationRender: (elem: HTMLDivElement) => void;
onClickReference?: (reference: GraphQLType) => void;
onCopyQuery?: () => void;
onPrettifyQuery?: () => void;
onMergeQuery?: () => void;
onRunQuery?: () => void;
editorTheme?: string;
operation?: string;
editorOptions?: monaco.editor.IStandaloneEditorConstructionOptions;
};

/**
Expand Down Expand Up @@ -64,6 +61,7 @@ export function QueryEditor(props: QueryEditorProps) {
value: session?.operation?.text ?? '',
language: 'graphqlDev',
automaticLayout: true,
...props.editorOptions,
},
));
if (!editor) {
Expand All @@ -74,11 +72,15 @@ export function QueryEditor(props: QueryEditorProps) {
if (!ignoreChangeEvent) {
cachedValueRef.current = editor.getValue();
session.changeOperation(cachedValueRef.current);
props.onEdit && props.onEdit(cachedValueRef.current);
}
});

// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

/**
* Handle incoming changes via props (quasi-controlled component?)
*/
React.useEffect(() => {
setIgnoreChangeEvent(true);
const editor = editorRef.current;
Expand Down
2 changes: 0 additions & 2 deletions packages/graphiql/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@
// eslint-disable-next-line spaced-comment
/// <reference path='../../../packages/monaco-graphql/src/typings/monaco.d.ts'/>

import 'regenerator-runtime/runtime';

import { GraphiQL } from './components/GraphiQL';

export { GraphiQL };
Expand Down
30 changes: 30 additions & 0 deletions packages/graphiql/src/workers/graphql.worker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/**
* Copyright (c) 2020 GraphQL Contributors.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

import type { worker as WorkerNamespace } from 'monaco-editor';
import 'regenerator-runtime/runtime';

// @ts-ignore
import * as worker from 'monaco-editor/esm/vs/editor/editor.worker';

import { GraphQLWorker } from 'monaco-graphql/esm/GraphQLWorker';

self.onmessage = () => {
try {
// ignore the first message
worker.initialize(
(
ctx: WorkerNamespace.IWorkerContext,
createData: monaco.languages.graphql.ICreateData,
) => {
return new GraphQLWorker(ctx, createData);
},
);
} catch (err) {
throw err;
}
};
14 changes: 11 additions & 3 deletions packages/monaco-graphql/src/GraphQLWorker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import {
toCompletion,
} from './utils';

import { GraphQLSchema } from 'graphql';
import type { GraphQLSchema, DocumentNode } from 'graphql';

export type MonacoCompletionItem = monaco.languages.CompletionItem & {
isDeprecated?: boolean;
Expand Down Expand Up @@ -55,12 +55,15 @@ export class GraphQLWorker {
this._languageService = new LanguageService(serviceConfig);
this._formattingOptions = createData.formattingOptions;
}

async getSchemaResponse(_uri?: string): Promise<SchemaResponse> {
return this._languageService.getSchemaResponse();
}

async loadSchema(_uri?: string): Promise<GraphQLSchema> {
return this._languageService.getSchema();
}

async doValidation(uri: string): Promise<editor.IMarkerData[]> {
const document = this._getTextDocument(uri);
const graphqlDiagnostics = await this._languageService.getDiagnostics(
Expand Down Expand Up @@ -112,14 +115,15 @@ export class GraphQLWorker {
range: toMonacoRange(
getRange(
{
column: graphQLPosition.character + 1,
line: graphQLPosition.line + 1,
column: graphQLPosition.character,
line: graphQLPosition.line,
},
document,
),
),
};
}

async doFormat(text: string): Promise<string> {
const prettierStandalone = await import('prettier/standalone');
const prettierGraphqlParser = await import('prettier/parser-graphql');
Expand All @@ -131,6 +135,10 @@ export class GraphQLWorker {
});
}

async doParse(text: string): Promise<DocumentNode> {
return this._languageService.parse(text);
}

private _getTextDocument(_uri: string): string {
const models = this._ctx.getMirrorModels();
if (models.length > 0) {
Expand Down
19 changes: 19 additions & 0 deletions packages/monaco-graphql/src/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import * as languageFeatures from './languageFeatures';
import type { DocumentNode } from 'graphql';
import { SchemaResponse } from 'graphql-languageservice';

export class MonacoGraphQLApi {
private worker: languageFeatures.WorkerAccessor;
constructor({ accessor }: { accessor: languageFeatures.WorkerAccessor }) {
this.worker = accessor;
}

async getSchema(): Promise<SchemaResponse> {
const langWorker = await this.worker();
return langWorker.getSchemaResponse();
}
async parse(graphqlString: string): Promise<DocumentNode> {
const langWorker = await this.worker();
return langWorker.doParse(graphqlString);
}
}
1 change: 1 addition & 0 deletions packages/monaco-graphql/src/graphql.worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
*/

import type { worker as WorkerNamespace } from 'monaco-editor';

// @ts-ignore
import * as worker from 'monaco-editor/esm/vs/editor/editor.worker';

Expand Down
19 changes: 6 additions & 13 deletions packages/monaco-graphql/src/graphqlMode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,16 @@
* LICENSE file in the root directory of this source tree.
*/

import { Uri, IDisposable } from 'monaco-editor';

import IRichLanguageConfiguration = monaco.languages.LanguageConfiguration;

import { WorkerManager } from './workerManager';
import { GraphQLWorker } from './GraphQLWorker';
import { monarchLanguage } from './monaco.contribution';
import { LanguageServiceDefaultsImpl } from './defaults';
import * as languageFeatures from './languageFeatures';
import { Uri, IDisposable } from 'monaco-editor';
import { MonacoGraphQLApi } from './api';

export function setupMode(defaults: LanguageServiceDefaultsImpl): IDisposable {
const disposables: IDisposable[] = [];
Expand All @@ -21,28 +23,19 @@ export function setupMode(defaults: LanguageServiceDefaultsImpl): IDisposable {
const { languageId } = defaults;
// client.getLanguageServiceWorker()
disposables.push(client);
let uriList: Uri[] = [];
const worker: languageFeatures.WorkerAccessor = (
...uris: Uri[]
): Promise<GraphQLWorker> => {
try {
uriList = uris;
return client.getLanguageServiceWorker(...uris);
} catch (err) {
throw Error('Error fetching graphql language service worker');
}
};

const getSchema = async () => {
try {
const langWorker = await worker(...uriList);
return langWorker.getSchemaResponse();
} catch (err) {
console.log(err);
}
};
// @ts-ignore
monaco.languages.graphql.getSchema = getSchema;
monaco.languages.graphql.api = new MonacoGraphQLApi({ accessor: worker });
// @ts-ignore
console.log(monaco.languages.graphql.api.getSchema);

monaco.languages.setLanguageConfiguration(languageId, richLanguageConfig);
monaco.languages.setMonarchTokensProvider(languageId, monarchLanguage);
Expand Down
2 changes: 1 addition & 1 deletion packages/monaco-graphql/src/monaco.contribution.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* global monaco */
/**
* Copyright (c) 2020 GraphQL Contributors.
*
Expand All @@ -17,7 +18,6 @@ import {
formattingDefaults,
modeConfigurationDefault,
} from './defaults';

import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';

// @ts-ignore
Expand Down
5 changes: 5 additions & 0 deletions packages/monaco-graphql/src/typings/monaco.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,12 @@ declare module monaco.languages.graphql {
SchemaLoader,
SchemaConfig as SchemaConfiguration,
} from 'graphql-languageservice';

import type { GraphQLSchema } from 'graphql';
import type { Options as PrettierConfig } from 'prettier';

import { MonacoGraphQLApi } from '../api';

export interface IDisposable {
dispose(): void;
}
Expand Down Expand Up @@ -106,6 +109,8 @@ declare module monaco.languages.graphql {
setModeConfiguration(modeConfiguration: ModeConfiguration): void;
}

export interface api extends MonacoGraphQLApi {}

// export const graphqlDefaults: LanguageServiceDefaults;
}

Expand Down
1 change: 1 addition & 0 deletions packages/monaco-graphql/src/workerManager.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* global monaco */
/**
* Copyright (c) 2020 GraphQL Contributors.
*
Expand Down
1 change: 1 addition & 0 deletions packages/monaco-graphql/tsconfig.esm.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"path": "../graphql-languageservice"
}
],
"include": ["src"],
"exclude": [
"**/__tests__/**",
"**/*.spec.*",
Expand Down
1 change: 1 addition & 0 deletions packages/monaco-graphql/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,6 @@
"path": "../graphql-languageservice"
}
],
"include": ["./src"],
"exclude": ["**/__tests__/**", "**/*.spec.*", "dist", "esm", "node_modules"]
}

0 comments on commit 8be3e24

Please sign in to comment.