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

feat: Add new components to simplify migration from DataSourceHttpSettings #67

Merged
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 CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@

All notable changes to this project will be documented in this file.

## v1.6.0

- Add new `ConnectionSettings` and `AdvancedHttpSettings` components to simplify migration from `DataSourceHttpSettings` component.
- Improve docs for some components.

## v1.5.1

- Fix Auth component to prevent it from failing when it is used in Grafana 8
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@grafana/experimental",
"version": "1.5.1",
"version": "1.6.0",
"description": "Experimental Grafana components and APIs",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
Expand Down
96 changes: 96 additions & 0 deletions src/ConfigEditor/AdvancedSettings/AdvancedHttpSettings.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { AdvancedHttpSettings, Props } from './AdvancedHttpSettings';
import { Config } from '../types';

const getProps = (partialProps?: Partial<Props>): Props => ({
config: {
jsonData: {
keepCookies: [],
timeout: 0,
...partialProps?.config?.jsonData,
},
...partialProps?.config,
} as Config,
onChange: () => {},
...partialProps,
});

describe('<AdvancedHttpSettings />', () => {
it('should render cookies and timeout fields', () => {
const props = getProps();

render(<AdvancedHttpSettings {...props} />);

expect(screen.getByLabelText('Allowed cookies')).toBeInTheDocument();
expect(screen.getByPlaceholderText('New cookie (hit enter to add)')).toBeInTheDocument();
expect(screen.getByLabelText('Timeout')).toBeInTheDocument();
expect(screen.getByPlaceholderText('Timeout in seconds')).toBeInTheDocument();
});

it('should render provided cookies', () => {
const props = getProps({
config: { jsonData: { keepCookies: ['test-cookie-1', 'test-cookie-2'] } } as Config,
});

render(<AdvancedHttpSettings {...props} />);

expect(screen.getByText('test-cookie-1')).toBeInTheDocument();
expect(screen.getByText('test-cookie-2')).toBeInTheDocument();
});

it('should render provided timeout', () => {
const props = getProps({
config: { jsonData: { timeout: 777 } } as Config,
});

render(<AdvancedHttpSettings {...props} />);

expect(screen.getByPlaceholderText('Timeout in seconds')).toHaveValue(777);
});

it('should call onChange when new cookie is added', async () => {
const onChange = jest.fn();
const props = getProps({
config: { jsonData: { keepCookies: ['cookie-1'] } } as Config,
onChange,
});
const user = userEvent.setup();

render(<AdvancedHttpSettings {...props} />);
const cookieInput = screen.getByPlaceholderText('New cookie (hit enter to add)');

await user.type(cookieInput, 'cookie-2{enter}');

expect(onChange).toHaveBeenCalledTimes(1);
expect(onChange).toHaveBeenCalledWith({ jsonData: { keepCookies: ['cookie-1', 'cookie-2'] } });
});

it('should call onChange when timeout changes', async () => {
const onChange = jest.fn();
const props = getProps({
config: { jsonData: { timeout: 123 } } as Config,
onChange,
});
const user = userEvent.setup();

render(<AdvancedHttpSettings {...props} />);
const timeoutInput = screen.getByPlaceholderText('Timeout in seconds');

// Select everything and type 7
await user.type(timeoutInput, '{Control>}A{/Control}7}');

expect(onChange).toHaveBeenCalledTimes(1);
expect(onChange).toHaveBeenCalledWith({ jsonData: { timeout: 7 } });
});

it('should render inputs as disabled when in read only mode', () => {
const props = getProps({ config: { readOnly: true, jsonData: {} } as Config });

render(<AdvancedHttpSettings {...props} />);

expect(screen.getByPlaceholderText('New cookie (hit enter to add)')).toBeDisabled();
expect(screen.getByPlaceholderText('Timeout in seconds')).toBeDisabled();
});
});
82 changes: 82 additions & 0 deletions src/ConfigEditor/AdvancedSettings/AdvancedHttpSettings.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import React from 'react';
import { css, cx } from '@emotion/css';
import { InlineField, Input, TagsInput } from '@grafana/ui';
import { ConfigSubSection } from '../ConfigSection';
import { Config, OnChangeHandler } from '../types';

