The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
GDGT-2578 Replace TokenField (#77768)
Egor Grushin184c415f6e3d
diff --git a/e2e/support/helpers/e2e-email-helpers.js b/e2e/support/helpers/e2e-email-helpers.jsindex 538dc151b42..72588db6c2f 100644--- a/e2e/support/helpers/e2e-email-helpers.js+++ b/e2e/support/helpers/e2e-email-helpers.js@@ -95,7 +95,7 @@ export const openAndAddEmailsToSubscriptions = (recipients) => {cy.findByTestId("token-field").find("input").click()- .type(`${recipient}{enter}`)+ .type(`${recipient}{downarrow}{enter}`).blur();});};diff --git a/e2e/test/scenarios/filters-reproductions/filters-reproductions.cy.spec.js b/e2e/test/scenarios/filters-reproductions/filters-reproductions.cy.spec.jsindex d334c928d5f..53d3f964b35 100644--- a/e2e/test/scenarios/filters-reproductions/filters-reproductions.cy.spec.js+++ b/e2e/test/scenarios/filters-reproductions/filters-reproductions.cy.spec.js@@ -934,7 +934,7 @@ describe("issue 49642", () => {H.saveDashboard();H.filterWidget().click();- H.popover().within(() => {+ H.dashboardParametersPopover().within(() => {cy.findByText("Zackery Bailey").should("not.exist");cy.findByPlaceholderText("Search the list").type("Zackery");cy.findByText("Zackery Bailey").should("be.visible");@@ -945,7 +945,7 @@ describe("issue 49642", () => {"Zackery Kuhn",);- cy.findByText("Zackery Bailey").should("be.visible");+ cy.findByText("Zackery Bailey").should("not.exist");});});diff --git a/e2e/test/scenarios/sharing/alert/alert-permissions.cy.spec.js b/e2e/test/scenarios/sharing/alert/alert-permissions.cy.spec.jsindex 6d54db6e4f3..82667c873bd 100644--- a/e2e/test/scenarios/sharing/alert/alert-permissions.cy.spec.js+++ b/e2e/test/scenarios/sharing/alert/alert-permissions.cy.spec.js@@ -159,8 +159,8 @@ function createBasicAlert({ includeNormal } = {}) {.findByText("Email").closest('[data-testid="channel-block"]').findByTestId("token-field")- .click();- cy.findByText(H.getFullName(normal)).click();+ .findByRole("combobox")+ .type(`${H.getFullName(normal)}{enter}`);}cy.findByText("Done").click();diff --git a/e2e/test/scenarios/sharing/alert/alert.cy.spec.js b/e2e/test/scenarios/sharing/alert/alert.cy.spec.jsindex a96a6b0d07a..1939e6a8385 100644--- a/e2e/test/scenarios/sharing/alert/alert.cy.spec.js+++ b/e2e/test/scenarios/sharing/alert/alert.cy.spec.js@@ -162,8 +162,11 @@ describe("scenarios > alert", () => {const adminSubscriptionError = `You're only allowed to email subscriptions to addresses ending in ${allowedDomain}`;function addEmailRecipient(email) {- // Mantine Select has the role `textbox` 🤦- cy.findAllByRole("textbox").first().click().type(`${email}`).blur();+ cy.findByTestId("token-field")+ .findByRole("combobox")+ .click()+ .type(`${email}`)+ .blur();}function setAllowedDomains() {@@ -187,9 +190,7 @@ describe("scenarios > alert", () => {H.modal().within(() => {cy.findByText("New alert").should("be.visible");- cy.findByTestId("token-field").within(() => {- addEmailRecipient(deniedEmail);- });+ addEmailRecipient(deniedEmail);cy.findByText(adminAlertError);cy.button("Done").should("be.disabled");@@ -220,9 +221,7 @@ describe("scenarios > alert", () => {H.modal().within(() => {cy.findByText("New alert").should("be.visible");- cy.findByTestId("token-field").within(() => {- addEmailRecipient(deniedEmail);- });+ addEmailRecipient(deniedEmail);cy.button("Done").click();});diff --git a/e2e/test/scenarios/sharing/subscriptions.cy.spec.js b/e2e/test/scenarios/sharing/subscriptions.cy.spec.jsindex 47eb55b514a..63651dd075e 100644--- a/e2e/test/scenarios/sharing/subscriptions.cy.spec.js+++ b/e2e/test/scenarios/sharing/subscriptions.cy.spec.js@@ -137,7 +137,7 @@ describe("scenarios > dashboard > subscriptions", () => {cy.findByPlaceholderText("Enter user names or email addresses").click();H.popover().should("be.visible").and("contain", `${admin.first_name}`);cy.realPress("Escape");- H.popover({ skipVisibilityCheck: true }).should("not.exist");+ H.popover({ skipVisibilityCheck: true }).should("not.be.visible");cy.findByPlaceholderText("Enter user names or email addresses").should("not.have.value",);@@ -184,9 +184,10 @@ describe("scenarios > dashboard > subscriptions", () => {openDashboardSubscriptions();H.sidebar().within(() => {- cy.findByPlaceholderText("Enter user names or email addresses")- .click()- .type(`${normal.first_name} ${normal.last_name}{enter}`);+ cy.findByPlaceholderText(+ "Enter user names or email addresses",+ ).click();+ H.popover().contains(normal.first_name).click();clickButton("Done");cy.findByLabelText("add icon").click();@@ -940,9 +941,9 @@ function assignRecipient({openDashboardSubscriptions(dashboard_id);cy.findByText("Email it").click();- cy.findByPlaceholderText("Enter user names or email addresses")- .type(`${user.first_name} ${user.last_name}{enter}`)- .blur();+ cy.findByPlaceholderText("Enter user names or email addresses").click();+ H.popover().contains(user.first_name).click();+ cy.realPress("Escape");}function assignRecipients({diff --git a/frontend/src/metabase/common/components/TokenField/TokenField.module.css b/frontend/src/metabase/common/components/TokenField/TokenField.module.cssdeleted file mode 100644index 53a201df21a..00000000000--- a/frontend/src/metabase/common/components/TokenField/TokenField.module.css+++ /dev/null@@ -1,3 +0,0 @@-.closeIcon {- color: var(--mb-color-text-primary-inverse);-}diff --git a/frontend/src/metabase/common/components/TokenField/TokenField.styled.tsx b/frontend/src/metabase/common/components/TokenField/TokenField.styled.tsxdeleted file mode 100644index 8c9a8b5cf2a..00000000000--- a/frontend/src/metabase/common/components/TokenField/TokenField.styled.tsx+++ /dev/null@@ -1,36 +0,0 @@-// eslint-disable-next-line no-restricted-imports-import styled from "@emotion/styled";--export const TokenFieldContainer = styled.ul`- display: flex;- flex-wrap: wrap;- padding: var(--mantine-spacing-xs);- gap: var(--mantine-spacing-xs);- font-weight: bold;- cursor: pointer;- max-height: 130px;- overflow-x: auto;- overflow-y: auto;- border-radius: var(--mantine-spacing-sm);- border: 1px solid var(--mb-color-border-neutral);-`;--export const TokenInputItem = styled.li`- display: flex;- flex: 1 0 auto;- align-items: center;- margin-right: 0.5rem;- height: 46px;- background: none;-`;--export const TokenInputControl = styled.input`- background: none;- color: var(--mb-color-text-primary);-`;--export const PrefixContainer = styled.div`- display: flex;- align-items: center;- color: var(--mb-color-text-secondary);-`;diff --git a/frontend/src/metabase/common/components/TokenField/TokenField.tsx b/frontend/src/metabase/common/components/TokenField/TokenField.tsxdeleted file mode 100644index 3949d2d5e87..00000000000--- a/frontend/src/metabase/common/components/TokenField/TokenField.tsx+++ /dev/null@@ -1,699 +0,0 @@-import cx from "classnames";-import { Component, createRef } from "react";-import _ from "underscore";--import FormS from "metabase/css/components/form.module.css";-import CS from "metabase/css/core/index.css";-import { Icon, Popover } from "metabase/ui";-import { isObscured } from "metabase/utils/dom";-import {- KEYCODE_BACKSPACE,- KEYCODE_DOWN,- KEYCODE_ENTER,- KEYCODE_ESCAPE,- KEYCODE_TAB,- KEYCODE_UP,- KEY_BACKSPACE,- KEY_COMMA,- KEY_ENTER,-} from "metabase/utils/keyboard";--import { TokenFieldAddon, TokenFieldItem } from "../TokenFieldItem";--import S from "./TokenField.module.css";-import {- PrefixContainer,- TokenFieldContainer,- TokenInputControl,- TokenInputItem,-} from "./TokenField.styled";--export type LayoutRendererArgs = {- valuesList: React.ReactNode;- optionsList: React.ReactNode;- isFocused: boolean;- isAllSelected: boolean;- isFiltered: boolean;- onClose: () => void;-};--export type TokenFieldProps = {- value: any[];- onChange: (value: any[]) => void;- options: any[];- placeholder?: string | undefined;- multi?: boolean;- validateValue?: (value: any) => boolean;- parseFreeformValue?: (value: string | undefined) => any;- updateOnInputChange?: boolean;- optionRenderer?: (option: any) => React.ReactNode;- valueRenderer?: (value: any) => React.ReactNode;- layoutRenderer?: (args: LayoutRendererArgs) => React.ReactNode;- color?: "core-brand";- style?: React.CSSProperties;- className?: string;- valueStyle?: React.CSSProperties;- optionsStyle?: React.CSSProperties;- optionsClassName?: string;- prefix?: string;- canAddItems?: boolean;- autoFocus?: boolean;- removeSelected?: boolean;- idKey?: string | ((option: any) => string);- valueKey?: string | ((option: any) => string);- labelKey?: string | ((option: any) => string);- onFocus?: () => void;- onBlur?: () => void;- onInputKeyDown?: (event: React.KeyboardEvent<HTMLInputElement>) => void;- onInputChange?: (value: string) => string | void;- updateOnInputBlur?: boolean;- filterOption?: (options: any[], filter: string) => boolean;-};--type TokenFieldState = {- inputValue: string;- searchValue: string;- filteredOptions: any[];- selectedOptionValue: any;- isFocused: boolean;- isAllSelected: boolean;- listIsHovered: boolean;-};--const defaultStyleValue = {- fontSize: 14,- fontWeight: 700,-};--class _TokenField extends Component<TokenFieldProps, TokenFieldState> {- inputRef = createRef<HTMLInputElement>();-- constructor(props: TokenFieldProps) {- super(props);-- this.state = {- inputValue: "",- searchValue: "",- filteredOptions: [],- selectedOptionValue: null,- isFocused: props.autoFocus || false,- isAllSelected: false,- listIsHovered: false,- };- }-- UNSAFE_componentWillMount() {- this._updateFilteredValues(this.props);- }-- UNSAFE_componentWillReceiveProps(nextProps: TokenFieldProps) {- this._updateFilteredValues(nextProps);- }-- setInputValue(inputValue: any, setSearchValue = true) {- const newState = {- inputValue,- searchValue: setSearchValue ? inputValue : this.state.searchValue,- };- this.setState(newState, () => this._updateFilteredValues(this.props));- }-- clearInputValue(clearSearchValue = true) {- this.setInputValue("", clearSearchValue);- }-- clearSelectedOption() {- this.setState({- selectedOptionValue: null,- });- }-- _id(value: any) {- const { idKey } = this.props;-- if (typeof idKey === "function") {- return idKey(value);- } else if (typeof idKey === "string") {- return value[idKey];- } else {- return value;- }- }-- _value(option: any) {- const { valueKey = "value" } = this.props;- if (typeof valueKey === "function") {- return valueKey(option);- } else {- return option[valueKey];- }- }-- _label(option: any) {- const { labelKey = "label" } = this.props;- if (typeof labelKey === "function") {- return labelKey(option);- } else {- return option[labelKey];- }- }-- _key(option: any) {- return JSON.stringify(this._value(option));- }-- _isLastFreeformValue(inputValue: any) {- const { value, parseFreeformValue, updateOnInputChange } = this.props;- if (parseFreeformValue && updateOnInputChange) {- const freeformValue = parseFreeformValue(inputValue);- const currentLastValue = value[value.length - 1];- // check to see if the current last value is the same as the inputValue, in which case we should replace it or remove it- return currentLastValue === freeformValue;- }- }-- _updateFilteredValues = (props: TokenFieldProps) => {- const { options = [], value, removeSelected = true } = props;- let { searchValue, selectedOptionValue } = this.state;- const selectedValueIds = new Set(- value.map((v) => JSON.stringify(this._id(v))),- );-- const filterOption =- props.filterOption ||- ((option, searchValue) =>- String(this._label(option) || "").indexOf(searchValue) >= 0);-- let selectedCount = 0;- const filteredOptions = options.filter((option) => {- const isSelected = selectedValueIds.has(- JSON.stringify(this._id(this._value(option))),- );- const isLastFreeform =- this._isLastFreeformValue(this._value(option)) &&- this._isLastFreeformValue(searchValue);- const isMatching = filterOption(option, searchValue);- if (isSelected) {- selectedCount++;- }- // filter out options who have already been selected, unless:- return (- // remove selected is disabled- (!removeSelected ||- // or it's not in the selectedValues- !isSelected || // or it's the current "freeform" value, which updates as we type- isLastFreeform) && // and it's matching- isMatching- );- });-- if (- selectedOptionValue == null ||- !_.find(filteredOptions, (option) =>- this._valueIsEqual(selectedOptionValue, this._value(option)),- )- ) {- // if there are results based on the user's typing...- if (filteredOptions.length > 0) {- // select the first option in the list and set the selected option to that- selectedOptionValue = this._value(filteredOptions[0]);- } else {- selectedOptionValue = null;- }- }-- this.setState({- filteredOptions,- selectedOptionValue,- isAllSelected: options.length > 0 && selectedCount === options.length,- });- };-- onInputChange = ({- target: { value },- }: React.ChangeEvent<HTMLInputElement>) => {- const { updateOnInputChange, onInputChange, parseFreeformValue } =- this.props;-- if (onInputChange) {- value = onInputChange(value) || "";- }-- // update the input value- this.setInputValue(value);-- // if updateOnInputChange is true and parseFreeformValue is enabled then try adding/updating the freeform value immediately- if (updateOnInputChange && parseFreeformValue) {- const replaceLast = this._isLastFreeformValue(this.state.inputValue);- // call parseFreeformValue to make sure we can add it- const freeformValue = parseFreeformValue(value);- if (freeformValue != null) {- // if so, add it, replacing the last value if necessary- this.addValue(freeformValue, replaceLast);- } else {- // otherwise remove the value if necessary, e.x. after deleting- if (replaceLast) {- this.removeValue(parseFreeformValue(this.state.inputValue));- }- }- }- };-- // capture events on the input to allow for convenient keyboard shortcuts- onInputKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {- if (this.props.onInputKeyDown) {- this.props.onInputKeyDown(event);- }- if (event.nativeEvent.isComposing) {- return;- }-- const { key, keyCode } = event;-- const { filteredOptions, selectedOptionValue } = this.state;-- if (keyCode === KEYCODE_ESCAPE) {- event.preventDefault();- this.inputRef.current?.blur();- this.setState({ isFocused: false });- } else if (- // enter, tab, comma- keyCode === KEYCODE_TAB ||- // We check event.key for comma presses because some keyboard layouts- // (e.g. Russian) have a letter on that key and require a modifier to type- // ",". Similarly, if you want to type "<" on the US keyboard layout, you- // need to look at `key` to distinguish it from ",".- key === KEY_COMMA ||- keyCode === KEYCODE_ENTER ||- key === KEY_ENTER- ) {- if (this.addSelectedOption(event)) {- event.preventDefault();- event.stopPropagation();- }- } else if (event.keyCode === KEYCODE_UP) {- // up arrow- event.preventDefault();- const index = _.findIndex(filteredOptions, (option) =>- this._valueIsEqual(selectedOptionValue, this._value(option)),- );- if (index > 0) {- this.setState({- selectedOptionValue: this._value(filteredOptions[index - 1]),- });- }- } else if (keyCode === KEYCODE_DOWN) {- // down arrow- event.preventDefault();- const index = _.findIndex(filteredOptions, (option) =>- this._valueIsEqual(selectedOptionValue, this._value(option)),- );- if (index >= 0 && index < filteredOptions.length - 1) {- this.setState({- selectedOptionValue: this._value(filteredOptions[index + 1]),- });- } else if (filteredOptions.length > 0) {- this.setState({- selectedOptionValue: this._value(filteredOptions[0]),- });- }- } else if (keyCode === KEYCODE_BACKSPACE || key === KEY_BACKSPACE) {- // backspace- const { value } = this.props;- if (!this.state.inputValue && value.length > 0) {- this.removeValue(value[value.length - 1]);- }- }- };-- onInputFocus = () => {- if (this.props.onFocus) {- this.props.onFocus();- }- this.setState({ isFocused: true, searchValue: this.state.inputValue }, () =>- this._updateFilteredValues(this.props),- );- };-- onInputBlur = () => {- if (this.props.updateOnInputBlur && this.props.parseFreeformValue) {- const input = this.inputRef.current;- const value = this.props.parseFreeformValue(input?.value);- if (- value != null &&- (this.props.multi || value !== this.props.value[0])- ) {- this.addValue(value);- this.clearInputValue();- }- }- if (this.props.onBlur) {- this.props.onBlur();- }- this.setState({ isFocused: false });- };-- onInputPaste = (e: React.ClipboardEvent<HTMLInputElement>) => {- if (this.props.parseFreeformValue) {- e.preventDefault();- const string = e.clipboardData.getData("Text");- const lines = this.props.multi ? string.split(/\n|,/g) : [string];- const values = lines.map(this.props.parseFreeformValue).filter((s) => s);- if (values.length > 0) {- this.addValue(values);- }- }- };-- onMouseDownCapture = (e: React.MouseEvent<HTMLElement>) => {- const input = this.inputRef.current;- input?.focus();- // prevents clicks from blurring input while still allowing text selection:- if (input !== e.target) {- e.preventDefault();- }- };-- onClose = () => {- this.setState({ isFocused: false });- };-- addSelectedOption(e: React.KeyboardEvent<HTMLInputElement>) {- const { multi } = this.props;- const { filteredOptions, selectedOptionValue } = this.state;- const input = this.inputRef.current;- const option = _.find(filteredOptions, (option) =>- this._valueIsEqual(selectedOptionValue, this._value(option)),- );- if (option) {- this.addOption(option);- // clear the input if the option is the same as the last value- if (this._isLastFreeformValue(this._value(option))) {- // also clear the search- this.clearInputValue(true);- } else {- // only clear the search if this was the last option- this.clearInputValue(filteredOptions.length === 1);- }- this.clearSelectedOption();- return true;- } else if (this.props.parseFreeformValue) {- // if we previously updated on input change then we don't need to do it again,- if (this.props.updateOnInputChange) {- // if multi=true also prevent the input from changing due to this key press- const value = this.props.parseFreeformValue(input?.value);- if (multi && value !== null) {- e.preventDefault();- }- // and clear the input- this.clearInputValue();- // return false so we don't stop the keyDown from propagating in case we're listening- // for it, e.x. in the filter popover this allows enter to commit the filter- return false;- } else {- const value = this.props.parseFreeformValue(input?.value);- if (value != null && (multi || value !== this.props.value[0])) {- this.addValue(value);- this.clearInputValue();- return true;- }- }- }- }-- addOption = (option: any) => {- const replaceLast = this._isLastFreeformValue(this.state.inputValue);- // add the option's value to the current value- this.addValue(this._value(option), replaceLast);- };-- addValue(valueToAdd: any, replaceLast = false) {- const { value, onChange, multi } = this.props;- if (!Array.isArray(valueToAdd)) {- valueToAdd = [valueToAdd];- }- if (multi) {- if (replaceLast) {- onChange(_.unique(value.slice(0, -1).concat(valueToAdd)));- } else {- onChange(_.unique(value.concat(valueToAdd)));- }- } else {- onChange(valueToAdd.slice(0, 1));- }- }-- removeValue(valueToRemove: any) {- const { value, onChange } = this.props;- const values = value.filter((v) => !this._valueIsEqual(v, valueToRemove));- onChange(values);- }-- _valueIsEqual(v1: any, v2: any) {- return JSON.stringify(v1) === JSON.stringify(v2);- }-- componentDidUpdate(prevProps: TokenFieldProps) {- const input = this.inputRef.current;-- // if we added a value then scroll to the last item (the input)- if (this.props.value.length > prevProps.value.length) {- if (input && isObscured(input)) {- input.scrollIntoView({ block: "nearest" });- }- }-- // We focus on the input here, and not on the input itself as a prop- // (say by passing prop autoFocus={isFocused})- // because certain TokenFields will live in position: fixed containers.- // Autofocusing like that would make the page jump in scroll position.- // One example: parameter filters in dashboard pages.- if (this.state.isFocused) {- input?.focus({ preventScroll: true });- }- }-- render() {- let {- value,- placeholder,- multi,-- validateValue = () => true,- parseFreeformValue,- updateOnInputChange,-- optionRenderer = (option: any) => <span>{option}</span>,- valueRenderer = (value: any) => <span>{value}</span>,- layoutRenderer = (props: LayoutRendererArgs) => (- <DefaultTokenFieldLayout {...props} />- ),-- color = "core-brand",-- style = {},- className,- valueStyle = {},- optionsStyle = {},- optionsClassName,- prefix,-- canAddItems = true,- } = this.props;- let {- inputValue,- searchValue,- filteredOptions,- isFocused,- isAllSelected,- selectedOptionValue,- } = this.state;-- // for non-multi fields, keep the value in the input- if (!multi) {- inputValue = inputValue || value[0];- value = [];- }-- // if we have a value and updateOnInputChange is enabled, and the last value matches the inputValue- if (- value.length > 0 &&- updateOnInputChange &&- parseFreeformValue &&- value[value.length - 1] === parseFreeformValue(inputValue) &&- multi- ) {- if (isFocused) {- // if focused, don't render the last value- value = value.slice(0, -1);- } else {- // if not focused, don't render the inputValue- inputValue = "";- }- }-- // if not focused we won't get key events to accept the selected value, so don't render as selected- if (!isFocused) {- selectedOptionValue = null;- }-- // don't show the placeholder if we already have a value- if (value.length > 0) {- placeholder = undefined;- }-- const isControlledInput = !!this.onInputChange;- const valuesList = (- <TokenFieldContainer- style={style}- className={cx(className, {- "TokenField--focused": isFocused,- })}- onMouseDownCapture={this.onMouseDownCapture}- data-testid="token-field"- >- {!!prefix && (- <PrefixContainer data-testid="input-prefix">{prefix}</PrefixContainer>- )}- {value.map((v, index) => (- <TokenFieldItem key={index} isValid={validateValue(v)}>- <span style={{ ...defaultStyleValue, ...valueStyle }}>- {valueRenderer(v)}- </span>- {multi && (- <TokenFieldAddon- isValid={validateValue(v)}- onClick={(e) => {- e.preventDefault();- this.removeValue(v);- this.inputRef?.current?.blur();- }}- onMouseDown={(e) => e.preventDefault()}- >- <Icon- name="close"- className={cx(CS.flex, CS.alignCenter, S.closeIcon)}- size={12}- />- </TokenFieldAddon>- )}- </TokenFieldItem>- ))}- {canAddItems && (- <TokenInputItem>- <TokenInputControl- ref={this.inputRef}- style={{ ...defaultStyleValue, ...valueStyle }}- className={cx(CS.full, FormS.noFocus, CS.borderless, CS.px1)}- // set size to be small enough that it fits in a parameter.- size={10}- placeholder={placeholder}- value={isControlledInput ? inputValue : undefined}- defaultValue={isControlledInput ? undefined : inputValue}- onKeyDown={this.onInputKeyDown}- onChange={isControlledInput ? this.onInputChange : undefined}- onFocus={this.onInputFocus}- onBlur={this.onInputBlur}- onPaste={this.onInputPaste}- />- </TokenInputItem>- )}- </TokenFieldContainer>- );-- const optionsList =- filteredOptions.length === 0 ? null : (- <ul- role="listbox"- className={cx(- optionsClassName,- CS.overflowAuto,- CS.pl1,- CS.my1,- CS.scrollHide,- )}- style={{ maxHeight: 300, ...optionsStyle }}- onMouseEnter={() => this.setState({ listIsHovered: true })}- onMouseLeave={() => this.setState({ listIsHovered: false })}- >- {filteredOptions.map((option) => (- <li className={CS.mr1} key={this._key(option)}>- <div- className={cx(- CS.py1,- CS.pl1,- CS.pr2,- CS.block,- CS.rounded,- CS.textBold,- CS.inlineBlock,- CS.full,- CS.cursorPointer,- CS.bgLightHover,- {- [cx(CS.bgLight, {- [color]: CS.textBrand,- })]:- !this.state.listIsHovered &&- this._valueIsEqual(- selectedOptionValue,- this._value(option),- ),- },- )}- onClick={(e) => {- this.addOption(option);- // clear the input value, and search value if last option- this.clearInputValue(filteredOptions.length === 1);- e.preventDefault();- }}- onMouseDown={(e) => e.preventDefault()}- >- {optionRenderer(option)}- </div>- </li>- ))}- </ul>- );-- return layoutRenderer({- valuesList,- optionsList,- isFocused,- isAllSelected,- isFiltered: !!searchValue,- onClose: this.onClose,- });- }-}--type DefaultTokenFieldLayoutProps = {- valuesList: React.ReactNode;- optionsList?: React.ReactNode;- isFocused?: boolean;-};--const DefaultTokenFieldLayout = ({- valuesList,- optionsList,- isFocused,-}: DefaultTokenFieldLayoutProps) => (- <div>- <Popover opened={Boolean(isFocused && optionsList)} position="bottom-start">- <Popover.Target>- <div>{valuesList}</div>- </Popover.Target>- <Popover.Dropdown data-testid="token-field-popover">- {optionsList}- </Popover.Dropdown>- </Popover>- </div>-);--/**- * @deprecated use MultiSelect or Autocomplete from metabase/ui- */-export const TokenField = Object.assign(_TokenField, {- FieldItem: TokenFieldItem,- NewItemInputContainer: TokenInputItem,-});diff --git a/frontend/src/metabase/common/components/TokenField/TokenField.unit.spec.tsx b/frontend/src/metabase/common/components/TokenField/TokenField.unit.spec.tsxdeleted file mode 100644index a10b6a6188f..00000000000--- a/frontend/src/metabase/common/components/TokenField/TokenField.unit.spec.tsx+++ /dev/null@@ -1,522 +0,0 @@-import userEvent from "@testing-library/user-event";-import { Component } from "react";--import { act, fireEvent, render, screen, within } from "__support__/ui";-import { KEYCODE_ENTER } from "metabase/utils/keyboard";--import type { LayoutRendererArgs, TokenFieldProps } from "./TokenField";-import { TokenField } from "./TokenField";--const DEFAULT_OPTIONS = ["Doohickey", "Gadget", "Gizmo", "Widget"];--const MockValue = ({ value }: { value: string }) => <span>{value}</span>;-const MockOption = ({ option }: { option: string }) => <span>{option}</span>;--const DEFAULT_TOKEN_FIELD_PROPS = {- options: [],- value: [],- valueKey: (option: string) => option,- labelKey: (option: string) => option,- valueRenderer: (value: string) => <MockValue value={value} />,- optionRenderer: (option: string) => <MockOption option={option} />,- layoutRenderer: ({ valuesList, optionsList }: LayoutRendererArgs) => (- <div>- {valuesList}- {optionsList}- </div>- ),-};--type WrapperProps = Partial<TokenFieldProps> & {- value?: string[];- onChange?: (value: string[]) => void;-};--interface WrapperState {- value: string[];-}--class TokenFieldWithStateAndDefaults extends Component<- WrapperProps,- WrapperState-> {- constructor(props: WrapperProps) {- super(props);- this.state = {- value: props.value || [],- };- }- render() {- // allow overriding everything except value and onChange which we provide- const { value: _value, onChange, ...props } = this.props;- return (- <TokenField- {...DEFAULT_TOKEN_FIELD_PROPS}- {...props}- value={this.state.value}- onChange={(value: string[]) => {- this.setState({ value });- if (onChange) {- onChange(value);- }- }}- />- );- }-}--describe("TokenField", () => {- beforeAll(() => {- // temporarily until JSDOM updates- // eslint-disable-next-line testing-library/no-node-access- if (!global.Element.prototype.closest) {- // eslint-disable-next-line testing-library/no-node-access- global.Element.prototype.closest = function (selector: string) {- let element: Element | null = this;- while (element) {- if (element.matches(selector)) {- return element;- }- // eslint-disable-next-line testing-library/no-node-access- element = element.parentElement;- }- };- }- });-- const input = () => {- return screen.getByRole<HTMLInputElement>("textbox");- };-- const values = () => {- return screen.getAllByRole("list")[0];- };-- const options = () => {- return screen.queryAllByRole("listbox")[0];- };-- const type = (str: string) =>- fireEvent.change(input(), { target: { value: str } });-- const clickText = (str: string) => fireEvent.click(screen.getByText(str));-- const inputKeydown = (keyCode: number) =>- fireEvent.keyDown(input(), { keyCode: keyCode });-- const assertWithinValues = (collection: string[]) =>- expect(values()).toHaveTextContent(collection.join(""));-- const assertWithinOptions = (collection: string[]) =>- expect(options()).toHaveTextContent(collection.join(""));-- it("should render with no options or values", () => {- render(<TokenFieldWithStateAndDefaults />);- expect(screen.queryByText("foo")).not.toBeInTheDocument();- expect(screen.queryByText("bar")).not.toBeInTheDocument();- });-- it("should render input prefix with prefix prop", () => {- render(<TokenFieldWithStateAndDefaults prefix="$$$" />);- expect(screen.getByTestId("input-prefix")).toHaveTextContent("$$$");- });-- it("should not render input prefix without prefix prop", () => {- render(<TokenFieldWithStateAndDefaults />);- expect(screen.queryByTestId("input-prefix")).not.toBeInTheDocument();- });-- it("should render with 1 options and 1 values", () => {- render(- <TokenFieldWithStateAndDefaults- multi- value={["foo"]}- options={["bar"]}- />,- );- assertWithinValues(["foo"]);- assertWithinOptions(["bar"]);- });-- it("shouldn't show previous used option by default", () => {- render(- <TokenFieldWithStateAndDefaults value={["foo"]} options={["foo"]} />,- );- // options() returns `undefined`- expect(options()).toBeFalsy();- });-- it("should show previous used option if removeSelected={false} is provided", () => {- render(- <TokenFieldWithStateAndDefaults- value={["foo"]}- options={["foo"]}- removeSelected={false}- />,- );- assertWithinOptions(["foo"]);- });-- it("should filter correctly", () => {- render(- <TokenFieldWithStateAndDefaults- value={["foo"]}- options={["bar", "baz"]}- />,- );- type("nope");- expect(options()).toBeFalsy();- type("bar");- assertWithinOptions(["bar"]);- });-- it("should not allow adding new items when canAddItems is false", () => {- render(- <TokenFieldWithStateAndDefaults- value={["foo"]}- options={["bar", "baz"]}- canAddItems={false}- />,- );- expect(screen.queryByRole("textbox")).not.toBeInTheDocument();- });-- it("should add freeform value if parseFreeformValue is provided", async () => {- render(- <TokenFieldWithStateAndDefaults- value={[]}- options={["bar", "baz"]}- parseFreeformValue={(value) => value}- />,- );- await userEvent.type(input(), "yep");- expect(input().value).toEqual("yep");-- type("yep");- expect(input().value).toEqual("yep");- });-- it("should add clicked option to values and hide it in options list", () => {- render(- <TokenFieldWithStateAndDefaults- multi- value={[]}- options={["bar", "baz"]}- />,- );- assertWithinOptions(["bar", "baz"]);-- clickText("bar");- assertWithinValues(["bar"]);- assertWithinOptions(["baz"]);- });-- it("should add option when filtered and clicked", () => {- render(- <TokenFieldWithStateAndDefaults- multi- value={[]}- options={["foo", "bar"]}- />,- );- type("ba");- clickText("bar");- assertWithinValues(["bar"]);- });-- describe("when updateOnInputChange is provided", () => {- function setup() {- render(- <TokenFieldWithStateAndDefaults- options={DEFAULT_OPTIONS}- multi- // return null for empty string since it's not a valid- parseFreeformValue={(value) => value || null}- updateOnInputChange- />,- );- }-- it("should add freeform value immediately if updateOnInputChange is provided", () => {- setup();- type("yep");- assertWithinValues(["yep"]);- });-- it("should only add one option when filtered and clicked", () => {- setup();-- type("Do");- assertWithinValues(["Do"]);-- clickText("Doohickey");- assertWithinValues(["Doohickey"]);- expect(input().value).toEqual("");- });-- it("should only add one option when filtered and enter is pressed", () => {- setup();-- type("Do");- assertWithinValues(["Do"]);-- inputKeydown(KEYCODE_ENTER);- assertWithinValues(["Doohickey"]);- expect(input().value).toEqual("");- assertWithinOptions(["Gadget", "Gizmo", "Widget"]);- });-- it("shouldn't hide option matching input freeform value", () => {- setup();-- type("Doohickey");- assertWithinValues(["Doohickey"]);- assertWithinOptions(["Doohickey"]);- });-- // This is messy and tricky to test with RTL- it("should not commit empty freeform value", async () => {- setup();-- type("Doohickey");- await userEvent.clear(input());- type("");- input().blur();- expect(values()).toHaveTextContent("");- expect(input().value).toEqual("");- });-- it("should hide the input but not clear the search after accepting an option", () => {- setup();-- type("G");- assertWithinOptions(["Gadget", "Gizmo"]);-- inputKeydown(KEYCODE_ENTER);- assertWithinOptions(["Gizmo"]);- expect(input().value).toEqual("");-- // Reset search on focus (it was a separate test before)- act(() => {- input().focus();- });- assertWithinOptions(["Doohickey", "Gizmo", "Widget"]);- });-- it("should reset the search when adding the last option", () => {- setup();-- type("G");- assertWithinOptions(["Gadget", "Gizmo"]);-- inputKeydown(KEYCODE_ENTER);- assertWithinOptions(["Gizmo"]);-- inputKeydown(KEYCODE_ENTER);- assertWithinOptions(["Doohickey", "Widget"]);- });-- it("should hide the option if typed exactly then press enter", () => {- setup();-- type("Gadget");- assertWithinOptions(["Gadget"]);- inputKeydown(KEYCODE_ENTER);- assertWithinValues(["Gadget"]);- assertWithinOptions(["Doohickey", "Gizmo", "Widget"]);- });-- it("should hide the option if typed partially then press enter", () => {- setup();-- type("Gad");- assertWithinOptions(["Gadget"]);- inputKeydown(KEYCODE_ENTER);- assertWithinValues(["Gadget"]);- assertWithinOptions(["Doohickey", "Gizmo", "Widget"]);- });-- it("should hide the option if typed exactly then clicked", () => {- setup();-- type("Gadget");- fireEvent.click(within(options()).getByText("Gadget"));- assertWithinValues(["Gadget"]);- assertWithinOptions(["Doohickey", "Gizmo", "Widget"]);- });-- it("should hide the option if typed partially then clicked", () => {- setup();-- type("Gad");- fireEvent.click(within(options()).getByText("Gadget"));- assertWithinValues(["Gadget"]);- assertWithinOptions(["Doohickey", "Gizmo", "Widget"]);- });- });-- describe("when updateOnInputBlur is false", () => {- function setup() {- render(- <TokenFieldWithStateAndDefaults- options={DEFAULT_OPTIONS}- multi- // return null for empty string since it's not a valid- parseFreeformValue={(value) => value || null}- updateOnInputBlur={false}- />,- );- }-- it("should not add freeform value immediately", () => {- setup();- type("yep");- expect(values()).toHaveTextContent("");- });-- it("should not add freeform value when blurring", () => {- setup();- type("yep");- fireEvent.blur(input());- expect(values()).toHaveTextContent("");- });- });-- describe("when updateOnInputBlur is true", () => {- function setup() {- render(- <TokenFieldWithStateAndDefaults- options={DEFAULT_OPTIONS}- multi- // return null for empty string since it's not a valid- parseFreeformValue={(value) => value || null}- updateOnInputBlur={true}- />,- );- }-- it("should not add freeform value immediately", () => {- setup();- type("yep");- expect(values()).toHaveTextContent("");- });-- it("should add freeform value when blurring", () => {- setup();- type("yep");- fireEvent.blur(input());- assertWithinValues(["yep"]);- });- });-- describe("with multi=true", () => {- it('should paste "1,2,3" as multiple values', () => {- render(- <TokenFieldWithStateAndDefaults- // return null for empty string since it's not a valid- parseFreeformValue={(value) => value || null}- updateOnInputChange- multi- />,- );-- fireEvent.paste(input(), {- clipboardData: {- getData: () => "1,2,3",- },- });-- assertWithinValues(["1", "2", "3"]);- // prevent pasting into <input>- expect(input().value).toBe("");- });- });-- describe("with multi=false", () => {- it("should not prevent blurring on tab", async () => {- render(- <TokenFieldWithStateAndDefaults- options={DEFAULT_OPTIONS}- // return null for empty string since it's not a valid- parseFreeformValue={(value) => value || null}- updateOnInputChange- />,- );- type("asdf");- input().focus();- await userEvent.tab();- expect(input()).not.toHaveFocus();- });-- it('should paste "1,2,3" as one value', () => {- const DATA = "1,2,3";- render(- <TokenFieldWithStateAndDefaults- // return null for empty string since it's not a valid- parseFreeformValue={(value) => value || null}- updateOnInputChange- />,- );- fireEvent.paste(input(), {- clipboardData: {- getData: () => DATA,- },- });-- expect(input().value).toBe(DATA);- });- });-- describe("custom layoutRenderer", () => {- let layoutRenderer: jest.Mock;-- beforeEach(() => {- layoutRenderer = jest- .fn()- .mockImplementation(- ({ valuesList, optionsList }: LayoutRendererArgs) => (- <div>- {valuesList}- {optionsList}- </div>- ),- );- });-- it("should be called with isFiltered=true when filtered", () => {- render(- <TokenFieldWithStateAndDefaults- options={["hello"]}- layoutRenderer={layoutRenderer}- />,- );-- let call = layoutRenderer.mock.calls.pop();- expect(call[0].isFiltered).toEqual(false);- expect(call[0].isAllSelected).toEqual(false);- type("blah");- call = layoutRenderer.mock.calls.pop();- expect(call[0].optionList).toEqual(undefined);- expect(call[0].isFiltered).toEqual(true);- expect(call[0].isAllSelected).toEqual(false);- });-- it("should be called with isAllSelected=true when all options are selected", () => {- render(- <TokenFieldWithStateAndDefaults- options={["hello"]}- layoutRenderer={layoutRenderer}- />,- );-- let call = layoutRenderer.mock.calls.pop();- expect(call[0].isFiltered).toEqual(false);- expect(call[0].isAllSelected).toEqual(false);- inputKeydown(KEYCODE_ENTER);- call = layoutRenderer.mock.calls.pop();- expect(call[0].optionList).toEqual(undefined);- expect(call[0].isFiltered).toEqual(false);- expect(call[0].isAllSelected).toEqual(true);- });- });-});diff --git a/frontend/src/metabase/common/components/TokenField/index.ts b/frontend/src/metabase/common/components/TokenField/index.tsdeleted file mode 100644index a4856698e0e..00000000000--- a/frontend/src/metabase/common/components/TokenField/index.ts+++ /dev/null@@ -1,2 +0,0 @@-export { TokenField } from "./TokenField";-export * from "./utils";diff --git a/frontend/src/metabase/common/components/TokenField/utils.ts b/frontend/src/metabase/common/components/TokenField/utils.tsdeleted file mode 100644index 989146d2a8c..00000000000--- a/frontend/src/metabase/common/components/TokenField/utils.ts+++ /dev/null@@ -1,12 +0,0 @@-export function parseStringValue(value: any): string | null {- const trimmedValue = trim(value);- if (trimmedValue === "") {- return null;- }-- return trimmedValue;-}--function trim(value: any) {- return String(value || "").trim();-}diff --git a/frontend/src/metabase/common/components/TokenField/utils.unit.spec.ts b/frontend/src/metabase/common/components/TokenField/utils.unit.spec.tsdeleted file mode 100644index c6976422082..00000000000--- a/frontend/src/metabase/common/components/TokenField/utils.unit.spec.ts+++ /dev/null@@ -1,20 +0,0 @@-import { parseStringValue } from "./utils";--describe("metabase/common/components/TokenField/utils", () => {- describe("parseStringValue", () => {- it("should return null for falsy and whitespace values", () => {- expect(parseStringValue("")).toBeNull();- expect(parseStringValue(" ")).toBeNull();- expect(parseStringValue(" \n ")).toBeNull();- expect(parseStringValue(null)).toBeNull();- expect(parseStringValue(false)).toBeNull();- expect(parseStringValue(0)).toBeNull();- });-- it("should return truthy values coerced into strings", () => {- expect(parseStringValue(123)).toBe("123");- expect(parseStringValue(true)).toBe("true");- expect(parseStringValue(" abc 123 \n ")).toBe("abc 123");- });- });-});diff --git a/frontend/src/metabase/common/components/TokenFieldItem/TokenFieldItem.stories.tsx b/frontend/src/metabase/common/components/TokenFieldItem/TokenFieldItem.stories.tsxdeleted file mode 100644index 7960100c9e2..00000000000--- a/frontend/src/metabase/common/components/TokenFieldItem/TokenFieldItem.stories.tsx+++ /dev/null@@ -1,85 +0,0 @@-import type { StoryFn } from "@storybook/react";-import cx from "classnames";-import type { ComponentProps } from "react";--import CS from "metabase/css/core/index.css";-import { Icon } from "metabase/ui";--import { TokenFieldAddon, TokenFieldItem } from "./TokenFieldItem.styled";--export default {- title: "Components/Ask Before Using/TokenFieldItem",- component: TokenFieldItem,-};--const Wrapper = ({ children }: { children: JSX.Element | JSX.Element[] }) => (- <div style={{ display: "flex", flexWrap: "wrap", maxWidth: 400 }}>- {children}- </div>-);--const Template: StoryFn<ComponentProps<typeof TokenFieldItem>> = (args) => {- return (- <Wrapper>- <TokenFieldItem {...args} />- </Wrapper>- );-};--const ManyTemplate: StoryFn<ComponentProps<typeof TokenFieldItem>> = (args) => {- return (- <Wrapper>- <TokenFieldItem {...args}> {`${args.children} 1`} </TokenFieldItem>- <TokenFieldItem {...args}> {`${args.children} 2`} </TokenFieldItem>- <TokenFieldItem {...args}> {`${args.children} 3`} </TokenFieldItem>- <TokenFieldItem {...args}> {`${args.children} 4`} </TokenFieldItem>- <TokenFieldItem {...args}> {`${args.children} 5`} </TokenFieldItem>- </Wrapper>- );-};--const AddonTemplate: StoryFn<ComponentProps<typeof TokenFieldItem>> = (- args,-) => {- return (- <Wrapper>- <TokenFieldItem isValid={args.isValid}>- {args.children}- <TokenFieldAddon isValid={args.isValid}>- <Icon- name="close"- className={cx(CS.flex, CS.alignCenter)}- size={12}- />- </TokenFieldAddon>- </TokenFieldItem>- </Wrapper>- );-};--export const Default = {- render: Template,-- args: {- isValid: true,- children: "Token Item Value",- },-};--export const Many = {- render: ManyTemplate,-- args: {- isValid: true,- children: "Token Item Value",- },-};--export const WithAddon = {- render: AddonTemplate,-- args: {- isValid: true,- children: "Token Item Value",- },-};diff --git a/frontend/src/metabase/common/components/TokenFieldItem/TokenFieldItem.styled.ts b/frontend/src/metabase/common/components/TokenFieldItem/TokenFieldItem.styled.tsdeleted file mode 100644index c52a03d34b1..00000000000--- a/frontend/src/metabase/common/components/TokenFieldItem/TokenFieldItem.styled.ts+++ /dev/null@@ -1,33 +0,0 @@-// eslint-disable-next-line no-restricted-imports-import styled from "@emotion/styled";--export const TokenFieldItem = styled.li<{- isValid: boolean;-}>`- display: flex;- align-items: center;- padding: 0.5rem 0.75rem;-- height: 46px;- border-radius: 0.5rem;- color: ${({ isValid }) =>- isValid- ? `var(--mb-color-text-primary-inverse)`- : `var(--mb-color-feedback-negative)`};-- background-color: var(--mb-color-core-brand);-`;--export const TokenFieldAddon = styled.a<{- isValid: boolean;-}>`- display: flex;- align-items: center;- margin-left: 0.5rem;- color: ${({ isValid }) =>- isValid ? "" : `var(--mb-color-feedback-negative)`};-- &:hover {- color: var(--mb-color-text-brand-hover);- }-`;diff --git a/frontend/src/metabase/common/components/TokenFieldItem/index.ts b/frontend/src/metabase/common/components/TokenFieldItem/index.tsdeleted file mode 100644index f948be60005..00000000000--- a/frontend/src/metabase/common/components/TokenFieldItem/index.ts+++ /dev/null@@ -1 +0,0 @@-export * from "./TokenFieldItem.styled";diff --git a/frontend/src/metabase/notifications/channels/RecipientPicker.tsx b/frontend/src/metabase/notifications/channels/RecipientPicker.tsxindex b2cc84cd2f2..7bf717c981f 100644--- a/frontend/src/metabase/notifications/channels/RecipientPicker.tsx+++ b/frontend/src/metabase/notifications/channels/RecipientPicker.tsx@@ -1,12 +1,10 @@-import cx from "classnames";+import { useMemo } from "react";import { t } from "ttag";-import { TokenField } from "metabase/common/components/TokenField";import { UserAvatar } from "metabase/common/components/UserAvatar";import { useSetting } from "metabase/common/hooks";-import CS from "metabase/css/core/index.css";import { type RecipientPickerValue, recipientIsValid } from "metabase/pulse";-import { Text } from "metabase/ui";+import { Flex, MultiAutocomplete, Text } from "metabase/ui";import { isEmail } from "metabase/utils/email";import type { User } from "metabase-types/api";@@ -20,6 +18,14 @@ interface RecipientPickerProps {invalidRecipientText: (domains: string) => string;}+const recipientKey = (recipient: RecipientPickerValue) =>+ "id" in recipient ? String(recipient.id) : recipient.email;++const recipientLabel = (recipient: RecipientPickerValue) =>+ "id" in recipient+ ? (recipient.common_name ?? recipient.email ?? "")+ : recipient.email;+export const RecipientPicker = ({recipients = [],users,@@ -27,48 +33,82 @@ export const RecipientPicker = ({autoFocus = true,invalidRecipientText,}: RecipientPickerProps) => {- const handleOnChange = (newRecipients: RecipientPickerValue[]) => {- onRecipientsChange(newRecipients);+ const userByKey = useMemo(+ () => new Map(users.map((user) => [recipientKey(user), user])),+ [users],+ );+ const recipientByKey = useMemo(+ () =>+ new Map(+ recipients.map((recipient) => [recipientKey(recipient), recipient]),+ ),+ [recipients],+ );++ const getRecipient = (key: string) =>+ userByKey.get(key) ?? recipientByKey.get(key);++ const handleChange = (keys: string[]) => {+ onRecipientsChange(keys.map((key) => getRecipient(key) ?? { email: key }));};- const isValid = recipients.every((r) => recipientIsValid(r));+ const isValid = recipients.every((recipient) => recipientIsValid(recipient));const domains = useSetting("subscription-allowed-domains");return (<div><div>- <TokenField- value={recipients}- options={users ? users.map((user) => ({ value: user })) : []}- onChange={handleOnChange}- className={S.tokenField}- idKey={(item: RecipientPickerValue) =>- "id" in item ? String(item.id) : item.email- }+ <MultiAutocomplete+ data-testid="token-field"+ classNames={{ input: S.tokenField }}+ value={recipients.map(recipientKey)}+ data={users.map((user) => ({+ value: recipientKey(user),+ label: recipientLabel(user),+ }))}+ onChange={handleChange}+ selectFirstOptionOnChangeplaceholder={recipients.length === 0? t`Enter user names or email addresses`: undefined}autoFocus={autoFocus && recipients.length === 0}- multi- valueRenderer={(value) => value.common_name ?? value.email}- optionRenderer={(option) => (- <div className={cx(CS.flex, CS.alignCenter)}>- <Text color="text-primary-inverse">- <UserAvatar user={option.value} />- </Text>- <span className={CS.ml1}>{option.value.common_name}</span>- </div>- )}- filterOption={filterOption}- validateValue={(value) => recipientIsValid(value)}- parseFreeformValue={(inputValue) => {- if (isEmail(inputValue)) {- return { email: inputValue };+ rightSection={null}+ parseValue={(rawValue) => {+ const value = rawValue.trim();+ return isEmail(value) ? value : null;+ }}+ filter={({ options, search }) =>+ options.filter((option) => {+ if ("items" in option) {+ return true;+ }+ const user = userByKey.get(option.value);+ return (+ includesIgnoreCase(option.label, search) ||+ includesIgnoreCase(user?.email ?? "", search)+ );+ })+ }+ renderValue={({ value }) => {+ const recipient = getRecipient(value);+ return recipient ? recipientLabel(recipient) : value;+ }}+ renderOption={({ option }) => {+ const user = userByKey.get(option.value);+ if (!user) {+ return option.label;}+ return (+ <Flex align="center" gap="sm">+ <Text c="text-primary-inverse">+ <UserAvatar user={user} />+ </Text>+ <span>{user.common_name}</span>+ </Flex>+ );}}- updateOnInputBlur/></div>{domains && !isValid && (@@ -78,13 +118,5 @@ export const RecipientPicker = ({);};-const filterOption = (option: any, text: string) => {- return (- includesIgnoreCase(option.value.common_name, text) ||- includesIgnoreCase(option.value.email, text)- );-};--const includesIgnoreCase = (sourceText: string, searchText: string) => {- return sourceText.toLowerCase().includes(searchText.toLowerCase());-};+const includesIgnoreCase = (sourceText: string, searchText: string) =>+ sourceText.toLowerCase().includes(searchText.toLowerCase());diff --git a/frontend/src/metabase/notifications/channels/RecipientPicker.unit.spec.tsx b/frontend/src/metabase/notifications/channels/RecipientPicker.unit.spec.tsxindex ba3a12abb9e..6d44da48e60 100644--- a/frontend/src/metabase/notifications/channels/RecipientPicker.unit.spec.tsx+++ b/frontend/src/metabase/notifications/channels/RecipientPicker.unit.spec.tsx@@ -41,8 +41,8 @@ describe("recipient picker", () => {/>,);// Now only the recipient name should be visible- screen.getByText("Barb");- expect(screen.queryByText("Dustin")).not.toBeInTheDocument();+ expect(screen.getByText("Barb")).toBeVisible();+ expect(screen.queryByText("Dustin")).not.toBeVisible();});});@@ -59,7 +59,7 @@ describe("recipient picker", () => {/>,);- await userEvent.type(await screen.findByRole("textbox"), "Na");+ await userEvent.type(await screen.findByRole("combobox"), "Na");await userEvent.click(await screen.findByText("Nancy"));expect(onRecipientsChange).toHaveBeenCalledWith([@@ -80,9 +80,7 @@ describe("recipient picker", () => {/>,);- await userEvent.click(- (await screen.findAllByRole("img", { name: /close/ }))[2],- );+ await userEvent.click((await screen.findAllByLabelText("Remove"))[2]);expect(onRecipientsChange).toHaveBeenCalledWith([TEST_USERS[0],@@ -90,6 +88,26 @@ describe("recipient picker", () => {]);});+ it("should add a matching user by typing their name and pressing enter", async () => {+ const onRecipientsChange = jest.fn();++ renderWithProviders(+ <RecipientPicker+ recipients={[TEST_USERS[0]]}+ users={TEST_USERS}+ onRecipientsChange={onRecipientsChange}+ invalidRecipientText={() => ""}+ />,+ );++ await userEvent.type(await screen.findByRole("combobox"), "Nancy{enter}");++ expect(onRecipientsChange).toHaveBeenCalledWith([+ TEST_USERS[0],+ TEST_USERS[5],+ ]);+ });+it("should support adding emails", async () => {const onRecipientsChange = jest.fn();@@ -103,7 +121,7 @@ describe("recipient picker", () => {);await userEvent.type(- await screen.findByRole("textbox"),+ await screen.findByRole("combobox"),"[email protected]{enter}",);diff --git a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/FieldValuesWidget.styled.tsx b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/FieldValuesWidget.styled.tsxdeleted file mode 100644index 65ed9cb3514..00000000000--- a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/FieldValuesWidget.styled.tsx+++ /dev/null@@ -1,19 +0,0 @@-// eslint-disable-next-line no-restricted-imports-import styled from "@emotion/styled";--import { Ellipsified } from "metabase/ui";--export const StyledEllipsified = styled(Ellipsified)`- font-weight: bold;- display: inline-block;- margin: 0 0.2rem;-`;--export const OptionsMessage = styled.div`- padding: 2rem;- position: relative;- display: flex;- align-items: center;- justify-content: center;- white-space: nowrap;-`;diff --git a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/FieldValuesWidget.tsx b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/FieldValuesWidget.tsxindex e250a36a55d..0e8ebe41764 100644--- a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/FieldValuesWidget.tsx+++ b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/FieldValuesWidget.tsx@@ -7,7 +7,7 @@ import {useState,} from "react";import { useMount, usePrevious } from "react-use";-import { jt, t } from "ttag";+import { t } from "ttag";import _ from "underscore";import ErrorBoundary from "metabase/ErrorBoundary";@@ -19,11 +19,6 @@ import {} from "metabase/api";import { ExplicitSize } from "metabase/common/components/ExplicitSize";import { MultiAutocompleteWithTranslation } from "metabase/common/components/MultiAutocomplete";-import {- TokenField,- parseStringValue,-} from "metabase/common/components/TokenField";-import type { LayoutRendererArgs } from "metabase/common/components/TokenField/TokenField";import { useTranslateContent } from "metabase/content-translation/hooks";import type { ContentTranslationFunction } from "metabase/content-translation/types";import CS from "metabase/css/core/index.css";@@ -38,7 +33,7 @@ import { addRemappings } from "metabase/redux/remappings";import type { State } from "metabase/redux/store";import { getMetadata } from "metabase/selectors/metadata";import {- type ComboboxItem,+ Autocomplete,Loader,MultiAutocompleteOption,MultiAutocompleteValue,@@ -59,7 +54,6 @@ import type {import { Value as ValueComponent } from "../Value";-import { OptionsMessage, StyledEllipsified } from "./FieldValuesWidget.styled";import { ListField } from "./ListField";import SingleSelectListField from "./SingleSelectListField";import type { LoadingStateType, ValuesMode } from "./types";@@ -75,7 +69,7 @@ import {hasList,isExtensionOfPreviousSearch,isNumeric,- isSearchable,+ parseStringValue,shouldList,} from "./utils";@@ -91,7 +85,6 @@ function mapStateToProps(state: State, { fields = [] }: { fields: Field[] }) {}export interface IFieldValuesWidgetProps {- color?: "core-brand";maxResults?: number;style?: StyleHTMLAttributes<HTMLDivElement>;formatOptions?: Record<string, any>;@@ -104,8 +97,6 @@ export interface IFieldValuesWidgetProps {disableList?: boolean;disableSearch?: boolean;disablePKRemappingForSearch?: boolean;- alwaysShowOptions?: boolean;- showOptionsInPopover?: boolean;parameter: Parameter;parameters?: Parameter[]; // linked parameters with values@@ -122,9 +113,7 @@ export interface IFieldValuesWidgetProps {placeholder?: string;checkedColor?: string;- valueRenderer?: (value: string | number) => JSX.Element;optionRenderer?: (option: FieldValue) => JSX.Element;- layoutRenderer?: (props: LayoutRendererArgs) => JSX.Element;}export const FieldValuesWidgetInner = forwardRef<@@ -132,10 +121,7 @@ export const FieldValuesWidgetInner = forwardRef<IFieldValuesWidgetProps>(function FieldValuesWidgetInner({- color,maxResults = MAX_SEARCH_RESULTS,- alwaysShowOptions = true,- style = {},formatOptions = {},containerWidth,maxWidth = 500,@@ -144,7 +130,6 @@ export const FieldValuesWidgetInner = forwardRef<disableList = false,disableSearch = false,disablePKRemappingForSearch,- showOptionsInPopover = false,parameter,parameters,fields,@@ -157,9 +142,7 @@ export const FieldValuesWidgetInner = forwardRef<className,placeholder,checkedColor,- valueRenderer,optionRenderer,- layoutRenderer,},ref,) {@@ -322,23 +305,6 @@ export const FieldValuesWidgetInner = forwardRef<search.current(value);};- if (!valueRenderer) {- valueRenderer = (value: string | number) => {- const option = options.find((option) => getValue(option) === value);- return renderValue({- fields,- formatOptions,- value,- parameter,- cardId,- dashboardId,- autoLoad: true,- compact: false,- displayValue: option?.[1],- });- };- }-if (!optionRenderer) {optionRenderer = (option: FieldValue) =>renderValue({@@ -353,36 +319,6 @@ export const FieldValuesWidgetInner = forwardRef<});}- if (!layoutRenderer) {- layoutRenderer = showOptionsInPopover- ? undefined- : ({- optionsList,- isFocused,- isAllSelected,- isFiltered,- valuesList,- }: LayoutRendererArgs) => (- <div>- {valuesList}- {renderOptions({- alwaysShowOptions,- parameter,- fields,- disableSearch,- disablePKRemappingForSearch,- loadingState,- options,- valuesMode,- optionsList,- isFocused,- isAllSelected,- isFiltered,- })}- </div>- );- }-const tokenFieldPlaceholder = getTokenFieldPlaceholder({fields,parameter,@@ -421,6 +357,15 @@ export const FieldValuesWidgetInner = forwardRef<: parseStringValue(value);};+ const parseValue = (value: string) =>+ parseFreeformValue(value)?.toString() ?? null;++ const commitValues = (values: string[]) =>+ onChange(isNumericParameter ? values.map(parseNumericValue) : values);++ const fieldValues = value.filter(isNotNull).map(String);+ const optionsData = options.map(getOption).filter(isNotNull);+return (<ErrorBoundary ref={ref}><div@@ -456,11 +401,8 @@ export const FieldValuesWidgetInner = forwardRef</>) : multi ? (<MultiAutocompleteWithTranslation- value={value.filter(isNotNull).map((value) => String(value))}- data={options- .filter((option) => getValue(option) != null)- .map((option) => getOption(option))- .filter(isNotNull)}+ value={fieldValues}+ data={optionsData}placeholder={tokenFieldPlaceholder}rightSection={isLoading ? <Loader size="xs" /> : undefined}nothingFoundMessage={getNothingFoundMessage({@@ -475,15 +417,7 @@ export const FieldValuesWidgetInner = forwardRef<position: "bottom-start",}}data-testid="token-field"- parseValue={(value) => {- if (isNumericParameter) {- const number = parseNumber(value);- return number != null ? String(number) : null;- } else {- const string = value.trim();- return string.length > 0 ? string : null;- }- }}+ parseValue={parseValue}renderValue={({ value }) => (<RemappedValueparameter={parameter}@@ -497,47 +431,32 @@ export const FieldValuesWidgetInner = forwardRef<renderOption={({ option }) => (<RemappedOption option={option} fields={fields} tc={tc} />)}- onChange={(values) => {- if (isNumericParameter) {- onChange(values.map(parseNumericValue));- } else {- onChange(values);- }- }}+ onChange={commitValues}onSearchChange={onInputChange}/>) : (- <TokenField- value={value.filter((v) => v != null)}- onChange={onChange}+ <Autocomplete+ value={fieldValues[0] ?? ""}+ data={optionsData}placeholder={tokenFieldPlaceholder}- updateOnInputChange- // forwarded props- multi={multi}+ rightSection={isLoading ? <Loader size="xs" /> : undefined}autoFocus={autoFocus}- color={color}- style={{ ...style, minWidth: "inherit" }}className={className}- optionsStyle={- !parameter && !showOptionsInPopover ? { maxHeight: "none" } : {}- }- // end forwarded props- options={options}- valueKey="0"- valueRenderer={valueRenderer}- optionRenderer={optionRenderer}- layoutRenderer={layoutRenderer}- filterOption={(option, filterString) => {- const lowerCaseFilterString = filterString.toLowerCase();- return option?.some?.(- (value) =>- value != null &&- String(value).toLowerCase().includes(lowerCaseFilterString),- );+ w={COMBOBOX_WIDTH}+ comboboxProps={{+ withinPortal: false,+ floatingStrategy: "fixed",+ width: DROPDOWN_WIDTH,+ position: "bottom-start",}}- onInputChange={onInputChange}- parseFreeformValue={parseFreeformValue}- updateOnInputBlur+ data-testid="token-field"+ selectFirstOptionOnChange+ renderOption={({ option }) => (+ <RemappedOption option={option} fields={fields} tc={tc} />+ )}+ parseValue={parseValue}+ onSearchChange={onInputChange}+ onChange={(value) => commitValues(value !== "" ? [value] : [])}/>)}</div>@@ -584,96 +503,6 @@ function getNothingFoundMessage({}}-const NoMatchState = ({ fields }: { fields: (Field | null)[] }) => {- if (fields.length === 1 && !!fields[0]) {- const [{ display_name }] = fields;-- return (- <OptionsMessage>- {jt`No matching ${(- <StyledEllipsified key={display_name}>- {display_name}- </StyledEllipsified>- )} found.`}- </OptionsMessage>- );- }-- return <OptionsMessage>{t`No matching result`}</OptionsMessage>;-};--const EveryOptionState = () => (- <OptionsMessage>{t`Including every option in your filter probably won’t do much…`}</OptionsMessage>-);--interface RenderOptionsProps {- alwaysShowOptions: boolean;- parameter?: Parameter;- fields: Field[];- disableSearch: boolean;- disablePKRemappingForSearch?: boolean;- loadingState: LoadingStateType;- options: FieldValue[];- valuesMode: ValuesMode;- optionsList: React.ReactNode;- isFocused: boolean;- isAllSelected: boolean;- isFiltered: boolean;-}--function renderOptions({- alwaysShowOptions,- parameter,- fields,- disableSearch,- disablePKRemappingForSearch,- loadingState,- options,- valuesMode,- optionsList,- isFocused,- isAllSelected,- isFiltered,-}: RenderOptionsProps) {- if (alwaysShowOptions || isFocused) {- if (optionsList) {- return optionsList;- } else if (- hasList({- parameter,- fields,- disableSearch,- options,- }) &&- valuesMode === "list"- ) {- if (isAllSelected) {- return <EveryOptionState />;- }- } else if (- isSearchable({- parameter,- fields,- disableSearch,- disablePKRemappingForSearch,- valuesMode,- })- ) {- if (loadingState === "LOADING") {- return <LoadingState />;- } else if (loadingState === "LOADED" && isFiltered) {- return (- <NoMatchState- fields={fields.map((field) =>- field.searchField(disablePKRemappingForSearch),- )}- />- );- }- }- }-}-function renderValue({parameter,cardId,@@ -786,18 +615,18 @@ function RemappedValue({}type RemappedOptionProps = {- option: ComboboxItem;+ option: { value: string; label?: string };fields: Field[];tc: ContentTranslationFunction;};function RemappedOption({ option, fields, tc }: RemappedOptionProps) {const isRemapped = Field.remappedField(fields) != null;+ const label = tc(option.label ?? option.value);+if (!isRemapped) {- return tc(option.label);+ return label;}- return (- <MultiAutocompleteOption value={option.value} label={tc(option.label)} />- );+ return <MultiAutocompleteOption value={option.value} label={label} />;}diff --git a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/FieldValuesWidget.unit.spec.tsx b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/FieldValuesWidget.unit.spec.tsxnew file mode 100644index 00000000000..bdad908fb2d--- /dev/null+++ b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/FieldValuesWidget.unit.spec.tsx@@ -0,0 +1,186 @@+import userEvent from "@testing-library/user-event";++import { setupParameterValuesEndpoints } from "__support__/server-mocks";+import { renderWithProviders, screen } from "__support__/ui";+import {+ createMockParameter,+ createMockParameterValues,+} from "metabase-types/api/mocks";++import {+ FieldValuesWidget,+ type IFieldValuesWidgetProps,+} from "./FieldValuesWidget";+import { state } from "./testMocks.spec";++const setup = (props: Partial<IFieldValuesWidgetProps> = {}) => {+ const onChange = jest.fn();+ renderWithProviders(+ <FieldValuesWidget+ value={[]}+ fields={[]}+ onChange={onChange}+ parameter={createMockParameter({ values_query_type: "none" })}+ {...props}+ />,+ { storeInitialState: state },+ );+ return { onChange };+};++describe("FieldValuesWidget", () => {+ describe("placeholder", () => {+ it("should prompt for text for a string parameter with no values", () => {+ setup({ parameter: createMockParameter({ values_query_type: "none" }) });+ expect(+ screen.getByPlaceholderText("Enter some text"),+ ).toBeInTheDocument();+ });++ it("should prompt for an ID for an id parameter with no values", () => {+ setup({+ parameter: createMockParameter({+ type: "id/=",+ values_query_type: "none",+ }),+ });+ expect(screen.getByPlaceholderText("Enter an ID")).toBeInTheDocument();+ });++ it("should prompt for a number for a number parameter with no values", () => {+ setup({+ parameter: createMockParameter({+ type: "number/=",+ values_query_type: "none",+ }),+ });+ expect(screen.getByPlaceholderText("Enter a number")).toBeInTheDocument();+ });+ });++ describe("multi-select", () => {+ it("should commit a typed value on enter", async () => {+ const { onChange } = setup({ multi: true, placeholder: "Value" });++ await userEvent.type(await screen.findByRole("combobox"), "foo{enter}");++ expect(onChange).toHaveBeenLastCalledWith(["foo"]);+ });++ it("should parse typed values for a numeric parameter", async () => {+ const { onChange } = setup({+ multi: true,+ placeholder: "Value",+ parameter: createMockParameter({+ type: "number/=",+ values_query_type: "none",+ }),+ });++ await userEvent.type(await screen.findByRole("combobox"), "42{enter}");++ expect(onChange).toHaveBeenLastCalledWith([42]);+ });+ });++ describe("single-select", () => {+ it("should commit a typed freeform value", async () => {+ const { onChange } = setup({ placeholder: "Value" });++ await userEvent.type(screen.getByPlaceholderText("Value"), "abc");++ expect(onChange).toHaveBeenLastCalledWith(["abc"]);+ });++ it("should parse a typed freeform value for a numeric parameter", async () => {+ const { onChange } = setup({+ placeholder: "Value",+ parameter: createMockParameter({+ type: "number/=",+ values_query_type: "none",+ }),+ });++ await userEvent.type(screen.getByPlaceholderText("Value"), "42");++ expect(onChange).toHaveBeenLastCalledWith([42]);+ });++ it("should accept the top matching option when pressing enter", async () => {+ setupParameterValuesEndpoints(+ createMockParameterValues({ values: [["Gadget"], ["Gizmo"]] }),+ );+ const { onChange } = setup({+ placeholder: "Value",+ disableList: true,+ parameter: createMockParameter({+ values_source_type: "static-list",+ values_source_config: { values: [["Gadget"], ["Gizmo"]] },+ values_query_type: "list",+ }),+ });++ const input = screen.getByPlaceholderText("Value");+ await userEvent.click(input);+ expect(await screen.findByText("Gadget")).toBeInTheDocument();+ await userEvent.type(input, "Ga");+ await userEvent.keyboard("{enter}");++ expect(onChange).toHaveBeenLastCalledWith(["Gadget"]);+ });+ });++ describe("remapped values (value ≠ label)", () => {+ const REMAPPED_VALUES: [string | number, string][] = [+ [1, "Gadget"],+ [2, "Gizmo"],+ ];++ it("should commit the underlying value, not the label, when clicking a remapped option", async () => {+ setupParameterValuesEndpoints(+ createMockParameterValues({ values: REMAPPED_VALUES }),+ );+ const { onChange } = setup({+ placeholder: "Value",+ disableList: true,+ parameter: createMockParameter({+ values_source_type: "static-list",+ values_source_config: { values: REMAPPED_VALUES },+ values_query_type: "list",+ }),+ });++ const input = screen.getByPlaceholderText("Value");+ await userEvent.click(input);+ await userEvent.click(await screen.findByText("Gadget"));++ // Mantine's Autocomplete commits option.label on submit; the widget must+ // commit the underlying value "1" instead of the display label "Gadget".+ expect(onChange).toHaveBeenLastCalledWith(["1"]);+ });++ it("should not clear a numeric filter when clicking a remapped option", async () => {+ setupParameterValuesEndpoints(+ createMockParameterValues({ values: REMAPPED_VALUES }),+ );+ const { onChange } = setup({+ placeholder: "Value",+ disableList: true,+ parameter: createMockParameter({+ type: "number/=",+ values_source_type: "static-list",+ values_source_config: { values: REMAPPED_VALUES },+ values_query_type: "list",+ }),+ });++ const input = screen.getByPlaceholderText("Value");+ await userEvent.click(input);+ await userEvent.click(await screen.findByText("Gadget"));++ // Committing the label "Gadget" fails numeric parsing and clears the+ // filter (onChange([])); the underlying value 1 must be committed.+ expect(onChange).toHaveBeenLastCalledWith([1]);+ });+ });+});diff --git a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/utils.ts b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/utils.tsindex a54d9e10d33..403afdf198a 100644--- a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/utils.ts+++ b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/utils.ts@@ -304,3 +304,16 @@ export function getOption(return { value: String(value), label: String(label ?? value) };}++export function parseStringValue(value: unknown): string | null {+ const trimmedValue = trim(value);+ if (trimmedValue === "") {+ return null;+ }++ return trimmedValue;+}++function trim(value: unknown) {+ return String(value || "").trim();+}diff --git a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/utils.unit.spec.tsx b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/utils.unit.spec.tsxindex 587b2df36f8..512e72dcb74 100644--- a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/utils.unit.spec.tsx+++ b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/utils.unit.spec.tsx@@ -7,11 +7,33 @@ import {STRING_PK_FIELD_ID,metadata,} from "./testMocks.spec";-import { getValuesMode, isSearchable, searchField } from "./utils";+import {+ getValuesMode,+ isSearchable,+ parseStringValue,+ searchField,+} from "./utils";const getField = (id: FieldId) => asNotNull(metadata.field(id));describe("Components > FieldValuesWidget > utils", () => {+ describe("parseStringValue", () => {+ it("should return null for falsy and whitespace values", () => {+ expect(parseStringValue("")).toBeNull();+ expect(parseStringValue(" ")).toBeNull();+ expect(parseStringValue(" \n ")).toBeNull();+ expect(parseStringValue(null)).toBeNull();+ expect(parseStringValue(false)).toBeNull();+ expect(parseStringValue(0)).toBeNull();+ });++ it("should return truthy values coerced into strings", () => {+ expect(parseStringValue(123)).toBe("123");+ expect(parseStringValue(true)).toBe("true");+ expect(parseStringValue(" abc 123 \n ")).toBe("abc 123");+ });+ });+describe("isSearchable", () => {const listField = getField(PRODUCTS.CATEGORY);const searchField = getField(PEOPLE.EMAIL);diff --git a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidget.tsx b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidget.tsxindex ec97dcc280d..764dd0fa8a9 100644--- a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidget.tsx+++ b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidget.tsx@@ -115,7 +115,6 @@ export function ParameterFieldWidget({getFilterArgumentFormatOptions(operator, index)),...fields?.[0]?.settings,}}- color="core-brand"minWidth={300}maxWidth={400}/>diff --git a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidget.unit.spec.tsx b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidget.unit.spec.tsxindex 6129d3bc412..77efd472176 100644--- a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidget.unit.spec.tsx+++ b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidget.unit.spec.tsx@@ -220,11 +220,11 @@ describe("ParameterFieldWidget", () => {expect(input).toHaveValue("f");expect(await screen.findByText("foo")).toBeInTheDocument();- await userEvent.type(input, "{enter}");+ await userEvent.type(input, "{enter}", { skipClick: true });expect(input).toHaveValue("foo");expect(setValue).not.toHaveBeenCalled();- await userEvent.type(input, "{enter}");+ await userEvent.type(input, "{enter}", { skipClick: true });expect(setValue).toHaveBeenCalledWith(["foo"]);});diff --git a/frontend/src/metabase/ui/components/inputs/Autocomplete/Autocomplete.config.tsx b/frontend/src/metabase/ui/components/inputs/Autocomplete/Autocomplete.config.tsxindex 01afb585fcb..95a24f864ab 100644--- a/frontend/src/metabase/ui/components/inputs/Autocomplete/Autocomplete.config.tsx+++ b/frontend/src/metabase/ui/components/inputs/Autocomplete/Autocomplete.config.tsx@@ -1,8 +1,5 @@import { Autocomplete, type MantineThemeOverride } from "@mantine/core";-import { selectOverrides } from "../Select";-import { DefaultSelectItem } from "../Select/SelectItem";-export const autocompleteOverrides: MantineThemeOverride["components"] = {Autocomplete: Autocomplete.extend({defaultProps: {@@ -10,12 +7,8 @@ export const autocompleteOverrides: MantineThemeOverride["components"] = {comboboxProps: {withinPortal: true,},- renderOption: (item) => <DefaultSelectItem {...item.option} />,maxDropdownHeight: 512,withScrollArea: false,},- classNames: {- ...selectOverrides.Select.classNames,- },}),};diff --git a/frontend/src/metabase/ui/components/inputs/Autocomplete/Autocomplete.tsx b/frontend/src/metabase/ui/components/inputs/Autocomplete/Autocomplete.tsxnew file mode 100644index 00000000000..2f2ebc51343--- /dev/null+++ b/frontend/src/metabase/ui/components/inputs/Autocomplete/Autocomplete.tsx@@ -0,0 +1,125 @@+import {+ Combobox,+ InputBase,+ type AutocompleteProps as MantineAutocompleteProps,+ OptionsDropdown,+ useProps,+} from "@mantine/core";++import { useAutocomplete } from "./use-autocomplete";++export type AutocompleteProps = Omit<MantineAutocompleteProps, "onChange"> & {+ parseValue?: (rawValue: string) => string | null;+ onChange?: (value: string) => void;+ onSearchChange?: (rawValue: string) => void;+};++const defaultParseValue = (rawValue: string) => {+ const trimmedValue = rawValue.trim();+ return trimmedValue.length > 0 ? trimmedValue : null;+};++export const Autocomplete = (props: AutocompleteProps) => {+ const {+ unstyled,+ size,+ value,+ defaultValue,+ data,+ parseValue = defaultParseValue,+ selectFirstOptionOnChange,+ readOnly,+ disabled,+ error,+ rightSection,+ filter,+ limit,+ withScrollArea,+ maxDropdownHeight,+ scrollAreaProps,+ renderOption,+ comboboxProps,+ autoSelectOnBlur,+ openOnFocus,+ onChange,+ onSearchChange,+ onFocus,+ onBlur,+ onClick,+ onDropdownOpen,+ onDropdownClose,+ onOptionSubmit,+ ...inputProps+ } = useProps("Autocomplete", null, props);++ const {+ combobox,+ parsedData,+ inputValue,+ handleInputChange,+ handleFocus,+ handleBlur,+ handleClick,+ handleOptionSubmit,+ } = useAutocomplete({+ value,+ defaultValue,+ data,+ selectFirstOptionOnChange,+ autoSelectOnBlur,+ openOnFocus,+ parseValue,+ onChange,+ onSearchChange,+ onFocus,+ onBlur,+ onClick,+ onDropdownOpen,+ onDropdownClose,+ onOptionSubmit,+ });++ return (+ <Combobox+ store={combobox}+ unstyled={unstyled}+ readOnly={readOnly}+ size={size}+ keepMounted={autoSelectOnBlur}+ onOptionSubmit={handleOptionSubmit}+ {...comboboxProps}+ >+ <Combobox.Target>+ <InputBase+ {...inputProps}+ unstyled={unstyled}+ size={size}+ value={inputValue}+ error={error}+ rightSection={rightSection}+ readOnly={readOnly}+ disabled={disabled}+ onChange={handleInputChange}+ onFocus={handleFocus}+ onBlur={handleBlur}+ onClick={handleClick}+ />+ </Combobox.Target>+ <OptionsDropdown+ data={parsedData}+ hidden={readOnly || disabled}+ filter={filter}+ search={inputValue}+ limit={limit}+ hiddenWhenEmpty+ withScrollArea={withScrollArea}+ maxDropdownHeight={maxDropdownHeight}+ unstyled={unstyled}+ labelId={undefined}+ aria-label={inputProps["aria-label"]}+ renderOption={renderOption}+ scrollAreaProps={scrollAreaProps}+ />+ </Combobox>+ );+};diff --git a/frontend/src/metabase/ui/components/inputs/Autocomplete/Autocomplete.unit.spec.tsx b/frontend/src/metabase/ui/components/inputs/Autocomplete/Autocomplete.unit.spec.tsxnew file mode 100644index 00000000000..230fe85691c--- /dev/null+++ b/frontend/src/metabase/ui/components/inputs/Autocomplete/Autocomplete.unit.spec.tsx@@ -0,0 +1,138 @@+import userEvent from "@testing-library/user-event";++import { render, screen, waitFor } from "__support__/ui";+import { Autocomplete, type AutocompleteProps } from "metabase/ui";++const DATA = [+ { value: "apple", label: "Apple" },+ { value: "apricot", label: "Apricot" },+ { value: "banana", label: "Banana" },+];++const setup = (props: Partial<AutocompleteProps> = {}) => {+ const onChange = jest.fn();+ const onSearchChange = jest.fn();+ const onOptionSubmit = jest.fn();+ const allProps: AutocompleteProps = {+ label: "Fruit",+ data: DATA,+ onChange,+ onSearchChange,+ onOptionSubmit,+ ...props,+ };++ const { rerender } = render(<Autocomplete {...allProps} />);+ const input = screen.getByLabelText<HTMLInputElement>("Fruit");++ return {+ input,+ onChange,+ onSearchChange,+ onOptionSubmit,+ rerender: (next: Partial<AutocompleteProps>) =>+ rerender(<Autocomplete {...allProps} {...next} />),+ };+};++const isSelected = (name: string) =>+ screen.getByRole("option", { name }).getAttribute("data-combobox-selected");++describe("Autocomplete", () => {+ it("renders the label and the formatted value", () => {+ const { input } = setup({ value: "apple" });+ expect(input).toHaveValue("Apple");+ });++ it("reports search and resolved value while typing", async () => {+ const { input, onSearchChange, onChange } = setup();++ await userEvent.type(input, "Apple");++ expect(onSearchChange).toHaveBeenLastCalledWith("Apple");+ expect(onChange).toHaveBeenLastCalledWith("apple");+ });++ it("filters options by the input", async () => {+ const { input } = setup();++ await userEvent.type(input, "Ap");++ expect(+ await screen.findByRole("option", { name: "Apple" }),+ ).toBeInTheDocument();+ expect(screen.getByRole("option", { name: "Apricot" })).toBeInTheDocument();+ expect(+ screen.queryByRole("option", { name: "Banana" }),+ ).not.toBeInTheDocument();+ });++ it("submits an option on click", async () => {+ const { input, onOptionSubmit } = setup();++ await userEvent.click(input);+ await userEvent.click(+ await screen.findByRole("option", { name: "Apricot" }),+ );++ expect(onOptionSubmit).toHaveBeenCalledWith("apricot");+ expect(input).toHaveValue("Apricot");+ });++ it("is not editable when readOnly", async () => {+ const { input, onChange } = setup({ readOnly: true, value: "apple" });++ expect(input).toHaveAttribute("readonly");++ await userEvent.type(input, "berry");++ expect(input).toHaveValue("Apple");+ expect(onChange).not.toHaveBeenCalled();+ });++ describe("selectFirstOptionOnChange", () => {+ it("highlights the first option on first open with an empty input", async () => {+ const { input } = setup({ selectFirstOptionOnChange: true });++ await userEvent.click(input);++ await screen.findByRole("option", { name: "Apple" });+ await waitFor(() => expect(isSelected("Apple")).toBe("true"));+ });++ it("highlights the first matching option after typing", async () => {+ const { input } = setup({ selectFirstOptionOnChange: true });++ await userEvent.type(input, "Ap");++ await screen.findByRole("option", { name: "Apple" });+ await waitFor(() => expect(isSelected("Apple")).toBe("true"));+ });++ it("re-highlights the first option when new data loads while open", async () => {+ const bananaData = [{ value: "banana", label: "Banana" }];+ const { input, rerender } = setup({+ selectFirstOptionOnChange: true,+ data: bananaData,+ });++ await userEvent.click(input);+ await screen.findByRole("option", { name: "Banana" });+ await waitFor(() => expect(isSelected("Banana")).toBe("true"));++ rerender({ data: DATA });++ await screen.findByRole("option", { name: "Apple" });+ await waitFor(() => expect(isSelected("Apple")).toBe("true"));+ });++ it("does not highlight any option by default", async () => {+ const { input } = setup();++ await userEvent.click(input);++ await screen.findByRole("option", { name: "Apple" });+ expect(isSelected("Apple")).toBeNull();+ });+ });+});diff --git a/frontend/src/metabase/ui/components/inputs/Autocomplete/index.ts b/frontend/src/metabase/ui/components/inputs/Autocomplete/index.tsindex b949f40df35..0928bba7fd9 100644--- a/frontend/src/metabase/ui/components/inputs/Autocomplete/index.ts+++ b/frontend/src/metabase/ui/components/inputs/Autocomplete/index.ts@@ -1,3 +1,3 @@-export { Autocomplete } from "@mantine/core";-export type { AutocompleteProps } from "@mantine/core";+export { Autocomplete } from "./Autocomplete";+export type { AutocompleteProps } from "./Autocomplete";export { autocompleteOverrides } from "./Autocomplete.config";diff --git a/frontend/src/metabase/ui/components/inputs/Autocomplete/use-autocomplete.ts b/frontend/src/metabase/ui/components/inputs/Autocomplete/use-autocomplete.tsnew file mode 100644index 00000000000..4eae42544be--- /dev/null+++ b/frontend/src/metabase/ui/components/inputs/Autocomplete/use-autocomplete.ts@@ -0,0 +1,172 @@+import {+ type ComboboxStringData,+ getLabelsLockup,+ getOptionsLockup,+ getParsedComboboxData,+ isOptionsGroup,+ useCombobox,+} from "@mantine/core";+import {+ type ChangeEvent,+ type FocusEvent,+ type MouseEvent,+ useCallback,+ useEffect,+ useLayoutEffect,+ useMemo,+ useState,+} from "react";+import { usePrevious } from "react-use";++type UseAutocompleteProps = {+ value?: string;+ defaultValue?: string;+ data?: ComboboxStringData;+ selectFirstOptionOnChange?: boolean;+ autoSelectOnBlur?: boolean;+ openOnFocus?: boolean;+ parseValue: (rawValue: string) => string | null;+ onChange?: (value: string) => void;+ onSearchChange?: (rawValue: string) => void;+ onFocus?: (event: FocusEvent<HTMLInputElement>) => void;+ onBlur?: (event: FocusEvent<HTMLInputElement>) => void;+ onClick?: (event: MouseEvent<HTMLInputElement>) => void;+ onDropdownOpen?: () => void;+ onDropdownClose?: () => void;+ onOptionSubmit?: (value: string) => void;+};++export const useAutocomplete = ({+ value,+ defaultValue,+ data,+ selectFirstOptionOnChange,+ autoSelectOnBlur,+ openOnFocus = true,+ parseValue,+ onChange,+ onSearchChange,+ onFocus,+ onBlur,+ onClick,+ onDropdownOpen,+ onDropdownClose,+ onOptionSubmit,+}: UseAutocompleteProps) => {+ const parsedData = useMemo(() => getParsedComboboxData(data), [data]);+ const optionsKey = useMemo(+ () =>+ parsedData+ .flatMap((item) => (isOptionsGroup(item) ? item.items : item))+ .map((item) => item.value)+ .join(" "),+ [parsedData],+ );+ const { valueLockup, labelLockup } = useMemo(+ () => ({+ valueLockup: getOptionsLockup(parsedData),+ labelLockup: getLabelsLockup(parsedData),+ }),+ [parsedData],+ );++ const formatValue = useCallback(+ (rawValue: string) => valueLockup[rawValue]?.label ?? rawValue,+ [valueLockup],+ );++ const resolveValue = useCallback(+ (rawValue: string) => {+ const match = valueLockup[rawValue] ?? labelLockup[rawValue];+ return match?.value ?? parseValue(rawValue) ?? "";+ },+ [valueLockup, labelLockup, parseValue],+ );++ const [inputValue, setInputValue] = useState(() =>+ formatValue(value ?? defaultValue ?? ""),+ );+ const previousValue = usePrevious(value);++ const combobox = useCombobox({+ onDropdownOpen,+ onDropdownClose: () => {+ onDropdownClose?.();+ combobox.resetSelectedOption();+ },+ });++ useEffect(() => {+ if (value === previousValue) {+ return;+ }+ if (resolveValue(inputValue) !== value) {+ setInputValue(formatValue(value ?? ""));+ }+ }, [value, previousValue, inputValue, resolveValue, formatValue]);++ const { dropdownOpened, selectFirstOption: selectFirst } = combobox;++ const selectFirstOption = useCallback(() => {+ if (selectFirstOptionOnChange && dropdownOpened) {+ selectFirst();+ }+ }, [selectFirstOptionOnChange, dropdownOpened, selectFirst]);++ // list change (typing / backend load): select before paint to avoid flicker+ useLayoutEffect(selectFirstOption, [+ optionsKey,+ inputValue,+ selectFirstOption,+ ]);+ // dropdown open: after paint, since Combobox.Options registers listId in a passive effect+ useEffect(selectFirstOption, [dropdownOpened, selectFirstOption]);++ const handleSearchChange = (rawValue: string) => {+ setInputValue(rawValue);+ onSearchChange?.(rawValue);+ onChange?.(resolveValue(rawValue));+ };++ const handleInputChange = (event: ChangeEvent<HTMLInputElement>) => {+ handleSearchChange(event.currentTarget.value);+ combobox.openDropdown();+ };++ const handleFocus = (event: FocusEvent<HTMLInputElement>) => {+ if (openOnFocus) {+ combobox.openDropdown();+ }+ onFocus?.(event);+ };++ const handleBlur = (event: FocusEvent<HTMLInputElement>) => {+ if (autoSelectOnBlur) {+ combobox.clickSelectedOption();+ }+ combobox.closeDropdown();+ onBlur?.(event);+ };++ const handleClick = (event: MouseEvent<HTMLInputElement>) => {+ combobox.openDropdown();+ onClick?.(event);+ };++ const handleOptionSubmit = (optionValue: string) => {+ onOptionSubmit?.(optionValue);+ handleSearchChange(formatValue(optionValue));+ combobox.closeDropdown();+ };++ return {+ combobox,+ parsedData,+ inputValue,+ handleInputChange,+ handleFocus,+ handleBlur,+ handleClick,+ handleOptionSubmit,+ };+};diff --git a/frontend/src/metabase/ui/components/inputs/MultiAutocomplete/MultiAutocomplete.tsx b/frontend/src/metabase/ui/components/inputs/MultiAutocomplete/MultiAutocomplete.tsxindex cbf2cc01b40..13d4ff03349 100644--- a/frontend/src/metabase/ui/components/inputs/MultiAutocomplete/MultiAutocomplete.tsx+++ b/frontend/src/metabase/ui/components/inputs/MultiAutocomplete/MultiAutocomplete.tsx@@ -142,6 +142,7 @@ export function MultiAutocomplete({} = useMultiAutocomplete({values: value,data: sortedData,+ selectFirstOptionOnChange,parseValue,onChange,onSearchChange,diff --git a/frontend/src/metabase/ui/components/inputs/MultiAutocomplete/use-multi-autocomplete/use-multi-autocomplete.ts b/frontend/src/metabase/ui/components/inputs/MultiAutocomplete/use-multi-autocomplete/use-multi-autocomplete.tsindex 901ed3dc826..d3446e1faf3 100644--- a/frontend/src/metabase/ui/components/inputs/MultiAutocomplete/use-multi-autocomplete/use-multi-autocomplete.ts+++ b/frontend/src/metabase/ui/components/inputs/MultiAutocomplete/use-multi-autocomplete/use-multi-autocomplete.ts@@ -13,6 +13,7 @@ import {type ClipboardEvent,type MouseEvent,type KeyboardEvent as ReactKeyboardEvent,+ useEffect,useMemo,useState,} from "react";@@ -54,6 +55,7 @@ export function useMultiAutocomplete({data,dropdownOpened,defaultDropdownOpened,+ selectFirstOptionOnChange,parseValue,onChange,onSearchChange,@@ -263,6 +265,16 @@ export function useMultiAutocomplete({useWindowEvent("keydown", handleWindowKeydownCapture, { capture: true });+ useEffect(() => {+ if (selectFirstOptionOnChange && combobox.dropdownOpened) {+ combobox.selectFirstOption();+ }+ // We only want to re-highlight the first option when the option list+ // changes (searchValue/values), not on every combobox state change, so+ // `combobox` is intentionally left out of the dependency array.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [searchValue, values, selectFirstOptionOnChange]);+return {combobox,pillValues: getPillValues(values, fieldSelection),