Skip to content

Commit

Permalink
add documention for @graphiql/react (#2657)
Browse files Browse the repository at this point in the history
* add JSDocs for component props and hooks

* add JSDocs for context types

* add README for `@graphiql/react`
  • Loading branch information
thomasheyenbrock committed Aug 15, 2022
1 parent 09554fa commit 796add6
Show file tree
Hide file tree
Showing 30 changed files with 456 additions and 73 deletions.
5 changes: 5 additions & 0 deletions .changeset/chilly-radios-tap.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@graphiql/react': minor
---

BREAKING: The `onHasCompletion` export has been removed as it is only meant to be used internally.
1 change: 1 addition & 0 deletions custom-words.txt
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,7 @@ paas
// these pop up when writing "GraphQL___"
qlapi
qlid
qlide

// other
architecting
Expand Down
93 changes: 90 additions & 3 deletions packages/graphiql-react/README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,94 @@
[Changelog](https://github.com/graphql/graphiql/blob/main/packages/graphiql-react/CHANGELOG.md) | [API Docs](https://graphiql-test.netlify.app/typedoc/modules/graphiql_react.html) | [NPM](https://www.npmjs.com/package/@graphiql/react)

A react SDK for building graphql developer experiences for the web
# `@graphiql/react`

Used by `graphiql@2` and beyond!
A React SDK for building integrated GraphQL developer experiences for the web.

(docs coming soon!)
## Purpose

This package contains a set of building blocks that allow its users to build GraphQL IDEs with ease. It's the set of components that make up Graph*i*QL, the first and official GraphQL IDE, owned and maintained by the GraphQL Foundation.

There are two kinds of building blocks that this package provides: Stateful context providers for state management and simple UI components.

## Getting started

All the state for your GraphQL IDE lives in multiple contexts. The easiest way to get started is by using the `GraphiQLProvider` component that renders all the individual providers.

There is one required prop called `fetcher`. This is a function that performs GraphQL request against a given endpoint. You can easily create a fetcher using the method `createGraphiQLFetcher` from the `@graphiql/toolkit` package.

```jsx
import { GraphiQLProvider } from '@graphiql/react';
import { createGraphiQLFetcher } from '@graphiql/toolkit';

const fetcher = createGraphiQLFetcher({
url: 'https://my.graphql.api/graphql',
});

function MyGraphQLIDE() {
return (
<GraphiQLProvider fetcher={fetcher}>
<div className="graphiql-container">Hello GraphQL</div>
</GraphiQLProvider>
);
}
```

Inside the provider you can now use any UI component provided by `@graphiql/react`. For example, you can render a query editor like this:

```jsx
import { QueryEditor } from '@graphiql/react';

function MyGraphQLIDE() {
return (
<GraphiQLProvider fetcher={fetcher}>
<div className="graphiql-container">
<QueryEditor />
</div>
</GraphiQLProvider>
);
}
```

The package also ships the necessary CSS that all its UI components need. You can import them from `@graphiql/react/dist/style.css`.

**Note**: In order for these styles to apply, the UI components need to be rendered inside an element that has a class name `graphiql-container`.

By default the UI components will try to use the [Roboto](https://fonts.google.com/specimen/Roboto) font for regular text and the [Fira Code](https://fonts.google.com/specimen/Fira+Code) font for mono-space text. If you want to use the default fonts you can load them using these files:

- `@graphiql/react/font/roboto.css`
- `@graphiql/react/font/fira-code.css`.

You can of course use any other method to load these fonts (for example loading them from Google Fonts).

Further details on how to use `@graphiql/react` can be found in the reference implementation of a GraphQL IDE - Graph*i*QL - in the [`graphiql` package](https://github.com/graphql/graphiql/blob/main/packages/graphiql/src/components/GraphiQL.tsx).

## Available contexts

There are multiple contexts that own different parts of the state that make up a complete GraphQL IDE. For each context there is a provider component (`<name>ContextProvider`) that makes sure the context is initialized and managed properly. These components contains all the logic related to state management. In addition, for each context there is also a hook (`use<name>Context`) that allows you to consume its current value.

Here is a list of all contexts that come with `@graphiql/react`

- `StorageContext`: Provides a storage API that can be used to persist state in the browser (by default using `localStorage`)
- `EditorContext`: Manages all the editors and tabs
- `SchemaContext`: Fetches, validates and stores the GraphQL schema
- `ExecutionContext`: Executes GraphQL requests
- `HistoryContext`: Persists executed requests in storage
- `ExplorerContext`: Handles the state for the docs explorer

All context properties are documented using JSDoc comments. If you're using an IDE like VSCode for development these descriptions will show up in auto-complete tooltips. All these descriptions can also be found in the [API Docs](https://graphiql-test.netlify.app/typedoc/modules/graphiql_react.html).

## Theming

All the components from `@graphiql/react` have been designed with customization in mind. We achieve this using CSS variables.

All variables that are available for customization can be found in the [`root.css` file](https://github.com/graphql/graphiql/blob/main/packages/graphiql-react/src/style/root.css).

### Colors

Colors are defined using the [HSL format](https://en.wikipedia.org/wiki/HSL_and_HSV). All CSS variables for colors are defined as a list of the three values that make up HSL (hue, saturation and lightness).

This approach allows `@graphiql/react` to use transparent colors by passing the value of the CSS variable in the `hsla` function. This enables us to provide truly reusable UI elements where good contrasts are preserved regardless of the elements background.

## Development

If you want to develop with `@graphiql/react` locally - in particular when working on the `graphiql` package - all you need to do is run `yarn dev` in the package folder in a separate terminal. This will build the package using Vite. When using it in combination with `yarn start-graphiql` (running in the repo root) this will give you auto-reloading when working on `graphiql` and `@graphiql/react` simultaneously.
5 changes: 2 additions & 3 deletions packages/graphiql-react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,8 @@
"types"
],
"scripts": {
"dev": "vite",
"build": "tsc --emitDeclarationOnly && vite build",
"preview": "vite preview"
"dev": "concurrently 'tsc --emitDeclarationOnly --watch' 'vite build --watch'",
"build": "tsc --emitDeclarationOnly && vite build"
},
"peerDependencies": {
"graphql": "^15.5.0 || ^16.0.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,13 @@ import '../style/codemirror.css';
import '../style/fold.css';
import '../style/editor.css';

type HeaderEditorProps = UseHeaderEditorArgs & { isHidden?: boolean };
type HeaderEditorProps = UseHeaderEditorArgs & {
/**
* Visually hide the header editor.
* @default false
*/
isHidden?: boolean;
};

export function HeaderEditor({ isHidden, ...hookArgs }: HeaderEditorProps) {
const { headerEditor } = useEditorContext({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ import '../style/hint.css';
import '../style/editor.css';

type VariableEditorProps = UseVariableEditorArgs & {
/**
* Visually hide the header editor.
* @default false
*/
isHidden?: boolean;
};

Expand Down
80 changes: 77 additions & 3 deletions packages/graphiql-react/src/editor/context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,35 +34,109 @@ export type CodeMirrorEditorWithOperationFacts = CodeMirrorEditor & {
variableToType: VariableToType | null;
};

export type EditorContextType = {
activeTabIndex: number;
tabs: TabState[];
export type EditorContextType = TabsState & {
/**
* Add a new tab.
*/
addTab(): void;
/**
* Switch to a different tab.
* @param index The index of the tab that should be switched to.
*/
changeTab(index: number): void;
/**
* Close a tab. If the currently active tab is closed the tab before it will
* become active. If there is no tab before the closed one, the tab after it
* will become active.
* @param index The index of the tab that should be closed.
*/
closeTab(index: number): void;
/**
* Update the state for the tab that is currently active. This will be
* reflected in the `tabs` object and the state will be persisted in storage
* (if available).
* @param partialTab A partial tab state object that will override the
* current values. The properties `id`, `hash` and `title` cannot be changed.
*/
updateActiveTabValues(
partialTab: Partial<Omit<TabState, 'id' | 'hash' | 'title'>>,
): void;

/**
* The CodeMirror editor instance for the headers editor.
*/
headerEditor: CodeMirrorEditor | null;
/**
* The CodeMirror editor instance for the query editor. This editor also
* stores the operation facts that are derived from the current editor
* contents.
*/
queryEditor: CodeMirrorEditorWithOperationFacts | null;
/**
* The CodeMirror editor instance for the response editor.
*/
responseEditor: CodeMirrorEditor | null;
/**
* The CodeMirror editor instance for the variables editor.
*/
variableEditor: CodeMirrorEditor | null;
/**
* Set the CodeMirror editor instance for the headers editor.
*/
setHeaderEditor(newEditor: CodeMirrorEditor): void;
/**
* Set the CodeMirror editor instance for the query editor.
*/
setQueryEditor(newEditor: CodeMirrorEditorWithOperationFacts): void;
/**
* Set the CodeMirror editor instance for the response editor.
*/
setResponseEditor(newEditor: CodeMirrorEditor): void;
/**
* Set the CodeMirror editor instance for the variables editor.
*/
setVariableEditor(newEditor: CodeMirrorEditor): void;

/**
* Changes the operation name and invokes the `onEditOperationName` callback.
*/
setOperationName(operationName: string): void;

/**
* The contents of the headers editor when initially rendering the provider
* component.
*/
initialHeaders: string;
/**
* The contents of the query editor when initially rendering the provider
* component.
*/
initialQuery: string;
/**
* The contents of the response editor when initially rendering the provider
* component.
*/
initialResponse: string;
/**
* The contents of the variables editor when initially rendering the provider
* component.
*/
initialVariables: string;

/**
* A map of fragment definitions using the fragment name as key which are
* made available to include in the query.
*/
externalFragments: Map<string, FragmentDefinitionNode>;
/**
* A list of custom validation rules that are run in addition to the rules
* provided by the GraphQL spec.
*/
validationRules: ValidationRule[];

/**
* If the contents of the headers editor are persisted in storage.
*/
shouldPersistHeaders: boolean;
};

Expand Down
56 changes: 42 additions & 14 deletions packages/graphiql-react/src/editor/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,11 +89,9 @@ export function useChangeHandler(
]);
}

export type OnClickReference = (reference: SchemaReference) => void;

export function useCompletion(
editor: CodeMirrorEditor | null,
callback: OnClickReference | null,
callback: ((reference: SchemaReference) => void) | null,
caller: Function,
) {
const { schema } = useSchemaContext({ nonNull: true, caller });
Expand Down Expand Up @@ -150,13 +148,20 @@ export function useKeyMap(
}, [editor, keys, callback]);
}

export function useCopyQuery({
caller,
onCopyQuery,
}: {
export type UseCopyQueryArgs = {
/**
* This is only meant to be used internally in `@graphiql/react`.
*/
caller?: Function;
/**
* Invoked when the current contents of the query editor are copied to the
* clipboard.
* @param query The content that has been copied.
*/
onCopyQuery?: (query: string) => void;
} = {}) {
};

export function useCopyQuery({ caller, onCopyQuery }: UseCopyQueryArgs = {}) {
const { queryEditor } = useEditorContext({
nonNull: true,
caller: caller || useCopyQuery,
Expand All @@ -173,7 +178,14 @@ export function useCopyQuery({
}, [queryEditor, onCopyQuery]);
}

export function useMergeQuery({ caller }: { caller?: Function } = {}) {
type UseMergeQueryArgs = {
/**
* This is only meant to be used internally in `@graphiql/react`.
*/
caller?: Function;
};

export function useMergeQuery({ caller }: UseMergeQueryArgs = {}) {
const { queryEditor } = useEditorContext({
nonNull: true,
caller: caller || useMergeQuery,
Expand All @@ -190,11 +202,14 @@ export function useMergeQuery({ caller }: { caller?: Function } = {}) {
}, [queryEditor, schema]);
}

export function usePrettifyEditors({
caller,
}: {
type UsePrettifyEditorsArgs = {
/**
* This is only meant to be used internally in `@graphiql/react`.
*/
caller?: Function;
} = {}) {
};

export function usePrettifyEditors({ caller }: UsePrettifyEditorsArgs = {}) {
const { queryEditor, headerEditor, variableEditor } = useEditorContext({
nonNull: true,
caller: caller || usePrettifyEditors,
Expand Down Expand Up @@ -244,10 +259,23 @@ export function usePrettifyEditors({
}, [queryEditor, variableEditor, headerEditor]);
}

export type UseAutoCompleteLeafsArgs = {
/**
* A function to determine which field leafs are automatically added when
* trying to execute a query with missing selection sets. It will be called
* with the `GraphQLType` for which fields need to be added.
*/
getDefaultFieldNames?: GetDefaultFieldNamesFn;
/**
* This is only meant to be used internally in `@graphiql/react`.
*/
caller?: Function;
};

export function useAutoCompleteLeafs({
getDefaultFieldNames,
caller,
}: { getDefaultFieldNames?: GetDefaultFieldNamesFn; caller?: Function } = {}) {
}: UseAutoCompleteLeafsArgs = {}) {
const { schema } = useSchemaContext({
nonNull: true,
caller: caller || useAutoCompleteLeafs,
Expand Down
1 change: 0 additions & 1 deletion packages/graphiql-react/src/editor/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
export { onHasCompletion } from './completion';
export {
HeaderEditor,
ImagePreview,
Expand Down
Loading

0 comments on commit 796add6

Please sign in to comment.