export type Props<C extends Config = Config> = {
config: C;
onChange: OnChangeHandler<C>;
className?: string;
};

export const AdvancedHttpSettings: <C extends Config = Config>(props: Props<C>) => JSX.Element = ({
config,
onChange,
className,
}) => {
const onCookiesChange = (cookies: string[]) => {
onChange({
...config,
jsonData: {
...config.jsonData,
keepCookies: cookies,
},
});
};

const onTimeoutChange = (event: React.FormEvent<HTMLInputElement>) => {
onChange({
...config,
jsonData: {
...config.jsonData,
timeout: parseInt(event.currentTarget.value, 10),
},
});
};

const styles = {
container: css({
maxWidth: 578,
}),
};

return (
<ConfigSubSection title="Advanced HTTP settings" className={cx(styles.container, className)}>
<InlineField
htmlFor="advanced-http-cookies"
label="Allowed cookies"
labelWidth={24}
tooltip="Grafana proxy deletes forwarded cookies by default. Specify cookies by name that should be forwarded to the data source."
disabled={config.readOnly}
grow
>
<TagsInput
id="advanced-http-cookies"
placeholder="New cookie (hit enter to add)"
tags={config.jsonData.keepCookies}
onChange={onCookiesChange}
/>
</InlineField>

<InlineField
htmlFor="advanced-http-timeout"
label="Timeout"
labelWidth={24}
tooltip="HTTP request timeout in seconds"
disabled={config.readOnly}
grow
>
<Input
id="advanced-http-timeout"
type="number"
min={0}
placeholder="Timeout in seconds"
aria-label="Timeout in seconds"
value={config.jsonData.timeout}
onChange={onTimeoutChange}
/>
</InlineField>
</ConfigSubSection>
);
};
67 changes: 67 additions & 0 deletions src/ConfigEditor/AdvancedSettings/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# AdvancedSettings

Contains components to be used for datasource advanced configuration.

## AdvancedHttpSettings

### Overview

`AdvancedHttpSettings` component is used to simplify migrating from legacy `DataSourceHttpSettings` component (you can find the detailed explanation [here](../migrating-from-datasource-http-settings.md)).
`AdvancedHttpSettings` renders as a config **sub section** with "Allowed cookies" and "Timeout" fields.

