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

add useResponseEditor hook to @graphiql/react #2411

Merged
merged 9 commits into from
May 19, 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
6 changes: 6 additions & 0 deletions .changeset/olive-seals-shake.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'graphiql': minor
'@graphiql/react': minor
---

Move the logic of the result viewer from the `graphiql` package into a hook `useResponseEditor` provided by `@graphiql/react`
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { importCodeMirror } from '../importCodeMirror';
import { importCodeMirror } from '../common';

describe('importCodeMirror', () => {
it('should dynamically load codemirror module', async () => {
Expand Down
88 changes: 88 additions & 0 deletions packages/graphiql-react/src/editor/components/image-preview.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import type { Token } from 'codemirror';
import { useEffect, useRef, useState } from 'react';

type ImagePreviewProps = { token: Token };

type Dimensions = {
width: number | null;
height: number | null;
};

export function ImagePreview(props: ImagePreviewProps) {
const [dimensions, setDimensions] = useState<Dimensions>({
width: null,
height: null,
});
const [mime, setMime] = useState<string | null>(null);

const ref = useRef<HTMLImageElement>(null);

const src = tokenToURL(props.token)?.href;

useEffect(() => {
if (!ref.current) {
return;
}
if (!src) {
setDimensions({ width: null, height: null });
setMime(null);
return;
}

fetch(src, { method: 'HEAD' })
.then(response => {
setMime(response.headers.get('Content-Type'));
})
.catch(() => {
setMime(null);
});
}, [src]);

const dims =
dimensions.width !== null && dimensions.height !== null ? (
<div>
{dimensions.width}x{dimensions.height}
{mime !== null ? ' ' + mime : null}
</div>
) : null;

return (
<div>
<img
onLoad={() => {
setDimensions({
width: ref.current?.naturalWidth ?? null,
height: ref.current?.naturalHeight ?? null,
});
}}
ref={ref}
src={src}
/>
{dims}
</div>
);
}

ImagePreview.shouldRender = function shouldRender(token: Token) {
const url = tokenToURL(token);
return url ? isImageURL(url) : false;
};

function tokenToURL(token: Token) {
if (token.type !== 'string') {
return;
}

const value = token.string.slice(1).slice(0, -1).trim();

try {
const location = window.location;
return new URL(value, location.protocol + '//' + location.host);
} catch (err) {
return;
}
}

function isImageURL(url: URL) {
return /(bmp|gif|jpeg|jpg|png|svg)$/.test(url.pathname);
}
3 changes: 3 additions & 0 deletions packages/graphiql-react/src/editor/components/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { ImagePreview } from './image-preview';

export { ImagePreview };
9 changes: 9 additions & 0 deletions packages/graphiql-react/src/editor/context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,22 @@ import { CodeMirrorEditor } from './types';
export type EditorContextType = {
headerEditor: CodeMirrorEditor | null;
queryEditor: CodeMirrorEditor | null;
responseEditor: CodeMirrorEditor | null;
variableEditor: CodeMirrorEditor | null;
setHeaderEditor(newEditor: CodeMirrorEditor): void;
setQueryEditor(newEditor: CodeMirrorEditor): void;
setResponseEditor(newEditor: CodeMirrorEditor): void;
setVariableEditor(newEditor: CodeMirrorEditor): void;
};

export const EditorContext = createContext<EditorContextType>({
headerEditor: null,
queryEditor: null,
responseEditor: null,
variableEditor: null,
setHeaderEditor() {},
setQueryEditor() {},
setResponseEditor() {},
setVariableEditor() {},
});

Expand All @@ -28,6 +32,9 @@ export function EditorContextProvider(props: {
null,
);
const [queryEditor, setQueryEditor] = useState<CodeMirrorEditor | null>(null);
const [responseEditor, setResponseEditor] = useState<CodeMirrorEditor | null>(
null,
);
const [variableEditor, setVariableEditor] = useState<CodeMirrorEditor | null>(
null,
);
Expand All @@ -36,9 +43,11 @@ export function EditorContextProvider(props: {
value={{
headerEditor,
queryEditor,
responseEditor,
variableEditor,
setHeaderEditor,
setQueryEditor,
setResponseEditor,
setVariableEditor,
}}>
{props.children}
Expand Down
10 changes: 10 additions & 0 deletions packages/graphiql-react/src/editor/index.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,36 @@
import { onHasCompletion } from './completion';
import { ImagePreview } from './components';
import { EditorContext, EditorContextProvider } from './context';
import { useHeaderEditor } from './header-editor';
import { useQueryEditor } from './query-editor';
import { useResponseEditor } from './response-editor';
import { useVariableEditor } from './variable-editor';

import type { EditorContextType } from './context';
import type { UseHeaderEditorArgs } from './header-editor';
import type { UseQueryEditorArgs } from './query-editor';
import type {
ResponseTooltipType,
UseResponseEditorArgs,
} from './response-editor';
import type { UseVariableEditorArgs } from './variable-editor';

export {
onHasCompletion,
ImagePreview,
EditorContext,
EditorContextProvider,
useHeaderEditor,
useQueryEditor,
useResponseEditor,
useVariableEditor,
};

export type {
EditorContextType,
ResponseTooltipType,
UseHeaderEditorArgs,
UseQueryEditorArgs,
UseResponseEditorArgs,
UseVariableEditorArgs,
};
123 changes: 123 additions & 0 deletions packages/graphiql-react/src/editor/response-editor.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import type { Position, Token } from 'codemirror';
import { ComponentType, useContext, useEffect, useRef } from 'react';
import ReactDOM from 'react-dom';

import { commonKeys, importCodeMirror } from './common';
import { ImagePreview } from './components';
import { EditorContext } from './context';
import { useResizeEditor, useSynchronizeValue } from './hooks';
import { CodeMirrorEditor } from './types';

export type ResponseTooltipType = ComponentType<{ pos: Position }>;

export type UseResponseEditorArgs = {
ResponseTooltip?: ResponseTooltipType;
editorTheme?: string;
value?: string;
};

export function useResponseEditor({
ResponseTooltip,
editorTheme = 'graphiql',
value,
}: UseResponseEditorArgs = {}) {
const context = useContext(EditorContext);
const ref = useRef<HTMLDivElement>(null);

const responseTooltipRef = useRef<ResponseTooltipType | undefined>(
ResponseTooltip,
);
useEffect(() => {
responseTooltipRef.current = ResponseTooltip;
}, [ResponseTooltip]);

if (!context) {
throw new Error(
'Tried to call the `useResponseEditor` hook without the necessary context. Make sure that the `EditorContextProvider` from `@graphiql/react` is rendered higher in the tree.',
);
}

const { responseEditor, setResponseEditor } = context;

useEffect(() => {
let isActive = true;
importCodeMirror(
[
import('codemirror/addon/fold/foldgutter'),
import('codemirror/addon/fold/brace-fold'),
import('codemirror/addon/dialog/dialog'),
import('codemirror/addon/search/search'),
import('codemirror/addon/search/searchcursor'),
import('codemirror/addon/search/jump-to-line'),
// @ts-expect-error
import('codemirror/keymap/sublime'),
import('codemirror-graphql/esm/results/mode'),
import('codemirror-graphql/esm/utils/info-addon'),
],
{ useCommonAddons: false },
).then(CodeMirror => {
// Don't continue if the effect has already been cleaned up
if (!isActive) {
return;
}

// Handle image tooltips and custom tooltips
const tooltipDiv = document.createElement('div');
CodeMirror.registerHelper(
'info',
'graphql-results',
(token: Token, _options: any, _cm: CodeMirrorEditor, pos: Position) => {
const infoElements: JSX.Element[] = [];

const ResponseTooltipComponent = responseTooltipRef.current;
if (ResponseTooltipComponent) {
infoElements.push(<ResponseTooltipComponent pos={pos} />);
}

if (ImagePreview.shouldRender(token)) {
infoElements.push(
<ImagePreview key="image-preview" token={token} />,
);
}

if (!infoElements.length) {
ReactDOM.unmountComponentAtNode(tooltipDiv);
return null;
}
ReactDOM.render(infoElements, tooltipDiv);
return tooltipDiv;
},
);

const container = ref.current;
if (!container) {
return;
}

const newEditor = CodeMirror(container, {
lineWrapping: true,
readOnly: true,
theme: editorTheme,
mode: 'graphql-results',
keyMap: 'sublime',
foldGutter: true,
gutters: ['CodeMirror-foldgutter'],
// @ts-expect-error
info: true,
extraKeys: commonKeys,
});

setResponseEditor(newEditor);
});

return () => {
isActive = false;
};
}, [editorTheme, setResponseEditor]);

useSynchronizeValue(responseEditor, value);

useResizeEditor(responseEditor, ref);

return ref;
}
8 changes: 8 additions & 0 deletions packages/graphiql-react/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import {
EditorContext,
EditorContextProvider,
ImagePreview,
onHasCompletion,
useHeaderEditor,
useQueryEditor,
useResponseEditor,
useVariableEditor,
} from './editor';
import {
Expand All @@ -14,8 +16,10 @@ import {

import type {
EditorContextType,
ResponseTooltipType,
UseHeaderEditorArgs,
UseQueryEditorArgs,
UseResponseEditorArgs,
UseVariableEditorArgs,
} from './editor';
import type {
Expand All @@ -29,9 +33,11 @@ export {
// editor
EditorContext,
EditorContextProvider,
ImagePreview,
onHasCompletion,
useHeaderEditor,
useQueryEditor,
useResponseEditor,
useVariableEditor,
// explorer
ExplorerContext,
Expand All @@ -42,8 +48,10 @@ export {
export type {
// editor
EditorContextType,
ResponseTooltipType,
UseHeaderEditorArgs,
UseQueryEditorArgs,
UseResponseEditorArgs,
UseVariableEditorArgs,
// explorer
ExplorerContextType,
Expand Down
7 changes: 7 additions & 0 deletions packages/graphiql/__mocks__/@graphiql/react.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
useExplorerNavStack,
useHeaderEditor as _useHeaderEditor,
useQueryEditor as _useQueryEditor,
useResponseEditor as _useResponseEditor,
useVariableEditor as _useVariableEditor,
} from '@graphiql/react';
import type {
Expand Down Expand Up @@ -139,6 +140,12 @@ export const useQueryEditor: typeof _useQueryEditor = function useQueryEditor({
return useMockedEditor('query', value, onEdit);
};

export const useResponseEditor: typeof _useResponseEditor = function useResponseEditor({
value,
}) {
return useMockedEditor('query', value);
};

export const useVariableEditor: typeof _useVariableEditor = function useVariableEditor({
onEdit,
value,
Expand Down
7 changes: 2 additions & 5 deletions packages/graphiql/cypress/integration/init.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,8 @@ describe('GraphiQL On Initialization', () => {
it('Shows the expected error when the schema is invalid', () => {
cy.visit(`/?bad=true`);
cy.wait(200);
cy.window().then(w => {
// @ts-ignore
const value = w.g.resultComponent.viewer.getValue();
// this message changes between graphql 15 & 16
expect(value).to.contain('Names must');
cy.get('section#graphiql-result-viewer').should(element => {
expect(element.get(0).innerText).to.contain('Names must');
});
});
});
Loading