Skip to content

Commit

Permalink
aa
Browse files Browse the repository at this point in the history
  • Loading branch information
dimaMachina committed Aug 15, 2024
1 parent c966fa1 commit 7e452e7
Show file tree
Hide file tree
Showing 6 changed files with 68 additions and 12 deletions.
6 changes: 6 additions & 0 deletions .changeset/add-on-prettify-callback.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@graphiql/react": minor
"graphiql": minor
---

Add support for `onPrettifyQuery` callback to enable customised query formatting
19 changes: 15 additions & 4 deletions packages/graphiql-react/src/editor/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,14 +204,23 @@ export function useMergeQuery({ caller }: UseMergeQueryArgs = {}) {
}, [queryEditor, schema]);
}

type UsePrettifyEditorsArgs = {
export type UsePrettifyEditorsArgs = {
/**
* This is only meant to be used internally in `@graphiql/react`.
*/
caller?: Function;
/**
* Invoked when the prettify callback is invoked
* @param query The current value of the query editor.
* @returns {string} The formatted query
*/
onPrettifyQuery?: (query: string) => string;
};

export function usePrettifyEditors({ caller }: UsePrettifyEditorsArgs = {}) {
export function usePrettifyEditors({
caller,
onPrettifyQuery,
}: UsePrettifyEditorsArgs = {}) {
const { queryEditor, headerEditor, variableEditor } = useEditorContext({
nonNull: true,
caller: caller || usePrettifyEditors,
Expand Down Expand Up @@ -252,13 +261,15 @@ export function usePrettifyEditors({ caller }: UsePrettifyEditorsArgs = {}) {

if (queryEditor) {
const editorContent = queryEditor.getValue();
const prettifiedEditorContent = print(parse(editorContent));
const prettifiedEditorContent = onPrettifyQuery
? onPrettifyQuery(editorContent)
: print(parse(editorContent));

if (prettifiedEditorContent !== editorContent) {
queryEditor.setValue(prettifiedEditorContent);
}
}
}, [queryEditor, variableEditor, headerEditor]);
}, [queryEditor, variableEditor, headerEditor, onPrettifyQuery]);
}

export type UseAutoCompleteLeafsArgs = {
Expand Down
7 changes: 5 additions & 2 deletions packages/graphiql-react/src/editor/query-editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import {
useCompletion,
useCopyQuery,
UseCopyQueryArgs,
UsePrettifyEditorsArgs,
useKeyMap,
useMergeQuery,
usePrettifyEditors,
Expand All @@ -52,7 +53,8 @@ import {
import { normalizeWhitespace } from './whitespace';

export type UseQueryEditorArgs = WriteableEditorProps &
Pick<UseCopyQueryArgs, 'onCopyQuery'> & {
Pick<UseCopyQueryArgs, 'onCopyQuery'> &
Pick<UsePrettifyEditorsArgs, 'onPrettifyQuery'> & {
/**
* Invoked when a reference to the GraphQL schema (type or field) is clicked
* as part of the editor or one of its tooltips.
Expand All @@ -74,6 +76,7 @@ export function useQueryEditor(
onClickReference,
onCopyQuery,
onEdit,
onPrettifyQuery,
readOnly = false,
}: UseQueryEditorArgs = {},
caller?: Function,
Expand Down Expand Up @@ -101,7 +104,7 @@ export function useQueryEditor(
const plugin = usePluginContext();
const copy = useCopyQuery({ caller: caller || useQueryEditor, onCopyQuery });
const merge = useMergeQuery({ caller: caller || useQueryEditor });
const prettify = usePrettifyEditors({ caller: caller || useQueryEditor });
const prettify = usePrettifyEditors({ caller: caller || useQueryEditor, onPrettifyQuery });
const ref = useRef<HTMLDivElement>(null);
const codeMirrorRef = useRef<CodeMirrorType>();

Expand Down
23 changes: 22 additions & 1 deletion packages/graphiql/cypress/e2e/prettify.cy.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { version } from 'graphql';

let describeOrSkip = describe.skip;

// hard to account for the extra \n between 15/16 so these only run for 16 for now
if (version.includes('16')) {
if (parseInt(version, 10) > 15) {
describeOrSkip = describe;
}

Expand All @@ -25,6 +26,26 @@ const brokenQuery = 'longDescriptionType {id}}';
const brokenVariables = '"a": 1}';

describeOrSkip('GraphiQL Prettify', () => {
describe('onPrettifyQuery', () => {
const rawQuery = '{ test\n\nid }';
const resultQuery = '{ test id }';

it('should work while click on prettify button', () => {
cy.visit(`/?query=${rawQuery}&onPrettifyQuery=true`);
cy.clickPrettify();
cy.assertHasValues({ query: resultQuery });
});

it('should work while click on key map short cut', () => {
cy.visit(`/?query=${rawQuery}&onPrettifyQuery=true`);
cy.get('.graphiql-query-editor textarea').type('{shift}{ctrl}P', {
force: true,
});
cy.get('.graphiql-query-editor textarea').type('{esc}');
cy.assertHasValues({ query: resultQuery });
});
});

it('Regular prettification', () => {
cy.visitWithOp({ query: uglyQuery, variablesString: uglyVariables });

Expand Down
6 changes: 6 additions & 0 deletions packages/graphiql/resources/renderExample.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ function confirmCloseTab(index) {
return confirm(`Are you sure you want to close tab with index ${index}?`);
}

function onPrettifyQuery(query) {
return query.replaceAll(/([ \n])+/g, ' ');
}

function updateURL() {
const newSearch = Object.entries(parameters)
.filter(([_key, value]) => value)
Expand Down Expand Up @@ -93,6 +97,8 @@ root.render(
inputValueDeprecation: !graphqlVersion.includes('15.5'),
confirmCloseTab:
parameters.confirmCloseTab === 'true' ? confirmCloseTab : undefined,
onPrettifyQuery:
parameters.onPrettifyQuery === 'true' ? onPrettifyQuery : undefined,
onTabChange,
forcedTheme: parameters.forcedTheme,
defaultQuery: parameters.defaultQuery,
Expand Down
19 changes: 14 additions & 5 deletions packages/graphiql/src/components/GraphiQL.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ type AddSuffix<Obj extends Record<string, any>, Suffix extends string> = {

export type GraphiQLInterfaceProps = WriteableEditorProps &
AddSuffix<Pick<UseQueryEditorArgs, 'onEdit'>, 'Query'> &
Pick<UseQueryEditorArgs, 'onCopyQuery'> &
Pick<UseQueryEditorArgs, 'onCopyQuery' | 'onPrettifyQuery'> &
AddSuffix<Pick<UseVariableEditorArgs, 'onEdit'>, 'Variables'> &
AddSuffix<Pick<UseHeaderEditorArgs, 'onEdit'>, 'Headers'> &
Pick<UseResponseEditorArgs, 'responseTooltip'> & {
Expand Down Expand Up @@ -328,8 +328,13 @@ export function GraphiQLInterface(props: GraphiQLInterfaceProps) {

const {
logo = <GraphiQL.Logo />,
// @ts-expect-error -- Prop exists but hidden for users
toolbar = <GraphiQL.Toolbar onCopyQuery={props.onCopyQuery} />,
toolbar = (
<GraphiQL.Toolbar
// @ts-expect-error -- Prop exists but hidden for users
onCopyQuery={props.onCopyQuery}
onPrettifyQuery={props.onPrettifyQuery}
/>
),
footer,
} = useMemo(
() =>
Expand All @@ -346,6 +351,7 @@ export function GraphiQLInterface(props: GraphiQLInterfaceProps) {
// @ts-expect-error -- fix type error
acc.toolbar = cloneElement(curr, {
onCopyQuery: props.onCopyQuery,
onPrettifyQuery: props.onPrettifyQuery,
});
break;
case GraphiQL.Footer:
Expand All @@ -354,7 +360,7 @@ export function GraphiQLInterface(props: GraphiQLInterfaceProps) {
}
return acc;
}, {}),
[props.children, props.onCopyQuery],
[props.children, props.onCopyQuery, props.onPrettifyQuery],
);

const onClickReference = useCallback(() => {
Expand Down Expand Up @@ -628,6 +634,7 @@ export function GraphiQLInterface(props: GraphiQLInterfaceProps) {
keyMap={props.keyMap}
onClickReference={onClickReference}
onCopyQuery={props.onCopyQuery}
onPrettifyQuery={props.onPrettifyQuery}
onEdit={props.onEditQuery}
readOnly={props.readOnly}
/>
Expand Down Expand Up @@ -981,6 +988,8 @@ function GraphiQLToolbar({
children = DefaultToolbarRenderProps,
// @ts-expect-error -- Hide this prop for user, we use cloneElement to pass onCopyQuery
onCopyQuery,
// @ts-expect-error -- Hide this prop for user, we use cloneElement to pass onPrettifyQuery
onPrettifyQuery,
}: {
children?: ToolbarRenderProps;
}) {
Expand All @@ -991,7 +1000,7 @@ function GraphiQLToolbar({
}
const onCopy = useCopyQuery({ onCopyQuery });
const onMerge = useMergeQuery();
const onPrettify = usePrettifyEditors();
const onPrettify = usePrettifyEditors({ onPrettifyQuery });

const prettify = (
<ToolbarButton onClick={onPrettify} label="Prettify query (Shift-Ctrl-P)">
Expand Down

0 comments on commit 7e452e7

Please sign in to comment.