> ❗️ Note: `AdvancedHttpSettings` should be used inside "Additional settings" config section alongside sub sections for other advanced datasource settings (see [usage example](#usage) below).

`AdvancedHttpSettings` has the following properties type:

```ts
type Props = {
// This is passed as `props.options` to datasource's ConfigEditor component
config: DataSourceConfig;

// This is passed as `props.onOptionsChange` to datasource's ConfigEditor component
onChange: DataSourceConfigOnChangeHandler;

// Optional className
className?: string;
};
```

### Usage

The common scenario if you are just replacing the legacy `DataSourceHttpSettings` component is as simple as:

```tsx
import {
ConfigSection,
ConfigSubSection,
AdvancedHttpSettings
} from '@grafana/experimental'


export const ConfigEditor = (props: Props) => {

return (
{/* ... */}

<ConfigSection
title="Advanced settings"
description="Additional settings are optional settings that can be configured for more control over your data source."
>
{/* Other sub sections if applicable */}

<AdvancedHttpSettings
config={props.options}
onChange={props.onOptionsChange}
/>

{/* Other sub sections if applicable */}
</ConfigSection>

{/* ... */}
)
}
```

### How it looks like

<img src="./docs-img/advanced-http-settings.png" width="600">
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions src/ConfigEditor/AdvancedSettings/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { AdvancedHttpSettings } from './AdvancedHttpSettings';
8 changes: 4 additions & 4 deletions src/ConfigEditor/Auth/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# Auth component

Auth component is meant to replace the old [`DataSourceHttpSettings`](https://github.com/grafana/grafana/blob/d02aee24795aecc09efa6d81e35b25d8f151bb25/packages/grafana-ui/src/components/DataSourceSettings/DataSourceHttpSettings.tsx) component which has a number of UX issues. The new component is stored here in `@grafana/experimental` so that it can be used in external datasources regardless of Grafana version (Enterprise datasources must support at least 2 latest major Grafana versions).
Auth component is meant to be used for authentication section of the datasource configuration page. It is also a replacement of the old [`DataSourceHttpSettings`](https://github.com/grafana/grafana/blob/d02aee24795aecc09efa6d81e35b25d8f151bb25/packages/grafana-ui/src/components/DataSourceSettings/DataSourceHttpSettings.tsx) component which has a number of UX issues.

> ❗️Note: The new component only takes care about the Auth section of the old component (see screenshot above). So the HTTP section of the old component (URL, Allowed cookies, Timeout) should be added alongside the new component separately when needed. For a complete migration guide from `DataSourceHttpSettings` check [this page](../migrating-from-datasource-http-settings.md).

In the new component only one authentication method can be selected at a time and all TLS options are located in a separate section and can be added to any selected authentication method.

Expand All @@ -16,9 +18,7 @@ Screenshots of the component:

Even though the new component has completely different props shape, there is a special utility that takes the legacy props and returns the new props.

> ❗️Note 1: The new component doesn't show "Enable cross-site access control requests" (previously known as "With credentials") auth method by default as in most of the cases it's not used and we are moving away from it. You can still enable it using `visibleMethods` prop if needed.

> ❗️Note 2: The new component only takes care about the Auth section of the old component (see screenshot above). So the HTTP section of the old component (URL, Allowed cookies, Timeout) should be added alongside the new component separately when needed.
> ❗️Note: The new component doesn't show "Enable cross-site access control requests" (previously known as "With credentials") auth method by default as in most of the cases it's not used and we are moving away from it. You can still enable it using `visibleMethods` prop if needed.

**Example**:

Expand Down
2 changes: 1 addition & 1 deletion src/ConfigEditor/Auth/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ import {
getTLSProps,
getCustomHeaders,
convertLegacyAuthProps,
Config,
} from './utils';
import { Props as AuthProps } from './Auth';
import { AuthMethod } from './types';
import { Config } from '../types';

describe('utils', () => {
describe('convertLegacyAuthProps', () => {
Expand Down
8 changes: 1 addition & 7 deletions src/ConfigEditor/Auth/utils.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,10 @@
import { DataSourceSettings, DataSourceJsonData } from '@grafana/data';
import { Props as AuthProps } from './Auth';
import { AuthMethod, Header, CustomMethodId } from './types';
import { Config, OnChangeHandler } from '../types';

const headerNamePrefix = 'httpHeaderName';
const headerValuePrefix = 'httpHeaderValue';

export type Config<JSONData extends DataSourceJsonData = any, SecureJSONData = any> = DataSourceSettings<
JSONData,
SecureJSONData
>;
export type OnChangeHandler<C extends Config = Config> = (config: C) => void;

export function convertLegacyAuthProps<C extends Config = Config>({
config,
onChange,
Expand Down
70 changes: 70 additions & 0 deletions src/ConfigEditor/ConfigSection/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# ConfigSection

## Overview

Exposes two components, `ConfigSection` and `ConfigSubSection` that are used to organize data source configuration page.

The properties type for both components is the same:

```ts
type Props = {
// Section title
title: string;

// Section description
description?: ReactNode;

// Defines whether section is collapsible
isCollapsible?: boolean;

// Defines whether collapsible section is initially open (on page load)
isInitiallyOpen?: boolean;

// Optional className
className?: string;

// Should always have child components
children: ReactNode;
};
```

The section description property is optional, but it should only be omitted if there is only one field in the section.

## Usage

```tsx
import {ConfigSection, ConfigSubSection} from '@grafana/experimental'


export const ConfigEditor = (props: Props) => {

return (
{/* ... */}

<ConfigSection
title="Connection"
>
<ConfigSubSection title="URL">
{/* URL field */}
</ConfigSubSection>
<ConfigSection/>

<ConfigSection
title="Additional settings"
description="Additional settings are optional settings that..."
isCollapsible
isInitiallyOpen={!!(props.options.jsonData.someSetting)}
>
<ConfigSubSection title="Some setting">
{/* Some setting fields */}
</ConfigSubSection>
<ConfigSection/>

{/* ... */}
)
}
```

## How it looks like

<img src="./docs-img/config-section.png" width="600">
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading