Skip to content
Closed
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
4 changes: 2 additions & 2 deletions ui-react/src/__tests__/autocomplete-comboboxes.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ describe('StandardVariableCombobox', () => {
expect(screen.getByRole('combobox')).not.toBeDisabled();
});

it('shows selected human-readable description when a value is provided', async () => {
it('shows the humanized title when a value is provided', async () => {
const selected = {
id: 'https://w3id.org/okn/i/mint/sv1',
label: 'Precipitation',
Expand All @@ -99,7 +99,7 @@ describe('StandardVariableCombobox', () => {
});
// Wait for loading to complete
await waitFor(() => {
expect(screen.getByText('Amount of precipitation')).toBeInTheDocument();
expect(screen.getByRole('combobox')).toHaveTextContent('Precipitation');
});
});

Expand Down
56 changes: 25 additions & 31 deletions ui-react/src/components/autocomplete/StandardVariableCombobox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@ import * as React from 'react';
import { Check, ChevronsUpDown, Plus } from 'lucide-react';

import { cn } from '@/lib/utils';
import { humanizeStandardVariable } from '@/lib/standard-variable-grammar';
import {
dedupeStandardVariables,
isUnlabeledStandardVariable,
standardVariableDescription,
standardVariableName,
standardVariableTitle,
} from '@/lib/standard-variable-display';
import { useSemanticSearch } from '@/hooks/useSemanticSearch';
import { Button } from '@/components/ui/button';
Expand Down Expand Up @@ -127,16 +127,27 @@ export function StandardVariableCombobox({

const options = narrowed && !showAll ? scoped : all;
const semanticSearch = useSemanticSearch(search, { target: 'svo', limit: 50 });
const semanticOptions = React.useMemo(
() =>
semanticSearch.results?.map((result) => ({
const knownById = React.useMemo(
() => new Map([...all, ...scoped].map((o) => [o.id, o])),
[all, scoped],
);
const semanticOptions = React.useMemo(() => {
if (!semanticSearch.results) return null;
// The service can answer with an empty label (or only a description) for a
// row the catalog names; take the catalog's label so the option has a title.
const mapped = semanticSearch.results.map((result) => {
const known = knownById.get(result.id);
return {
id: result.id,
label: result.label ?? '',
description: result.description ?? null,
label: result.label?.trim() || known?.label || '',
description: result.description ?? known?.description ?? null,
models: Array.isArray(result.models) ? result.models : [],
})) ?? null,
[semanticSearch.results],
);
};
});
// One row per id, and one per label: the service can return the same
// variable under a catalog id and under an adapter URI.
return dedupeStandardVariables(mapped, { byLabel: true });
}, [semanticSearch.results, knownById]);

/**
* Semantic results are ranked over the whole catalog, so the scope has to be
Expand All @@ -160,7 +171,7 @@ export function StandardVariableCombobox({
* a control that reads as empty.
*/
const visibleOptions = React.useMemo(() => {
const listed = rankedOptions ?? options;
const listed = dedupeStandardVariables(rankedOptions ?? options);
const base = requireLabel ? listed.filter((o) => !isUnlabeledStandardVariable(o)) : listed;
// Semantic search results already have a query-specific ranking. Apply the
// task/goal ranking only to the unfiltered catalog list.
Expand Down Expand Up @@ -196,15 +207,7 @@ export function StandardVariableCombobox({
[value, visibleOptions, all, onChange],
);

const triggerLabel = !value
? placeholder
: (standardVariableDescription(value) ??
(isUnlabeledStandardVariable(value)
? standardVariableName(value)
: (() => {
const { phenomenon, property } = humanizeStandardVariable(value.label);
return phenomenon ? `${phenomenon} — ${property}` : property;
})()));
const triggerLabel = !value ? placeholder : standardVariableTitle(value);

return (
<>
Expand Down Expand Up @@ -270,21 +273,12 @@ export function StandardVariableCombobox({
)}
/>
<div className="flex min-w-0 flex-col">
<span className="line-clamp-1 font-medium">{standardVariableTitle(sv)}</span>
{standardVariableDescription(sv) && (
<span className="line-clamp-1 font-medium">
<span className="line-clamp-1 text-xs text-muted-foreground">
{standardVariableDescription(sv)}
</span>
)}
<span
className={cn(
'line-clamp-1',
standardVariableDescription(sv) || !isUnlabeledStandardVariable(sv)
? 'text-xs text-muted-foreground'
: 'font-medium',
)}
>
{standardVariableName(sv)}
</span>
{!!sv.models?.length && (
<span className="line-clamp-1 text-[11px] text-muted-foreground/80">
{sv.models
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ describe('StandardVariableCombobox create', () => {
description: null,
}),
);
expect(screen.getByRole('combobox')).toHaveTextContent(/zzz_new/i);
expect(screen.getByRole('combobox')).toHaveTextContent(/zzz new/i);
});

it('does not offer create unless asked to', async () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
/**
* Every option leads with a readable title (the humanized label), shows its
* description as smaller secondary text, and is listed once.
*/
import { MockedProvider } from '@apollo/client/testing';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { beforeEach, describe, expect, it, vi } from 'vitest';

import { StandardVariableCombobox } from '@/components/autocomplete/StandardVariableCombobox';
import { IndicatorAdapterInferenceDocument } from '@/components/autocomplete/useScopedStandardVariables';
import {
GetIndicatorVariableOptionsDocument,
PrefetchReferenceDataDocument,
} from '@/graphql/generated/graphql';

const semantic = vi.hoisted(() => ({
results: null as Array<{
id: string;
label?: string | null;
description?: string | null;
}> | null,
}));
vi.mock('@/hooks/useSemanticSearch', () => ({
useSemanticSearch: (query: string) => ({
results: query.trim() ? semantic.results : null,
loading: false,
error: null,
}),
}));

const sv = (id: string, label: string | null, description: string | null = null) => ({
__typename: 'modelcatalog_standard_variable',
id,
label,
description,
});

const TERM_COUNT = 'https://w3id.org/okn/i/mint/document_lexicon_group__term_count';
const DESCRIPTION = "For each document and lexicon group, how often the group's terms occur.";

const catalogMock = {
request: { query: PrefetchReferenceDataDocument },
result: {
data: {
modelcatalog_standard_variable: [
sv(TERM_COUNT, 'document_lexicon_group__term_count', DESCRIPTION),
],
modelcatalog_unit: [],
},
},
};

async function open(mocks: unknown[]) {
render(
<MockedProvider mocks={mocks as never[]}>
<StandardVariableCombobox value={null} onChange={() => {}} scope="all" />
</MockedProvider>,
);
await userEvent.click(await screen.findByRole('combobox'));
}

describe('StandardVariableCombobox option titles and repeats', () => {
beforeEach(() => {
semantic.results = null;
});

it('leads with the humanized label and keeps the description as secondary text', async () => {
await open([catalogMock]);
const title = await screen.findByText('Document lexicon group — Term count');
expect(title).toHaveClass('font-medium');
const description = screen.getByText(DESCRIPTION);
expect(description).toHaveClass('text-xs', 'line-clamp-1');
expect(screen.getAllByRole('option')).toHaveLength(1);
});

it('gives a search hit with no label the catalog title, and lists each variable once', async () => {
// The service answers with an empty label, then again under the same id.
semantic.results = [
{ id: TERM_COUNT, label: '', description: DESCRIPTION },
{ id: TERM_COUNT, label: 'document_lexicon_group__term_count', description: null },
];
await open([catalogMock]);
await userEvent.type(screen.getByPlaceholderText(/search standard variables/i), 'term');
await waitFor(() => expect(screen.getAllByRole('option')).toHaveLength(1));
expect(screen.getByText('Document lexicon group — Term count')).toBeInTheDocument();
});

it('titles a search hit that has only an id from the id tail', async () => {
semantic.results = [{ id: 'https://w3id.org/okn/i/mint/air__daily_max_of_temperature' }];
await open([catalogMock]);
await userEvent.type(screen.getByPlaceholderText(/search standard variables/i), 'air');
expect(await screen.findByText('Air — Daily max of temperature')).toBeInTheDocument();
});

it('lists a variable once when the catalog and an adapter contract both name it', async () => {
const ID = 'https://w3id.org/okn/i/mint/air__daily_max_of_temperature';
const mocks = [
{
request: { query: GetIndicatorVariableOptionsDocument },
result: {
data: {
modelcatalog_dataset_specification_presentation: [
{
__typename: 'modelcatalog_dataset_specification_presentation',
dataset_specification_id: 'ds',
presentation_id: 'p',
presentation: {
__typename: 'modelcatalog_variable_presentation',
id: 'p',
standard_variable: sv(
'catalog-uuid-1',
'air__daily_max_of_temperature',
'Daily max',
),
},
},
],
},
},
},
{
request: { query: IndicatorAdapterInferenceDocument },
result: {
data: {
adapterTransforms: [
{ contracts: [{ role: 'output', standard_variable_uri: ID, format: null }] },
],
},
},
},
];
render(
<MockedProvider mocks={mocks as never[]}>
<StandardVariableCombobox value={null} onChange={() => {}} scope="indicator" />
</MockedProvider>,
);
await waitFor(() => expect(screen.getByRole('combobox')).toBeEnabled());
await userEvent.click(screen.getByRole('combobox'));
expect(await screen.findByText('Air — Daily max of temperature')).toBeInTheDocument();
expect(screen.getAllByRole('option')).toHaveLength(1);
expect(screen.getByText('Daily max')).toBeInTheDocument();
});
});
Loading
Loading