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 debounce for GSelect and RemoteSelect #2466

Merged
merged 4 commits into from
Jul 11, 2023
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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## Unreleased

### Fixed

- Add debounce on Select UI components to avoid making API search requests on each key-down event by
@maskin25 ([#2466](https://github.com/grafana/oncall/pull/2466))

## v1.3.8 (2023-07-11)

### Added
Expand Down
9 changes: 1 addition & 8 deletions grafana-plugin/integration-tests/utils/forms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,14 +88,7 @@ const chooseDropdownValue = async ({ page, value, optionExactMatch = true }: Sel

export const selectDropdownValue = async (args: SelectDropdownValueArgs): Promise<Locator> => {
const selectElement = await openSelect(args);

/**
* use the select search to filter down the options
* TODO: get rid of the slice when we fix the GSelect component..
* without slicing this would fire off an API request for every key-stroke
*/
await selectElement.type(args.value.slice(0, 5));

await selectElement.type(args.value);
await chooseDropdownValue(args);

return selectElement;
Expand Down
2 changes: 1 addition & 1 deletion grafana-plugin/playwright.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ const config: PlaywrightTestConfig = {
* to flaky tests.. let's just retry failed tests. If the same test fails 3 times, you know something must be up
*/
retries: !!process.env.CI ? 3 : 0,
workers: !!process.env.CI ? 2 : 1,
workers: 3,
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
reporter: 'html',
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
Expand Down
19 changes: 6 additions & 13 deletions grafana-plugin/src/containers/GSelect/GSelect.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { get, isNil } from 'lodash-es';
import { observer } from 'mobx-react';

import { useStore } from 'state/useStore';
import { useDebouncedCallback } from 'utils/hooks';

import styles from './GSelect.module.scss';

Expand Down Expand Up @@ -89,30 +90,22 @@ const GSelect = observer((props: GSelectProps) => {
[model, onChange]
);

/**
* without debouncing this function when search is available
* we risk hammering the API endpoint for every single key stroke
* some context on 250ms as the choice here - https://stackoverflow.com/a/44755058/3902555
*/
const loadOptions = (query: string) => {
return model.updateItems(query).then(() => {
const loadOptions = useDebouncedCallback((query: string, cb) => {
model.updateItems(query).then(() => {
const searchResult = model.getSearchResult(query);
let items = Array.isArray(searchResult.results) ? searchResult.results : searchResult;
if (filterOptions) {
items = items.filter((opt: any) => filterOptions(opt[valueField]));
}

return items.map((item: any) => ({
const options = items.map((item: any) => ({
value: item[valueField],
label: get(item, displayField),
imgUrl: item.avatar_url,
description: getDescription && getDescription(item),
}));
cb(options);
});
};

// TODO: why doesn't this work properly?
// const loadOptions = debounce(_loadOptions, showSearch ? 250 : 0);
}, 250);

const values = isMulti
? (value ? (value as string[]) : [])
Expand Down
17 changes: 7 additions & 10 deletions grafana-plugin/src/containers/RemoteSelect/RemoteSelect.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import React, { useCallback, useEffect, useMemo, useReducer, useState } from 'react';
import React, { useCallback, useMemo, useReducer, useState } from 'react';

import { SelectableValue } from '@grafana/data';
import { AsyncMultiSelect, AsyncSelect } from '@grafana/ui';
import { inject, observer } from 'mobx-react';

import { makeRequest, isNetworkError } from 'network';
import { UserAction, generateMissingPermissionMessage } from 'utils/authorization';
import { useDebouncedCallback } from 'utils/hooks';

interface RemoteSelectProps {
autoFocus?: boolean;
Expand Down Expand Up @@ -67,24 +68,20 @@ const RemoteSelect = inject('store')(

const [options, setOptions] = useReducer(mergeOptions, []);

const loadOptionsCallback = useCallback(async (query?: string): Promise<SelectableValue[]> => {
const loadOptionsCallback = useDebouncedCallback(async (query: string, cb) => {
try {
const data = await makeRequest(href, { params: { search: query } });
const options = getOptions(data.results || data);
setOptions(options);

return options;
cb(options);
} catch (e) {
if (isNetworkError(e) && e.response.status === 403 && requiredUserAction) {
setNoOptionsMessage(generateMissingPermissionMessage(requiredUserAction));
}
return [];
cb([]);
}
}, []);

useEffect(() => {
loadOptionsCallback();
}, []);
}, 250);

const onChangeCallback = useCallback(
(option) => {
Expand Down Expand Up @@ -127,7 +124,7 @@ const RemoteSelect = inject('store')(
isSearchable={showSearch}
value={value}
onChange={onChangeCallback}
defaultOptions={options}
defaultOptions
Comment on lines -130 to +127
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what is this change for?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

from specs

defaultOptions | When specified as boolean the loadOptions will execute when component is mounted

it exactly what we need

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

gotcha, thanks for clarifying 👍

loadOptions={loadOptionsCallback}
getOptionLabel={getOptionLabel}
noOptionsMessage={noOptionsMessage}
Expand Down
5 changes: 4 additions & 1 deletion grafana-plugin/src/models/grafana_team/grafana_team.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { action, observable } from 'mobx';

import BaseStore from 'models/base_store';
import { GrafanaTeam } from 'models/grafana_team/grafana_team.types';
import { makeRequest } from 'network';
import { RootStore } from 'state';

export class GrafanaTeamStore extends BaseStore {
Expand Down Expand Up @@ -29,7 +30,9 @@ export class GrafanaTeamStore extends BaseStore {

@action
async updateItems(query = '') {
const result = await this.getAll();
const result = await makeRequest(`${this.path}`, {
params: { search: query },
});
joeyorlando marked this conversation as resolved.
Show resolved Hide resolved

this.items = {
...this.items,
Expand Down