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 3 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>
);
};
70 changes: 70 additions & 0 deletions src/ConfigEditor/AdvancedSettings/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# AdvancedSettings

Contains components to be used for datasource advanced configuration.

## AdvancedHttpSettings

### Overview

`AdvancedHttpSettings` component is used to simplify migrating from legacy `DataSourceHttpSettings` component.
Currently renders as a config **sub section** with "Allowed cookies" and "Timeout" fields.

> ❗️ Note: If you are not migrating from `DataSourceHttpSettings` then you might not need this component.\
cletter7 marked this conversation as resolved.
Show resolved Hide resolved
> If you need to add more fields to the `AdvancedHttpSettings` for your datasource then it's better that you create your own implementation of the component.

> ❗️ 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';
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