You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by ru...@apache.org on 2026/07/20 16:42:59 UTC
(superset) branch master updated: fix(native-filters): support double-quote escaping for comma in filte… (#39068)
This is an automated email from the ASF dual-hosted git repository.
rusackas pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/superset.git
The following commit(s) were added to refs/heads/master by this push:
new 3a3f087869c fix(native-filters): support double-quote escaping for comma in filte… (#39068)
3a3f087869c is described below
commit 3a3f087869c03b12762fae53162fcdeef9a8db25
Author: Jean Massucatto <ma...@gmail.com>
AuthorDate: Mon Jul 20 13:42:52 2026 -0300
fix(native-filters): support double-quote escaping for comma in filte… (#39068)
Co-authored-by: Evan <ev...@preset.io>
Co-authored-by: Claude Opus 4.8 <no...@anthropic.com>
---
.../src/shared-controls/dndControls.tsx | 4 +-
.../src/components/Select/AsyncSelect.tsx | 87 ++++++++++---
.../src/components/Select/Select.test.tsx | 87 +++++++++++++
.../src/components/Select/Select.tsx | 86 ++++++++++---
.../src/components/Select/utils.test.ts | 140 +++++++++++++++++++++
.../src/components/Select/utils.tsx | 75 ++++++++++-
.../FilterBar/FilterControls/FilterControl.tsx | 10 ++
.../components/Select/SelectFilterPlugin.tsx | 8 +-
8 files changed, 457 insertions(+), 40 deletions(-)
diff --git a/superset-frontend/packages/superset-ui-chart-controls/src/shared-controls/dndControls.tsx b/superset-frontend/packages/superset-ui-chart-controls/src/shared-controls/dndControls.tsx
index 807c698f83d..9abd97c234d 100644
--- a/superset-frontend/packages/superset-ui-chart-controls/src/shared-controls/dndControls.tsx
+++ b/superset-frontend/packages/superset-ui-chart-controls/src/shared-controls/dndControls.tsx
@@ -152,7 +152,9 @@ export const dndAdhocFilterControl: SharedControlConfig<
type: 'DndFilterSelect',
label: t('Filters'),
default: [],
- description: '',
+ description: t(
+ 'Add columns to filter by. When typing or pasting filter values, commas will separate values into multiple entries. To include a comma within a value, wrap it in double quotes: "San Francisco, CA"',
+ ),
mapStateToProps: ({ datasource, form_data }) => ({
columns: isDataset(datasource)
? datasource.columns.filter(c => c.filterable)
diff --git a/superset-frontend/packages/superset-ui-core/src/components/Select/AsyncSelect.tsx b/superset-frontend/packages/superset-ui-core/src/components/Select/AsyncSelect.tsx
index 35e6c887886..61e944cb5ae 100644
--- a/superset-frontend/packages/superset-ui-core/src/components/Select/AsyncSelect.tsx
+++ b/superset-frontend/packages/superset-ui-core/src/components/Select/AsyncSelect.tsx
@@ -57,9 +57,12 @@ import {
getSuffixIcon,
dropDownRenderHelper,
handleFilterOptionHelper,
+ makeQuoteAwareTokenizer,
mapOptions,
getOption,
isObject,
+ splitWithQuoteEscaping,
+ stripSurroundingQuotes,
isEqual as utilsIsEqual,
} from './utils';
import {
@@ -173,6 +176,21 @@ const AsyncSelect = forwardRef(
// request is still pending.
const inFlightFetchesRef = useRef(0);
const mappedMode = isSingleMode ? undefined : 'multiple';
+
+ const reconcileTokensRef = useRef<(tokens: string[]) => void>(() => {});
+ const fullSelectOptionsRef = useRef<SelectOptionsType>(EMPTY_OPTIONS);
+
+ const quoteAwareTokenSeparators = useMemo(() => {
+ const tokenize = makeQuoteAwareTokenizer(tokenSeparators);
+ return (input: string) => {
+ const tokens = tokenize(input);
+ if (tokens.length !== 1 || tokens[0] !== input) {
+ reconcileTokensRef.current(tokens);
+ }
+ return tokens;
+ };
+ }, [tokenSeparators]);
+
const allowFetch = !fetchOnlyOnSearch || inputValue;
const [maxTagCount, setMaxTagCount] = useState(
propsMaxTagCount ?? MAX_TAG_COUNT,
@@ -281,6 +299,39 @@ const AsyncSelect = forwardRef(
onSelect?.(selectedItem, option);
};
+ // The underlying Select silently drops tokens it cannot match against the
+ // rendered options. That happens whenever tokenization outpaces the
+ // debounced option registration, e.g. dead-key keyboard layouts deliver a
+ // closing quote and a separator in a single input event.
+ reconcileTokensRef.current = (tokens: string[]) => {
+ if (isSingleMode || !allowNewOptions) {
+ return;
+ }
+ setTimeout(() => {
+ tokens.forEach(token => {
+ const matched = getOption(token, fullSelectOptionsRef.current, true);
+ const matchedValue = isObject(matched) ? matched.value : matched;
+ if (hasOption(matchedValue ?? token, selectValueRef.current)) {
+ return;
+ }
+ const option = isObject(matched)
+ ? (matched as AntdLabeledValue)
+ : { label: token, value: token, isNewOption: true };
+ if (!matched) {
+ setSelectOptions(previous =>
+ hasOption(token, previous, true)
+ ? previous
+ : [option, ...previous],
+ );
+ }
+ handleOnSelect(
+ { label: option.label, value: option.value } as AntdLabeledValue,
+ option as AntdLabeledValue,
+ );
+ });
+ });
+ };
+
const handleOnDeselect: SelectProps['onDeselect'] = (value, option) => {
if (Array.isArray(selectValue)) {
if (isLabeledValue(value)) {
@@ -318,6 +369,8 @@ const AsyncSelect = forwardRef(
[onError],
);
+ fullSelectOptionsRef.current = fullSelectOptions;
+
const mergeData = useCallback(
(data: SelectOptionsType) => {
let mergedData: SelectOptionsType = [];
@@ -394,6 +447,14 @@ const AsyncSelect = forwardRef(
initialOptionsRef.current = accumulated;
if (!fetchOnlyOnSearch && accumulated.length >= totalCount) {
setAllValuesLoaded(true);
+ // Once every base value is loaded, searches are served by
+ // client-side filtering (fetchPage short-circuits), so the
+ // full set must reach the live options even when this
+ // response lands mid-search — otherwise the dropdown stays
+ // empty for the active search.
+ if (!matchesCurrentSearch) {
+ mergeData(accumulated);
+ }
}
fetchedQueries.current.set(key, totalCount);
if (matchesCurrentSearch) {
@@ -455,10 +516,11 @@ const AsyncSelect = forwardRef(
const handleOnSearch = debounce((search: string) => {
const searchValue = search.trim();
if (allowNewOptions) {
- const newOption = searchValue &&
- !hasOption(searchValue, fullSelectOptions, true) && {
- label: searchValue,
- value: searchValue,
+ const unquotedSearch = stripSurroundingQuotes(searchValue);
+ const newOption = unquotedSearch &&
+ !hasOption(unquotedSearch, fullSelectOptions, true) && {
+ label: unquotedSearch,
+ value: unquotedSearch,
isNewOption: true,
};
const cleanSelectOptions = fullSelectOptions.filter(
@@ -695,22 +757,11 @@ const AsyncSelect = forwardRef(
setSelectValue(value);
}
} else {
- // antd v6 widened `tokenSeparators` to `string[] | (input => string[])`;
- // Superset always uses the array form.
+ // Superset's prop is the array form; antd receives the function form
const separators = Array.isArray(tokenSeparators)
? tokenSeparators
: [];
- const token = separators.find((token: string) =>
- pastedText.includes(token),
- );
- const array = token
- ? uniq(
- pastedText
- .split(token)
- .map(s => s.trim())
- .filter(Boolean),
- )
- : [pastedText.trim()].filter(Boolean);
+ const array = uniq(splitWithQuoteEscaping(pastedText, separators));
const values = (
await Promise.all(array.map(item => getPastedTextValue(item)))
).filter(item => item !== undefined) as AntdLabeledValue[];
@@ -791,7 +842,7 @@ const AsyncSelect = forwardRef(
optionRender={option => <Space>{option.label || option.value}</Space>}
placeholder={placeholder}
showSearch={shouldShowSearch}
- tokenSeparators={tokenSeparators}
+ tokenSeparators={quoteAwareTokenSeparators}
builtinPlacements={DROPDOWN_BUILTIN_PLACEMENTS}
value={selectValue}
suffixIcon={getSuffixIcon(
diff --git a/superset-frontend/packages/superset-ui-core/src/components/Select/Select.test.tsx b/superset-frontend/packages/superset-ui-core/src/components/Select/Select.test.tsx
index 08a8fb7c345..f2afddd882b 100644
--- a/superset-frontend/packages/superset-ui-core/src/components/Select/Select.test.tsx
+++ b/superset-frontend/packages/superset-ui-core/src/components/Select/Select.test.tsx
@@ -390,6 +390,93 @@ test('removes duplicated values', async () => {
expect(values[3]).toHaveTextContent('d');
});
+test('typing an unquoted comma splits the value into a chip', async () => {
+ render(<Select {...defaultProps} mode="multiple" allowNewOptions />);
+ await type('Australia');
+ expect(await findSelectOption('Australia')).toBeInTheDocument();
+ await type(',', undefined, false);
+ const values = await findAllSelectValues();
+ expect(values.length).toBe(1);
+ expect(values[0]).toHaveTextContent('Australia');
+});
+
+test('closing quote and separator arriving in a single input event still create the chip', async () => {
+ render(<Select {...defaultProps} mode="multiple" allowNewOptions />);
+ await open();
+ await type('"Australia, U');
+ // dead-key keyboard layouts deliver the closing quote together with the
+ // next character in one input event
+ fireEvent.change(getSelect(), { target: { value: '"Australia, US",' } });
+ await waitFor(() =>
+ expect(getElementsByClassName('.ant-select-selection-item')).toHaveLength(
+ 1,
+ ),
+ );
+ expect(getElementByClassName('.ant-select-selection-item')).toHaveTextContent(
+ 'Australia, US',
+ );
+});
+
+test('an options prop update mid-typing keeps the created option tokenizable', async () => {
+ const { rerender } = render(
+ <Select {...defaultProps} mode="multiple" allowNewOptions />,
+ );
+ await type('"Australia, US"');
+ expect(await findSelectOption('Australia, US')).toBeInTheDocument();
+ rerender(
+ <Select
+ {...defaultProps}
+ options={[...OPTIONS]}
+ mode="multiple"
+ allowNewOptions
+ />,
+ );
+ await type(',', undefined, false);
+ await waitFor(() =>
+ expect(getElementsByClassName('.ant-select-selection-item')).toHaveLength(
+ 1,
+ ),
+ );
+ expect(getElementByClassName('.ant-select-selection-item')).toHaveTextContent(
+ 'Australia, US',
+ );
+});
+
+test('typing a comma inside double quotes keeps the value as a single chip', async () => {
+ render(<Select {...defaultProps} mode="multiple" allowNewOptions />);
+ await type('"Australia, US"');
+ expect(await findSelectOption('Australia, US')).toBeInTheDocument();
+ await type(',', undefined, false);
+ const values = await findAllSelectValues();
+ expect(values.length).toBe(1);
+ expect(values[0]).toHaveTextContent('Australia, US');
+});
+
+test('prevents the default paste action when pasted values are consumed', async () => {
+ render(<Select {...defaultProps} mode="multiple" allowNewOptions />);
+ const input = getElementByClassName('.ant-select-input');
+ const paste = createEvent.paste(input, {
+ clipboardData: {
+ getData: () => `${OPTIONS[0].label},${OPTIONS[1].label}`,
+ },
+ });
+ fireEvent(input, paste);
+ await findAllSelectValues();
+ expect(paste.defaultPrevented).toBe(true);
+});
+
+test('allows the default paste action when nothing is consumable', async () => {
+ render(<Select {...defaultProps} mode="multiple" />);
+ const input = getElementByClassName('.ant-select-input');
+ const paste = createEvent.paste(input, {
+ clipboardData: {
+ getData: () => 'zzz,yyy',
+ },
+ });
+ fireEvent(input, paste);
+ expect(paste.defaultPrevented).toBe(false);
+});
+
test('trims whitespace from pasted comma-separated values', async () => {
render(<Select {...defaultProps} mode="multiple" allowNewOptions />);
const input = getElementByClassName('.ant-select-input');
diff --git a/superset-frontend/packages/superset-ui-core/src/components/Select/Select.tsx b/superset-frontend/packages/superset-ui-core/src/components/Select/Select.tsx
index bc7578fc864..0532615c5db 100644
--- a/superset-frontend/packages/superset-ui-core/src/components/Select/Select.tsx
+++ b/superset-frontend/packages/superset-ui-core/src/components/Select/Select.tsx
@@ -49,10 +49,13 @@ import {
hasOption,
isLabeledValue,
isObject,
+ makeQuoteAwareTokenizer,
mapOptions,
mapValues,
sortComparatorWithSearchHelper,
sortSelectedFirstHelper,
+ splitWithQuoteEscaping,
+ stripSurroundingQuotes,
isEqual as utilsIsEqual,
} from './utils';
import { RawValue, SelectOptionsType, SelectProps } from './types';
@@ -192,6 +195,19 @@ const Select = forwardRef(
const mappedMode = isSingleMode ? undefined : 'multiple';
+ const reconcileTokensRef = useRef<(tokens: string[]) => void>(() => {});
+
+ const quoteAwareTokenSeparators = useMemo(() => {
+ const tokenize = makeQuoteAwareTokenizer(tokenSeparators);
+ return (input: string) => {
+ const tokens = tokenize(input);
+ if (tokens.length !== 1 || tokens[0] !== input) {
+ reconcileTokensRef.current(tokens);
+ }
+ return tokens;
+ };
+ }, [tokenSeparators]);
+
const sortSelectedFirst = useCallback(
(a: AntdLabeledValue, b: AntdLabeledValue) =>
sortSelectedFirstHelper(a, b, selectValue),
@@ -267,6 +283,11 @@ const Select = forwardRef(
);
}, [selectOptions, selectValue, sortSelectedFirst]);
+ const fullSelectOptionsRef = useRef(fullSelectOptions);
+ fullSelectOptionsRef.current = fullSelectOptions;
+ const selectValueRef = useRef(selectValue);
+ selectValueRef.current = selectValue;
+
const enabledOptions = useMemo(
() => visibleOptions.filter(option => !option.disabled),
[visibleOptions],
@@ -366,6 +387,42 @@ const Select = forwardRef(
onSelect?.(selectedItem, option);
};
+ // The underlying Select silently drops tokens it cannot match against the
+ // rendered options. That happens whenever tokenization outpaces the
+ // debounced option registration, e.g. dead-key keyboard layouts deliver a
+ // closing quote and a separator in a single input event.
+ reconcileTokensRef.current = (tokens: string[]) => {
+ if (isSingleMode || !allowNewOptions) {
+ return;
+ }
+ setTimeout(() => {
+ tokens.forEach(token => {
+ const matched = getOption(token, fullSelectOptionsRef.current, true);
+ const matchedValue = isObject(matched) ? matched.value : matched;
+ if (hasOption(matchedValue ?? token, selectValueRef.current)) {
+ return;
+ }
+ const option = isObject(matched)
+ ? (matched as AntdLabeledValue)
+ : { label: token, value: token, isNewOption: true };
+ if (!matched) {
+ const addOption = (previous: SelectOptionsType) =>
+ hasOption(token, previous, true)
+ ? previous
+ : [option, ...previous];
+ setSelectOptions(addOption);
+ setVisibleOptions(addOption);
+ }
+ handleOnSelect(
+ (labelInValue
+ ? { label: option.label, value: option.value }
+ : option.value) as string | AntdLabeledValue,
+ option as AntdLabeledValue,
+ );
+ });
+ });
+ };
+
const clear = () => {
if (isSingleMode) {
setSelectValue(undefined);
@@ -424,12 +481,14 @@ const Select = forwardRef(
const optionsWithoutTemporary = ensureIsArray(fullSelectOptions).filter(
opt => !opt.isNewOption,
);
+ const unquotedSearch = stripSurroundingQuotes(searchValue);
const shouldCreateNewOption =
- searchValue && !hasOption(searchValue, optionsWithoutTemporary, true);
+ unquotedSearch &&
+ !hasOption(unquotedSearch, optionsWithoutTemporary, true);
const newOption = shouldCreateNewOption && {
- label: searchValue,
- value: searchValue,
+ label: unquotedSearch,
+ value: unquotedSearch,
isNewOption: true,
};
const cleanSelectOptions = ensureIsArray(fullSelectOptions).filter(
@@ -721,22 +780,11 @@ const Select = forwardRef(
setSelectValue(value);
}
} else {
- // antd v6 widened `tokenSeparators` to `string[] | (input => string[])`;
- // Superset always uses the array form.
+ // Superset's prop is the array form; antd receives the function form
const separators = Array.isArray(tokenSeparators)
? tokenSeparators
: [];
- const token = separators.find((token: string) =>
- pastedText.includes(token),
- );
- const array = token
- ? uniq(
- pastedText
- .split(token)
- .map(item => item.trim())
- .filter(Boolean),
- )
- : [pastedText.trim()].filter(Boolean);
+ const array = uniq(splitWithQuoteEscaping(pastedText, separators));
const newOptions: SelectOptionsType = [];
// When `allowNewOptionsOnPaste` is set, accept pasted values that are
@@ -762,6 +810,10 @@ const Select = forwardRef(
})
.filter(item => item !== undefined);
+ if (values.length > 0) {
+ e.preventDefault();
+ }
+
if (newOptions.length > 0) {
const updatedOptions = [...fullSelectOptions, ...newOptions];
setSelectOptions(updatedOptions);
@@ -854,7 +906,7 @@ const Select = forwardRef(
}
onClear={handleClear}
placeholder={placeholder}
- tokenSeparators={tokenSeparators}
+ tokenSeparators={quoteAwareTokenSeparators}
value={selectValue}
virtual={
virtual !== undefined
diff --git a/superset-frontend/packages/superset-ui-core/src/components/Select/utils.test.ts b/superset-frontend/packages/superset-ui-core/src/components/Select/utils.test.ts
new file mode 100644
index 00000000000..3443bb00017
--- /dev/null
+++ b/superset-frontend/packages/superset-ui-core/src/components/Select/utils.test.ts
@@ -0,0 +1,140 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import {
+ splitWithQuoteEscaping,
+ stripSurroundingQuotes,
+ makeQuoteAwareTokenizer,
+} from './utils';
+
+test('stripSurroundingQuotes removes matching surrounding double quotes', () => {
+ expect(stripSurroundingQuotes('"foo"')).toBe('foo');
+});
+
+test('stripSurroundingQuotes trims whitespace before stripping', () => {
+ expect(stripSurroundingQuotes(' "foo" ')).toBe('foo');
+});
+
+test('stripSurroundingQuotes leaves text untouched when only one side is quoted', () => {
+ expect(stripSurroundingQuotes('"foo')).toBe('"foo');
+ expect(stripSurroundingQuotes('foo"')).toBe('foo"');
+});
+
+test('stripSurroundingQuotes preserves quotes in the middle of the string', () => {
+ expect(stripSurroundingQuotes('a"b"c')).toBe('a"b"c');
+});
+
+test('stripSurroundingQuotes returns an empty string for `""`', () => {
+ expect(stripSurroundingQuotes('""')).toBe('');
+});
+
+test('stripSurroundingQuotes does not strip a single lone quote', () => {
+ expect(stripSurroundingQuotes('"')).toBe('"');
+});
+
+test('stripSurroundingQuotes returns an empty string for empty/whitespace input', () => {
+ expect(stripSurroundingQuotes('')).toBe('');
+ expect(stripSurroundingQuotes(' ')).toBe('');
+});
+
+test('stripSurroundingQuotes unescapes doubled quotes when stripping', () => {
+ expect(stripSurroundingQuotes('"Bob ""The Builder"", Inc"')).toBe(
+ 'Bob "The Builder", Inc',
+ );
+ expect(stripSurroundingQuotes('"a""b"')).toBe('a"b');
+});
+
+test('splitWithQuoteEscaping splits by separator and trims tokens', () => {
+ expect(splitWithQuoteEscaping('a, b ,c', [','])).toEqual(['a', 'b', 'c']);
+});
+
+test('splitWithQuoteEscaping treats doubled quotes inside a quoted region as a literal quote', () => {
+ expect(splitWithQuoteEscaping('"Bob ""The Builder"", Inc"', [','])).toEqual([
+ 'Bob "The Builder", Inc',
+ ]);
+ expect(splitWithQuoteEscaping('"a ""b""",c', [','])).toEqual(['a "b"', 'c']);
+});
+
+test('splitWithQuoteEscaping preserves separator characters inside double quotes', () => {
+ expect(splitWithQuoteEscaping('"a, b",c', [','])).toEqual(['a, b', 'c']);
+});
+
+test('splitWithQuoteEscaping strips quote characters from the output tokens', () => {
+ expect(splitWithQuoteEscaping('"foo","bar"', [','])).toEqual(['foo', 'bar']);
+});
+
+test('splitWithQuoteEscaping drops empty tokens from adjacent or edge separators', () => {
+ expect(splitWithQuoteEscaping('a,,b', [','])).toEqual(['a', 'b']);
+ expect(splitWithQuoteEscaping(',a,b,', [','])).toEqual(['a', 'b']);
+});
+
+test('splitWithQuoteEscaping treats unclosed quotes as opening a region that runs to end', () => {
+ expect(splitWithQuoteEscaping('"a, b', [','])).toEqual(['a, b']);
+});
+
+test('splitWithQuoteEscaping returns the original text when no separator is present', () => {
+ expect(splitWithQuoteEscaping('hello world', [','])).toEqual(['hello world']);
+});
+
+test('splitWithQuoteEscaping strips surrounding quotes when no separator is present', () => {
+ expect(splitWithQuoteEscaping('"Canada"', [','])).toEqual(['Canada']);
+ expect(splitWithQuoteEscaping('"Bob ""B"""', [','])).toEqual(['Bob "B"']);
+});
+
+test('splitWithQuoteEscaping uses the first separator from the list that appears in the text', () => {
+ expect(splitWithQuoteEscaping('a;b,c', [',', ';'])).toEqual(['a;b', 'c']);
+ expect(splitWithQuoteEscaping('a;b', [',', ';'])).toEqual(['a', 'b']);
+});
+
+test('splitWithQuoteEscaping supports multi-character separators', () => {
+ expect(splitWithQuoteEscaping('a, b, c', [', '])).toEqual(['a', 'b', 'c']);
+});
+
+test('makeQuoteAwareTokenizer returns input unchanged while quotes are open', () => {
+ const tokenize = makeQuoteAwareTokenizer([',']);
+ expect(tokenize('"Australia, US')).toEqual(['"Australia, US']);
+});
+
+test('makeQuoteAwareTokenizer returns input unchanged when separators only appear inside quotes', () => {
+ const tokenize = makeQuoteAwareTokenizer([',']);
+ expect(tokenize('"Australia, US"')).toEqual(['"Australia, US"']);
+});
+
+test('makeQuoteAwareTokenizer returns input unchanged when no separator is present', () => {
+ const tokenize = makeQuoteAwareTokenizer([',']);
+ expect(tokenize('Australia')).toEqual(['Australia']);
+});
+
+test('makeQuoteAwareTokenizer splits on a trailing unquoted separator', () => {
+ const tokenize = makeQuoteAwareTokenizer([',']);
+ expect(tokenize('Australia,')).toEqual(['Australia']);
+});
+
+test('makeQuoteAwareTokenizer splits mixed quoted and unquoted values', () => {
+ const tokenize = makeQuoteAwareTokenizer([',']);
+ expect(tokenize('"Australia, Austria",Canada')).toEqual([
+ 'Australia, Austria',
+ 'Canada',
+ ]);
+});
+
+test('makeQuoteAwareTokenizer detects any separator from the list outside quotes', () => {
+ const tokenize = makeQuoteAwareTokenizer([',', '\n']);
+ expect(tokenize('a\nb')).toEqual(['a', 'b']);
+ expect(tokenize('"a\nb"')).toEqual(['"a\nb"']);
+});
diff --git a/superset-frontend/packages/superset-ui-core/src/components/Select/utils.tsx b/superset-frontend/packages/superset-ui-core/src/components/Select/utils.tsx
index 2f245cb9ab7..4ae9ef93a75 100644
--- a/superset-frontend/packages/superset-ui-core/src/components/Select/utils.tsx
+++ b/superset-frontend/packages/superset-ui-core/src/components/Select/utils.tsx
@@ -201,6 +201,15 @@ export const dropDownRenderHelper = (
);
};
+// Strips surrounding double quotes from a string, e.g. `"foo"` → `foo`.
+export function stripSurroundingQuotes(text: string): string {
+ const trimmed = text.trim();
+ if (trimmed.length > 1 && trimmed.startsWith('"') && trimmed.endsWith('"')) {
+ return trimmed.slice(1, -1).replace(/""/g, '"');
+ }
+ return trimmed;
+}
+
export const handleFilterOptionHelper = (
search: string,
option: AntdLabeledValue,
@@ -216,7 +225,7 @@ export const handleFilterOptionHelper = (
}
if (filterOption) {
- const searchValue = search.trim().toLowerCase();
+ const searchValue = stripSurroundingQuotes(search).toLowerCase();
if (optionFilterProps?.length) {
return optionFilterProps.some(prop => {
const optionProp = option?.[prop as keyof CustomLabeledValue]
@@ -250,3 +259,67 @@ export const mapOptions = (values: SelectOptionsType): Record<string, any>[] =>
key: opt.value,
...opt,
}));
+
+// Splits text by separators, preserving commas inside double quotes.
+export function splitWithQuoteEscaping(
+ text: string,
+ separators: string[],
+): string[] {
+ const separator = separators.find(sep => text.includes(sep));
+ if (!separator) {
+ return [stripSurroundingQuotes(text)].filter(Boolean);
+ }
+
+ const results: string[] = [];
+ let current = '';
+ let inQuotes = false;
+
+ for (let i = 0; i < text.length; i += 1) {
+ const char = text[i];
+
+ if (char === '"') {
+ if (inQuotes && text[i + 1] === '"') {
+ current += '"';
+ i += 1;
+ } else {
+ inQuotes = !inQuotes;
+ }
+ } else if (!inQuotes && text.startsWith(separator, i)) {
+ results.push(current.trim());
+ current = '';
+ i += separator.length - 1;
+ } else {
+ current += char;
+ }
+ }
+
+ if (current.trim()) {
+ results.push(current.trim());
+ }
+
+ return results.filter(Boolean);
+}
+
+function hasUnquotedSeparator(text: string, separators: string[]): boolean {
+ let inQuotes = false;
+ for (let i = 0; i < text.length; i += 1) {
+ if (text[i] === '"') {
+ inQuotes = !inQuotes;
+ } else if (!inQuotes && separators.some(sep => text.startsWith(sep, i))) {
+ return true;
+ }
+ }
+ return false;
+}
+
+// Quote-aware tokenizer for antd's function form of `tokenSeparators`.
+// Returning the input unchanged tells the Select not to tokenize, so typing
+// continues while quotes are open or separators only appear inside them.
+export function makeQuoteAwareTokenizer(
+ separators: string[],
+): (input: string) => string[] {
+ return (input: string) =>
+ hasUnquotedSeparator(input, separators)
+ ? splitWithQuoteEscaping(input, separators)
+ : [input];
+}
diff --git a/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/FilterControls/FilterControl.tsx b/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/FilterControls/FilterControl.tsx
index 6c95cc4a28f..6ae74668498 100644
--- a/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/FilterControls/FilterControl.tsx
+++ b/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/FilterControls/FilterControl.tsx
@@ -25,6 +25,7 @@ import {
import { FilterBarOrientation } from 'src/dashboard/types';
import { isChartCustomization } from '@superset-ui/core';
import { ChartCustomizationPlugins } from 'src/constants';
+import { t } from '@apache-superset/core/translation';
import { checkIsMissingRequiredValue } from '../utils';
import FilterValue from './FilterValue';
import { FilterCard } from '../../FilterCard';
@@ -84,6 +85,14 @@ const FilterControl = ({
{name}
</FilterControlTitle>
{isRequired && <RequiredFieldIndicator />}
+ {filter.filterType === 'filter_select' &&
+ filter.controlValues?.multiSelect && (
+ <DescriptionToolTip
+ description={t(
+ 'When typing or pasting filter values, commas will separate values into multiple entries. To include a comma within a value, wrap it in double quotes: "San Francisco, CA"',
+ )}
+ />
+ )}
{filter.description?.trim() && (
<DescriptionToolTip description={filter.description} />
)}
@@ -101,6 +110,7 @@ const FilterControl = ({
isRequired,
filter.description,
filter.filterType,
+ filter.controlValues?.multiSelect,
icon,
],
);
diff --git a/superset-frontend/src/filters/components/Select/SelectFilterPlugin.tsx b/superset-frontend/src/filters/components/Select/SelectFilterPlugin.tsx
index d6b32dd0abf..09660563895 100644
--- a/superset-frontend/src/filters/components/Select/SelectFilterPlugin.tsx
+++ b/superset-frontend/src/filters/components/Select/SelectFilterPlugin.tsx
@@ -43,6 +43,7 @@ import {
import {
hasOption,
propertyComparator,
+ stripSurroundingQuotes,
} from '@superset-ui/core/components/Select/utils';
import { FilterBarOrientation } from 'src/dashboard/types';
import { getDataRecordFormatter, getSelectExtraFormData } from '../../utils';
@@ -330,14 +331,15 @@ export default function PluginFilterSelect(props: PluginFilterSelectProps) {
}, [data, datatype, col, labelFormatter, creatable, filterState.value]);
const options = useMemo(() => {
+ const unquotedSearch = stripSurroundingQuotes(search);
if (
- search &&
+ unquotedSearch &&
!searchAllOptions &&
creatable !== false &&
- !hasOption(search, uniqueOptions, true)
+ !hasOption(unquotedSearch, uniqueOptions, true)
) {
return [
- { label: search, value: search, isNewOption: true },
+ { label: unquotedSearch, value: unquotedSearch, isNewOption: true },
...uniqueOptions,
];
}