Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
163 changes: 112 additions & 51 deletions packages/compass-query-bar/src/components/option-editor.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,14 @@ import {
waitFor,
userEvent,
} from '@mongodb-js/testing-library-compass';
import { OptionEditor } from './option-editor';
import { OptionEditor, getOptionBasedQueries } from './option-editor';
import type { SinonSpy } from 'sinon';
import { applyFromHistory } from '../stores/query-bar-reducer';
import sinon from 'sinon';
import { createSandboxFromDefaultPreferences } from 'compass-preferences-model';
import type { PreferencesAccess } from 'compass-preferences-model';
import { PreferencesProvider } from 'compass-preferences-model/provider';
import type { RecentQuery } from '@mongodb-js/my-queries-storage';

class MockPasteEvent extends window.Event {
constructor(private text: string) {
Expand Down Expand Up @@ -167,7 +168,7 @@ describe('OptionEditor', function () {
});
});

describe('when render filter bar with the query history autocompleter', function () {
describe('when rendering filter option', function () {
let onApplySpy: SinonSpy;
let preferencesAccess: PreferencesAccess;

Expand Down Expand Up @@ -198,48 +199,42 @@ describe('OptionEditor', function () {
sort: { a: -1 },
},
},
{
type: 'recent',
lastExecuted: new Date(),
queryProperties: {
filter: { a: 2 },
sort: { a: -1 },
update: { a: 10 },
},
},
]}
onApplyQuery={onApplySpy}
/>
</PreferencesProvider>
);
userEvent.click(screen.getByRole('textbox'));
await waitFor(() => {
screen.getByLabelText('Completions');
});
});

afterEach(function () {
cleanup();
});

it('filter applied correctly when autocomplete option is clicked', async function () {
userEvent.click(screen.getByRole('textbox'));
await waitFor(() => {
expect(screen.getAllByText('{ a: 1 }')[0]).to.be.visible;
expect(screen.getByText('{ a: 2 }, sort: { a: -1 }')).to.be.visible;
expect(
screen.queryByText('{ a: 2 }, sort: { a: -1 }, update: { a: 10 }')
).to.be.null;
});
it('renders autocomplete options', function () {
expect(screen.getAllByText('{ a: 1 }')[0]).to.be.visible;
expect(screen.getByText('{ a: 2 }, sort: { a: -1 }')).to.be.visible;
});

it('calls onApply with correct params', async function () {
// Simulate selecting the autocomplete option
userEvent.click(screen.getByText('{ a: 2 }, sort: { a: -1 }'));
await waitFor(() => {
expect(onApplySpy.lastCall).to.be.calledWithExactly({
filter: { a: 2 },
sort: { a: -1 },
});
expect(onApplySpy.lastCall).to.be.calledWithExactly(
{
filter: { a: 2 },
sort: { a: -1 },
},
[]
);
});
});
});

