Skip to content

Commit

Permalink
QueryVariable: Use correct option property for variable options sorti…
Browse files Browse the repository at this point in the history
…ng (#1015)
  • Loading branch information
Sergej-Vlasov authored Jan 2, 2025
1 parent e385790 commit a5f78be
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 34 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -322,9 +322,9 @@ describe.each(['11.1.2', '11.1.1'])('QueryVariable', (v) => {
await lastValueFrom(variable.validateAndUpdate());

expect(variable.state.options).toEqual([
{ label: 'val1', value: 'val1' },
{ label: 'val2', value: 'val2' },
{ label: 'val11', value: 'val11' },
{ label: 'val2', value: 'val2' },
{ label: 'val1', value: 'val1' },
]);
});

Expand All @@ -339,9 +339,9 @@ describe.each(['11.1.2', '11.1.1'])('QueryVariable', (v) => {
await lastValueFrom(variable.validateAndUpdate());

expect(variable.state.options).toEqual([
{ label: 'val11', value: 'val11' },
{ label: 'val2', value: 'val2' },
{ label: 'val1', value: 'val1' },
{ label: 'val2', value: 'val2' },
{ label: 'val11', value: 'val11' },
]);
});

Expand Down
51 changes: 21 additions & 30 deletions packages/scenes/src/variables/variants/query/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,40 +74,11 @@ const getAllMatches = (str: string, regex: RegExp): RegExpExecArray[] => {
return results;
};

export const sortVariableValues = (options: any[], sortOrder: VariableSort) => {
export const sortVariableValues = (options: VariableValueOption[], sortOrder: VariableSort) => {
if (sortOrder === VariableSort.disabled) {
return options;
}

// @ts-ignore
const sortByNumeric = (opt) => {
if (!opt.text) {
return -1;
}
const matches = opt.text.match(/.*?(\d+).*/);
if (!matches || matches.length < 2) {
return -1;
} else {
return parseInt(matches[1], 10);
}
};

// @ts-ignore
const sortByNaturalSort = (options) => {
//@ts-ignore
return options.sort((a, b) => {
if (!a.text) {
return -1;
}

if (!b.text) {
return 1;
}

return a.text.localeCompare(b.text, undefined, { numeric: true });
});
};

switch (sortOrder) {
case VariableSort.alphabeticalAsc:
options = sortBy(options, 'label');
Expand Down Expand Up @@ -146,3 +117,23 @@ export const sortVariableValues = (options: any[], sortOrder: VariableSort) => {
}
return options;
};

function sortByNumeric(opt: VariableValueOption) {
if (!opt.label) {
return -1;
}
const matches = opt.label.match(/.*?(\d+).*/);
if (!matches || matches.length < 2) {
return -1;
} else {
return parseInt(matches[1], 10);
}
}

const collator = new Intl.Collator(undefined, { sensitivity: 'accent', numeric: true });

function sortByNaturalSort(options: VariableValueOption[]) {
return options.slice().sort((a, b) => {
return collator.compare(a.label, b.label);
});
}

0 comments on commit a5f78be

Please sign in to comment.