Skip to content
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
5 changes: 5 additions & 0 deletions .changeset/four-carrots-leave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@graphiql/plugin-doc-explorer': patch
---

Use an additional `Alt` key for focus doc explorer search input instead of `Cmd/Ctrl+K` because monaco-editor has a built-in shortcut for `Cmd/Ctrl+K`
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@

&:not(:focus-within) [role='combobox'] {
height: 24px;
width: 5ch;
width: 6.5ch;
}

& [role='combobox']:focus {
Expand Down
13 changes: 1 addition & 12 deletions packages/graphiql-plugin-doc-explorer/src/components/search.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,17 +45,6 @@ export const Search: FC = () => {
debouncedGetSearchResults(searchValue);
}, [debouncedGetSearchResults, searchValue]);

useEffect(() => {
function handleKeyDown(event: KeyboardEvent) {
if (event.metaKey && event.key === 'k') {
inputRef.current.focus();
}
}

window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, []);

const navItem = explorerNavStack.at(-1)!;

const onSelect = (def: TypeMatch | FieldMatch | null) => {
Expand Down Expand Up @@ -97,7 +86,7 @@ export const Search: FC = () => {
autoComplete="off"
onChange={event => setSearchValue(event.target.value)}
placeholder={formatShortcutForOS(
KEY_MAP.searchInDocs.key.replace('-', ' '),
formatShortcutForOS(KEY_MAP.searchInDocs.key).replaceAll('-', ' '),
)}
ref={inputRef}
value={searchValue}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,27 @@ import {
useGraphiQL,
pick,
createBoundedUseStore,
GraphiQLPlugin,
DocsFilledIcon,
DocsIcon,
isMacOs,
} from '@graphiql/react';
import { createStore } from 'zustand';
import { getSchemaReference } from './schema-reference';
import { DocExplorer } from './components';

export const DOC_EXPLORER_PLUGIN: GraphiQLPlugin = {
title: 'Documentation Explorer',
icon: function Icon() {
const visiblePlugin = useGraphiQL(state => state.visiblePlugin);
return visiblePlugin === DOC_EXPLORER_PLUGIN ? (
<DocsFilledIcon />
) : (
<DocsIcon />
);
},
content: DocExplorer,
};

export type DocExplorerFieldDef =
| GraphQLField<unknown, unknown>
Expand Down Expand Up @@ -275,6 +293,38 @@ export const DocExplorerStore: FC<{
}
}, [schema, validationErrors]);

useEffect(() => {
function handleKeyDown(event: KeyboardEvent) {
const shouldFocusInput =
// Use an additional `Alt` key instead of `Cmd/Ctrl+K` because monaco-editor has a built-in
// shortcut for `Cmd/Ctrl+K`
event.altKey &&
event[isMacOs ? 'metaKey' : 'ctrlKey'] &&
// Using `event.code` because `event.key` will trigger different character
// in English `˚` and in French `È`
event.code === 'KeyK';
if (!shouldFocusInput) {
return;
}
const button = document.querySelector<HTMLButtonElement>(
'.graphiql-sidebar button[aria-label="Show Documentation Explorer"]',
);
button?.click();
// Execute on next tick when doc explorer is opened and input exists in DOM
requestAnimationFrame(() => {
const el = document.querySelector<HTMLDivElement>(
'.graphiql-doc-explorer-search-input',
);
el?.click();
});
}

window.addEventListener('keydown', handleKeyDown);
return () => {
window.removeEventListener('keydown', handleKeyDown);
};
}, []);

return children as ReactElement;
};

Expand Down
14 changes: 14 additions & 0 deletions packages/graphiql-plugin-doc-explorer/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
export * from './components';

export {
DocExplorerStore,
useDocExplorer,
useDocExplorerActions,
DOC_EXPLORER_PLUGIN,
} from './context';

export type {
DocExplorerFieldDef,
DocExplorerNavStack,
DocExplorerNavStackItem,
} from './context';
34 changes: 0 additions & 34 deletions packages/graphiql-plugin-doc-explorer/src/index.tsx

This file was deleted.

2 changes: 1 addition & 1 deletion packages/graphiql-plugin-doc-explorer/vite.config.mts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export default defineConfig({
minify: false,
sourcemap: true,
lib: {
entry: 'src/index.tsx',
entry: 'src/index.ts',
fileName(_format, entryName) {
const filePath = entryName.replace(/\.svg$/, '');
return `${filePath}.js`;
Expand Down
9 changes: 6 additions & 3 deletions packages/graphiql-react/src/components/response-editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -87,14 +87,16 @@ export const ResponseEditor: FC<ResponseEditorProps> = ({
$model,
position,
) => {
if ($model.uri !== model.uri) {
const sameModel = $model.uri === model.uri;
if (!sameModel) {
return null; // Ignore for other editors
}
const wordAtPosition = $model.getWordAtPosition(position);
if (!wordAtPosition?.word.startsWith('/')) {
return null;
}
if (!ImagePreview.shouldRender(wordAtPosition.word)) {
const shouldRender = ImagePreview.shouldRender(wordAtPosition.word);
if (!shouldRender) {
return null;
}

Expand Down Expand Up @@ -138,8 +140,9 @@ export const ResponseEditor: FC<ResponseEditorProps> = ({
],
};
};
const languageId = model.getLanguageId();
const disposables = [
languages.registerHoverProvider(model.getLanguageId(), { provideHover }),
languages.registerHoverProvider(languageId, { provideHover }),
editor.addAction({ ...KEY_BINDINGS.runQuery, run }),
editor,
model,
Expand Down
8 changes: 4 additions & 4 deletions packages/graphiql-react/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { parse, print } from 'graphql';
import { KeyCode, KeyMod, Uri, languages } from './monaco-editor';
import { EditorSlice } from './stores';

const isMacOs =
export const isMacOs =
typeof navigator !== 'undefined' && navigator.userAgent.includes('Mac');

export function formatShortcutForOS(key: string, replaced = '⌘') {
Expand Down Expand Up @@ -38,7 +38,7 @@ export const KEY_MAP = Object.freeze({
key: 'Ctrl-F',
},
searchInDocs: {
key: 'Ctrl-K',
key: 'Ctrl-Alt-K',
},
});

Expand Down Expand Up @@ -75,7 +75,7 @@ export const DEFAULT_QUERY = `# Welcome to GraphiQL

`;

export const KEY_BINDINGS = Object.freeze({
export const KEY_BINDINGS = {
prettify: {
id: 'graphql-prettify',
label: 'Prettify Editors',
Expand All @@ -100,7 +100,7 @@ export const KEY_BINDINGS = Object.freeze({
contextMenuGroupId: 'graphql',
keybindings: KEY_MAP.copyQuery.keybindings,
},
});
} as const;

export const QUERY_URI = Uri.file('query.graphql');
export const VARIABLE_URI = Uri.file('variable.json');
Expand Down
2 changes: 1 addition & 1 deletion packages/graphiql-react/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ export * from './components';

export type { EditorProps, SchemaReference, AllSlices } from './types';
export type { GraphiQLPlugin } from './stores/plugin';
export { KEY_MAP, formatShortcutForOS } from './constants';
export { KEY_MAP, formatShortcutForOS, isMacOs } from './constants';
15 changes: 8 additions & 7 deletions packages/graphiql-react/src/stores/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,9 @@ export interface PluginSlice {
visiblePlugin: GraphiQLPlugin | null;
/**
* The plugin which is used to display the reference documentation when selecting a type.
* Pass `null` to remove plugin.
*/
referencePlugin?: GraphiQLPlugin;
referencePlugin?: GraphiQLPlugin | null;

/**
* Invoked when the visibility state of any plugin changes.
Expand Down Expand Up @@ -72,16 +73,16 @@ export interface PluginProps

type CreatePluginSlice = StateCreator<AllSlices, [], [], PluginSlice>;

export const createPluginSlice: CreatePluginSlice = (set, get) => ({
export const createPluginSlice: CreatePluginSlice = set => ({
plugins: [],
visiblePlugin: null,
referencePlugin: undefined,
setVisiblePlugin(plugin) {
const { plugins, onTogglePluginVisibility } = get();
const byTitle = typeof plugin === 'string';
const newVisiblePlugin: PluginSlice['visiblePlugin'] =
(plugin && plugins.find(p => (byTitle ? p.title : p) === plugin)) || null;
set(({ visiblePlugin }) => {
set(({ visiblePlugin, plugins, onTogglePluginVisibility }) => {
const byTitle = typeof plugin === 'string';
const newVisiblePlugin: PluginSlice['visiblePlugin'] =
(plugin && plugins.find(p => (byTitle ? p.title : p) === plugin)) ||
null;
if (newVisiblePlugin === visiblePlugin) {
return { visiblePlugin };
}
Expand Down
17 changes: 11 additions & 6 deletions packages/graphiql/src/GraphiQL.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import type {
FC,
ComponentPropsWithoutRef,
} from 'react';
import { useState, useEffect, Children, useRef } from 'react';
import { useState, useEffect, Children, useRef, Fragment } from 'react';
import {
Button,
ButtonGroup,
Expand Down Expand Up @@ -121,17 +121,22 @@ const GraphiQL_: FC<GraphiQLProps> = ({
confirmCloseTab,
className,
};
const hasHistoryPlugin = plugins.includes(HISTORY_PLUGIN);
const HistoryToUse = hasHistoryPlugin ? HistoryStore : Fragment;
const DocExplorerToUse =
referencePlugin === DOC_EXPLORER_PLUGIN ? DocExplorerStore : Fragment;

return (
<GraphiQLProvider
plugins={[referencePlugin, ...plugins]}
plugins={[...(referencePlugin ? [referencePlugin] : []), ...plugins]}
referencePlugin={referencePlugin}
{...props}
>
<HistoryStore maxHistoryLength={maxHistoryLength}>
<DocExplorerStore>
<HistoryToUse {...(hasHistoryPlugin && { maxHistoryLength })}>
<DocExplorerToUse>
<GraphiQLInterface {...interfaceProps}>{children}</GraphiQLInterface>
</DocExplorerStore>
</HistoryStore>
</DocExplorerToUse>
</HistoryToUse>
</GraphiQLProvider>
);
};
Expand Down
8 changes: 4 additions & 4 deletions packages/graphiql/src/ui/short-keys.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ import { FC, Fragment } from 'react';
import { formatShortcutForOS, KEY_MAP } from '@graphiql/react';

const SHORT_KEYS = Object.entries({
'Search in editor': formatShortcutForOS(KEY_MAP.searchInEditor.key),
'Search in documentation': formatShortcutForOS(KEY_MAP.searchInDocs.key),
'Execute query': formatShortcutForOS(KEY_MAP.runQuery.key),
'Prettify editors': KEY_MAP.prettify.key,
'Merge fragments definitions into operation definition':
KEY_MAP.mergeFragments.key,
'Copy query': KEY_MAP.copyQuery.key,
'Re-fetch schema using introspection': KEY_MAP.refetchSchema.key,
'Search in documentation': formatShortcutForOS(KEY_MAP.searchInDocs.key),
'Search in editor': formatShortcutForOS(KEY_MAP.searchInEditor.key),
'Merge fragments definitions into operation definition':
KEY_MAP.mergeFragments.key,
});

export const ShortKeys: FC = () => {
Expand Down
8 changes: 6 additions & 2 deletions packages/graphiql/test/schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -235,9 +235,13 @@ Example query:
}
\`\`\`

And we have a cool logo:
And we have a local image:

![](/resources/logo.svg)
![GraphQL Logo](/resources/logo.svg)

And external image:

![Cat](https://placecats.com/300/200)
`.trim();

const TestType = new GraphQLObjectType({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -439,7 +439,7 @@ describe('MessageProcessor with config', () => {
character: 0,
},
end: {
line: 102 + offset,
line: 106 + offset,
character: 1,
},
});
Expand All @@ -453,11 +453,11 @@ describe('MessageProcessor with config', () => {
// this might break, please adjust if you see a failure here
expect(serializeRange(schemaDefs[0].range)).toEqual({
start: {
line: 104 + offset,
line: 108 + offset,
character: 0,
},
end: {
line: 112 + offset,
line: 116 + offset,
character: 1,
},
});
Expand Down
Loading