describe('when render project bar with the query history autocompleter', function () {
describe('when rendering project option', function () {
let onApplySpy: SinonSpy;
let preferencesAccess: PreferencesAccess;

Expand All @@ -262,20 +257,10 @@ describe('OptionEditor', function () {
project: { a: 1 },
},
},
{
type: 'favorite',
lastExecuted: new Date(),
queryProperties: {
filter: { a: 2 },
sort: { a: -1 },
},
},
{
type: 'recent',
lastExecuted: new Date(),
queryProperties: {
filter: { a: 2 },
sort: { a: -1 },
project: { a: 0 },
},
},
Expand All @@ -284,32 +269,108 @@ describe('OptionEditor', function () {
/>
</PreferencesProvider>
);
userEvent.click(screen.getByRole('textbox'));
await waitFor(() => {
screen.getByLabelText('Completions');
});
});

afterEach(function () {
cleanup();
});

it('only queries with project property are shown in project editor', async function () {
userEvent.click(screen.getByRole('textbox'));
await waitFor(() => {
expect(screen.getAllByText('project: { a: 1 }')[0]).to.be.visible;
expect(screen.queryByText('{ a: 2 }, sort: { a: -1 }')).to.be.null;
expect(screen.getByText('{ a: 2 }, sort: { a: -1 }, project: { a: 0 }'))
.to.be.visible;
});
it('renders autocomplete options', function () {
expect(screen.getAllByText('project: { a: 1 }')[0]).to.be.visible;
expect(screen.getAllByText('project: { a: 0 }')[0]).to.be.visible;
});

it('calls onApply with correct params', async function () {
// Simulate selecting the autocomplete option
userEvent.click(
screen.getByText('{ a: 2 }, sort: { a: -1 }, project: { a: 0 }')
);
userEvent.click(screen.getByText('project: { a: 0 }'));
await waitFor(() => {
expect(onApplySpy.lastCall).to.be.calledWithExactly({
filter: { a: 2 },
sort: { a: -1 },
project: { a: 0 },
});
expect(onApplySpy).to.have.been.calledOnceWithExactly(
{
project: { a: 0 },
},
['filter', 'collation', 'sort', 'hint', 'skip', 'limit', 'maxTimeMS']
);
});
});
});

describe('getOptionBasedQueries', function () {
const savedQueries = [
{
_lastExecuted: new Date(),
filter: { a: 1 },
project: { b: 1 },
sort: { c: 1 },
collation: { locale: 'en' },
hint: { a: 1 },
skip: 1,
limit: 1,
},
] as unknown as RecentQuery[];

it('filters out update queries', function () {
const queries = getOptionBasedQueries('filter', 'recent', [
...savedQueries,
{ _lastExecuted: new Date(), update: { a: 1 }, filter: { a: 2 } },
] as unknown as RecentQuery[]);
expect(queries.length).to.equal(1);
});

it('filters out empty queries', function () {
const queries = getOptionBasedQueries('filter', 'recent', [
...savedQueries,
{ _lastExecuted: new Date() },
] as unknown as RecentQuery[]);
expect(queries.length).to.equal(1);
});

it('filters out duplicate queries', function () {
const queries = getOptionBasedQueries('filter', 'recent', [
...savedQueries,
...savedQueries,
...savedQueries,
{ _lastExecuted: new Date() },
{ _lastExecuted: new Date() },
] as unknown as RecentQuery[]);
expect(queries.length).to.equal(1);
});

const optionNames = [
'filter',
'project',
'sort',
'collation',
'hint',
] as const;
for (const name of optionNames) {
it(`maps query for ${name}`, function () {
const queries = getOptionBasedQueries(name, 'recent', savedQueries);

// For filter, we include all the query properties and for the rest
// we only include that specific option.
const queryProperties =
name === 'filter'
? Object.fromEntries(
Object.entries(savedQueries[0]).filter(
([key]) => key !== '_lastExecuted'
)
)
: {
[name]: savedQueries[0][name],
};

expect(queries).to.deep.equal([
{
type: 'recent',
lastExecuted: savedQueries[0]._lastExecuted,
queryProperties,
},
]);
});
}
});
});
109 changes: 78 additions & 31 deletions packages/compass-query-bar/src/components/option-editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,20 @@ import type { RootState } from '../stores/query-bar-store';
import { useAutocompleteFields } from '@mongodb-js/compass-field-store';
import { applyFromHistory } from '../stores/query-bar-reducer';
import { getQueryAttributes } from '../utils';
import type { BaseQuery, QueryFormFields } from '../constants/query-properties';
import type {
BaseQuery,
QueryFormFields,
QueryProperty,
} from '../constants/query-properties';
import { QUERY_PROPERTIES } from '../constants/query-properties';
import { mapQueryToFormFields } from '../utils/query';
import { DEFAULT_FIELD_VALUES } from '../constants/query-bar-store';
import type {
FavoriteQuery,
RecentQuery,
} from '@mongodb-js/my-queries-storage';
import _ from 'lodash';
import type { QueryOptionOfTypeDocument } from '../constants/query-option-definition';

const editorContainerStyles = css({
position: 'relative',
Expand Down Expand Up @@ -88,7 +99,7 @@ const insightsBadgeStyles = css({
});

type OptionEditorProps = {
optionName: string;
optionName: QueryOptionOfTypeDocument;
namespace: string;
id?: string;
hasError?: boolean;
Expand All @@ -107,7 +118,7 @@ type OptionEditorProps = {
insights?: Signal | Signal[];
disabled?: boolean;
savedQueries: SavedQuery[];
onApplyQuery: (query: BaseQuery) => void;
onApplyQuery: (query: BaseQuery, fieldsToPreserve: QueryProperty[]) => void;
};

export const OptionEditor: React.FunctionComponent<OptionEditorProps> = ({
Expand Down Expand Up @@ -166,27 +177,19 @@ export const OptionEditor: React.FunctionComponent<OptionEditorProps> = ({
return isQueryHistoryAutocompleteEnabled
? createQueryWithHistoryAutocompleter({
queryProperty: optionName,
savedQueries: savedQueries
.filter((query) => {
const isOptionNameInQuery =
optionName === 'filter' || optionName in query.queryProperties;
const isUpdateNotInQuery = !('update' in query.queryProperties);
return isOptionNameInQuery && isUpdateNotInQuery;
})
.map((query) => ({
type: query.type,
lastExecuted: query.lastExecuted,
queryProperties: query.queryProperties,
}))
.sort(
(a, b) => a.lastExecuted.getTime() - b.lastExecuted.getTime()
),
savedQueries,
options: {
fields: schemaFields,
serverVersion,
},
onApply: (query: SavedQuery['queryProperties']) => {
onApplyQuery(query);
// When we are applying a query from `filter` field, we want to apply the whole query,
// otherwise we want to preserve the other fields that are already in the current query.
const fieldsToPreserve =
optionName === 'filter'
? []
: QUERY_PROPERTIES.filter((x) => x !== optionName);
onApplyQuery(query, fieldsToPreserve);
if (!query[optionName]) {
return;
}
Expand Down Expand Up @@ -295,25 +298,69 @@ export const OptionEditor: React.FunctionComponent<OptionEditorProps> = ({
);
};

const ConnectedOptionEditor = (state: RootState) => ({
export function getOptionBasedQueries(
optionName: QueryOptionOfTypeDocument,
type: 'recent' | 'favorite',
queries: (RecentQuery | FavoriteQuery)[]
) {
return (
queries
.map((query) => ({
type,
lastExecuted: query._lastExecuted,
// For query that's being autocompeted from the main `filter`, we want to
// show whole query to the user, so that when its applied, it will replace
// the whole query (filter, project, sort etc).
// For other options, we only want to show the query for that specific option.
queryProperties: getQueryAttributes(
optionName !== 'filter' ? { [optionName]: query[optionName] } : query
),
}))
// Filter the query if:
// - its empty
// - its an `update` query
// - its a duplicate
.filter((query, i, arr) => {
const queryIsUpdate = _.has(query.queryProperties, 'update');
const queryIsEmpty = _.isEmpty(query.queryProperties);
if (queryIsEmpty || queryIsUpdate) {
return false;
}
return (
i ===
arr.findIndex(
(t) =>
JSON.stringify(t.queryProperties) ===
JSON.stringify(query.queryProperties)
)
);
})
.sort((a, b) => a.lastExecuted.getTime() - b.lastExecuted.getTime())
);
}

const mapStateToProps = (
state: RootState,
ownProps: Pick<OptionEditorProps, 'optionName'>
) => ({
namespace: state.queryBar.namespace,
serverVersion: state.queryBar.serverVersion,
savedQueries: [
...state.queryBar.recentQueries.map((query) => ({
type: 'recent',
lastExecuted: query._lastExecuted,
queryProperties: getQueryAttributes(query),
})),
...state.queryBar.favoriteQueries.map((query) => ({
type: 'favorite',
lastExecuted: query._lastExecuted,
queryProperties: getQueryAttributes(query),
})),
...getOptionBasedQueries(
ownProps.optionName,
'recent',
state.queryBar.recentQueries
),
...getOptionBasedQueries(
ownProps.optionName,
'favorite',
state.queryBar.favoriteQueries
),
],
});

const mapDispatchToProps = {
onApplyQuery: applyFromHistory,
};

export default connect(ConnectedOptionEditor, mapDispatchToProps)(OptionEditor);
export default connect(mapStateToProps, mapDispatchToProps)(OptionEditor);
Loading
Loading