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 support for onPrettifyQuery callback to enable customised query formatting #3733

Merged
merged 2 commits into from
Aug 15, 2024
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/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 @@
}, [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 @@

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

Check warning on line 266 in packages/graphiql-react/src/editor/hooks.ts

View check run for this annotation

Codecov / codecov/patch

packages/graphiql-react/src/editor/hooks.ts#L265-L266

Added lines #L265 - L266 were not covered by tests

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

export type UseAutoCompleteLeafsArgs = {
Expand Down
10 changes: 8 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,10 @@ 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
Loading